From 139938dc0edd81532a12cd437879d91c3488c1c3 Mon Sep 17 00:00:00 2001 From: GitHub Action Date: Tue, 25 Jul 2023 16:57:50 +0000 Subject: [PATCH] release PHP 7.2 downgraded --- .editorconfig | 9 - .gitignore | 4 +- bin/ecs | 3 +- bin/ecs.php | 93 +- .../bootstrap.php => bootstrap.php | 0 build/rector-downgrade-php-72.php | 16 - build/target-repository/.gitignore | 10 - build/target-repository/composer.json | 22 - composer.json | 91 +- config/config.php | 17 +- config/set/clean-code.php | 21 +- config/set/common.php | 17 +- config/set/common/array.php | 31 +- config/set/common/comments.php | 6 +- config/set/common/control-structures.php | 38 +- config/set/common/docblock.php | 26 +- config/set/common/namespaces.php | 12 +- config/set/common/phpunit.php | 6 +- config/set/common/spaces.php | 54 +- config/set/common/strict.php | 13 +- config/set/doctrine-annotations.php | 17 +- config/set/laravel.php | 232 +- config/set/psr12.php | 94 +- config/set/symplify.php | 14 +- easy-ci.php | 20 - ecs.php | 20 - full_ecs_build.sh | 18 - .../ChangedFilesDetectorTest.php | 58 - .../ChangedFilesDetector/Source/OneClass.php | 10 - .../Source/another-configuration.php | 9 - .../Source/easy-coding-standard.php | 9 - .../FileHashComputer/FileHashComputerTest.php | 67 - .../Fixture/config-including-another-one.php | 9 - .../Source/ChangedScannedClass.php | 10 - .../Source/SomeScannedClass.php | 10 - .../FileHashComputer/Source/empty_config.php | 10 - .../FileHashComputer/Source/first_config.php | 10 - .../easy-coding-standard.php | 22 - .../Application/FileProcessorTest.php | 33 - .../FixerServiceRegistrationTest.php | 45 - .../config/easy-coding-standard.php | 17 - .../FileSystem/Fixture/in/it/KeepThisFile.txt | 0 .../Fixture/path/in/it/KeepThisFile.txt | 0 .../Fixture/path/with/KeepThisFile.txt | 0 .../FileSystem/FnMatchPathNormalizerTest.php | 39 - .../Fixture/existing_paths.txt | 1 - .../SkippedPathsResolverTest.php | 27 - .../SkippedPathsResolver/config/config.php | 14 - .../Fixture/AlwaysSkippedPath/some_file.txt | 1 - .../PathSkippedWithMask/another_file.txt | 1 - .../Skipper/Skipper/Skip/Fixture/skip.php.inc | 17 - .../Fixture/someDirectory/anotherFile.php | 5 - .../Skip/Fixture/someDirectory/someFile | 0 .../Skip/Fixture/someDirectory/someFile.php | 5 - .../Skipper/Skipper/Skip/Fixture/someFile | 1 - .../Skipper/Skip/Fixture/someOtherFile | 1 - .../Skipper/Skipper/Skip/SkipSkipperTest.php | 79 - .../Skip/Source/AnotherClassToSkip.php | 9 - .../Skipper/Skip/Source/NotSkippedClass.php | 9 - .../Skipper/Skip/Source/SomeClassToSkip.php | 9 - .../Skipper/Skipper/Skip/config/config.php | 30 - .../Skipper/Fixture/Element/FifthElement.php | 9 - .../Skipper/Fixture/Element/SixthSense.php | 9 - .../Skipper/Fixture/Element/ThreeMan.php | 9 - .../Skipper/Fixture/SomeRandom/file.txt | 1 - .../Skipper/Fixture/SomeSkipped/any.txt | 1 - .../Skipper/Skipper/Skipper/SkipperTest.php | 72 - .../Skipper/Skipper/Skipper/config/config.php | 18 - .../Application/FixerSource/SomeFile.php | 10 - .../SniffRunner/Application/FixerTest.php | 143 - .../DI/SniffServiceRegistrationTest.php | 24 - .../SniffRunner/DI/Source/AnotherSniff.php | 24 - packages-tests/SniffRunner/DI/config/ecs.php | 13 - .../File/FileFactorySource/SomeFile.php | 3 - .../SniffRunner/File/FileFactoryTest.php | 25 - .../ValueObject/FileSource/SomeFile.php | 3 - .../SniffRunner/ValueObject/FileTest.php | 21 - packages/Caching/Cache.php | 27 +- packages/Caching/CacheFactory.php | 27 +- packages/Caching/ChangedFilesDetector.php | 62 +- packages/Caching/FileHashComputer.php | 27 +- .../Caching/ValueObject/CacheFilePaths.php | 37 +- packages/Caching/ValueObject/CacheItem.php | 36 +- .../ValueObject/Storage/FileCacheStorage.php | 79 +- .../Application/FixerFileProcessor.php | 138 +- .../FixerRunner/Parser/FileToTokensParser.php | 8 +- packages/FixerRunner/ValueObject/Spacing.php | 5 +- .../WhitespacesFixerConfigFactory.php | 36 +- .../Application/ParallelFileProcessor.php | 172 +- packages/Parallel/ValueObject/Bridge.php | 7 +- packages/Parallel/ValueObject/Name.php | 9 +- packages/Parallel/WorkerRunner.php | 84 +- .../Skipper/Contract/SkipVoterInterface.php | 17 +- .../FileSystem/FnMatchPathNormalizer.php | 23 +- packages/Skipper/Fnmatcher.php | 18 +- packages/Skipper/Matcher/FileInfoMatcher.php | 52 +- .../SkippedClassAndCodesResolver.php | 21 +- .../SkippedClassResolver.php | 21 +- .../SkippedMessagesResolver.php | 21 +- .../SkippedPathsResolver.php | 31 +- .../SkipVoter/ClassAndCodeSkipVoter.php | 56 +- packages/Skipper/SkipVoter/ClassSkipVoter.php | 43 +- .../Skipper/SkipVoter/MessageSkipVoter.php | 56 +- packages/Skipper/SkipVoter/PathSkipVoter.php | 38 +- packages/Skipper/Skipper/SkipSkipper.php | 34 +- packages/Skipper/Skipper/Skipper.php | 42 +- .../Application/SniffFileProcessor.php | 114 +- .../DataCollector/SniffMetadataCollector.php | 24 +- packages/SniffRunner/File/FileFactory.php | 51 +- .../ValueObject/Error/CodingStandardError.php | 74 +- packages/SniffRunner/ValueObject/File.php | 172 +- phpstan.neon | 50 - phpunit.xml | 14 - prefix-code.sh | 51 - .../preload.php => preload.php | 0 rector.php | 49 - scoper.php | 147 - .../EasyCodingStandardApplication.php | 168 +- src/Application/FileProcessorCollector.php | 10 +- src/Application/SingleFileProcessor.php | 41 +- .../Version/StaticVersionResolver.php | 46 +- src/Config/ECSConfig.php | 156 +- src/Configuration/ConfigInitializer.php | 74 +- src/Configuration/ConfigurationFactory.php | 62 +- src/Configuration/InitPathsResolver.php | 38 +- src/Console/Command/AbstractCheckCommand.php | 42 +- src/Console/Command/CheckCommand.php | 61 +- src/Console/Command/ListCheckersCommand.php | 97 +- src/Console/Command/WorkerCommand.php | 74 +- .../EasyCodingStandardConsoleApplication.php | 65 +- src/Console/ExitCode.php | 8 +- .../Formatter/ColorConsoleDiffFormatter.php | 57 +- src/Console/Output/ConsoleOutputFormatter.php | 110 +- src/Console/Output/ExitCodeResolver.php | 8 +- src/Console/Output/JsonOutputFormatter.php | 62 +- .../Output/OutputFormatterCollector.php | 20 +- src/Console/Reporter/CheckerListReporter.php | 28 +- src/Console/Style/EasyCodingStandardStyle.php | 63 +- .../Style/EasyCodingStandardStyleFactory.php | 33 +- src/Console/Style/SymfonyStyleFactory.php | 25 +- .../Application/FileProcessorInterface.php | 12 +- .../Output/OutputFormatterInterface.php | 9 +- .../CompilerPass/CompilerPassHelper.php | 29 +- .../ConflictingCheckersCompilerPass.php | 43 +- .../RemoveExcludedCheckersCompilerPass.php | 42 +- .../RemoveMutualCheckersCompilerPass.php | 81 +- .../EasyCodingStandardContainerFactory.php | 25 +- .../NewContainerFactory.php | 141 +- .../SimpleParameterProvider.php | 63 +- src/Error/FileDiffFactory.php | 25 +- .../ConflictingCheckersLoadedException.php | 4 +- .../Configuration/FileNotFoundException.php | 4 +- .../Configuration/InitializationException.php | 4 +- .../OutputFormatterNotFoundException.php | 4 +- .../Configuration/SourceNotFoundException.php | 4 +- .../WhitespaceConfigurationException.php | 4 +- src/Exception/ShouldNotHappenException.php | 4 +- src/Exception/VersionException.php | 4 +- src/FileSystem/FileFilter.php | 25 +- src/FileSystem/PathNormalizer.php | 41 +- .../StaticRelativeFilePathHelper.php | 13 +- src/Finder/SourceFinder.php | 44 +- src/MemoryLimitter.php | 26 +- src/Reporter/ProcessedFileReporter.php | 22 +- src/Testing/Contract/ConfigAwareInterface.php | 5 +- .../PHPUnit/AbstractCheckerTestCase.php | 74 +- src/Testing/PHPUnit/AbstractTestCase.php | 23 +- src/Testing/PHPUnit/FixtureFinder.php | 15 +- src/Utils/ParametersMerger.php | 55 +- src/Utils/PrivatesAccessorHelper.php | 21 +- src/ValueObject/Configuration.php | 118 +- src/ValueObject/Error/ErrorAndDiffResult.php | 73 +- src/ValueObject/Error/FileDiff.php | 75 +- src/ValueObject/Error/SystemError.php | 50 +- src/ValueObject/Option.php | 27 +- src/ValueObject/Set/SetList.php | 16 +- .../ColorConsoleDiffFormatterTest.php | 41 - .../Formatter/Fixture/expected_dots.txt | 3 - .../Formatter/Fixture/expected_old_new.txt | 4 - .../expected_with_full_diff_by_phpunit.diff | 3 - .../Fixture/with_full_diff_by_phpunit.diff | 3 - .../Output/Fixture/expected_json_output.json | 24 - .../Output/Fixture/expected_plain.json | 7 - .../Output/JsonOutputFormatterTest.php | 56 - tests/Console/Output/Source/RandomFile.php | 9 - .../ConfigurationFileSource/empty-config.php | 8 - .../include-another-config.php | 11 - .../ConfigurationFileSource/simple-config.php | 10 - .../ConfigurationFileTest.php | 34 - .../ConflictingCheckersTest.php | 22 - .../ConflictingCheckers/config/config.php | 12 - .../ExcludedCheckers/ExcludedCheckersTest.php | 19 - .../ExcludedCheckers/config/config.php | 12 - .../MutualExcludedCheckersTest.php | 23 - .../MutualExcludedCheckers/config/config.php | 18 - .../ConstantWithoutPublicDeclaration.php.inc | 10 - .../ErrorCollectorSource/NotPsr2Class.php.inc | 17 - .../ErrorCollector/FixerFileProcessorTest.php | 33 - .../easy-coding-standard.php | 15 - .../phpunit-fixer-config.php | 10 - .../ErrorCollector/SniffFileProcessorTest.php | 38 - .../easy-coding-standard.php | 10 - tests/FileSystem/PathNormalizerTest.php | 37 - .../SourceFinderSource/Source/SomeClass.php | 9 - .../Source/SomeClass.php.inc | 9 - .../Source/whatever/FindThisTest.php.inc | 7 - tests/Finder/SourceFinderTest.php | 25 - tests/Indentation/IndentationTest.php | 48 - .../Source/config-with-spaces-indentation.php | 12 - .../Source/config-with-tabs-indentation.php | 12 - tests/Set/Array/ArrayTest.php | 28 - tests/Set/Array/Fixture/nested_array.php.inc | 19 - .../Fixture/nested_array_complex.php.inc | 22 - tests/Set/Array/config.php | 10 - tests/Set/Psr12/Fixture/fixture.php.inc | 282 - tests/Set/Psr12/Fixture/fixture2.php.inc | 253 - tests/Set/Psr12/Psr12Test.php | 29 - .../PHPUnit/Fixture/another_file.php.inc | 3 - .../Testing/PHPUnit/Fixture/some_file.php.inc | 3 - tests/Testing/PHPUnit/FixtureFinderTest.php | 17 - tests/bootstrap.php | 6 - tests/functions.php | 15 - vendor/autoload.php | 25 + vendor/bin/php-cs-fixer | 94 + vendor/bin/phpcbf | 94 + vendor/bin/phpcs | 94 + vendor/clue/ndjson-react/CHANGELOG.md | 75 + vendor/clue/ndjson-react/LICENSE | 21 + vendor/clue/ndjson-react/README.md | 365 ++ vendor/clue/ndjson-react/composer.json | 38 + vendor/clue/ndjson-react/src/Decoder.php | 140 + vendor/clue/ndjson-react/src/Encoder.php | 122 + vendor/composer/ClassLoader.php | 579 ++ vendor/composer/InstalledVersions.php | 313 ++ vendor/composer/LICENSE | 21 + vendor/composer/autoload_classmap.php | 1249 +++++ vendor/composer/autoload_files.php | 14 + vendor/composer/autoload_namespaces.php | 9 + vendor/composer/autoload_psr4.php | 44 + vendor/composer/autoload_real.php | 49 + vendor/composer/autoload_static.php | 1460 +++++ vendor/composer/installed.json | 2732 ++++++++++ vendor/composer/installed.php | 5 + vendor/composer/pcre/LICENSE | 19 + vendor/composer/pcre/README.md | 181 + vendor/composer/pcre/composer.json | 46 + vendor/composer/pcre/src/MatchAllResult.php | 42 + .../pcre/src/MatchAllStrictGroupsResult.php | 42 + .../pcre/src/MatchAllWithOffsetsResult.php | 44 + vendor/composer/pcre/src/MatchResult.php | 36 + .../pcre/src/MatchStrictGroupsResult.php | 36 + .../pcre/src/MatchWithOffsetsResult.php | 38 + vendor/composer/pcre/src/PcreException.php | 52 + vendor/composer/pcre/src/Preg.php | 382 ++ vendor/composer/pcre/src/Regex.php | 148 + vendor/composer/pcre/src/ReplaceResult.php | 39 + .../pcre/src/UnexpectedNullMatchException.php | 19 + vendor/composer/semver/CHANGELOG.md | 209 + vendor/composer/semver/LICENSE | 19 + vendor/composer/semver/README.md | 98 + vendor/composer/semver/composer.json | 59 + vendor/composer/semver/src/Comparator.php | 104 + .../composer/semver/src/CompilingMatcher.php | 77 + .../composer/semver/src/Constraint/Bound.php | 103 + .../semver/src/Constraint/Constraint.php | 354 ++ .../src/Constraint/ConstraintInterface.php | 68 + .../src/Constraint/MatchAllConstraint.php | 76 + .../src/Constraint/MatchNoneConstraint.php | 74 + .../semver/src/Constraint/MultiConstraint.php | 258 + vendor/composer/semver/src/Interval.php | 84 + vendor/composer/semver/src/Intervals.php | 399 ++ vendor/composer/semver/src/Semver.php | 111 + vendor/composer/semver/src/VersionParser.php | 488 ++ vendor/composer/xdebug-handler/CHANGELOG.md | 134 + vendor/composer/xdebug-handler/LICENSE | 21 + vendor/composer/xdebug-handler/README.md | 298 + vendor/composer/xdebug-handler/composer.json | 44 + .../composer/xdebug-handler/src/PhpConfig.php | 82 + .../composer/xdebug-handler/src/Process.php | 99 + vendor/composer/xdebug-handler/src/Status.php | 175 + .../xdebug-handler/src/XdebugHandler.php | 540 ++ vendor/doctrine/annotations/LICENSE | 19 + vendor/doctrine/annotations/README.md | 24 + vendor/doctrine/annotations/UPGRADE.md | 18 + vendor/doctrine/annotations/composer.json | 72 + .../annotations/docs/en/annotations.rst | 189 + .../doctrine/annotations/docs/en/custom.rst | 443 ++ vendor/doctrine/annotations/docs/en/index.rst | 102 + .../doctrine/annotations/docs/en/sidebar.rst | 6 + .../Common/Annotations/Annotation.php | 45 + .../Annotations/Annotation/Attribute.php | 19 + .../Annotations/Annotation/Attributes.php | 15 + .../Common/Annotations/Annotation/Enum.php | 55 + .../Annotation/IgnoreAnnotation.php | 35 + .../Annotation/NamedArgumentConstructor.php | 13 + .../Annotations/Annotation/Required.php | 13 + .../Common/Annotations/Annotation/Target.php | 71 + .../Annotations/AnnotationException.php | 105 + .../Common/Annotations/AnnotationReader.php | 305 ++ .../Common/Annotations/AnnotationRegistry.php | 36 + .../Doctrine/Common/Annotations/DocLexer.php | 92 + .../Doctrine/Common/Annotations/DocParser.php | 1040 ++++ .../ImplicitlyIgnoredAnnotationNames.php | 82 + .../Common/Annotations/IndexedReader.php | 86 + .../Doctrine/Common/Annotations/PhpParser.php | 66 + .../Common/Annotations/PsrCachedReader.php | 176 + .../Doctrine/Common/Annotations/Reader.php | 74 + .../Common/Annotations/TokenParser.php | 173 + vendor/doctrine/annotations/psalm.xml | 15 + vendor/doctrine/lexer/LICENSE | 19 + vendor/doctrine/lexer/README.md | 9 + vendor/doctrine/lexer/UPGRADE.md | 22 + vendor/doctrine/lexer/composer.json | 55 + vendor/doctrine/lexer/src/AbstractLexer.php | 285 + vendor/doctrine/lexer/src/Token.php | 50 + vendor/evenement/evenement/CHANGELOG.md | 35 + vendor/evenement/evenement/LICENSE | 19 + vendor/evenement/evenement/README.md | 83 + vendor/evenement/evenement/composer.json | 34 + vendor/evenement/evenement/doc/00-intro.md | 28 + vendor/evenement/evenement/doc/01-api.md | 91 + .../evenement/doc/02-plugin-system.md | 155 + .../examples/benchmark-emit-no-arguments.php | 25 + .../examples/benchmark-emit-once.php | 26 + .../examples/benchmark-emit-one-argument.php | 25 + .../evenement/examples/benchmark-emit.php | 25 + .../benchmark-remove-listener-once.php | 35 + vendor/evenement/evenement/phpunit.xml.dist | 24 + .../evenement/src/Evenement/EventEmitter.php | 17 + .../src/Evenement/EventEmitterInterface.php | 22 + .../src/Evenement/EventEmitterTrait.php | 108 + .../Evenement/Tests/EventEmitterTest.php | 345 ++ .../tests/Evenement/Tests/Listener.php | 43 + .../tests/Evenement/Tests/functions.php | 17 + vendor/fidry/cpu-core-counter/LICENSE.md | 16 + vendor/fidry/cpu-core-counter/README.md | 114 + .../fidry/cpu-core-counter/bin/diagnose.php | 18 + vendor/fidry/cpu-core-counter/bin/execute.php | 18 + vendor/fidry/cpu-core-counter/composer.json | 48 + .../cpu-core-counter/src/CpuCoreCounter.php | 76 + .../fidry/cpu-core-counter/src/Diagnoser.php | 63 + .../src/Executor/ProcOpenExecutor.php | 43 + .../src/Executor/ProcessExecutor.php | 20 + .../src/Finder/CpuCoreFinder.php | 33 + .../src/Finder/CpuInfoFinder.php | 70 + .../src/Finder/DummyCpuCoreFinder.php | 44 + .../src/Finder/FinderRegistry.php | 40 + .../src/Finder/HwLogicalFinder.php | 30 + .../src/Finder/HwPhysicalFinder.php | 30 + .../src/Finder/LscpuLogicalFinder.php | 44 + .../src/Finder/LscpuPhysicalFinder.php | 55 + .../src/Finder/NProcFinder.php | 44 + .../src/Finder/NProcessorFinder.php | 29 + .../src/Finder/NullCpuCoreFinder.php | 31 + .../src/Finder/OnlyOnOSFamilyFinder.php | 71 + .../src/Finder/ProcOpenBasedFinder.php | 71 + .../src/Finder/SkipOnOSFamilyFinder.php | 71 + .../src/Finder/WmicLogicalFinder.php | 39 + .../src/Finder/WmicPhysicalFinder.php | 39 + .../src/Finder/_NProcessorFinder.php | 29 + .../src/NumberOfCpuCoreNotFound.php | 21 + vendor/friendsofphp/php-cs-fixer/CHANGELOG.md | 4794 +++++++++++++++++ .../friendsofphp/php-cs-fixer/CONTRIBUTING.md | 104 + vendor/friendsofphp/php-cs-fixer/LICENSE | 19 + vendor/friendsofphp/php-cs-fixer/README.md | 89 + .../friendsofphp/php-cs-fixer/UPGRADE-v3.md | 167 + .../php-cs-fixer/ci-integration.sh | 8 + .../friendsofphp/php-cs-fixer/composer.json | 82 + .../php-cs-fixer/feature-or-bug.rst | 24 + vendor/friendsofphp/php-cs-fixer/logo.md | 3 + vendor/friendsofphp/php-cs-fixer/logo.png | Bin 0 -> 18627 bytes vendor/friendsofphp/php-cs-fixer/php-cs-fixer | 87 + .../src/AbstractDoctrineAnnotationFixer.php | 199 + .../php-cs-fixer/src/AbstractFixer.php | 147 + .../src/AbstractFopenFlagFixer.php | 74 + .../src/AbstractFunctionReferenceFixer.php | 63 + .../src/AbstractNoUselessElseFixer.php | 150 + .../AbstractPhpdocToTypeDeclarationFixer.php | 157 + .../src/AbstractPhpdocTypesFixer.php | 98 + .../php-cs-fixer/src/AbstractProxyFixer.php | 89 + .../php-cs-fixer/src/Cache/Cache.php | 89 + .../php-cs-fixer/src/Cache/CacheInterface.php | 28 + .../src/Cache/CacheManagerInterface.php | 24 + .../php-cs-fixer/src/Cache/Directory.php | 42 + .../src/Cache/DirectoryInterface.php | 21 + .../src/Cache/FileCacheManager.php | 130 + .../php-cs-fixer/src/Cache/FileHandler.php | 77 + .../src/Cache/FileHandlerInterface.php | 25 + .../src/Cache/NullCacheManager.php | 29 + .../php-cs-fixer/src/Cache/Signature.php | 94 + .../src/Cache/SignatureInterface.php | 31 + .../friendsofphp/php-cs-fixer/src/Config.php | 192 + .../php-cs-fixer/src/ConfigInterface.php | 115 + .../InvalidConfigurationException.php | 29 + .../InvalidFixerConfigurationException.php | 38 + ...validForEnvFixerConfigurationException.php | 22 + .../RequiredFixerConfigurationException.php | 22 + .../php-cs-fixer/src/Console/Application.php | 110 + .../src/Console/Command/DescribeCommand.php | 286 + .../Command/DescribeNameNotFoundException.php | 43 + .../Console/Command/DocumentationCommand.php | 82 + .../src/Console/Command/FixCommand.php | 258 + .../FixCommandExitStatusCalculator.php | 44 + .../src/Console/Command/HelpCommand.php | 63 + .../src/Console/Command/ListFilesCommand.php | 68 + .../src/Console/Command/ListSetsCommand.php | 60 + .../src/Console/Command/SelfUpdateCommand.php | 126 + .../src/Console/ConfigurationResolver.php | 683 +++ .../src/Console/Output/ErrorOutput.php | 116 + .../src/Console/Output/OutputContext.php | 51 + .../Console/Output/Progress/DotsOutput.php | 98 + .../Console/Output/Progress/NullOutput.php | 27 + .../Output/Progress/ProgressOutputFactory.php | 35 + .../Progress/ProgressOutputInterface.php | 23 + .../Output/Progress/ProgressOutputType.php | 23 + .../Report/FixReport/CheckstyleReporter.php | 54 + .../Report/FixReport/GitlabReporter.php | 58 + .../Console/Report/FixReport/JsonReporter.php | 44 + .../Report/FixReport/JunitReporter.php | 101 + .../Report/FixReport/ReportSummary.php | 96 + .../Report/FixReport/ReporterFactory.php | 69 + .../Report/FixReport/ReporterInterface.php | 27 + .../Console/Report/FixReport/TextReporter.php | 64 + .../Console/Report/FixReport/XmlReporter.php | 97 + .../Report/ListSetsReport/JsonReporter.php | 40 + .../Report/ListSetsReport/ReportSummary.php | 41 + .../Report/ListSetsReport/ReporterFactory.php | 68 + .../ListSetsReport/ReporterInterface.php | 27 + .../Report/ListSetsReport/TextReporter.php | 42 + .../src/Console/SelfUpdate/GithubClient.php | 33 + .../SelfUpdate/GithubClientInterface.php | 29 + .../Console/SelfUpdate/NewVersionChecker.php | 86 + .../SelfUpdate/NewVersionCheckerInterface.php | 33 + .../src/Console/WarningsDetector.php | 63 + .../src/Differ/DiffConsoleFormatter.php | 61 + .../src/Differ/DifferInterface.php | 24 + .../php-cs-fixer/src/Differ/FullDiffer.php | 36 + .../php-cs-fixer/src/Differ/NullDiffer.php | 24 + .../php-cs-fixer/src/Differ/UnifiedDiffer.php | 34 + .../php-cs-fixer/src/DocBlock/Annotation.php | 248 + .../php-cs-fixer/src/DocBlock/DocBlock.php | 202 + .../php-cs-fixer/src/DocBlock/Line.php | 114 + .../src/DocBlock/ShortDescription.php | 56 + .../php-cs-fixer/src/DocBlock/Tag.php | 85 + .../src/DocBlock/TagComparator.php | 52 + .../src/DocBlock/TypeExpression.php | 415 ++ .../src/Doctrine/Annotation/Token.php | 75 + .../src/Doctrine/Annotation/Tokens.php | 239 + .../Documentation/DocumentationLocator.php | 65 + .../Documentation/FixerDocumentGenerator.php | 283 + .../Documentation/ListDocumentGenerator.php | 136 + .../src/Documentation/RstUtils.php | 34 + .../RuleSetDocumentationGenerator.php | 99 + .../php-cs-fixer/src/Error/Error.php | 90 + .../php-cs-fixer/src/Error/ErrorsManager.php | 72 + .../php-cs-fixer/src/FileReader.php | 57 + .../php-cs-fixer/src/FileRemoval.php | 88 + .../friendsofphp/php-cs-fixer/src/Finder.php | 27 + .../Fixer/AbstractIncrementOperatorFixer.php | 48 + .../src/Fixer/AbstractPhpUnitFixer.php | 127 + .../src/Fixer/Alias/ArrayPushFixer.php | 141 + .../Fixer/Alias/BacktickToShellExecFixer.php | 118 + .../src/Fixer/Alias/EregToPregFixer.php | 151 + .../src/Fixer/Alias/MbStrFunctionsFixer.php | 96 + .../src/Fixer/Alias/ModernizeStrposFixer.php | 162 + .../src/Fixer/Alias/NoAliasFunctionsFixer.php | 157 + .../NoAliasLanguageConstructCallFixer.php | 45 + .../src/Fixer/Alias/NoMixedEchoPrintFixer.php | 108 + .../Fixer/Alias/PowToExponentiationFixer.php | 172 + .../Fixer/Alias/RandomApiMigrationFixer.php | 96 + .../src/Fixer/Alias/SetTypeToCastFixer.php | 148 + .../Fixer/ArrayNotation/ArraySyntaxFixer.php | 100 + ...tilineWhitespaceAroundDoubleArrowFixer.php | 67 + .../NoTrailingCommaInSinglelineArrayFixer.php | 43 + .../NoWhitespaceBeforeCommaInArrayFixer.php | 112 + .../NormalizeIndexBraceFixer.php | 45 + .../ArrayNotation/TrimArraySpacesFixer.php | 70 + .../WhitespaceAfterCommaInArrayFixer.php | 104 + .../YieldFromArrayToYieldsFixer.php | 140 + .../src/Fixer/Basic/BracesFixer.php | 166 + .../Fixer/Basic/CurlyBracesPositionFixer.php | 283 + .../src/Fixer/Basic/EncodingFixer.php | 65 + .../NoMultipleStatementsPerLineFixer.php | 79 + .../NoTrailingCommaInSinglelineFixer.php | 102 + .../Basic/NonPrintableCharacterFixer.php | 127 + .../src/Fixer/Basic/OctalNotationFixer.php | 46 + .../src/Fixer/Basic/PsrAutoloadingFixer.php | 204 + .../Fixer/Basic/SingleLineEmptyBodyFixer.php | 70 + .../Casing/ClassReferenceNameCasingFixer.php | 131 + .../src/Fixer/Casing/ConstantCaseFixer.php | 105 + .../Fixer/Casing/IntegerLiteralCaseFixer.php | 49 + .../Fixer/Casing/LowercaseKeywordsFixer.php | 59 + .../Casing/LowercaseStaticReferenceFixer.php | 89 + .../Fixer/Casing/MagicConstantCasingFixer.php | 67 + .../Fixer/Casing/MagicMethodCasingFixer.php | 141 + .../Casing/NativeFunctionCasingFixer.php | 73 + ...tiveFunctionTypeDeclarationCasingFixer.php | 117 + .../Fixer/CastNotation/CastSpacesFixer.php | 76 + .../Fixer/CastNotation/LowercaseCastFixer.php | 68 + .../ModernizeTypesCastingFixer.php | 119 + .../CastNotation/NoShortBoolCastFixer.php | 70 + .../Fixer/CastNotation/NoUnsetCastFixer.php | 72 + .../CastNotation/ShortScalarCastFixer.php | 47 + .../ClassAttributesSeparationFixer.php | 430 ++ .../ClassNotation/ClassDefinitionFixer.php | 355 ++ .../Fixer/ClassNotation/FinalClassFixer.php | 45 + .../ClassNotation/FinalInternalClassFixer.php | 229 + ...FinalPublicMethodForAbstractClassFixer.php | 105 + .../NoBlankLinesAfterClassOpeningFixer.php | 77 + .../NoNullPropertyInitializationFixer.php | 104 + .../ClassNotation/NoPhp4ConstructorFixer.php | 305 ++ .../NoUnneededFinalMethodFixer.php | 148 + .../OrderedClassElementsFixer.php | 407 ++ .../ClassNotation/OrderedInterfacesFixer.php | 141 + .../ClassNotation/OrderedTraitsFixer.php | 133 + .../Fixer/ClassNotation/OrderedTypesFixer.php | 309 ++ .../ClassNotation/ProtectedToPrivateFixer.php | 144 + .../Fixer/ClassNotation/SelfAccessorFixer.php | 143 + .../ClassNotation/SelfStaticAccessorFixer.php | 173 + .../SingleClassElementPerStatementFixer.php | 172 + .../SingleTraitInsertPerStatementFixer.php | 93 + .../ClassNotation/VisibilityRequiredFixer.php | 157 + .../ClassUsage/DateTimeImmutableFixer.php | 115 + .../Fixer/Comment/CommentToPhpdocFixer.php | 168 + .../src/Fixer/Comment/HeaderCommentFixer.php | 306 ++ .../MultilineCommentOpeningClosingFixer.php | 70 + .../src/Fixer/Comment/NoEmptyCommentFixer.php | 121 + .../NoTrailingWhitespaceInCommentFixer.php | 64 + .../Comment/SingleLineCommentSpacingFixer.php | 93 + .../Comment/SingleLineCommentStyleFixer.php | 127 + .../src/Fixer/ConfigurableFixerInterface.php | 43 + .../NativeConstantInvocationFixer.php | 175 + .../ControlStructureBracesFixer.php | 178 + ...trolStructureContinuationPositionFixer.php | 96 + .../Fixer/ControlStructure/ElseifFixer.php | 81 + .../ControlStructure/EmptyLoopBodyFixer.php | 93 + .../EmptyLoopConditionFixer.php | 150 + .../Fixer/ControlStructure/IncludeFixer.php | 112 + .../NoAlternativeSyntaxFixer.php | 170 + .../ControlStructure/NoBreakCommentFixer.php | 263 + .../NoSuperfluousElseifFixer.php | 79 + .../NoTrailingCommaInListCallFixer.php | 42 + .../NoUnneededControlParenthesesFixer.php | 523 ++ .../NoUnneededCurlyBracesFixer.php | 126 + .../ControlStructure/NoUselessElseFixer.php | 100 + .../SimplifiedIfReturnFixer.php | 87 + .../SwitchCaseSemicolonToColonFixer.php | 71 + .../ControlStructure/SwitchCaseSpaceFixer.php | 67 + .../SwitchContinueToBreakFixer.php | 192 + .../TrailingCommaInMultilineFixer.php | 164 + .../Fixer/ControlStructure/YodaStyleFixer.php | 549 ++ .../src/Fixer/DeprecatedFixerInterface.php | 26 + ...DoctrineAnnotationArrayAssignmentFixer.php | 70 + .../DoctrineAnnotationBracesFixer.php | 85 + .../DoctrineAnnotationIndentationFixer.php | 133 + .../DoctrineAnnotationSpacesFixer.php | 194 + .../php-cs-fixer/src/Fixer/FixerInterface.php | 70 + .../CombineNestedDirnameFixer.php | 170 + .../DateTimeCreateFromFormatCallFixer.php | 121 + .../FunctionNotation/FopenFlagOrderFixer.php | 98 + .../FunctionNotation/FopenFlagsFixer.php | 80 + .../FunctionDeclarationFixer.php | 177 + .../FunctionTypehintSpaceFixer.php | 47 + .../FunctionNotation/ImplodeCallFixer.php | 105 + .../LambdaNotUsedImportFixer.php | 270 + .../MethodArgumentSpaceFixer.php | 295 + .../NativeFunctionInvocationFixer.php | 299 + .../NoSpacesAfterFunctionNameFixer.php | 123 + ...lingCommaInSinglelineFunctionCallFixer.php | 49 + ...NoUnreachableDefaultArgumentValueFixer.php | 146 + .../NoUselessSprintfFixer.php | 80 + ...ypeDeclarationForDefaultNullValueFixer.php | 155 + .../PhpdocToParamTypeFixer.php | 134 + .../PhpdocToPropertyTypeFixer.php | 164 + .../PhpdocToReturnTypeFixer.php | 136 + .../RegularCallableCallFixer.php | 189 + .../ReturnTypeDeclarationFixer.php | 83 + .../FunctionNotation/SingleLineThrowFixer.php | 119 + .../FunctionNotation/StaticLambdaFixer.php | 127 + .../UseArrowFunctionsFixer.php | 154 + .../FunctionNotation/VoidReturnFixer.php | 186 + .../Import/FullyQualifiedStrictTypesFixer.php | 189 + .../Import/GlobalNamespaceImportFixer.php | 554 ++ .../src/Fixer/Import/GroupImportFixer.php | 191 + .../Import/NoLeadingImportSlashFixer.php | 72 + .../Import/NoUnneededImportAliasFixer.php | 70 + .../src/Fixer/Import/NoUnusedImportsFixer.php | 213 + .../src/Fixer/Import/OrderedImportsFixer.php | 425 ++ .../Import/SingleImportPerStatementFixer.php | 193 + .../Import/SingleLineAfterImportsFixer.php | 128 + .../php-cs-fixer/src/Fixer/Indentation.php | 69 + .../ClassKeywordRemoveFixer.php | 183 + .../CombineConsecutiveIssetsFixer.php | 131 + .../CombineConsecutiveUnsetsFixer.php | 140 + .../DeclareEqualNormalizeFixer.php | 106 + .../DeclareParenthesesFixer.php | 44 + .../LanguageConstruct/DirConstantFixer.php | 99 + .../ErrorSuppressionFixer.php | 113 + .../ExplicitIndirectVariableFixer.php | 67 + .../FunctionToConstantFixer.php | 191 + .../GetClassToClassKeywordFixer.php | 117 + .../Fixer/LanguageConstruct/IsNullFixer.php | 125 + .../NoUnsetOnPropertyFixer.php | 161 + .../NullableTypeDeclarationFixer.php | 246 + .../SingleSpaceAfterConstructFixer.php | 89 + .../SingleSpaceAroundConstructFixer.php | 248 + .../Fixer/ListNotation/ListSyntaxFixer.php | 97 + .../BlankLineAfterNamespaceFixer.php | 99 + .../BlankLinesBeforeNamespaceFixer.php | 154 + .../NamespaceNotation/CleanNamespaceFixer.php | 81 + .../NoBlankLinesBeforeNamespaceFixer.php | 56 + .../NoLeadingNamespaceWhitespaceFixer.php | 74 + .../SingleBlankLineBeforeNamespaceFixer.php | 47 + .../Fixer/Naming/NoHomoglyphNamesFixer.php | 75 + ...signNullCoalescingToCoalesceEqualFixer.php | 128 + .../Operator/BinaryOperatorSpacesFixer.php | 662 +++ .../src/Fixer/Operator/ConcatSpaceFixer.php | 113 + .../Fixer/Operator/IncrementStyleFixer.php | 116 + .../Fixer/Operator/LogicalOperatorsFixer.php | 52 + .../src/Fixer/Operator/NewWithBracesFixer.php | 110 + .../NoSpaceAroundDoubleColonFixer.php | 52 + .../Operator/NoUselessConcatOperatorFixer.php | 240 + .../NoUselessNullsafeOperatorFixer.php | 56 + .../Operator/NotOperatorWithSpaceFixer.php | 62 + .../NotOperatorWithSuccessorSpaceFixer.php | 56 + .../ObjectOperatorWithoutWhitespaceFixer.php | 52 + .../Fixer/Operator/OperatorLinebreakFixer.php | 234 + .../Operator/StandardizeIncrementFixer.php | 83 + .../Operator/StandardizeNotEqualsFixer.php | 51 + .../Operator/TernaryOperatorSpacesFixer.php | 123 + .../Operator/TernaryToElvisOperatorFixer.php | 180 + .../Operator/TernaryToNullCoalescingFixer.php | 146 + .../Operator/UnaryOperatorSpacesFixer.php | 59 + .../PhpTag/BlankLineAfterOpeningTagFixer.php | 76 + .../src/Fixer/PhpTag/EchoTagSyntaxFixer.php | 181 + .../src/Fixer/PhpTag/FullOpeningTagFixer.php | 97 + .../PhpTag/LinebreakAfterOpeningTagFixer.php | 58 + .../src/Fixer/PhpTag/NoClosingTagFixer.php | 52 + .../Fixer/PhpUnit/PhpUnitConstructFixer.php | 129 + .../PhpUnit/PhpUnitDataProviderNameFixer.php | 120 + .../PhpUnitDataProviderReturnTypeFixer.php | 87 + .../PhpUnitDataProviderStaticFixer.php | 94 + .../PhpUnit/PhpUnitDedicateAssertFixer.php | 404 ++ ...PhpUnitDedicateAssertInternalTypeFixer.php | 124 + .../Fixer/PhpUnit/PhpUnitExpectationFixer.php | 197 + .../PhpUnit/PhpUnitFqcnAnnotationFixer.php | 69 + .../PhpUnit/PhpUnitInternalClassFixer.php | 70 + .../PhpUnit/PhpUnitMethodCasingFixer.php | 146 + .../src/Fixer/PhpUnit/PhpUnitMockFixer.php | 94 + .../PhpUnitMockShortWillReturnFixer.php | 95 + .../Fixer/PhpUnit/PhpUnitNamespacedFixer.php | 147 + .../PhpUnitNoExpectationAnnotationFixer.php | 193 + .../PhpUnitSetUpTearDownVisibilityFixer.php | 84 + .../Fixer/PhpUnit/PhpUnitSizeClassFixer.php | 61 + .../src/Fixer/PhpUnit/PhpUnitStrictFixer.php | 94 + .../Fixer/PhpUnit/PhpUnitTargetVersion.php | 51 + .../PhpUnit/PhpUnitTestAnnotationFixer.php | 310 ++ .../PhpUnitTestCaseStaticMethodCallsFixer.php | 397 ++ .../PhpUnitTestClassRequiresCoversFixer.php | 59 + .../Phpdoc/AlignMultilineCommentFixer.php | 125 + .../GeneralPhpdocAnnotationRemoveFixer.php | 122 + .../Phpdoc/GeneralPhpdocTagRenameFixer.php | 114 + .../Phpdoc/NoBlankLinesAfterPhpdocFixer.php | 79 + .../src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php | 52 + .../Phpdoc/NoSuperfluousPhpdocTagsFixer.php | 483 ++ .../PhpdocAddMissingParamAnnotationFixer.php | 182 + .../src/Fixer/Phpdoc/PhpdocAlignFixer.php | 301 ++ .../PhpdocAnnotationWithoutDotFixer.php | 94 + .../src/Fixer/Phpdoc/PhpdocIndentFixer.php | 112 + .../Phpdoc/PhpdocInlineTagNormalizerFixer.php | 74 + .../src/Fixer/Phpdoc/PhpdocLineSpanFixer.php | 102 + .../src/Fixer/Phpdoc/PhpdocNoAccessFixer.php | 54 + .../Fixer/Phpdoc/PhpdocNoAliasTagFixer.php | 87 + .../Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php | 91 + .../src/Fixer/Phpdoc/PhpdocNoPackageFixer.php | 54 + .../Phpdoc/PhpdocNoUselessInheritdocFixer.php | 119 + .../Fixer/Phpdoc/PhpdocOrderByValueFixer.php | 122 + .../src/Fixer/Phpdoc/PhpdocOrderFixer.php | 168 + .../Fixer/Phpdoc/PhpdocParamOrderFixer.php | 219 + .../Phpdoc/PhpdocReturnSelfReferenceFixer.php | 159 + .../src/Fixer/Phpdoc/PhpdocScalarFixer.php | 92 + .../Fixer/Phpdoc/PhpdocSeparationFixer.php | 236 + .../PhpdocSingleLineVarSpacingFixer.php | 71 + .../src/Fixer/Phpdoc/PhpdocSummaryFixer.php | 80 + .../src/Fixer/Phpdoc/PhpdocTagCasingFixer.php | 65 + .../src/Fixer/Phpdoc/PhpdocTagTypeFixer.php | 125 + .../src/Fixer/Phpdoc/PhpdocToCommentFixer.php | 113 + ...rimConsecutiveBlankLineSeparationFixer.php | 155 + .../src/Fixer/Phpdoc/PhpdocTrimFixer.php | 95 + .../src/Fixer/Phpdoc/PhpdocTypesFixer.php | 97 + .../Fixer/Phpdoc/PhpdocTypesOrderFixer.php | 127 + .../PhpdocVarAnnotationCorrectOrderFixer.php | 64 + .../Phpdoc/PhpdocVarWithoutNameFixer.php | 125 + .../ReturnNotation/NoUselessReturnFixer.php | 84 + .../ReturnNotation/ReturnAssignmentFixer.php | 411 ++ .../SimplifiedNullReturnFixer.php | 138 + ...ltilineWhitespaceBeforeSemicolonsFixer.php | 172 + .../Fixer/Semicolon/NoEmptyStatementFixer.php | 140 + ...glelineWhitespaceBeforeSemicolonsFixer.php | 56 + .../SemicolonAfterInstructionFixer.php | 53 + .../Semicolon/SpaceAfterSemicolonFixer.php | 83 + .../Fixer/Strict/DeclareStrictTypesFixer.php | 105 + .../Fixer/Strict/StrictComparisonFixer.php | 57 + .../src/Fixer/Strict/StrictParamFixer.php | 121 + .../EscapeImplicitBackslashesFixer.php | 103 + .../ExplicitStringVariableFixer.php | 120 + .../StringNotation/HeredocToNowdocFixer.php | 85 + .../StringNotation/NoBinaryStringFixer.php | 56 + .../NoTrailingWhitespaceInStringFixer.php | 75 + .../SimpleToComplexStringVariableFixer.php | 89 + .../Fixer/StringNotation/SingleQuoteFixer.php | 81 + .../StringLengthToEmptyFixer.php | 250 + .../StringNotation/StringLineEndingFixer.php | 52 + .../Whitespace/ArrayIndentationFixer.php | 127 + .../BlankLineBeforeStatementFixer.php | 198 + .../BlankLineBetweenImportGroupsFixer.php | 139 + .../CompactNullableTypehintFixer.php | 48 + .../Whitespace/HeredocIndentationFixer.php | 141 + .../Fixer/Whitespace/IndentationTypeFixer.php | 116 + .../src/Fixer/Whitespace/LineEndingFixer.php | 55 + .../MethodChainingIndentationFixer.php | 157 + .../Whitespace/NoExtraBlankLinesFixer.php | 327 ++ .../Whitespace/NoSpacesAroundOffsetFixer.php | 74 + .../NoSpacesInsideParenthesisFixer.php | 78 + .../Whitespace/NoTrailingWhitespaceFixer.php | 83 + .../NoWhitespaceInBlankLineFixer.php | 71 + .../Whitespace/SingleBlankLineAtEofFixer.php | 51 + .../Whitespace/StatementIndentationFixer.php | 417 ++ .../Whitespace/TypeDeclarationSpacesFixer.php | 147 + .../src/Fixer/Whitespace/TypesSpacesFixer.php | 108 + .../Fixer/WhitespacesAwareFixerInterface.php | 22 + .../FixerConfiguration/AliasedFixerOption.php | 67 + .../AliasedFixerOptionBuilder.php | 68 + .../FixerConfiguration/AllowedValueSubset.php | 56 + .../DeprecatedFixerOption.php | 62 + .../DeprecatedFixerOptionInterface.php | 18 + .../FixerConfigurationResolver.php | 99 + .../FixerConfigurationResolverInterface.php | 27 + .../src/FixerConfiguration/FixerOption.php | 122 + .../FixerConfiguration/FixerOptionBuilder.php | 109 + .../FixerOptionInterface.php | 35 + .../InvalidOptionsForEnvException.php | 23 + .../src/FixerDefinition/CodeSample.php | 44 + .../FixerDefinition/CodeSampleInterface.php | 25 + .../FileSpecificCodeSample.php | 50 + .../FileSpecificCodeSampleInterface.php | 23 + .../src/FixerDefinition/FixerDefinition.php | 65 + .../FixerDefinitionInterface.php | 32 + .../VersionSpecificCodeSample.php | 48 + .../VersionSpecificCodeSampleInterface.php | 21 + .../FixerDefinition/VersionSpecification.php | 63 + .../VersionSpecificationInterface.php | 21 + .../php-cs-fixer/src/FixerFactory.php | 193 + .../src/FixerFileProcessedEvent.php | 47 + .../php-cs-fixer/src/FixerNameValidator.php | 29 + .../Indicator/PhpUnitTestCaseIndicator.php | 75 + .../php-cs-fixer/src/Linter/CachingLinter.php | 54 + .../php-cs-fixer/src/Linter/Linter.php | 44 + .../src/Linter/LinterInterface.php | 31 + .../src/Linter/LintingException.php | 24 + .../src/Linter/LintingResultInterface.php | 24 + .../php-cs-fixer/src/Linter/ProcessLinter.php | 134 + .../Linter/ProcessLinterProcessBuilder.php | 38 + .../src/Linter/ProcessLintingResult.php | 77 + .../src/Linter/TokenizerLinter.php | 50 + .../src/Linter/TokenizerLintingResult.php | 40 + .../src/Linter/UnavailableLinterException.php | 26 + .../php-cs-fixer/src/PharChecker.php | 34 + .../php-cs-fixer/src/PharCheckerInterface.php | 24 + vendor/friendsofphp/php-cs-fixer/src/Preg.php | 165 + .../php-cs-fixer/src/PregException.php | 24 + .../AbstractMigrationSetDescription.php | 32 + .../RuleSet/AbstractRuleSetDescription.php | 32 + .../php-cs-fixer/src/RuleSet/RuleSet.php | 119 + .../RuleSet/RuleSetDescriptionInterface.php | 29 + .../src/RuleSet/RuleSetInterface.php | 44 + .../php-cs-fixer/src/RuleSet/RuleSets.php | 60 + .../RuleSet/Sets/DoctrineAnnotationSet.php | 29 + .../src/RuleSet/Sets/PERCS1x0RiskySet.php | 37 + .../src/RuleSet/Sets/PERCS1x0Set.php | 37 + .../src/RuleSet/Sets/PERRiskySet.php | 39 + .../php-cs-fixer/src/RuleSet/Sets/PERSet.php | 35 + .../src/RuleSet/Sets/PHP54MigrationSet.php | 25 + .../RuleSet/Sets/PHP56MigrationRiskySet.php | 25 + .../RuleSet/Sets/PHP70MigrationRiskySet.php | 25 + .../src/RuleSet/Sets/PHP70MigrationSet.php | 25 + .../RuleSet/Sets/PHP71MigrationRiskySet.php | 25 + .../src/RuleSet/Sets/PHP71MigrationSet.php | 25 + .../src/RuleSet/Sets/PHP73MigrationSet.php | 25 + .../RuleSet/Sets/PHP74MigrationRiskySet.php | 25 + .../src/RuleSet/Sets/PHP74MigrationSet.php | 25 + .../RuleSet/Sets/PHP80MigrationRiskySet.php | 34 + .../src/RuleSet/Sets/PHP80MigrationSet.php | 25 + .../src/RuleSet/Sets/PHP81MigrationSet.php | 25 + .../src/RuleSet/Sets/PHP82MigrationSet.php | 25 + .../Sets/PHPUnit100MigrationRiskySet.php | 25 + .../Sets/PHPUnit30MigrationRiskySet.php | 26 + .../Sets/PHPUnit32MigrationRiskySet.php | 26 + .../Sets/PHPUnit35MigrationRiskySet.php | 26 + .../Sets/PHPUnit43MigrationRiskySet.php | 26 + .../Sets/PHPUnit48MigrationRiskySet.php | 26 + .../Sets/PHPUnit50MigrationRiskySet.php | 26 + .../Sets/PHPUnit52MigrationRiskySet.php | 26 + .../Sets/PHPUnit54MigrationRiskySet.php | 26 + .../Sets/PHPUnit55MigrationRiskySet.php | 26 + .../Sets/PHPUnit56MigrationRiskySet.php | 26 + .../Sets/PHPUnit57MigrationRiskySet.php | 26 + .../Sets/PHPUnit60MigrationRiskySet.php | 26 + .../Sets/PHPUnit75MigrationRiskySet.php | 26 + .../Sets/PHPUnit84MigrationRiskySet.php | 26 + .../src/RuleSet/Sets/PSR12RiskySet.php | 29 + .../src/RuleSet/Sets/PSR12Set.php | 33 + .../php-cs-fixer/src/RuleSet/Sets/PSR1Set.php | 29 + .../php-cs-fixer/src/RuleSet/Sets/PSR2Set.php | 29 + .../src/RuleSet/Sets/PhpCsFixerRiskySet.php | 47 + .../src/RuleSet/Sets/PhpCsFixerSet.php | 29 + .../src/RuleSet/Sets/SymfonyRiskySet.php | 29 + .../src/RuleSet/Sets/SymfonySet.php | 29 + .../src/Runner/FileCachingLintingIterator.php | 72 + .../src/Runner/FileFilterIterator.php | 82 + .../src/Runner/FileLintingIterator.php | 60 + .../php-cs-fixer/src/Runner/Runner.php | 213 + .../php-cs-fixer/src/StdinFileInfo.php | 144 + .../src/Tokenizer/AbstractTransformer.php | 34 + .../src/Tokenizer/AbstractTypeTransformer.php | 76 + .../Analyzer/AlternativeSyntaxAnalyzer.php | 77 + .../AbstractControlCaseStructuresAnalysis.php | 50 + .../Analyzer/Analysis/ArgumentAnalysis.php | 71 + .../Analyzer/Analysis/CaseAnalysis.php | 43 + .../Analysis/DataProviderAnalysis.php | 51 + .../Analyzer/Analysis/DefaultAnalysis.php | 41 + .../Analyzer/Analysis/EnumAnalysis.php | 39 + .../Analyzer/Analysis/MatchAnalysis.php | 33 + .../Analyzer/Analysis/NamespaceAnalysis.php | 87 + .../Analysis/NamespaceUseAnalysis.php | 99 + .../Analysis/StartEndTokenAwareAnalysis.php | 25 + .../Analyzer/Analysis/SwitchAnalysis.php | 48 + .../Analyzer/Analysis/TypeAnalysis.php | 81 + .../Tokenizer/Analyzer/ArgumentsAnalyzer.php | 117 + .../Tokenizer/Analyzer/AttributeAnalyzer.php | 46 + .../src/Tokenizer/Analyzer/BlocksAnalyzer.php | 53 + .../src/Tokenizer/Analyzer/ClassyAnalyzer.php | 65 + .../Tokenizer/Analyzer/CommentsAnalyzer.php | 230 + .../ControlCaseStructuresAnalyzer.php | 232 + .../Analyzer/DataProviderAnalyzer.php | 75 + .../Tokenizer/Analyzer/FunctionsAnalyzer.php | 204 + .../Tokenizer/Analyzer/GotoLabelAnalyzer.php | 33 + .../Analyzer/NamespaceUsesAnalyzer.php | 97 + .../Tokenizer/Analyzer/NamespacesAnalyzer.php | 67 + .../src/Tokenizer/Analyzer/RangeAnalyzer.php | 72 + .../Tokenizer/Analyzer/ReferenceAnalyzer.php | 42 + .../Analyzer/WhitespacesAnalyzer.php | 41 + .../php-cs-fixer/src/Tokenizer/CT.php | 97 + .../php-cs-fixer/src/Tokenizer/CodeHasher.php | 33 + .../php-cs-fixer/src/Tokenizer/Token.php | 402 ++ .../php-cs-fixer/src/Tokenizer/Tokens.php | 1143 ++++ .../src/Tokenizer/TokensAnalyzer.php | 590 ++ .../Transformer/ArrayTypehintTransformer.php | 47 + .../Transformer/AttributeTransformer.php | 55 + .../BraceClassInstantiationTransformer.php | 54 + .../Transformer/ClassConstantTransformer.php | 47 + .../ConstructorPromotionTransformer.php | 59 + .../Transformer/CurlyBraceTransformer.php | 209 + ...veNormalFormTypeParenthesisTransformer.php | 55 + .../FirstClassCallableTransformer.php | 38 + .../Transformer/ImportTransformer.php | 59 + .../Transformer/NameQualifiedTransformer.php | 72 + .../Transformer/NamedArgumentTransformer.php | 58 + .../NamespaceOperatorTransformer.php | 46 + .../Transformer/NullableTypeTransformer.php | 59 + .../Transformer/ReturnRefTransformer.php | 42 + .../Transformer/SquareBraceTransformer.php | 128 + .../TypeAlternationTransformer.php | 50 + .../Transformer/TypeColonTransformer.php | 67 + .../TypeIntersectionTransformer.php | 48 + .../Tokenizer/Transformer/UseTransformer.php | 86 + .../WhitespacyCommentTransformer.php | 54 + .../src/Tokenizer/TransformerInterface.php | 62 + .../src/Tokenizer/Transformers.php | 95 + .../php-cs-fixer/src/ToolInfo.php | 87 + .../php-cs-fixer/src/ToolInfoInterface.php | 29 + .../friendsofphp/php-cs-fixer/src/Utils.php | 205 + .../src/WhitespacesFixerConfig.php | 47 + .../php-cs-fixer/src/WordMatcher.php | 46 + vendor/illuminate/container/BoundMethod.php | 170 + vendor/illuminate/container/Container.php | 1293 +++++ .../container/ContextualBindingBuilder.php | 88 + .../container/EntryNotFoundException.php | 10 + vendor/illuminate/container/LICENSE.md | 21 + .../container/RewindableGenerator.php | 55 + vendor/illuminate/container/Util.php | 65 + vendor/illuminate/container/composer.json | 38 + .../contracts/Auth/Access/Authorizable.php | 15 + .../illuminate/contracts/Auth/Access/Gate.php | 135 + .../contracts/Auth/Authenticatable.php | 44 + .../contracts/Auth/CanResetPassword.php | 20 + vendor/illuminate/contracts/Auth/Factory.php | 21 + vendor/illuminate/contracts/Auth/Guard.php | 51 + .../Auth/Middleware/AuthenticatesRequests.php | 8 + .../contracts/Auth/MustVerifyEmail.php | 31 + .../contracts/Auth/PasswordBroker.php | 54 + .../contracts/Auth/PasswordBrokerFactory.php | 14 + .../contracts/Auth/StatefulGuard.php | 57 + .../contracts/Auth/SupportsBasicAuth.php | 23 + .../contracts/Auth/UserProvider.php | 45 + .../contracts/Broadcasting/Broadcaster.php | 33 + .../contracts/Broadcasting/Factory.php | 14 + .../Broadcasting/HasBroadcastChannel.php | 19 + .../contracts/Broadcasting/ShouldBeUnique.php | 8 + .../Broadcasting/ShouldBroadcast.php | 13 + .../Broadcasting/ShouldBroadcastNow.php | 8 + .../illuminate/contracts/Bus/Dispatcher.php | 60 + .../contracts/Bus/QueueingDispatcher.php | 28 + vendor/illuminate/contracts/Cache/Factory.php | 14 + vendor/illuminate/contracts/Cache/Lock.php | 40 + .../contracts/Cache/LockProvider.php | 24 + .../contracts/Cache/LockTimeoutException.php | 9 + .../illuminate/contracts/Cache/Repository.php | 105 + vendor/illuminate/contracts/Cache/Store.php | 83 + .../contracts/Config/Repository.php | 52 + .../contracts/Console/Application.php | 22 + .../contracts/Console/Isolatable.php | 8 + .../illuminate/contracts/Console/Kernel.php | 58 + .../Console/PromptsForMissingInput.php | 8 + .../Container/BindingResolutionException.php | 10 + .../Container/CircularDependencyException.php | 10 + .../contracts/Container/Container.php | 196 + .../Container/ContextualBindingBuilder.php | 36 + .../illuminate/contracts/Cookie/Factory.php | 45 + .../contracts/Cookie/QueueingFactory.php | 28 + .../contracts/Database/Eloquent/Builder.php | 13 + .../contracts/Database/Eloquent/Castable.php | 14 + .../Database/Eloquent/CastsAttributes.php | 32 + .../Eloquent/CastsInboundAttributes.php | 18 + .../Eloquent/DeviatesCastableAttributes.php | 27 + .../Eloquent/SerializesCastableAttributes.php | 18 + .../Eloquent/SupportsPartialRelations.php | 28 + .../Database/Events/MigrationEvent.php | 8 + .../contracts/Database/ModelIdentifier.php | 66 + .../contracts/Database/Query/Builder.php | 12 + .../Database/Query/ConditionExpression.php | 7 + .../contracts/Database/Query/Expression.php | 15 + .../contracts/Debug/ExceptionHandler.php | 44 + .../contracts/Encryption/DecryptException.php | 9 + .../contracts/Encryption/EncryptException.php | 9 + .../contracts/Encryption/Encrypter.php | 33 + .../contracts/Encryption/StringEncrypter.php | 25 + .../contracts/Events/Dispatcher.php | 74 + .../illuminate/contracts/Filesystem/Cloud.php | 14 + .../contracts/Filesystem/Factory.php | 14 + .../Filesystem/FileNotFoundException.php | 9 + .../contracts/Filesystem/Filesystem.php | 170 + .../Filesystem/LockTimeoutException.php | 9 + .../contracts/Foundation/Application.php | 222 + .../Foundation/CachesConfiguration.php | 25 + .../contracts/Foundation/CachesRoutes.php | 19 + .../Foundation/ExceptionRenderer.php | 14 + .../contracts/Foundation/MaintenanceMode.php | 32 + .../illuminate/contracts/Hashing/Hasher.php | 39 + vendor/illuminate/contracts/Http/Kernel.php | 34 + vendor/illuminate/contracts/LICENSE.md | 21 + .../illuminate/contracts/Mail/Attachable.php | 13 + vendor/illuminate/contracts/Mail/Factory.php | 14 + .../illuminate/contracts/Mail/MailQueue.php | 24 + vendor/illuminate/contracts/Mail/Mailable.php | 68 + vendor/illuminate/contracts/Mail/Mailer.php | 38 + .../contracts/Notifications/Dispatcher.php | 23 + .../contracts/Notifications/Factory.php | 30 + .../contracts/Pagination/CursorPaginator.php | 109 + .../Pagination/LengthAwarePaginator.php | 27 + .../contracts/Pagination/Paginator.php | 109 + vendor/illuminate/contracts/Pipeline/Hub.php | 15 + .../contracts/Pipeline/Pipeline.php | 36 + .../contracts/Process/InvokedProcess.php | 57 + .../contracts/Process/ProcessResult.php | 58 + .../contracts/Queue/ClearableQueue.php | 14 + .../Queue/EntityNotFoundException.php | 20 + .../contracts/Queue/EntityResolver.php | 15 + vendor/illuminate/contracts/Queue/Factory.php | 14 + vendor/illuminate/contracts/Queue/Job.php | 143 + vendor/illuminate/contracts/Queue/Monitor.php | 28 + vendor/illuminate/contracts/Queue/Queue.php | 90 + .../contracts/Queue/QueueableCollection.php | 31 + .../contracts/Queue/QueueableEntity.php | 25 + .../contracts/Queue/ShouldBeEncrypted.php | 8 + .../contracts/Queue/ShouldBeUnique.php | 8 + .../Queue/ShouldBeUniqueUntilProcessing.php | 8 + .../contracts/Queue/ShouldQueue.php | 8 + .../illuminate/contracts/Redis/Connection.php | 32 + .../illuminate/contracts/Redis/Connector.php | 24 + vendor/illuminate/contracts/Redis/Factory.php | 14 + .../Redis/LimiterTimeoutException.php | 9 + .../contracts/Routing/BindingRegistrar.php | 22 + .../contracts/Routing/Registrar.php | 95 + .../contracts/Routing/ResponseFactory.php | 142 + .../contracts/Routing/UrlGenerator.php | 78 + .../contracts/Routing/UrlRoutable.php | 36 + .../Middleware/AuthenticatesSessions.php | 8 + .../illuminate/contracts/Session/Session.php | 179 + .../contracts/Support/Arrayable.php | 17 + .../Support/CanBeEscapedWhenCastToString.php | 14 + .../contracts/Support/DeferrableProvider.php | 13 + .../Support/DeferringDisplayableValue.php | 13 + .../illuminate/contracts/Support/Htmlable.php | 13 + .../illuminate/contracts/Support/Jsonable.php | 14 + .../contracts/Support/MessageBag.php | 97 + .../contracts/Support/MessageProvider.php | 13 + .../contracts/Support/Renderable.php | 13 + .../contracts/Support/Responsable.php | 14 + .../contracts/Support/ValidatedData.php | 10 + .../Translation/HasLocalePreference.php | 13 + .../contracts/Translation/Loader.php | 37 + .../contracts/Translation/Translator.php | 39 + .../contracts/Validation/DataAwareRule.php | 14 + .../contracts/Validation/Factory.php | 43 + .../contracts/Validation/ImplicitRule.php | 11 + .../contracts/Validation/InvokableRule.php | 20 + .../illuminate/contracts/Validation/Rule.php | 24 + .../Validation/UncompromisedVerifier.php | 14 + .../Validation/ValidatesWhenResolved.php | 13 + .../contracts/Validation/ValidationRule.php | 17 + .../contracts/Validation/Validator.php | 58 + .../Validation/ValidatorAwareRule.php | 15 + vendor/illuminate/contracts/View/Engine.php | 15 + vendor/illuminate/contracts/View/Factory.php | 72 + vendor/illuminate/contracts/View/View.php | 28 + .../View/ViewCompilationException.php | 9 + vendor/illuminate/contracts/composer.json | 35 + vendor/nette/utils/composer.json | 72 + vendor/nette/utils/license.md | 60 + vendor/nette/utils/readme.md | 54 + vendor/nette/utils/src/HtmlStringable.php | 17 + .../utils/src/Iterators/CachingIterator.php | 133 + vendor/nette/utils/src/Iterators/Mapper.php | 27 + vendor/nette/utils/src/SmartObject.php | 120 + vendor/nette/utils/src/StaticClass.php | 32 + vendor/nette/utils/src/Translator.php | 22 + vendor/nette/utils/src/Utils/ArrayHash.php | 84 + vendor/nette/utils/src/Utils/ArrayList.php | 109 + vendor/nette/utils/src/Utils/Arrays.php | 394 ++ vendor/nette/utils/src/Utils/Callback.php | 150 + vendor/nette/utils/src/Utils/DateTime.php | 105 + vendor/nette/utils/src/Utils/FileSystem.php | 185 + vendor/nette/utils/src/Utils/Floats.php | 83 + vendor/nette/utils/src/Utils/Helpers.php | 78 + vendor/nette/utils/src/Utils/Html.php | 744 +++ vendor/nette/utils/src/Utils/Image.php | 607 +++ vendor/nette/utils/src/Utils/Json.php | 49 + .../nette/utils/src/Utils/ObjectHelpers.php | 173 + vendor/nette/utils/src/Utils/ObjectMixin.php | 32 + vendor/nette/utils/src/Utils/Paginator.php | 182 + vendor/nette/utils/src/Utils/Random.php | 38 + vendor/nette/utils/src/Utils/Reflection.php | 322 ++ vendor/nette/utils/src/Utils/Strings.php | 486 ++ vendor/nette/utils/src/Utils/Type.php | 212 + vendor/nette/utils/src/Utils/Validators.php | 340 ++ vendor/nette/utils/src/Utils/exceptions.php | 40 + vendor/nette/utils/src/compatibility.php | 28 + vendor/nette/utils/src/exceptions.php | 84 + vendor/psr/cache/CHANGELOG.md | 16 + vendor/psr/cache/LICENSE.txt | 19 + vendor/psr/cache/README.md | 12 + vendor/psr/cache/composer.json | 29 + vendor/psr/cache/src/CacheException.php | 10 + vendor/psr/cache/src/CacheItemInterface.php | 100 + .../psr/cache/src/CacheItemPoolInterface.php | 130 + .../cache/src/InvalidArgumentException.php | 13 + vendor/psr/container/LICENSE | 21 + vendor/psr/container/README.md | 13 + vendor/psr/container/composer.json | 33 + .../src/ContainerExceptionInterface.php | 11 + .../psr/container/src/ContainerInterface.php | 34 + .../src/NotFoundExceptionInterface.php | 10 + vendor/psr/log/LICENSE | 19 + vendor/psr/log/README.md | 58 + vendor/psr/log/composer.json | 30 + vendor/psr/log/src/AbstractLogger.php | 15 + .../psr/log/src/InvalidArgumentException.php | 7 + vendor/psr/log/src/LogLevel.php | 18 + vendor/psr/log/src/LoggerAwareInterface.php | 18 + vendor/psr/log/src/LoggerAwareTrait.php | 25 + vendor/psr/log/src/LoggerInterface.php | 117 + vendor/psr/log/src/LoggerTrait.php | 134 + vendor/psr/log/src/NullLogger.php | 30 + vendor/psr/simple-cache/LICENSE.md | 21 + vendor/psr/simple-cache/README.md | 8 + vendor/psr/simple-cache/composer.json | 31 + .../psr/simple-cache/src/CacheException.php | 10 + .../psr/simple-cache/src/CacheInterface.php | 107 + .../src/InvalidArgumentException.php | 13 + vendor/react/cache/CHANGELOG.md | 96 + vendor/react/cache/LICENSE | 21 + vendor/react/cache/README.md | 367 ++ vendor/react/cache/composer.json | 50 + vendor/react/cache/src/ArrayCache.php | 153 + vendor/react/cache/src/CacheInterface.php | 186 + vendor/react/child-process/CHANGELOG.md | 165 + vendor/react/child-process/LICENSE | 21 + vendor/react/child-process/README.md | 619 +++ vendor/react/child-process/composer.json | 53 + vendor/react/child-process/src/Process.php | 500 ++ vendor/react/dns/CHANGELOG.md | 439 ++ vendor/react/dns/LICENSE | 21 + vendor/react/dns/README.md | 453 ++ vendor/react/dns/composer.json | 54 + vendor/react/dns/src/BadServerException.php | 7 + vendor/react/dns/src/Config/Config.php | 125 + vendor/react/dns/src/Config/HostsFile.php | 134 + vendor/react/dns/src/Model/Message.php | 203 + vendor/react/dns/src/Model/Record.php | 148 + .../react/dns/src/Protocol/BinaryDumper.php | 149 + vendor/react/dns/src/Protocol/Parser.php | 267 + .../react/dns/src/Query/CachingExecutor.php | 74 + .../dns/src/Query/CancellationException.php | 7 + vendor/react/dns/src/Query/CoopExecutor.php | 85 + .../react/dns/src/Query/ExecutorInterface.php | 43 + .../react/dns/src/Query/FallbackExecutor.php | 43 + .../react/dns/src/Query/HostsFileExecutor.php | 75 + vendor/react/dns/src/Query/Query.php | 62 + vendor/react/dns/src/Query/RetryExecutor.php | 65 + .../src/Query/SelectiveTransportExecutor.php | 78 + .../dns/src/Query/TcpTransportExecutor.php | 322 ++ .../react/dns/src/Query/TimeoutException.php | 7 + .../react/dns/src/Query/TimeoutExecutor.php | 60 + .../dns/src/Query/UdpTransportExecutor.php | 183 + .../react/dns/src/RecordNotFoundException.php | 7 + vendor/react/dns/src/Resolver/Factory.php | 160 + vendor/react/dns/src/Resolver/Resolver.php | 121 + .../dns/src/Resolver/ResolverInterface.php | 93 + vendor/react/event-loop/CHANGELOG.md | 457 ++ vendor/react/event-loop/LICENSE | 21 + vendor/react/event-loop/README.md | 930 ++++ vendor/react/event-loop/composer.json | 50 + vendor/react/event-loop/src/ExtEvLoop.php | 203 + vendor/react/event-loop/src/ExtEventLoop.php | 224 + vendor/react/event-loop/src/ExtLibevLoop.php | 166 + .../react/event-loop/src/ExtLibeventLoop.php | 232 + vendor/react/event-loop/src/ExtUvLoop.php | 275 + vendor/react/event-loop/src/Factory.php | 67 + vendor/react/event-loop/src/Loop.php | 243 + vendor/react/event-loop/src/LoopInterface.php | 461 ++ .../react/event-loop/src/SignalsHandler.php | 52 + .../react/event-loop/src/StreamSelectLoop.php | 278 + .../event-loop/src/Tick/FutureTickQueue.php | 52 + vendor/react/event-loop/src/Timer/Timer.php | 48 + vendor/react/event-loop/src/Timer/Timers.php | 95 + .../react/event-loop/src/TimerInterface.php | 25 + vendor/react/promise/CHANGELOG.md | 134 + vendor/react/promise/LICENSE | 24 + vendor/react/promise/README.md | 722 +++ vendor/react/promise/composer.json | 57 + vendor/react/promise/src/Deferred.php | 43 + .../src/Exception/CompositeException.php | 29 + .../promise/src/Exception/LengthException.php | 7 + .../src/Internal/CancellationQueue.php | 52 + .../promise/src/Internal/FulfilledPromise.php | 79 + .../promise/src/Internal/RejectedPromise.php | 111 + vendor/react/promise/src/Promise.php | 244 + vendor/react/promise/src/PromiseInterface.php | 147 + vendor/react/promise/src/functions.php | 288 + .../react/promise/src/functions_include.php | 7 + vendor/react/socket/CHANGELOG.md | 764 +++ vendor/react/socket/LICENSE | 21 + vendor/react/socket/README.md | 1564 ++++++ vendor/react/socket/composer.json | 58 + vendor/react/socket/src/Connection.php | 151 + .../react/socket/src/ConnectionInterface.php | 117 + vendor/react/socket/src/Connector.php | 179 + .../react/socket/src/ConnectorInterface.php | 58 + vendor/react/socket/src/DnsConnector.php | 88 + vendor/react/socket/src/FdServer.php | 178 + vendor/react/socket/src/FixedUriConnector.php | 39 + .../src/HappyEyeBallsConnectionBuilder.php | 275 + .../socket/src/HappyEyeBallsConnector.php | 51 + vendor/react/socket/src/LimitingServer.php | 183 + vendor/react/socket/src/SecureConnector.php | 91 + vendor/react/socket/src/SecureServer.php | 184 + vendor/react/socket/src/Server.php | 97 + vendor/react/socket/src/ServerInterface.php | 147 + vendor/react/socket/src/SocketServer.php | 178 + vendor/react/socket/src/StreamEncryption.php | 116 + vendor/react/socket/src/TcpConnector.php | 116 + vendor/react/socket/src/TcpServer.php | 221 + vendor/react/socket/src/TimeoutConnector.php | 60 + vendor/react/socket/src/UnixConnector.php | 38 + vendor/react/socket/src/UnixServer.php | 126 + vendor/react/stream/CHANGELOG.md | 449 ++ vendor/react/stream/LICENSE | 21 + vendor/react/stream/README.md | 1249 +++++ vendor/react/stream/composer.json | 56 + vendor/react/stream/src/CompositeStream.php | 67 + .../react/stream/src/DuplexResourceStream.php | 183 + .../stream/src/DuplexStreamInterface.php | 39 + .../stream/src/ReadableResourceStream.php | 148 + .../stream/src/ReadableStreamInterface.php | 357 ++ vendor/react/stream/src/ThroughStream.php | 168 + vendor/react/stream/src/Util.php | 66 + .../stream/src/WritableResourceStream.php | 136 + .../stream/src/WritableStreamInterface.php | 343 ++ vendor/scoper-autoload.php | 15 + vendor/sebastian/diff/ChangeLog.md | 120 + vendor/sebastian/diff/LICENSE | 29 + vendor/sebastian/diff/README.md | 206 + vendor/sebastian/diff/SECURITY.md | 30 + vendor/sebastian/diff/composer.json | 56 + vendor/sebastian/diff/src/Chunk.php | 79 + vendor/sebastian/diff/src/Diff.php | 60 + vendor/sebastian/diff/src/Differ.php | 206 + .../src/Exception/ConfigurationException.php | 24 + .../diff/src/Exception/Exception.php | 17 + .../Exception/InvalidArgumentException.php | 16 + vendor/sebastian/diff/src/Line.php | 40 + .../LongestCommonSubsequenceCalculator.php | 20 + ...ientLongestCommonSubsequenceCalculator.php | 79 + .../src/Output/AbstractChunkOutputBuilder.php | 49 + .../diff/src/Output/DiffOnlyOutputBuilder.php | 68 + .../src/Output/DiffOutputBuilderInterface.php | 21 + .../Output/StrictUnifiedDiffOutputBuilder.php | 252 + .../src/Output/UnifiedDiffOutputBuilder.php | 198 + vendor/sebastian/diff/src/Parser.php | 84 + ...ientLongestCommonSubsequenceCalculator.php | 74 + .../squizlabs/php_codesniffer/CONTRIBUTING.md | 13 + .../php_codesniffer/CodeSniffer.conf.dist | 9 + vendor/squizlabs/php_codesniffer/README.md | 134 + vendor/squizlabs/php_codesniffer/autoload.php | 282 + vendor/squizlabs/php_codesniffer/bin/phpcbf | 19 + .../squizlabs/php_codesniffer/bin/phpcbf.bat | 12 + vendor/squizlabs/php_codesniffer/bin/phpcs | 19 + .../squizlabs/php_codesniffer/bin/phpcs.bat | 12 + .../squizlabs/php_codesniffer/composer.json | 41 + vendor/squizlabs/php_codesniffer/licence.txt | 24 + vendor/squizlabs/php_codesniffer/phpcs.xsd | 136 + .../squizlabs/php_codesniffer/src/Config.php | 1483 +++++ .../src/Exceptions/DeepExitException.php | 18 + .../src/Exceptions/RuntimeException.php | 15 + .../src/Exceptions/TokenizerException.php | 15 + .../php_codesniffer/src/Files/DummyFile.php | 72 + .../php_codesniffer/src/Files/File.php | 2263 ++++++++ .../php_codesniffer/src/Files/FileList.php | 219 + .../php_codesniffer/src/Files/LocalFile.php | 161 + .../src/Filters/ExactMatch.php | 90 + .../php_codesniffer/src/Filters/Filter.php | 242 + .../src/Filters/GitModified.php | 54 + .../php_codesniffer/src/Filters/GitStaged.php | 57 + .../squizlabs/php_codesniffer/src/Fixer.php | 677 +++ .../src/Generators/Generator.php | 99 + .../php_codesniffer/src/Generators/HTML.php | 243 + .../src/Generators/Markdown.php | 139 + .../php_codesniffer/src/Generators/Text.php | 228 + .../php_codesniffer/src/Reporter.php | 334 ++ .../php_codesniffer/src/Reports/Cbf.php | 200 + .../src/Reports/Checkstyle.php | 89 + .../php_codesniffer/src/Reports/Code.php | 297 + .../php_codesniffer/src/Reports/Csv.php | 74 + .../php_codesniffer/src/Reports/Diff.php | 107 + .../php_codesniffer/src/Reports/Emacs.php | 72 + .../php_codesniffer/src/Reports/Full.php | 188 + .../php_codesniffer/src/Reports/Gitblame.php | 72 + .../php_codesniffer/src/Reports/Hgblame.php | 87 + .../php_codesniffer/src/Reports/Info.php | 131 + .../php_codesniffer/src/Reports/Json.php | 86 + .../php_codesniffer/src/Reports/Junit.php | 108 + .../src/Reports/Notifysend.php | 198 + .../php_codesniffer/src/Reports/Report.php | 48 + .../php_codesniffer/src/Reports/Source.php | 272 + .../php_codesniffer/src/Reports/Summary.php | 140 + .../php_codesniffer/src/Reports/Svnblame.php | 61 + .../src/Reports/VersionControl.php | 301 ++ .../php_codesniffer/src/Reports/Xml.php | 106 + .../squizlabs/php_codesniffer/src/Ruleset.php | 1170 ++++ .../squizlabs/php_codesniffer/src/Runner.php | 782 +++ .../src/Sniffs/AbstractArraySniff.php | 140 + .../src/Sniffs/AbstractPatternSniff.php | 766 +++ .../src/Sniffs/AbstractScopeSniff.php | 166 + .../src/Sniffs/AbstractVariableSniff.php | 184 + .../php_codesniffer/src/Sniffs/Sniff.php | 74 + .../DisallowLongArraySyntaxStandard.xml | 23 + .../DisallowShortArraySyntaxStandard.xml | 23 + .../Classes/DuplicateClassNameStandard.xml | 27 + .../Classes/OpeningBraceSameLineStandard.xml | 36 + .../AssignmentInConditionStandard.xml | 23 + .../CodeAnalysis/EmptyStatementStandard.xml | 23 + .../ForLoopShouldBeWhileLoopStandard.xml | 23 + .../ForLoopWithTestFunctionCallStandard.xml | 24 + .../JumbledIncrementerStandard.xml | 25 + .../UnconditionalIfStatementStandard.xml | 39 + .../UnnecessaryFinalModifierStandard.xml | 29 + .../UnusedFunctionParameterStandard.xml | 25 + .../UselessOverridingMethodStandard.xml | 32 + .../Generic/Docs/Commenting/FixmeStandard.xml | 25 + .../Generic/Docs/Commenting/TodoStandard.xml | 25 + .../DisallowYodaConditionsStandard.xml | 23 + .../InlineControlStructureStandard.xml | 22 + .../Generic/Docs/Debug/CSSLintStandard.xml | 19 + .../Docs/Debug/ClosureLinterStandard.xml | 19 + .../Generic/Docs/Debug/JSHintStandard.xml | 19 + .../Docs/Files/ByteOrderMarkStandard.xml | 7 + .../Docs/Files/EndFileNewlineStandard.xml | 7 + .../Docs/Files/EndFileNoNewlineStandard.xml | 7 + .../Docs/Files/ExecutableFileStandard.xml | 7 + .../Generic/Docs/Files/InlineHTMLStandard.xml | 24 + .../Docs/Files/LineEndingsStandard.xml | 7 + .../Generic/Docs/Files/LineLengthStandard.xml | 7 + .../Docs/Files/LowercasedFilenameStandard.xml | 7 + .../Docs/Files/OneClassPerFileStandard.xml | 29 + .../Files/OneInterfacePerFileStandard.xml | 29 + .../OneObjectStructurePerFileStandard.xml | 29 + .../Docs/Files/OneTraitPerFileStandard.xml | 29 + .../DisallowMultipleStatementsStandard.xml | 20 + .../MultipleStatementAlignmentStandard.xml | 56 + .../Formatting/NoSpaceAfterCastStandard.xml | 19 + .../Formatting/SpaceAfterCastStandard.xml | 19 + .../Docs/Formatting/SpaceAfterNotStandard.xml | 22 + .../CallTimePassByReferenceStandard.xml | 31 + .../FunctionCallArgumentSpacingStandard.xml | 39 + .../OpeningFunctionBraceBsdAllmanStandard.xml | 24 + ...gFunctionBraceKernighanRitchieStandard.xml | 24 + .../Metrics/CyclomaticComplexityStandard.xml | 7 + .../Docs/Metrics/NestingLevelStandard.xml | 7 + .../AbstractClassNamePrefixStandard.xml | 23 + .../CamelCapsFunctionNameStandard.xml | 23 + .../ConstructorNameStandard.xml | 29 + .../InterfaceNameSuffixStandard.xml | 23 + .../TraitNameSuffixStandard.xml | 23 + .../UpperCaseConstantNameStandard.xml | 29 + .../Docs/PHP/BacktickOperatorStandard.xml | 7 + .../CharacterBeforePHPOpeningTagStandard.xml | 22 + .../Docs/PHP/ClosingPHPTagStandard.xml | 22 + .../Docs/PHP/DeprecatedFunctionsStandard.xml | 19 + .../DisallowAlternativePHPTagsStandard.xml | 7 + .../DisallowRequestSuperglobalStandard.xml | 7 + .../Docs/PHP/DisallowShortOpenTagStandard.xml | 7 + .../Docs/PHP/DiscourageGotoStandard.xml | 7 + .../Docs/PHP/ForbiddenFunctionsStandard.xml | 19 + .../Docs/PHP/LowerCaseConstantStandard.xml | 23 + .../Docs/PHP/LowerCaseKeywordStandard.xml | 19 + .../Docs/PHP/LowerCaseTypeStandard.xml | 38 + .../Docs/PHP/NoSilencedErrorsStandard.xml | 23 + .../Generic/Docs/PHP/SAPIUsageStandard.xml | 23 + .../Docs/PHP/UpperCaseConstantStandard.xml | 23 + .../UnnecessaryStringConcatStandard.xml | 19 + .../SubversionPropertiesStandard.xml | 7 + .../ArbitraryParenthesesSpacingStandard.xml | 23 + .../DisallowSpaceIndentStandard.xml | 7 + .../WhiteSpace/DisallowTabIndentStandard.xml | 7 + .../Docs/WhiteSpace/ScopeIndentStandard.xml | 23 + .../SpreadOperatorSpacingAfterStandard.xml | 34 + .../Sniffs/Arrays/ArrayIndentSniff.php | 147 + .../Arrays/DisallowLongArraySyntaxSniff.php | 62 + .../Arrays/DisallowShortArraySyntaxSniff.php | 52 + .../Classes/DuplicateClassNameSniff.php | 83 + .../Classes/OpeningBraceSameLineSniff.php | 106 + .../AssignmentInConditionSniff.php | 135 + .../CodeAnalysis/EmptyPHPStatementSniff.php | 115 + .../CodeAnalysis/EmptyStatementSniff.php | 69 + .../ForLoopShouldBeWhileLoopSniff.php | 78 + .../ForLoopWithTestFunctionCallSniff.php | 93 + .../CodeAnalysis/JumbledIncrementerSniff.php | 118 + .../UnconditionalIfStatementSniff.php | 81 + .../UnnecessaryFinalModifierSniff.php | 74 + .../UnusedFunctionParameterSniff.php | 224 + .../UselessOverridingMethodSniff.php | 143 + .../Sniffs/Commenting/DocCommentSniff.php | 292 + .../Generic/Sniffs/Commenting/FixmeSniff.php | 66 + .../Generic/Sniffs/Commenting/TodoSniff.php | 65 + .../DisallowYodaConditionsSniff.php | 139 + .../InlineControlStructureSniff.php | 288 + .../Generic/Sniffs/Debug/CSSLintSniff.php | 77 + .../Sniffs/Debug/ClosureLinterSniff.php | 98 + .../Generic/Sniffs/Debug/ESLintSniff.php | 96 + .../Generic/Sniffs/Debug/JSHintSniff.php | 81 + .../Sniffs/Files/ByteOrderMarkSniff.php | 66 + .../Sniffs/Files/EndFileNewlineSniff.php | 66 + .../Sniffs/Files/EndFileNoNewlineSniff.php | 71 + .../Sniffs/Files/ExecutableFileSniff.php | 51 + .../Generic/Sniffs/Files/InlineHTMLSniff.php | 65 + .../Generic/Sniffs/Files/LineEndingsSniff.php | 117 + .../Generic/Sniffs/Files/LineLengthSniff.php | 164 + .../Sniffs/Files/LowercasedFilenameSniff.php | 56 + .../Sniffs/Files/OneClassPerFileSniff.php | 50 + .../Sniffs/Files/OneInterfacePerFileSniff.php | 50 + .../Files/OneObjectStructurePerFileSniff.php | 50 + .../Sniffs/Files/OneTraitPerFileSniff.php | 50 + .../DisallowMultipleStatementsSniff.php | 89 + .../MultipleStatementAlignmentSniff.php | 359 ++ .../Formatting/NoSpaceAfterCastSniff.php | 53 + .../Sniffs/Formatting/SpaceAfterCastSniff.php | 125 + .../Sniffs/Formatting/SpaceAfterNotSniff.php | 109 + .../Formatting/SpaceBeforeCastSniff.php | 62 + .../CallTimePassByReferenceSniff.php | 100 + .../FunctionCallArgumentSpacingSniff.php | 153 + .../OpeningFunctionBraceBsdAllmanSniff.php | 186 + ...ningFunctionBraceKernighanRitchieSniff.php | 150 + .../Metrics/CyclomaticComplexitySniff.php | 85 + .../Sniffs/Metrics/NestingLevelSniff.php | 82 + .../AbstractClassNamePrefixSniff.php | 52 + .../CamelCapsFunctionNameSniff.php | 158 + .../ConstructorNameSniff.php | 139 + .../InterfaceNameSuffixSniff.php | 47 + .../TraitNameSuffixSniff.php | 47 + .../UpperCaseConstantNameSniff.php | 110 + .../Sniffs/PHP/BacktickOperatorSniff.php | 42 + .../PHP/CharacterBeforePHPOpeningTagSniff.php | 72 + .../Generic/Sniffs/PHP/ClosingPHPTagSniff.php | 45 + .../Sniffs/PHP/DeprecatedFunctionsSniff.php | 64 + .../PHP/DisallowAlternativePHPTagsSniff.php | 211 + .../PHP/DisallowRequestSuperglobalSniff.php | 47 + .../Sniffs/PHP/DisallowShortOpenTagSniff.php | 139 + .../Sniffs/PHP/DiscourageGotoSniff.php | 41 + .../Sniffs/PHP/ForbiddenFunctionsSniff.php | 182 + .../Sniffs/PHP/LowerCaseConstantSniff.php | 140 + .../Sniffs/PHP/LowerCaseKeywordSniff.php | 63 + .../Generic/Sniffs/PHP/LowerCaseTypeSniff.php | 208 + .../Sniffs/PHP/NoSilencedErrorsSniff.php | 68 + .../Sniffs/PHP/RequireStrictTypesSniff.php | 59 + .../Generic/Sniffs/PHP/SAPIUsageSniff.php | 52 + .../Generic/Sniffs/PHP/SyntaxSniff.php | 63 + .../Sniffs/PHP/UpperCaseConstantSniff.php | 47 + .../Strings/UnnecessaryStringConcatSniff.php | 104 + .../VersionControl/GitMergeConflictSniff.php | 176 + .../SubversionPropertiesSniff.php | 144 + .../ArbitraryParenthesesSpacingSniff.php | 193 + .../WhiteSpace/DisallowSpaceIndentSniff.php | 176 + .../WhiteSpace/DisallowTabIndentSniff.php | 154 + .../IncrementDecrementSpacingSniff.php | 129 + .../LanguageConstructSpacingSniff.php | 115 + .../Sniffs/WhiteSpace/ScopeIndentSniff.php | 1297 +++++ .../SpreadOperatorSpacingAfterSniff.php | 125 + .../src/Standards/Generic/ruleset.xml | 4 + .../Sniffs/CSS/BrowserSpecificStylesSniff.php | 71 + .../Channels/DisallowSelfActionsSniff.php | 101 + .../Sniffs/Channels/IncludeOwnSystemSniff.php | 83 + .../Sniffs/Channels/IncludeSystemSniff.php | 266 + .../Sniffs/Channels/UnusedSystemSniff.php | 125 + .../Commenting/FunctionCommentSniff.php | 77 + .../MySource/Sniffs/Debug/DebugCodeSniff.php | 48 + .../Sniffs/Debug/FirebugConsoleSniff.php | 51 + .../Sniffs/Objects/AssignThisSniff.php | 70 + .../Objects/CreateWidgetTypeCallbackSniff.php | 174 + .../Sniffs/Objects/DisallowNewWidgetSniff.php | 51 + .../Sniffs/PHP/AjaxNullComparisonSniff.php | 86 + .../Sniffs/PHP/EvalObjectFactorySniff.php | 102 + .../Sniffs/PHP/GetRequestDataSniff.php | 94 + .../Sniffs/PHP/ReturnFunctionValueSniff.php | 54 + .../Sniffs/Strings/JoinStringsSniff.php | 66 + .../src/Standards/MySource/ruleset.xml | 18 + .../Docs/Classes/ClassDeclarationStandard.xml | 22 + .../Docs/Commenting/ClassCommentStandard.xml | 177 + .../Docs/Commenting/FileCommentStandard.xml | 286 + .../Commenting/FunctionCommentStandard.xml | 230 + .../Docs/Commenting/InlineCommentStandard.xml | 19 + .../ControlSignatureStandard.xml | 36 + .../MultiLineConditionStandard.xml | 60 + .../PEAR/Docs/Files/IncludingFileStandard.xml | 24 + .../PEAR/Docs/Files/LineLengthStandard.xml | 7 + .../MultiLineAssignmentStandard.xml | 35 + .../FunctionCallSignatureStandard.xml | 19 + .../Functions/FunctionDeclarationStandard.xml | 41 + .../Functions/ValidDefaultValueStandard.xml | 25 + .../ValidClassNameStandard.xml | 23 + .../ValidFunctionNameStandard.xml | 23 + .../ValidVariableNameStandard.xml | 29 + .../ObjectOperatorIndentStandard.xml | 39 + .../WhiteSpace/ScopeClosingBraceStandard.xml | 23 + .../Docs/WhiteSpace/ScopeIndentStandard.xml | 29 + .../Sniffs/Classes/ClassDeclarationSniff.php | 122 + .../Sniffs/Commenting/ClassCommentSniff.php | 93 + .../Sniffs/Commenting/FileCommentSniff.php | 434 ++ .../Commenting/FunctionCommentSniff.php | 418 ++ .../Sniffs/Commenting/InlineCommentSniff.php | 60 + .../ControlSignatureSniff.php | 32 + .../MultiLineConditionSniff.php | 247 + .../PEAR/Sniffs/Files/IncludingFileSniff.php | 124 + .../Formatting/MultiLineAssignmentSniff.php | 88 + .../Functions/FunctionCallSignatureSniff.php | 528 ++ .../Functions/FunctionDeclarationSniff.php | 453 ++ .../Functions/ValidDefaultValueSniff.php | 65 + .../NamingConventions/ValidClassNameSniff.php | 83 + .../ValidFunctionNameSniff.php | 220 + .../ValidVariableNameSniff.php | 87 + .../WhiteSpace/ObjectOperatorIndentSniff.php | 163 + .../WhiteSpace/ScopeClosingBraceSniff.php | 144 + .../Sniffs/WhiteSpace/ScopeIndentSniff.php | 22 + .../src/Standards/PEAR/ruleset.xml | 41 + .../Docs/Classes/ClassDeclarationStandard.xml | 48 + .../PSR1/Docs/Files/SideEffectsStandard.xml | 27 + .../Methods/CamelCapsMethodNameStandard.xml | 29 + .../Sniffs/Classes/ClassDeclarationSniff.php | 61 + .../PSR1/Sniffs/Files/SideEffectsSniff.php | 211 + .../Methods/CamelCapsMethodNameSniff.php | 78 + .../src/Standards/PSR1/ruleset.xml | 47 + .../Classes/ClassInstantiationStandard.xml | 19 + .../NullableTypeDeclarationStandard.xml | 45 + .../ShortFormTypeKeywordsStandard.xml | 19 + .../CompoundNamespaceDepthStandard.xml | 28 + .../Operators/OperatorSpacingStandard.xml | 27 + .../Classes/AnonClassDeclarationSniff.php | 206 + .../Classes/ClassInstantiationSniff.php | 84 + .../Sniffs/Classes/ClosingBraceSniff.php | 51 + .../Sniffs/Classes/OpeningBraceSpaceSniff.php | 66 + .../BooleanOperatorPlacementSniff.php | 187 + .../ControlStructureSpacingSniff.php | 150 + .../Sniffs/Files/DeclareStatementSniff.php | 230 + .../PSR12/Sniffs/Files/FileHeaderSniff.php | 342 ++ .../Sniffs/Files/ImportStatementSniff.php | 62 + .../PSR12/Sniffs/Files/OpenTagSniff.php | 63 + .../NullableTypeDeclarationSniff.php | 71 + .../Functions/ReturnTypeDeclarationSniff.php | 87 + .../Keywords/ShortFormTypeKeywordsSniff.php | 59 + .../CompoundNamespaceDepthSniff.php | 68 + .../Sniffs/Operators/OperatorSpacingSniff.php | 90 + .../Properties/ConstantVisibilitySniff.php | 54 + .../Sniffs/Traits/UseDeclarationSniff.php | 650 +++ .../src/Standards/PSR12/ruleset.xml | 347 ++ .../Docs/Classes/ClassDeclarationStandard.xml | 23 + .../Classes/PropertyDeclarationStandard.xml | 81 + .../ControlStructureSpacingStandard.xml | 23 + .../ElseIfDeclarationStandard.xml | 27 + .../SwitchDeclarationStandard.xml | 104 + .../Docs/Files/EndFileNewlineStandard.xml | 7 + .../Methods/MethodDeclarationStandard.xml | 51 + .../NamespaceDeclarationStandard.xml | 22 + .../Namespaces/UseDeclarationStandard.xml | 57 + .../Sniffs/Classes/ClassDeclarationSniff.php | 432 ++ .../Classes/PropertyDeclarationSniff.php | 165 + .../ControlStructureSpacingSniff.php | 113 + .../ElseIfDeclarationSniff.php | 59 + .../SwitchDeclarationSniff.php | 347 ++ .../PSR2/Sniffs/Files/ClosingTagSniff.php | 73 + .../PSR2/Sniffs/Files/EndFileNewlineSniff.php | 86 + .../Methods/FunctionCallSignatureSniff.php | 68 + .../Methods/FunctionClosingBraceSniff.php | 73 + .../Sniffs/Methods/MethodDeclarationSniff.php | 142 + .../Namespaces/NamespaceDeclarationSniff.php | 84 + .../Sniffs/Namespaces/UseDeclarationSniff.php | 252 + .../src/Standards/PSR2/ruleset.xml | 218 + .../Arrays/ArrayBracketSpacingStandard.xml | 19 + .../Docs/Arrays/ArrayDeclarationStandard.xml | 117 + .../LowercaseClassKeywordsStandard.xml | 23 + .../Classes/SelfMemberReferenceStandard.xml | 63 + .../DocCommentAlignmentStandard.xml | 39 + .../FunctionCommentThrowTagStandard.xml | 32 + .../ForEachLoopDeclarationStandard.xml | 39 + .../ForLoopDeclarationStandard.xml | 55 + .../LowercaseDeclarationStandard.xml | 23 + .../FunctionDuplicateArgumentStandard.xml | 23 + .../LowercaseFunctionKeywordsStandard.xml | 25 + .../Docs/Scope/StaticThisUsageStandard.xml | 31 + .../Docs/Strings/EchoedStringsStandard.xml | 19 + .../Docs/WhiteSpace/CastSpacingStandard.xml | 19 + .../FunctionOpeningBraceStandard.xml | 41 + .../LanguageConstructSpacingStandard.xml | 19 + .../ObjectOperatorSpacingStandard.xml | 19 + .../ScopeKeywordSpacingStandard.xml | 23 + .../WhiteSpace/SemicolonSpacingStandard.xml | 19 + .../Arrays/ArrayBracketSpacingSniff.php | 73 + .../Sniffs/Arrays/ArrayDeclarationSniff.php | 749 +++ .../ClassDefinitionClosingBraceSpaceSniff.php | 115 + .../CSS/ClassDefinitionNameSpacingSniff.php | 89 + .../ClassDefinitionOpeningBraceSpaceSniff.php | 159 + .../Squiz/Sniffs/CSS/ColonSpacingSniff.php | 96 + .../Sniffs/CSS/ColourDefinitionSniff.php | 70 + .../DisallowMultipleStyleDefinitionsSniff.php | 62 + .../CSS/DuplicateClassDefinitionSniff.php | 96 + .../CSS/DuplicateStyleDefinitionSniff.php | 75 + .../Sniffs/CSS/EmptyClassDefinitionSniff.php | 53 + .../Sniffs/CSS/EmptyStyleDefinitionSniff.php | 55 + .../Squiz/Sniffs/CSS/ForbiddenStylesSniff.php | 141 + .../Squiz/Sniffs/CSS/IndentationSniff.php | 118 + .../CSS/LowercaseStyleDefinitionSniff.php | 79 + .../Squiz/Sniffs/CSS/MissingColonSniff.php | 81 + .../Squiz/Sniffs/CSS/NamedColoursSniff.php | 63 + .../Squiz/Sniffs/CSS/OpacitySniff.php | 94 + .../Sniffs/CSS/SemicolonSpacingSniff.php | 87 + .../Squiz/Sniffs/CSS/ShorthandSizeSniff.php | 143 + .../Sniffs/Classes/ClassDeclarationSniff.php | 176 + .../Sniffs/Classes/ClassFileNameSniff.php | 53 + .../Sniffs/Classes/DuplicatePropertySniff.php | 67 + .../Classes/LowercaseClassKeywordsSniff.php | 59 + .../Classes/SelfMemberReferenceSniff.php | 200 + .../Sniffs/Classes/ValidClassNameSniff.php | 70 + .../Sniffs/Commenting/BlockCommentSniff.php | 310 ++ .../Sniffs/Commenting/ClassCommentSniff.php | 87 + .../ClosingDeclarationCommentSniff.php | 114 + .../Commenting/DocCommentAlignmentSniff.php | 121 + .../Commenting/EmptyCatchCommentSniff.php | 47 + .../Sniffs/Commenting/FileCommentSniff.php | 167 + .../Commenting/FunctionCommentSniff.php | 637 +++ .../FunctionCommentThrowTagSniff.php | 173 + .../Sniffs/Commenting/InlineCommentSniff.php | 258 + .../LongConditionClosingCommentSniff.php | 167 + .../Commenting/PostStatementCommentSniff.php | 88 + .../Commenting/VariableCommentSniff.php | 155 + .../ControlSignatureSniff.php | 265 + .../ElseIfDeclarationSniff.php | 45 + .../ForEachLoopDeclarationSniff.php | 211 + .../ForLoopDeclarationSniff.php | 261 + .../InlineIfDeclarationSniff.php | 142 + .../LowercaseDeclarationSniff.php | 51 + .../SwitchDeclarationSniff.php | 257 + .../Squiz/Sniffs/Debug/JSLintSniff.php | 73 + .../Sniffs/Debug/JavaScriptLintSniff.php | 76 + .../Squiz/Sniffs/Files/FileExtensionSniff.php | 60 + .../Formatting/OperatorBracketSniff.php | 285 + ...unctionDeclarationArgumentSpacingSniff.php | 326 ++ .../Functions/FunctionDeclarationSniff.php | 26 + .../FunctionDuplicateArgumentSniff.php | 56 + .../Sniffs/Functions/GlobalFunctionSniff.php | 53 + .../LowercaseFunctionKeywordsSniff.php | 56 + .../MultiLineFunctionDeclarationSniff.php | 224 + .../ValidFunctionNameSniff.php | 46 + .../ValidVariableNameSniff.php | 164 + .../DisallowObjectStringIndexSniff.php | 73 + .../Objects/ObjectInstantiationSniff.php | 60 + .../Sniffs/Objects/ObjectMemberCommaSniff.php | 56 + .../ComparisonOperatorUsageSniff.php | 185 + .../IncrementDecrementUsageSniff.php | 184 + .../Operators/ValidLogicalOperatorsSniff.php | 49 + .../Sniffs/PHP/CommentedOutCodeSniff.php | 225 + .../PHP/DisallowBooleanStatementSniff.php | 52 + .../PHP/DisallowComparisonAssignmentSniff.php | 77 + .../Sniffs/PHP/DisallowInlineIfSniff.php | 47 + .../PHP/DisallowMultipleAssignmentsSniff.php | 140 + .../PHP/DisallowSizeFunctionsInLoopsSniff.php | 88 + .../Sniffs/PHP/DiscouragedFunctionsSniff.php | 31 + .../Squiz/Sniffs/PHP/EmbeddedPhpSniff.php | 348 ++ .../Standards/Squiz/Sniffs/PHP/EvalSniff.php | 42 + .../Squiz/Sniffs/PHP/GlobalKeywordSniff.php | 46 + .../Squiz/Sniffs/PHP/HeredocSniff.php | 42 + .../Squiz/Sniffs/PHP/InnerFunctionsSniff.php | 58 + .../Sniffs/PHP/LowercasePHPFunctionsSniff.php | 122 + .../Sniffs/PHP/NonExecutableCodeSniff.php | 213 + .../Sniffs/Scope/MemberVarScopeSniff.php | 67 + .../Squiz/Sniffs/Scope/MethodScopeSniff.php | 72 + .../Sniffs/Scope/StaticThisUsageSniff.php | 108 + .../Strings/ConcatenationSpacingSniff.php | 134 + .../Sniffs/Strings/DoubleQuoteUsageSniff.php | 101 + .../Sniffs/Strings/EchoedStringsSniff.php | 75 + .../Sniffs/WhiteSpace/CastSpacingSniff.php | 53 + .../ControlStructureSpacingSniff.php | 234 + .../FunctionClosingBraceSpaceSniff.php | 140 + .../FunctionOpeningBraceSpaceSniff.php | 78 + .../WhiteSpace/FunctionSpacingSniff.php | 296 + .../LanguageConstructSpacingSniff.php | 71 + .../LogicalOperatorSpacingSniff.php | 86 + .../WhiteSpace/MemberVarSpacingSniff.php | 208 + .../WhiteSpace/ObjectOperatorSpacingSniff.php | 134 + .../WhiteSpace/OperatorSpacingSniff.php | 289 + .../WhiteSpace/PropertyLabelSpacingSniff.php | 66 + .../WhiteSpace/ScopeClosingBraceSniff.php | 91 + .../WhiteSpace/ScopeKeywordSpacingSniff.php | 129 + .../WhiteSpace/SemicolonSpacingSniff.php | 89 + .../WhiteSpace/SuperfluousWhitespaceSniff.php | 215 + .../src/Standards/Squiz/ruleset.xml | 132 + .../Zend/Docs/Debug/CodeAnalyzerStandard.xml | 25 + .../Zend/Docs/Files/ClosingTagStandard.xml | 22 + .../ValidVariableNameStandard.xml | 37 + .../Zend/Sniffs/Debug/CodeAnalyzerSniff.php | 84 + .../Zend/Sniffs/Files/ClosingTagSniff.php | 67 + .../ValidVariableNameSniff.php | 182 + .../src/Standards/Zend/ruleset.xml | 32 + .../php_codesniffer/src/Tokenizers/CSS.php | 410 ++ .../src/Tokenizers/Comment.php | 202 + .../php_codesniffer/src/Tokenizers/JS.php | 852 +++ .../php_codesniffer/src/Tokenizers/PHP.php | 2268 ++++++++ .../src/Tokenizers/Tokenizer.php | 1504 ++++++ .../php_codesniffer/src/Util/Cache.php | 286 + .../php_codesniffer/src/Util/Common.php | 481 ++ .../php_codesniffer/src/Util/Standards.php | 288 + .../php_codesniffer/src/Util/Timing.php | 75 + .../php_codesniffer/src/Util/Tokens.php | 448 ++ vendor/symfony/console/Application.php | 1147 ++++ .../symfony/console/Attribute/AsCommand.php | 41 + vendor/symfony/console/CHANGELOG.md | 252 + .../console/CI/GithubActionReporter.php | 79 + vendor/symfony/console/Color.php | 99 + vendor/symfony/console/Command/Command.php | 675 +++ .../console/Command/CompleteCommand.php | 158 + .../console/Command/DumpCompletionCommand.php | 143 + .../symfony/console/Command/HelpCommand.php | 68 + .../symfony/console/Command/LazyCommand.php | 188 + .../symfony/console/Command/ListCommand.php | 60 + .../symfony/console/Command/LockableTrait.php | 62 + .../Command/SignalableCommandInterface.php | 31 + .../CommandLoader/CommandLoaderInterface.php | 34 + .../CommandLoader/ContainerCommandLoader.php | 54 + .../CommandLoader/FactoryCommandLoader.php | 49 + .../console/Completion/CompletionInput.php | 210 + .../Completion/CompletionSuggestions.php | 86 + .../Output/BashCompletionOutput.php | 31 + .../Output/CompletionOutputInterface.php | 23 + .../Output/FishCompletionOutput.php | 31 + .../Completion/Output/ZshCompletionOutput.php | 34 + .../symfony/console/Completion/Suggestion.php | 47 + vendor/symfony/console/ConsoleEvents.php | 61 + vendor/symfony/console/Cursor.php | 167 + .../AddConsoleCommandPass.php | 107 + .../Descriptor/ApplicationDescription.php | 129 + .../symfony/console/Descriptor/Descriptor.php | 78 + .../Descriptor/DescriptorInterface.php | 25 + .../console/Descriptor/JsonDescriptor.php | 112 + .../console/Descriptor/MarkdownDescriptor.php | 128 + .../Descriptor/ReStructuredTextDescriptor.php | 234 + .../console/Descriptor/TextDescriptor.php | 274 + .../console/Descriptor/XmlDescriptor.php | 191 + .../console/Event/ConsoleCommandEvent.php | 47 + .../console/Event/ConsoleErrorEvent.php | 54 + vendor/symfony/console/Event/ConsoleEvent.php | 60 + .../console/Event/ConsoleSignalEvent.php | 60 + .../console/Event/ConsoleTerminateEvent.php | 40 + .../console/EventListener/ErrorListener.php | 82 + .../Exception/CommandNotFoundException.php | 42 + .../console/Exception/ExceptionInterface.php | 20 + .../Exception/InvalidArgumentException.php | 18 + .../Exception/InvalidOptionException.php | 20 + .../console/Exception/LogicException.php | 18 + .../Exception/MissingInputException.php | 20 + .../Exception/NamespaceNotFoundException.php | 20 + .../console/Exception/RuntimeException.php | 18 + .../console/Formatter/NullOutputFormatter.php | 47 + .../Formatter/NullOutputFormatterStyle.php | 48 + .../console/Formatter/OutputFormatter.php | 235 + .../Formatter/OutputFormatterInterface.php | 50 + .../Formatter/OutputFormatterStyle.php | 113 + .../OutputFormatterStyleInterface.php | 54 + .../Formatter/OutputFormatterStyleStack.php | 94 + .../WrappableOutputFormatterInterface.php | 26 + .../console/Helper/DebugFormatterHelper.php | 89 + .../console/Helper/DescriptorHelper.php | 74 + vendor/symfony/console/Helper/Dumper.php | 73 + .../console/Helper/FormatterHelper.php | 71 + vendor/symfony/console/Helper/Helper.php | 130 + .../console/Helper/HelperInterface.php | 36 + vendor/symfony/console/Helper/HelperSet.php | 68 + .../console/Helper/InputAwareHelper.php | 30 + .../symfony/console/Helper/OutputWrapper.php | 75 + .../symfony/console/Helper/ProcessHelper.php | 116 + vendor/symfony/console/Helper/ProgressBar.php | 591 ++ .../console/Helper/ProgressIndicator.php | 225 + .../symfony/console/Helper/QuestionHelper.php | 517 ++ .../console/Helper/SymfonyQuestionHelper.php | 85 + vendor/symfony/console/Helper/Table.php | 801 +++ vendor/symfony/console/Helper/TableCell.php | 64 + .../symfony/console/Helper/TableCellStyle.php | 59 + vendor/symfony/console/Helper/TableRows.php | 30 + .../symfony/console/Helper/TableSeparator.php | 24 + vendor/symfony/console/Helper/TableStyle.php | 378 ++ vendor/symfony/console/Input/ArgvInput.php | 336 ++ vendor/symfony/console/Input/ArrayInput.php | 181 + vendor/symfony/console/Input/Input.php | 173 + .../symfony/console/Input/InputArgument.php | 155 + .../console/Input/InputAwareInterface.php | 27 + .../symfony/console/Input/InputDefinition.php | 384 ++ .../symfony/console/Input/InputInterface.php | 136 + vendor/symfony/console/Input/InputOption.php | 237 + .../Input/StreamableInputInterface.php | 37 + vendor/symfony/console/Input/StringInput.php | 78 + vendor/symfony/console/LICENSE | 19 + .../symfony/console/Logger/ConsoleLogger.php | 101 + .../symfony/console/Output/AnsiColorMode.php | 76 + .../symfony/console/Output/BufferedOutput.php | 41 + .../symfony/console/Output/ConsoleOutput.php | 146 + .../console/Output/ConsoleOutputInterface.php | 30 + .../console/Output/ConsoleSectionOutput.php | 217 + vendor/symfony/console/Output/NullOutput.php | 95 + vendor/symfony/console/Output/Output.php | 142 + .../console/Output/OutputInterface.php | 94 + .../symfony/console/Output/StreamOutput.php | 95 + .../console/Output/TrimmedBufferOutput.php | 58 + vendor/symfony/console/PATCHES.txt | 7 + .../console/Question/ChoiceQuestion.php | 163 + .../console/Question/ConfirmationQuestion.php | 53 + vendor/symfony/console/Question/Question.php | 285 + vendor/symfony/console/README.md | 36 + .../console/Resources/bin/hiddeninput.exe | Bin 0 -> 9216 bytes .../symfony/console/Resources/completion.bash | 94 + .../symfony/console/Resources/completion.fish | 29 + .../symfony/console/Resources/completion.zsh | 82 + .../console/SignalRegistry/SignalRegistry.php | 51 + .../console/SingleCommandApplication.php | 71 + vendor/symfony/console/Style/OutputStyle.php | 118 + .../symfony/console/Style/StyleInterface.php | 130 + vendor/symfony/console/Style/SymfonyStyle.php | 462 ++ vendor/symfony/console/Terminal.php | 208 + .../console/Tester/ApplicationTester.php | 79 + .../Tester/CommandCompletionTester.php | 48 + .../symfony/console/Tester/CommandTester.php | 66 + .../Tester/Constraint/CommandIsSuccessful.php | 34 + vendor/symfony/console/Tester/TesterTrait.php | 167 + vendor/symfony/console/composer.json | 58 + .../deprecation-contracts/CHANGELOG.md | 5 + vendor/symfony/deprecation-contracts/LICENSE | 19 + .../symfony/deprecation-contracts/README.md | 26 + .../deprecation-contracts/composer.json | 35 + .../deprecation-contracts/function.php | 28 + vendor/symfony/filesystem/CHANGELOG.md | 82 + .../Exception/ExceptionInterface.php | 20 + .../Exception/FileNotFoundException.php | 32 + .../filesystem/Exception/IOException.php | 35 + .../Exception/IOExceptionInterface.php | 24 + .../Exception/InvalidArgumentException.php | 18 + .../filesystem/Exception/RuntimeException.php | 18 + vendor/symfony/filesystem/Filesystem.php | 667 +++ vendor/symfony/filesystem/LICENSE | 19 + vendor/symfony/filesystem/Path.php | 708 +++ vendor/symfony/filesystem/README.md | 13 + vendor/symfony/filesystem/composer.json | 32 + vendor/symfony/finder/CHANGELOG.md | 98 + .../symfony/finder/Comparator/Comparator.php | 69 + .../finder/Comparator/DateComparator.php | 45 + .../finder/Comparator/NumberComparator.php | 75 + .../Exception/AccessDeniedException.php | 18 + .../Exception/DirectoryNotFoundException.php | 18 + vendor/symfony/finder/Finder.php | 804 +++ vendor/symfony/finder/Gitignore.php | 81 + vendor/symfony/finder/Glob.php | 100 + .../finder/Iterator/CustomFilterIterator.php | 58 + .../Iterator/DateRangeFilterIterator.php | 53 + .../Iterator/DepthRangeFilterIterator.php | 47 + .../ExcludeDirectoryFilterIterator.php | 87 + .../Iterator/FileTypeFilterIterator.php | 50 + .../Iterator/FilecontentFilterIterator.php | 51 + .../Iterator/FilenameFilterIterator.php | 42 + .../symfony/finder/Iterator/LazyIterator.php | 32 + .../Iterator/MultiplePcreFilterIterator.php | 96 + .../finder/Iterator/PathFilterIterator.php | 51 + .../Iterator/RecursiveDirectoryIterator.php | 139 + .../Iterator/SizeRangeFilterIterator.php | 53 + .../finder/Iterator/SortableIterator.php | 117 + .../Iterator/VcsIgnoredFilterIterator.php | 134 + vendor/symfony/finder/LICENSE | 19 + vendor/symfony/finder/README.md | 14 + vendor/symfony/finder/SplFileInfo.php | 82 + vendor/symfony/finder/composer.json | 33 + vendor/symfony/options-resolver/CHANGELOG.md | 91 + .../Debug/OptionsResolverIntrospector.php | 93 + .../Exception/AccessException.php | 21 + .../Exception/ExceptionInterface.php | 20 + .../Exception/InvalidArgumentException.php | 20 + .../Exception/InvalidOptionsException.php | 22 + .../Exception/MissingOptionsException.php | 22 + .../Exception/NoConfigurationException.php | 24 + .../Exception/NoSuchOptionException.php | 25 + .../Exception/OptionDefinitionException.php | 20 + .../Exception/UndefinedOptionsException.php | 23 + vendor/symfony/options-resolver/LICENSE | 19 + .../options-resolver/OptionConfigurator.php | 130 + vendor/symfony/options-resolver/Options.php | 21 + .../options-resolver/OptionsResolver.php | 1119 ++++ vendor/symfony/options-resolver/README.md | 15 + vendor/symfony/options-resolver/composer.json | 35 + vendor/symfony/polyfill-mbstring/LICENSE | 19 + vendor/symfony/polyfill-mbstring/Mbstring.php | 698 +++ vendor/symfony/polyfill-mbstring/README.md | 13 + .../Resources/unidata/lowerCase.php | 5 + .../Resources/unidata/titleCaseRegexp.php | 6 + .../Resources/unidata/upperCase.php | 5 + .../symfony/polyfill-mbstring/bootstrap.php | 147 + .../symfony/polyfill-mbstring/bootstrap80.php | 214 + .../symfony/polyfill-mbstring/composer.json | 51 + vendor/symfony/polyfill-php80/LICENSE | 19 + vendor/symfony/polyfill-php80/Php80.php | 107 + vendor/symfony/polyfill-php80/PhpToken.php | 90 + vendor/symfony/polyfill-php80/README.md | 25 + .../Resources/stubs/Attribute.php | 31 + .../Resources/stubs/PhpToken.php | 16 + .../Resources/stubs/Stringable.php | 20 + .../Resources/stubs/UnhandledMatchError.php | 16 + .../Resources/stubs/ValueError.php | 16 + vendor/symfony/polyfill-php80/bootstrap.php | 42 + vendor/symfony/polyfill-php80/composer.json | 51 + vendor/symfony/polyfill-php81/LICENSE | 19 + vendor/symfony/polyfill-php81/Php81.php | 33 + vendor/symfony/polyfill-php81/README.md | 17 + .../Resources/stubs/ReturnTypeWillChange.php | 20 + vendor/symfony/polyfill-php81/bootstrap.php | 28 + vendor/symfony/polyfill-php81/composer.json | 47 + .../service-contracts/Attribute/Required.php | 24 + .../Attribute/SubscribedService.php | 55 + vendor/symfony/service-contracts/CHANGELOG.md | 5 + vendor/symfony/service-contracts/LICENSE | 19 + vendor/symfony/service-contracts/README.md | 9 + .../service-contracts/ResetInterface.php | 32 + .../service-contracts/ServiceLocatorTrait.php | 112 + .../ServiceProviderInterface.php | 41 + .../ServiceSubscriberInterface.php | 60 + .../ServiceSubscriberTrait.php | 67 + .../Test/ServiceLocatorTest.php | 21 + .../Test/ServiceLocatorTestCase.php | 83 + .../symfony/service-contracts/composer.json | 50 + vendor/symplify/coding-standard/LICENSE | 25 + vendor/symplify/coding-standard/composer.json | 48 + .../coding-standard/config/symplify.php | 36 + vendor/symplify/coding-standard/easy-ci.php | 9 + vendor/symplify/coding-standard/ecs.php | 11 + vendor/symplify/coding-standard/phpstan.neon | 23 + vendor/symplify/coding-standard/rector.php | 15 + .../src/DocBlock/UselessDocBlockCleaner.php | 97 + .../src/Enum/BlockBorderType.php | 16 + .../src/Fixer/AbstractSymplifyFixer.php | 30 + .../RemovePHPStormAnnotationFixer.php | 90 + .../ArrayListItemNewlineFixer.php | 91 + .../ArrayOpenerAndCloserNewlineFixer.php | 181 + .../StandaloneLineInMultilineArrayFixer.php | 126 + .../ParamReturnAndVarTagMalformsFixer.php | 132 + .../RemoveUselessDefaultCommentFixer.php | 98 + .../src/Fixer/LineLength/LineLengthFixer.php | 267 + .../Spacing/MethodChainingNewlineFixer.php | 162 + .../SpaceAfterCommaHereNowDocFixer.php | 81 + .../StandaloneLineConstructorParamFixer.php | 102 + .../StandaloneLinePromotedPropertyFixer.php | 103 + .../Strict/BlankLineAfterStrictTypesFixer.php | 86 + .../TokenAnalyzer/ChainMethodCallAnalyzer.php | 95 + .../DocblockRelatedParamNamesResolver.php | 47 + .../TokenAnalyzer/FunctionCallNameMatcher.php | 42 + .../src/TokenAnalyzer/HeredocAnalyzer.php | 34 + .../Naming/MethodNameResolver.php | 48 + .../src/TokenAnalyzer/NewlineAnalyzer.php | 41 + .../src/TokenAnalyzer/ParamNewliner.php | 40 + .../Analyzer/FixerAnalyzer/ArrayAnalyzer.php | 77 + .../Analyzer/FixerAnalyzer/BlockFinder.php | 125 + .../Analyzer/FixerAnalyzer/CallAnalyzer.php | 26 + .../Analyzer/FixerAnalyzer/IndentDetector.php | 43 + .../Analyzer/FixerAnalyzer/TokenSkipper.php | 64 + .../TokenRunner/Arrays/ArrayItemNewliner.php | 52 + .../DocBlock/MalformWorkerInterface.php | 14 + .../MalformWorker/InlineVarMalformWorker.php | 29 + .../InlineVariableDocBlockMalformWorker.php | 69 + .../MissingParamNameMalformWorker.php | 122 + .../MissingVarNameMalformWorker.php | 51 + .../ParamNameReferenceMalformWorker.php | 26 + .../ParamNameTypoMalformWorker.php | 114 + .../SuperfluousReturnNameMalformWorker.php | 68 + .../SuperfluousVarNameMalformWorker.php | 69 + .../SwitchedTypeAndNameMalformWorker.php | 46 + .../src/TokenRunner/Enum/LineKind.php | 19 + .../MissingImplementationException.php | 9 + .../Exception/TokenNotFoundException.php | 14 + .../src/TokenRunner/TokenFinder.php | 53 + .../FirstLineLengthResolver.php | 75 + .../LineLengthCloserTransformer.php | 69 + .../LineLengthOpenerTransformer.php | 43 + .../FixerTransformer/LineLengthResolver.php | 89 + .../LineLengthTransformer.php | 70 + .../FixerTransformer/TokensInliner.php | 57 + .../FixerTransformer/TokensNewliner.php | 108 + .../Traverser/ArrayBlockInfoFinder.php | 50 + .../TokenRunner/Traverser/TokenReverser.php | 26 + .../src/TokenRunner/ValueObject/BlockInfo.php | 31 + .../ValueObject/LineLengthAndPosition.php | 31 + .../TokenRunner/ValueObject/TokenKinds.php | 13 + .../Wrapper/FixerWrapper/ArrayWrapper.php | 82 + .../LineLengthAndPositionFactory.php | 53 + .../TokenRunner/Whitespace/IndentResolver.php | 60 + .../FixerWrapper/ArrayWrapperFactory.php | 29 + .../src/ValueObject/BlockInfoMetadata.php | 32 + .../src/ValueObject/CodingStandardConfig.php | 15 + vendor/symplify/easy-parallel/LICENSE | 25 + vendor/symplify/easy-parallel/composer.json | 57 + .../symplify/easy-parallel/config/config.php | 11 + vendor/symplify/easy-parallel/easy-ci.php | 10 + vendor/symplify/easy-parallel/ecs.php | 11 + vendor/symplify/easy-parallel/phpstan.neon | 22 + vendor/symplify/easy-parallel/rector.php | 26 + .../CommandLine/WorkerCommandLineFactory.php | 136 + .../src/Contract/SerializableInterface.php | 13 + .../src/CpuCoreCountProvider.php | 25 + .../easy-parallel/src/Enum/Action.php | 23 + .../easy-parallel/src/Enum/Content.php | 19 + .../easy-parallel/src/Enum/ReactCommand.php | 19 + .../easy-parallel/src/Enum/ReactEvent.php | 27 + .../ParallelShouldNotHappenException.php | 9 + .../src/FileSystem/FilePathNormalizer.php | 24 + .../CommandFromReflectionFactory.php | 33 + .../easy-parallel/src/ScheduleFactory.php | 25 + .../src/ValueObject/EasyParallelConfig.php | 15 + .../src/ValueObject/ParallelProcess.php | 150 + .../src/ValueObject/ProcessPool.php | 62 + .../src/ValueObject/Schedule.php | 43 + .../rule-doc-generator-contracts/LICENSE | 25 + .../composer.json | 46 + .../Category/CategoryInfererInterface.php | 10 + .../src/Contract/CodeSampleInterface.php | 10 + .../Contract/ConfigurableRuleInterface.php | 8 + .../src/Contract/DocumentedRuleInterface.php | 13 + .../RuleCodeSamplePrinterInterface.php | 14 + .../Exception/PoorDocumentationException.php | 9 + .../Exception/ShouldNotHappenException.php | 9 + .../src/ValueObject/AbstractCodeSample.php | 45 + .../src/ValueObject/CodeSample/CodeSample.php | 12 + .../ComposerJsonAwareCodeSample.php | 23 + .../CodeSample/ConfiguredCodeSample.php | 34 + .../CodeSample/ExtraFileCodeSample.php | 23 + .../src/ValueObject/RuleDefinition.php | 91 + vendor/webmozart/assert/CHANGELOG.md | 207 + vendor/webmozart/assert/LICENSE | 20 + vendor/webmozart/assert/README.md | 287 + vendor/webmozart/assert/composer.json | 43 + vendor/webmozart/assert/src/Assert.php | 1606 ++++++ .../assert/src/InvalidArgumentException.php | 15 + vendor/webmozart/assert/src/Mixin.php | 4630 ++++++++++++++++ 2001 files changed, 208918 insertions(+), 5792 deletions(-) delete mode 100644 .editorconfig rename build/target-repository/bootstrap.php => bootstrap.php (100%) delete mode 100644 build/rector-downgrade-php-72.php delete mode 100644 build/target-repository/.gitignore delete mode 100644 build/target-repository/composer.json delete mode 100644 easy-ci.php delete mode 100644 ecs.php delete mode 100644 full_ecs_build.sh delete mode 100644 packages-tests/ChangedFilesDetector/ChangedFilesDetector/ChangedFilesDetectorTest.php delete mode 100644 packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/OneClass.php delete mode 100644 packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/another-configuration.php delete mode 100644 packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/easy-coding-standard.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/FileHashComputerTest.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/Fixture/config-including-another-one.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/Source/ChangedScannedClass.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/Source/SomeScannedClass.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/Source/empty_config.php delete mode 100644 packages-tests/ChangedFilesDetector/FileHashComputer/Source/first_config.php delete mode 100644 packages-tests/FixerRunner/Application/FileProcessorSource/easy-coding-standard.php delete mode 100644 packages-tests/FixerRunner/Application/FileProcessorTest.php delete mode 100644 packages-tests/FixerRunner/DependencyInjection/FixerServiceRegistrationTest.php delete mode 100644 packages-tests/FixerRunner/DependencyInjection/config/easy-coding-standard.php delete mode 100644 packages-tests/Skipper/FileSystem/Fixture/in/it/KeepThisFile.txt delete mode 100644 packages-tests/Skipper/FileSystem/Fixture/path/in/it/KeepThisFile.txt delete mode 100644 packages-tests/Skipper/FileSystem/Fixture/path/with/KeepThisFile.txt delete mode 100644 packages-tests/Skipper/FileSystem/FnMatchPathNormalizerTest.php delete mode 100644 packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/Fixture/existing_paths.txt delete mode 100644 packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/SkippedPathsResolverTest.php delete mode 100644 packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/config/config.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/AlwaysSkippedPath/some_file.txt delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/PathSkippedWithMask/another_file.txt delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/skip.php.inc delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/someDirectory/anotherFile.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/someDirectory/someFile delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/someDirectory/someFile.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/someFile delete mode 100644 packages-tests/Skipper/Skipper/Skip/Fixture/someOtherFile delete mode 100644 packages-tests/Skipper/Skipper/Skip/SkipSkipperTest.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Source/AnotherClassToSkip.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Source/NotSkippedClass.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/Source/SomeClassToSkip.php delete mode 100644 packages-tests/Skipper/Skipper/Skip/config/config.php delete mode 100644 packages-tests/Skipper/Skipper/Skipper/Fixture/Element/FifthElement.php delete mode 100644 packages-tests/Skipper/Skipper/Skipper/Fixture/Element/SixthSense.php delete mode 100644 packages-tests/Skipper/Skipper/Skipper/Fixture/Element/ThreeMan.php delete mode 100644 packages-tests/Skipper/Skipper/Skipper/Fixture/SomeRandom/file.txt delete mode 100644 packages-tests/Skipper/Skipper/Skipper/Fixture/SomeSkipped/any.txt delete mode 100644 packages-tests/Skipper/Skipper/Skipper/SkipperTest.php delete mode 100644 packages-tests/Skipper/Skipper/Skipper/config/config.php delete mode 100644 packages-tests/SniffRunner/Application/FixerSource/SomeFile.php delete mode 100644 packages-tests/SniffRunner/Application/FixerTest.php delete mode 100644 packages-tests/SniffRunner/DI/SniffServiceRegistrationTest.php delete mode 100644 packages-tests/SniffRunner/DI/Source/AnotherSniff.php delete mode 100644 packages-tests/SniffRunner/DI/config/ecs.php delete mode 100644 packages-tests/SniffRunner/File/FileFactorySource/SomeFile.php delete mode 100644 packages-tests/SniffRunner/File/FileFactoryTest.php delete mode 100644 packages-tests/SniffRunner/ValueObject/FileSource/SomeFile.php delete mode 100644 packages-tests/SniffRunner/ValueObject/FileTest.php delete mode 100644 phpstan.neon delete mode 100644 phpunit.xml delete mode 100755 prefix-code.sh rename build/target-repository/preload.php => preload.php (100%) delete mode 100644 rector.php delete mode 100644 scoper.php delete mode 100644 tests/Console/Formatter/ColorConsoleDiffFormatterTest.php delete mode 100644 tests/Console/Formatter/Fixture/expected_dots.txt delete mode 100644 tests/Console/Formatter/Fixture/expected_old_new.txt delete mode 100644 tests/Console/Formatter/Fixture/expected_with_full_diff_by_phpunit.diff delete mode 100644 tests/Console/Formatter/Fixture/with_full_diff_by_phpunit.diff delete mode 100644 tests/Console/Output/Fixture/expected_json_output.json delete mode 100644 tests/Console/Output/Fixture/expected_plain.json delete mode 100644 tests/Console/Output/JsonOutputFormatterTest.php delete mode 100644 tests/Console/Output/Source/RandomFile.php delete mode 100644 tests/DependencyInjection/ConfigurationFileSource/empty-config.php delete mode 100644 tests/DependencyInjection/ConfigurationFileSource/include-another-config.php delete mode 100644 tests/DependencyInjection/ConfigurationFileSource/simple-config.php delete mode 100644 tests/DependencyInjection/ConfigurationFileTest.php delete mode 100644 tests/DependencyInjection/ConflictingCheckers/ConflictingCheckersTest.php delete mode 100644 tests/DependencyInjection/ConflictingCheckers/config/config.php delete mode 100644 tests/DependencyInjection/ExcludedCheckers/ExcludedCheckersTest.php delete mode 100644 tests/DependencyInjection/ExcludedCheckers/config/config.php delete mode 100644 tests/DependencyInjection/MutualExcludedCheckers/MutualExcludedCheckersTest.php delete mode 100644 tests/DependencyInjection/MutualExcludedCheckers/config/config.php delete mode 100644 tests/Error/ErrorCollector/ErrorCollectorSource/ConstantWithoutPublicDeclaration.php.inc delete mode 100644 tests/Error/ErrorCollector/ErrorCollectorSource/NotPsr2Class.php.inc delete mode 100644 tests/Error/ErrorCollector/FixerFileProcessorTest.php delete mode 100644 tests/Error/ErrorCollector/FixerRunnerSource/easy-coding-standard.php delete mode 100644 tests/Error/ErrorCollector/FixerRunnerSource/phpunit-fixer-config.php delete mode 100644 tests/Error/ErrorCollector/SniffFileProcessorTest.php delete mode 100644 tests/Error/ErrorCollector/SniffRunnerSource/easy-coding-standard.php delete mode 100644 tests/FileSystem/PathNormalizerTest.php delete mode 100644 tests/Finder/SourceFinderSource/Source/SomeClass.php delete mode 100644 tests/Finder/SourceFinderSource/Source/SomeClass.php.inc delete mode 100644 tests/Finder/SourceFinderSource/Source/whatever/FindThisTest.php.inc delete mode 100644 tests/Finder/SourceFinderTest.php delete mode 100644 tests/Indentation/IndentationTest.php delete mode 100644 tests/Indentation/Source/config-with-spaces-indentation.php delete mode 100644 tests/Indentation/Source/config-with-tabs-indentation.php delete mode 100644 tests/Set/Array/ArrayTest.php delete mode 100644 tests/Set/Array/Fixture/nested_array.php.inc delete mode 100644 tests/Set/Array/Fixture/nested_array_complex.php.inc delete mode 100644 tests/Set/Array/config.php delete mode 100644 tests/Set/Psr12/Fixture/fixture.php.inc delete mode 100644 tests/Set/Psr12/Fixture/fixture2.php.inc delete mode 100644 tests/Set/Psr12/Psr12Test.php delete mode 100644 tests/Testing/PHPUnit/Fixture/another_file.php.inc delete mode 100644 tests/Testing/PHPUnit/Fixture/some_file.php.inc delete mode 100644 tests/Testing/PHPUnit/FixtureFinderTest.php delete mode 100644 tests/bootstrap.php delete mode 100644 tests/functions.php create mode 100644 vendor/autoload.php create mode 100644 vendor/bin/php-cs-fixer create mode 100644 vendor/bin/phpcbf create mode 100644 vendor/bin/phpcs create mode 100644 vendor/clue/ndjson-react/CHANGELOG.md create mode 100644 vendor/clue/ndjson-react/LICENSE create mode 100644 vendor/clue/ndjson-react/README.md create mode 100644 vendor/clue/ndjson-react/composer.json create mode 100644 vendor/clue/ndjson-react/src/Decoder.php create mode 100644 vendor/clue/ndjson-react/src/Encoder.php create mode 100644 vendor/composer/ClassLoader.php create mode 100644 vendor/composer/InstalledVersions.php create mode 100644 vendor/composer/LICENSE create mode 100644 vendor/composer/autoload_classmap.php create mode 100644 vendor/composer/autoload_files.php create mode 100644 vendor/composer/autoload_namespaces.php create mode 100644 vendor/composer/autoload_psr4.php create mode 100644 vendor/composer/autoload_real.php create mode 100644 vendor/composer/autoload_static.php create mode 100644 vendor/composer/installed.json create mode 100644 vendor/composer/installed.php create mode 100644 vendor/composer/pcre/LICENSE create mode 100644 vendor/composer/pcre/README.md create mode 100644 vendor/composer/pcre/composer.json create mode 100644 vendor/composer/pcre/src/MatchAllResult.php create mode 100644 vendor/composer/pcre/src/MatchAllStrictGroupsResult.php create mode 100644 vendor/composer/pcre/src/MatchAllWithOffsetsResult.php create mode 100644 vendor/composer/pcre/src/MatchResult.php create mode 100644 vendor/composer/pcre/src/MatchStrictGroupsResult.php create mode 100644 vendor/composer/pcre/src/MatchWithOffsetsResult.php create mode 100644 vendor/composer/pcre/src/PcreException.php create mode 100644 vendor/composer/pcre/src/Preg.php create mode 100644 vendor/composer/pcre/src/Regex.php create mode 100644 vendor/composer/pcre/src/ReplaceResult.php create mode 100644 vendor/composer/pcre/src/UnexpectedNullMatchException.php create mode 100644 vendor/composer/semver/CHANGELOG.md create mode 100644 vendor/composer/semver/LICENSE create mode 100644 vendor/composer/semver/README.md create mode 100644 vendor/composer/semver/composer.json create mode 100644 vendor/composer/semver/src/Comparator.php create mode 100644 vendor/composer/semver/src/CompilingMatcher.php create mode 100644 vendor/composer/semver/src/Constraint/Bound.php create mode 100644 vendor/composer/semver/src/Constraint/Constraint.php create mode 100644 vendor/composer/semver/src/Constraint/ConstraintInterface.php create mode 100644 vendor/composer/semver/src/Constraint/MatchAllConstraint.php create mode 100644 vendor/composer/semver/src/Constraint/MatchNoneConstraint.php create mode 100644 vendor/composer/semver/src/Constraint/MultiConstraint.php create mode 100644 vendor/composer/semver/src/Interval.php create mode 100644 vendor/composer/semver/src/Intervals.php create mode 100644 vendor/composer/semver/src/Semver.php create mode 100644 vendor/composer/semver/src/VersionParser.php create mode 100644 vendor/composer/xdebug-handler/CHANGELOG.md create mode 100644 vendor/composer/xdebug-handler/LICENSE create mode 100644 vendor/composer/xdebug-handler/README.md create mode 100644 vendor/composer/xdebug-handler/composer.json create mode 100644 vendor/composer/xdebug-handler/src/PhpConfig.php create mode 100644 vendor/composer/xdebug-handler/src/Process.php create mode 100644 vendor/composer/xdebug-handler/src/Status.php create mode 100644 vendor/composer/xdebug-handler/src/XdebugHandler.php create mode 100644 vendor/doctrine/annotations/LICENSE create mode 100644 vendor/doctrine/annotations/README.md create mode 100644 vendor/doctrine/annotations/UPGRADE.md create mode 100644 vendor/doctrine/annotations/composer.json create mode 100644 vendor/doctrine/annotations/docs/en/annotations.rst create mode 100644 vendor/doctrine/annotations/docs/en/custom.rst create mode 100644 vendor/doctrine/annotations/docs/en/index.rst create mode 100644 vendor/doctrine/annotations/docs/en/sidebar.rst create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php create mode 100644 vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php create mode 100644 vendor/doctrine/annotations/psalm.xml create mode 100644 vendor/doctrine/lexer/LICENSE create mode 100644 vendor/doctrine/lexer/README.md create mode 100644 vendor/doctrine/lexer/UPGRADE.md create mode 100644 vendor/doctrine/lexer/composer.json create mode 100644 vendor/doctrine/lexer/src/AbstractLexer.php create mode 100644 vendor/doctrine/lexer/src/Token.php create mode 100644 vendor/evenement/evenement/CHANGELOG.md create mode 100644 vendor/evenement/evenement/LICENSE create mode 100644 vendor/evenement/evenement/README.md create mode 100644 vendor/evenement/evenement/composer.json create mode 100644 vendor/evenement/evenement/doc/00-intro.md create mode 100644 vendor/evenement/evenement/doc/01-api.md create mode 100644 vendor/evenement/evenement/doc/02-plugin-system.md create mode 100644 vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php create mode 100644 vendor/evenement/evenement/examples/benchmark-emit-once.php create mode 100644 vendor/evenement/evenement/examples/benchmark-emit-one-argument.php create mode 100644 vendor/evenement/evenement/examples/benchmark-emit.php create mode 100644 vendor/evenement/evenement/examples/benchmark-remove-listener-once.php create mode 100644 vendor/evenement/evenement/phpunit.xml.dist create mode 100644 vendor/evenement/evenement/src/Evenement/EventEmitter.php create mode 100644 vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php create mode 100644 vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php create mode 100644 vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php create mode 100644 vendor/evenement/evenement/tests/Evenement/Tests/Listener.php create mode 100644 vendor/evenement/evenement/tests/Evenement/Tests/functions.php create mode 100644 vendor/fidry/cpu-core-counter/LICENSE.md create mode 100644 vendor/fidry/cpu-core-counter/README.md create mode 100644 vendor/fidry/cpu-core-counter/bin/diagnose.php create mode 100644 vendor/fidry/cpu-core-counter/bin/execute.php create mode 100644 vendor/fidry/cpu-core-counter/composer.json create mode 100644 vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php create mode 100644 vendor/fidry/cpu-core-counter/src/Diagnoser.php create mode 100644 vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php create mode 100644 vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php create mode 100644 vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php create mode 100644 vendor/friendsofphp/php-cs-fixer/CHANGELOG.md create mode 100644 vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md create mode 100644 vendor/friendsofphp/php-cs-fixer/LICENSE create mode 100644 vendor/friendsofphp/php-cs-fixer/README.md create mode 100644 vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md create mode 100644 vendor/friendsofphp/php-cs-fixer/ci-integration.sh create mode 100644 vendor/friendsofphp/php-cs-fixer/composer.json create mode 100644 vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst create mode 100644 vendor/friendsofphp/php-cs-fixer/logo.md create mode 100644 vendor/friendsofphp/php-cs-fixer/logo.png create mode 100644 vendor/friendsofphp/php-cs-fixer/php-cs-fixer create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Config.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Application.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Documentation/ListDocumentGenerator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Documentation/RuleSetDocumentationGenerator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Error/Error.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FileReader.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Finder.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/PharChecker.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Preg.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/PregException.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformers.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/Utils.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php create mode 100644 vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php create mode 100644 vendor/illuminate/container/BoundMethod.php create mode 100644 vendor/illuminate/container/Container.php create mode 100644 vendor/illuminate/container/ContextualBindingBuilder.php create mode 100644 vendor/illuminate/container/EntryNotFoundException.php create mode 100644 vendor/illuminate/container/LICENSE.md create mode 100644 vendor/illuminate/container/RewindableGenerator.php create mode 100644 vendor/illuminate/container/Util.php create mode 100644 vendor/illuminate/container/composer.json create mode 100644 vendor/illuminate/contracts/Auth/Access/Authorizable.php create mode 100644 vendor/illuminate/contracts/Auth/Access/Gate.php create mode 100644 vendor/illuminate/contracts/Auth/Authenticatable.php create mode 100644 vendor/illuminate/contracts/Auth/CanResetPassword.php create mode 100644 vendor/illuminate/contracts/Auth/Factory.php create mode 100644 vendor/illuminate/contracts/Auth/Guard.php create mode 100644 vendor/illuminate/contracts/Auth/Middleware/AuthenticatesRequests.php create mode 100644 vendor/illuminate/contracts/Auth/MustVerifyEmail.php create mode 100644 vendor/illuminate/contracts/Auth/PasswordBroker.php create mode 100644 vendor/illuminate/contracts/Auth/PasswordBrokerFactory.php create mode 100644 vendor/illuminate/contracts/Auth/StatefulGuard.php create mode 100644 vendor/illuminate/contracts/Auth/SupportsBasicAuth.php create mode 100644 vendor/illuminate/contracts/Auth/UserProvider.php create mode 100644 vendor/illuminate/contracts/Broadcasting/Broadcaster.php create mode 100644 vendor/illuminate/contracts/Broadcasting/Factory.php create mode 100644 vendor/illuminate/contracts/Broadcasting/HasBroadcastChannel.php create mode 100644 vendor/illuminate/contracts/Broadcasting/ShouldBeUnique.php create mode 100644 vendor/illuminate/contracts/Broadcasting/ShouldBroadcast.php create mode 100644 vendor/illuminate/contracts/Broadcasting/ShouldBroadcastNow.php create mode 100644 vendor/illuminate/contracts/Bus/Dispatcher.php create mode 100644 vendor/illuminate/contracts/Bus/QueueingDispatcher.php create mode 100644 vendor/illuminate/contracts/Cache/Factory.php create mode 100644 vendor/illuminate/contracts/Cache/Lock.php create mode 100644 vendor/illuminate/contracts/Cache/LockProvider.php create mode 100644 vendor/illuminate/contracts/Cache/LockTimeoutException.php create mode 100644 vendor/illuminate/contracts/Cache/Repository.php create mode 100644 vendor/illuminate/contracts/Cache/Store.php create mode 100644 vendor/illuminate/contracts/Config/Repository.php create mode 100644 vendor/illuminate/contracts/Console/Application.php create mode 100644 vendor/illuminate/contracts/Console/Isolatable.php create mode 100644 vendor/illuminate/contracts/Console/Kernel.php create mode 100644 vendor/illuminate/contracts/Console/PromptsForMissingInput.php create mode 100644 vendor/illuminate/contracts/Container/BindingResolutionException.php create mode 100644 vendor/illuminate/contracts/Container/CircularDependencyException.php create mode 100644 vendor/illuminate/contracts/Container/Container.php create mode 100644 vendor/illuminate/contracts/Container/ContextualBindingBuilder.php create mode 100644 vendor/illuminate/contracts/Cookie/Factory.php create mode 100644 vendor/illuminate/contracts/Cookie/QueueingFactory.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/Builder.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/Castable.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/DeviatesCastableAttributes.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php create mode 100644 vendor/illuminate/contracts/Database/Eloquent/SupportsPartialRelations.php create mode 100644 vendor/illuminate/contracts/Database/Events/MigrationEvent.php create mode 100644 vendor/illuminate/contracts/Database/ModelIdentifier.php create mode 100644 vendor/illuminate/contracts/Database/Query/Builder.php create mode 100644 vendor/illuminate/contracts/Database/Query/ConditionExpression.php create mode 100644 vendor/illuminate/contracts/Database/Query/Expression.php create mode 100644 vendor/illuminate/contracts/Debug/ExceptionHandler.php create mode 100644 vendor/illuminate/contracts/Encryption/DecryptException.php create mode 100644 vendor/illuminate/contracts/Encryption/EncryptException.php create mode 100644 vendor/illuminate/contracts/Encryption/Encrypter.php create mode 100644 vendor/illuminate/contracts/Encryption/StringEncrypter.php create mode 100644 vendor/illuminate/contracts/Events/Dispatcher.php create mode 100644 vendor/illuminate/contracts/Filesystem/Cloud.php create mode 100644 vendor/illuminate/contracts/Filesystem/Factory.php create mode 100644 vendor/illuminate/contracts/Filesystem/FileNotFoundException.php create mode 100644 vendor/illuminate/contracts/Filesystem/Filesystem.php create mode 100644 vendor/illuminate/contracts/Filesystem/LockTimeoutException.php create mode 100644 vendor/illuminate/contracts/Foundation/Application.php create mode 100644 vendor/illuminate/contracts/Foundation/CachesConfiguration.php create mode 100644 vendor/illuminate/contracts/Foundation/CachesRoutes.php create mode 100644 vendor/illuminate/contracts/Foundation/ExceptionRenderer.php create mode 100644 vendor/illuminate/contracts/Foundation/MaintenanceMode.php create mode 100644 vendor/illuminate/contracts/Hashing/Hasher.php create mode 100644 vendor/illuminate/contracts/Http/Kernel.php create mode 100644 vendor/illuminate/contracts/LICENSE.md create mode 100644 vendor/illuminate/contracts/Mail/Attachable.php create mode 100644 vendor/illuminate/contracts/Mail/Factory.php create mode 100644 vendor/illuminate/contracts/Mail/MailQueue.php create mode 100644 vendor/illuminate/contracts/Mail/Mailable.php create mode 100644 vendor/illuminate/contracts/Mail/Mailer.php create mode 100644 vendor/illuminate/contracts/Notifications/Dispatcher.php create mode 100644 vendor/illuminate/contracts/Notifications/Factory.php create mode 100644 vendor/illuminate/contracts/Pagination/CursorPaginator.php create mode 100644 vendor/illuminate/contracts/Pagination/LengthAwarePaginator.php create mode 100644 vendor/illuminate/contracts/Pagination/Paginator.php create mode 100644 vendor/illuminate/contracts/Pipeline/Hub.php create mode 100644 vendor/illuminate/contracts/Pipeline/Pipeline.php create mode 100644 vendor/illuminate/contracts/Process/InvokedProcess.php create mode 100644 vendor/illuminate/contracts/Process/ProcessResult.php create mode 100644 vendor/illuminate/contracts/Queue/ClearableQueue.php create mode 100644 vendor/illuminate/contracts/Queue/EntityNotFoundException.php create mode 100644 vendor/illuminate/contracts/Queue/EntityResolver.php create mode 100644 vendor/illuminate/contracts/Queue/Factory.php create mode 100644 vendor/illuminate/contracts/Queue/Job.php create mode 100644 vendor/illuminate/contracts/Queue/Monitor.php create mode 100644 vendor/illuminate/contracts/Queue/Queue.php create mode 100644 vendor/illuminate/contracts/Queue/QueueableCollection.php create mode 100644 vendor/illuminate/contracts/Queue/QueueableEntity.php create mode 100644 vendor/illuminate/contracts/Queue/ShouldBeEncrypted.php create mode 100644 vendor/illuminate/contracts/Queue/ShouldBeUnique.php create mode 100644 vendor/illuminate/contracts/Queue/ShouldBeUniqueUntilProcessing.php create mode 100644 vendor/illuminate/contracts/Queue/ShouldQueue.php create mode 100644 vendor/illuminate/contracts/Redis/Connection.php create mode 100644 vendor/illuminate/contracts/Redis/Connector.php create mode 100644 vendor/illuminate/contracts/Redis/Factory.php create mode 100644 vendor/illuminate/contracts/Redis/LimiterTimeoutException.php create mode 100644 vendor/illuminate/contracts/Routing/BindingRegistrar.php create mode 100644 vendor/illuminate/contracts/Routing/Registrar.php create mode 100644 vendor/illuminate/contracts/Routing/ResponseFactory.php create mode 100644 vendor/illuminate/contracts/Routing/UrlGenerator.php create mode 100644 vendor/illuminate/contracts/Routing/UrlRoutable.php create mode 100644 vendor/illuminate/contracts/Session/Middleware/AuthenticatesSessions.php create mode 100644 vendor/illuminate/contracts/Session/Session.php create mode 100644 vendor/illuminate/contracts/Support/Arrayable.php create mode 100644 vendor/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php create mode 100644 vendor/illuminate/contracts/Support/DeferrableProvider.php create mode 100644 vendor/illuminate/contracts/Support/DeferringDisplayableValue.php create mode 100644 vendor/illuminate/contracts/Support/Htmlable.php create mode 100644 vendor/illuminate/contracts/Support/Jsonable.php create mode 100644 vendor/illuminate/contracts/Support/MessageBag.php create mode 100644 vendor/illuminate/contracts/Support/MessageProvider.php create mode 100644 vendor/illuminate/contracts/Support/Renderable.php create mode 100644 vendor/illuminate/contracts/Support/Responsable.php create mode 100644 vendor/illuminate/contracts/Support/ValidatedData.php create mode 100644 vendor/illuminate/contracts/Translation/HasLocalePreference.php create mode 100644 vendor/illuminate/contracts/Translation/Loader.php create mode 100644 vendor/illuminate/contracts/Translation/Translator.php create mode 100644 vendor/illuminate/contracts/Validation/DataAwareRule.php create mode 100644 vendor/illuminate/contracts/Validation/Factory.php create mode 100644 vendor/illuminate/contracts/Validation/ImplicitRule.php create mode 100644 vendor/illuminate/contracts/Validation/InvokableRule.php create mode 100644 vendor/illuminate/contracts/Validation/Rule.php create mode 100644 vendor/illuminate/contracts/Validation/UncompromisedVerifier.php create mode 100644 vendor/illuminate/contracts/Validation/ValidatesWhenResolved.php create mode 100644 vendor/illuminate/contracts/Validation/ValidationRule.php create mode 100644 vendor/illuminate/contracts/Validation/Validator.php create mode 100644 vendor/illuminate/contracts/Validation/ValidatorAwareRule.php create mode 100644 vendor/illuminate/contracts/View/Engine.php create mode 100644 vendor/illuminate/contracts/View/Factory.php create mode 100644 vendor/illuminate/contracts/View/View.php create mode 100644 vendor/illuminate/contracts/View/ViewCompilationException.php create mode 100644 vendor/illuminate/contracts/composer.json create mode 100644 vendor/nette/utils/composer.json create mode 100644 vendor/nette/utils/license.md create mode 100644 vendor/nette/utils/readme.md create mode 100644 vendor/nette/utils/src/HtmlStringable.php create mode 100644 vendor/nette/utils/src/Iterators/CachingIterator.php create mode 100644 vendor/nette/utils/src/Iterators/Mapper.php create mode 100644 vendor/nette/utils/src/SmartObject.php create mode 100644 vendor/nette/utils/src/StaticClass.php create mode 100644 vendor/nette/utils/src/Translator.php create mode 100644 vendor/nette/utils/src/Utils/ArrayHash.php create mode 100644 vendor/nette/utils/src/Utils/ArrayList.php create mode 100644 vendor/nette/utils/src/Utils/Arrays.php create mode 100644 vendor/nette/utils/src/Utils/Callback.php create mode 100644 vendor/nette/utils/src/Utils/DateTime.php create mode 100644 vendor/nette/utils/src/Utils/FileSystem.php create mode 100644 vendor/nette/utils/src/Utils/Floats.php create mode 100644 vendor/nette/utils/src/Utils/Helpers.php create mode 100644 vendor/nette/utils/src/Utils/Html.php create mode 100644 vendor/nette/utils/src/Utils/Image.php create mode 100644 vendor/nette/utils/src/Utils/Json.php create mode 100644 vendor/nette/utils/src/Utils/ObjectHelpers.php create mode 100644 vendor/nette/utils/src/Utils/ObjectMixin.php create mode 100644 vendor/nette/utils/src/Utils/Paginator.php create mode 100644 vendor/nette/utils/src/Utils/Random.php create mode 100644 vendor/nette/utils/src/Utils/Reflection.php create mode 100644 vendor/nette/utils/src/Utils/Strings.php create mode 100644 vendor/nette/utils/src/Utils/Type.php create mode 100644 vendor/nette/utils/src/Utils/Validators.php create mode 100644 vendor/nette/utils/src/Utils/exceptions.php create mode 100644 vendor/nette/utils/src/compatibility.php create mode 100644 vendor/nette/utils/src/exceptions.php create mode 100644 vendor/psr/cache/CHANGELOG.md create mode 100644 vendor/psr/cache/LICENSE.txt create mode 100644 vendor/psr/cache/README.md create mode 100644 vendor/psr/cache/composer.json create mode 100644 vendor/psr/cache/src/CacheException.php create mode 100644 vendor/psr/cache/src/CacheItemInterface.php create mode 100644 vendor/psr/cache/src/CacheItemPoolInterface.php create mode 100644 vendor/psr/cache/src/InvalidArgumentException.php create mode 100644 vendor/psr/container/LICENSE create mode 100644 vendor/psr/container/README.md create mode 100644 vendor/psr/container/composer.json create mode 100644 vendor/psr/container/src/ContainerExceptionInterface.php create mode 100644 vendor/psr/container/src/ContainerInterface.php create mode 100644 vendor/psr/container/src/NotFoundExceptionInterface.php create mode 100644 vendor/psr/log/LICENSE create mode 100644 vendor/psr/log/README.md create mode 100644 vendor/psr/log/composer.json create mode 100644 vendor/psr/log/src/AbstractLogger.php create mode 100644 vendor/psr/log/src/InvalidArgumentException.php create mode 100644 vendor/psr/log/src/LogLevel.php create mode 100644 vendor/psr/log/src/LoggerAwareInterface.php create mode 100644 vendor/psr/log/src/LoggerAwareTrait.php create mode 100644 vendor/psr/log/src/LoggerInterface.php create mode 100644 vendor/psr/log/src/LoggerTrait.php create mode 100644 vendor/psr/log/src/NullLogger.php create mode 100644 vendor/psr/simple-cache/LICENSE.md create mode 100644 vendor/psr/simple-cache/README.md create mode 100644 vendor/psr/simple-cache/composer.json create mode 100644 vendor/psr/simple-cache/src/CacheException.php create mode 100644 vendor/psr/simple-cache/src/CacheInterface.php create mode 100644 vendor/psr/simple-cache/src/InvalidArgumentException.php create mode 100644 vendor/react/cache/CHANGELOG.md create mode 100644 vendor/react/cache/LICENSE create mode 100644 vendor/react/cache/README.md create mode 100644 vendor/react/cache/composer.json create mode 100644 vendor/react/cache/src/ArrayCache.php create mode 100644 vendor/react/cache/src/CacheInterface.php create mode 100644 vendor/react/child-process/CHANGELOG.md create mode 100644 vendor/react/child-process/LICENSE create mode 100644 vendor/react/child-process/README.md create mode 100644 vendor/react/child-process/composer.json create mode 100644 vendor/react/child-process/src/Process.php create mode 100644 vendor/react/dns/CHANGELOG.md create mode 100644 vendor/react/dns/LICENSE create mode 100644 vendor/react/dns/README.md create mode 100644 vendor/react/dns/composer.json create mode 100644 vendor/react/dns/src/BadServerException.php create mode 100644 vendor/react/dns/src/Config/Config.php create mode 100644 vendor/react/dns/src/Config/HostsFile.php create mode 100644 vendor/react/dns/src/Model/Message.php create mode 100644 vendor/react/dns/src/Model/Record.php create mode 100644 vendor/react/dns/src/Protocol/BinaryDumper.php create mode 100644 vendor/react/dns/src/Protocol/Parser.php create mode 100644 vendor/react/dns/src/Query/CachingExecutor.php create mode 100644 vendor/react/dns/src/Query/CancellationException.php create mode 100644 vendor/react/dns/src/Query/CoopExecutor.php create mode 100644 vendor/react/dns/src/Query/ExecutorInterface.php create mode 100644 vendor/react/dns/src/Query/FallbackExecutor.php create mode 100644 vendor/react/dns/src/Query/HostsFileExecutor.php create mode 100644 vendor/react/dns/src/Query/Query.php create mode 100644 vendor/react/dns/src/Query/RetryExecutor.php create mode 100644 vendor/react/dns/src/Query/SelectiveTransportExecutor.php create mode 100644 vendor/react/dns/src/Query/TcpTransportExecutor.php create mode 100644 vendor/react/dns/src/Query/TimeoutException.php create mode 100644 vendor/react/dns/src/Query/TimeoutExecutor.php create mode 100644 vendor/react/dns/src/Query/UdpTransportExecutor.php create mode 100644 vendor/react/dns/src/RecordNotFoundException.php create mode 100644 vendor/react/dns/src/Resolver/Factory.php create mode 100644 vendor/react/dns/src/Resolver/Resolver.php create mode 100644 vendor/react/dns/src/Resolver/ResolverInterface.php create mode 100644 vendor/react/event-loop/CHANGELOG.md create mode 100644 vendor/react/event-loop/LICENSE create mode 100644 vendor/react/event-loop/README.md create mode 100644 vendor/react/event-loop/composer.json create mode 100644 vendor/react/event-loop/src/ExtEvLoop.php create mode 100644 vendor/react/event-loop/src/ExtEventLoop.php create mode 100644 vendor/react/event-loop/src/ExtLibevLoop.php create mode 100644 vendor/react/event-loop/src/ExtLibeventLoop.php create mode 100644 vendor/react/event-loop/src/ExtUvLoop.php create mode 100644 vendor/react/event-loop/src/Factory.php create mode 100644 vendor/react/event-loop/src/Loop.php create mode 100644 vendor/react/event-loop/src/LoopInterface.php create mode 100644 vendor/react/event-loop/src/SignalsHandler.php create mode 100644 vendor/react/event-loop/src/StreamSelectLoop.php create mode 100644 vendor/react/event-loop/src/Tick/FutureTickQueue.php create mode 100644 vendor/react/event-loop/src/Timer/Timer.php create mode 100644 vendor/react/event-loop/src/Timer/Timers.php create mode 100644 vendor/react/event-loop/src/TimerInterface.php create mode 100644 vendor/react/promise/CHANGELOG.md create mode 100644 vendor/react/promise/LICENSE create mode 100644 vendor/react/promise/README.md create mode 100644 vendor/react/promise/composer.json create mode 100644 vendor/react/promise/src/Deferred.php create mode 100644 vendor/react/promise/src/Exception/CompositeException.php create mode 100644 vendor/react/promise/src/Exception/LengthException.php create mode 100644 vendor/react/promise/src/Internal/CancellationQueue.php create mode 100644 vendor/react/promise/src/Internal/FulfilledPromise.php create mode 100644 vendor/react/promise/src/Internal/RejectedPromise.php create mode 100644 vendor/react/promise/src/Promise.php create mode 100644 vendor/react/promise/src/PromiseInterface.php create mode 100644 vendor/react/promise/src/functions.php create mode 100644 vendor/react/promise/src/functions_include.php create mode 100644 vendor/react/socket/CHANGELOG.md create mode 100644 vendor/react/socket/LICENSE create mode 100644 vendor/react/socket/README.md create mode 100644 vendor/react/socket/composer.json create mode 100644 vendor/react/socket/src/Connection.php create mode 100644 vendor/react/socket/src/ConnectionInterface.php create mode 100644 vendor/react/socket/src/Connector.php create mode 100644 vendor/react/socket/src/ConnectorInterface.php create mode 100644 vendor/react/socket/src/DnsConnector.php create mode 100644 vendor/react/socket/src/FdServer.php create mode 100644 vendor/react/socket/src/FixedUriConnector.php create mode 100644 vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php create mode 100644 vendor/react/socket/src/HappyEyeBallsConnector.php create mode 100644 vendor/react/socket/src/LimitingServer.php create mode 100644 vendor/react/socket/src/SecureConnector.php create mode 100644 vendor/react/socket/src/SecureServer.php create mode 100644 vendor/react/socket/src/Server.php create mode 100644 vendor/react/socket/src/ServerInterface.php create mode 100644 vendor/react/socket/src/SocketServer.php create mode 100644 vendor/react/socket/src/StreamEncryption.php create mode 100644 vendor/react/socket/src/TcpConnector.php create mode 100644 vendor/react/socket/src/TcpServer.php create mode 100644 vendor/react/socket/src/TimeoutConnector.php create mode 100644 vendor/react/socket/src/UnixConnector.php create mode 100644 vendor/react/socket/src/UnixServer.php create mode 100644 vendor/react/stream/CHANGELOG.md create mode 100644 vendor/react/stream/LICENSE create mode 100644 vendor/react/stream/README.md create mode 100644 vendor/react/stream/composer.json create mode 100644 vendor/react/stream/src/CompositeStream.php create mode 100644 vendor/react/stream/src/DuplexResourceStream.php create mode 100644 vendor/react/stream/src/DuplexStreamInterface.php create mode 100644 vendor/react/stream/src/ReadableResourceStream.php create mode 100644 vendor/react/stream/src/ReadableStreamInterface.php create mode 100644 vendor/react/stream/src/ThroughStream.php create mode 100644 vendor/react/stream/src/Util.php create mode 100644 vendor/react/stream/src/WritableResourceStream.php create mode 100644 vendor/react/stream/src/WritableStreamInterface.php create mode 100644 vendor/scoper-autoload.php create mode 100644 vendor/sebastian/diff/ChangeLog.md create mode 100644 vendor/sebastian/diff/LICENSE create mode 100644 vendor/sebastian/diff/README.md create mode 100644 vendor/sebastian/diff/SECURITY.md create mode 100644 vendor/sebastian/diff/composer.json create mode 100644 vendor/sebastian/diff/src/Chunk.php create mode 100644 vendor/sebastian/diff/src/Diff.php create mode 100644 vendor/sebastian/diff/src/Differ.php create mode 100644 vendor/sebastian/diff/src/Exception/ConfigurationException.php create mode 100644 vendor/sebastian/diff/src/Exception/Exception.php create mode 100644 vendor/sebastian/diff/src/Exception/InvalidArgumentException.php create mode 100644 vendor/sebastian/diff/src/Line.php create mode 100644 vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php create mode 100644 vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php create mode 100644 vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php create mode 100644 vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php create mode 100644 vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php create mode 100644 vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php create mode 100644 vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php create mode 100644 vendor/sebastian/diff/src/Parser.php create mode 100644 vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php create mode 100644 vendor/squizlabs/php_codesniffer/CONTRIBUTING.md create mode 100644 vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist create mode 100644 vendor/squizlabs/php_codesniffer/README.md create mode 100644 vendor/squizlabs/php_codesniffer/autoload.php create mode 100644 vendor/squizlabs/php_codesniffer/bin/phpcbf create mode 100644 vendor/squizlabs/php_codesniffer/bin/phpcbf.bat create mode 100644 vendor/squizlabs/php_codesniffer/bin/phpcs create mode 100644 vendor/squizlabs/php_codesniffer/bin/phpcs.bat create mode 100644 vendor/squizlabs/php_codesniffer/composer.json create mode 100644 vendor/squizlabs/php_codesniffer/licence.txt create mode 100644 vendor/squizlabs/php_codesniffer/phpcs.xsd create mode 100644 vendor/squizlabs/php_codesniffer/src/Config.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Files/File.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Files/FileList.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Filters/Filter.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Fixer.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Generators/Generator.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Generators/HTML.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Generators/Text.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reporter.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Code.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Csv.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Diff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Full.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Info.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Json.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Junit.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Report.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Source.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Summary.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Reports/Xml.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Ruleset.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Runner.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowRequestSuperglobalSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowShortOpenTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DiscourageGotoSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ForbiddenFunctionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/LowerCaseConstantSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/LowerCaseKeywordSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/LowerCaseTypeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/NoSilencedErrorsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/RequireStrictTypesSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/SAPIUsageSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/SyntaxSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/UpperCaseConstantSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Strings/UnnecessaryStringConcatSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/VersionControl/GitMergeConflictSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/VersionControl/SubversionPropertiesSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/ArbitraryParenthesesSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/DisallowSpaceIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/DisallowTabIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/IncrementDecrementSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/LanguageConstructSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/ScopeIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/WhiteSpace/SpreadOperatorSpacingAfterSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Generic/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/CSS/BrowserSpecificStylesSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/DisallowSelfActionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeOwnSystemSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/IncludeSystemSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Channels/UnusedSystemSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Commenting/FunctionCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/DebugCodeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Debug/FirebugConsoleSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/AssignThisSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/CreateWidgetTypeCallbackSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Objects/DisallowNewWidgetSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/AjaxNullComparisonSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/EvalObjectFactorySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/GetRequestDataSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/PHP/ReturnFunctionValueSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/Sniffs/Strings/JoinStringsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/MySource/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Classes/ClassDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/ClassCommentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FileCommentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/FunctionCommentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Commenting/InlineCommentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/ControlSignatureStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/ControlStructures/MultiLineConditionStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/IncludingFileStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Files/LineLengthStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Formatting/MultiLineAssignmentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionCallSignatureStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/FunctionDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/Functions/ValidDefaultValueStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidClassNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidFunctionNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/NamingConventions/ValidVariableNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ObjectOperatorIndentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeClosingBraceStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs/WhiteSpace/ScopeIndentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Classes/ClassDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/ClassCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FileCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/FunctionCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Commenting/InlineCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/ControlSignatureSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/ControlStructures/MultiLineConditionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Files/IncludingFileSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Formatting/MultiLineAssignmentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionCallSignatureSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/FunctionDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/Functions/ValidDefaultValueSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidClassNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidFunctionNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/NamingConventions/ValidVariableNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ObjectOperatorIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Sniffs/WhiteSpace/ScopeIndentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PEAR/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Classes/ClassDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Files/SideEffectsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs/Methods/CamelCapsMethodNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Classes/ClassDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Files/SideEffectsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Sniffs/Methods/CamelCapsMethodNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR1/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Classes/ClassInstantiationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Functions/NullableTypeDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Keywords/ShortFormTypeKeywordsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Namespaces/CompoundNamespaceDepthStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs/Operators/OperatorSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/AnonClassDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClassInstantiationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/ClosingBraceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Classes/OpeningBraceSpaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/BooleanOperatorPlacementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/ControlStructures/ControlStructureSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/DeclareStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/FileHeaderSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/ImportStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Files/OpenTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/NullableTypeDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Functions/ReturnTypeDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Keywords/ShortFormTypeKeywordsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Namespaces/CompoundNamespaceDepthSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Operators/OperatorSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Properties/ConstantVisibilitySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Sniffs/Traits/UseDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR12/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/ClassDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Classes/PropertyDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ControlStructureSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/ElseIfDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/ControlStructures/SwitchDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Files/EndFileNewlineStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Methods/MethodDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/NamespaceDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs/Namespaces/UseDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/ClassDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Classes/PropertyDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ControlStructureSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/ElseIfDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/ControlStructures/SwitchDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/ClosingTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Files/EndFileNewlineSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionCallSignatureSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/FunctionClosingBraceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Methods/MethodDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/NamespaceDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Sniffs/Namespaces/UseDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/PSR2/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayBracketSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Arrays/ArrayDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/LowercaseClassKeywordsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Classes/SelfMemberReferenceStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/DocCommentAlignmentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Commenting/FunctionCommentThrowTagStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForEachLoopDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/ForLoopDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/ControlStructures/LowercaseDeclarationStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/FunctionDuplicateArgumentStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Functions/LowercaseFunctionKeywordsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Scope/StaticThisUsageStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/Strings/EchoedStringsStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/CastSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/FunctionOpeningBraceStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/LanguageConstructSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ObjectOperatorSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/ScopeKeywordSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs/WhiteSpace/SemicolonSpacingStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayBracketSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Arrays/ArrayDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionClosingBraceSpaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionNameSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ClassDefinitionOpeningBraceSpaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColonSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ColourDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DisallowMultipleStyleDefinitionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateClassDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/DuplicateStyleDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyClassDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/EmptyStyleDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ForbiddenStylesSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/IndentationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/LowercaseStyleDefinitionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/MissingColonSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/NamedColoursSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/OpacitySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/SemicolonSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/CSS/ShorthandSizeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ClassFileNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/DuplicatePropertySniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/LowercaseClassKeywordsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/SelfMemberReferenceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Classes/ValidClassNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/BlockCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClassCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/ClosingDeclarationCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/DocCommentAlignmentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/EmptyCatchCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FileCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/FunctionCommentThrowTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/InlineCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/LongConditionClosingCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/PostStatementCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Commenting/VariableCommentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ControlSignatureSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ElseIfDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForEachLoopDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/ForLoopDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/InlineIfDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/LowercaseDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/ControlStructures/SwitchDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JSLintSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Debug/JavaScriptLintSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Files/FileExtensionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Formatting/OperatorBracketSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationArgumentSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/FunctionDuplicateArgumentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/GlobalFunctionSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/LowercaseFunctionKeywordsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Functions/MultiLineFunctionDeclarationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidFunctionNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/NamingConventions/ValidVariableNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/DisallowObjectStringIndexSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectInstantiationSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Objects/ObjectMemberCommaSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ComparisonOperatorUsageSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/IncrementDecrementUsageSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Operators/ValidLogicalOperatorsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/CommentedOutCodeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowBooleanStatementSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowComparisonAssignmentSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowInlineIfSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowMultipleAssignmentsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DisallowSizeFunctionsInLoopsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/DiscouragedFunctionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EmbeddedPhpSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/EvalSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/GlobalKeywordSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/HeredocSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/InnerFunctionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/LowercasePHPFunctionsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/PHP/NonExecutableCodeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MemberVarScopeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/MethodScopeSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Scope/StaticThisUsageSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/ConcatenationSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/DoubleQuoteUsageSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/Strings/EchoedStringsSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/CastSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionClosingBraceSpaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionOpeningBraceSpaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/FunctionSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LanguageConstructSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/LogicalOperatorSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/MemberVarSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/OperatorSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/PropertyLabelSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeClosingBraceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/ScopeKeywordSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SemicolonSpacingSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Sniffs/WhiteSpace/SuperfluousWhitespaceSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Squiz/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Debug/CodeAnalyzerStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/Files/ClosingTagStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs/NamingConventions/ValidVariableNameStandard.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Debug/CodeAnalyzerSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/Files/ClosingTagSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/Sniffs/NamingConventions/ValidVariableNameSniff.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Standards/Zend/ruleset.xml create mode 100644 vendor/squizlabs/php_codesniffer/src/Tokenizers/CSS.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Tokenizers/Comment.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Tokenizers/JS.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Tokenizers/PHP.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Tokenizers/Tokenizer.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Util/Cache.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Util/Common.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Util/Standards.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Util/Timing.php create mode 100644 vendor/squizlabs/php_codesniffer/src/Util/Tokens.php create mode 100644 vendor/symfony/console/Application.php create mode 100644 vendor/symfony/console/Attribute/AsCommand.php create mode 100644 vendor/symfony/console/CHANGELOG.md create mode 100644 vendor/symfony/console/CI/GithubActionReporter.php create mode 100644 vendor/symfony/console/Color.php create mode 100644 vendor/symfony/console/Command/Command.php create mode 100644 vendor/symfony/console/Command/CompleteCommand.php create mode 100644 vendor/symfony/console/Command/DumpCompletionCommand.php create mode 100644 vendor/symfony/console/Command/HelpCommand.php create mode 100644 vendor/symfony/console/Command/LazyCommand.php create mode 100644 vendor/symfony/console/Command/ListCommand.php create mode 100644 vendor/symfony/console/Command/LockableTrait.php create mode 100644 vendor/symfony/console/Command/SignalableCommandInterface.php create mode 100644 vendor/symfony/console/CommandLoader/CommandLoaderInterface.php create mode 100644 vendor/symfony/console/CommandLoader/ContainerCommandLoader.php create mode 100644 vendor/symfony/console/CommandLoader/FactoryCommandLoader.php create mode 100644 vendor/symfony/console/Completion/CompletionInput.php create mode 100644 vendor/symfony/console/Completion/CompletionSuggestions.php create mode 100644 vendor/symfony/console/Completion/Output/BashCompletionOutput.php create mode 100644 vendor/symfony/console/Completion/Output/CompletionOutputInterface.php create mode 100644 vendor/symfony/console/Completion/Output/FishCompletionOutput.php create mode 100644 vendor/symfony/console/Completion/Output/ZshCompletionOutput.php create mode 100644 vendor/symfony/console/Completion/Suggestion.php create mode 100644 vendor/symfony/console/ConsoleEvents.php create mode 100644 vendor/symfony/console/Cursor.php create mode 100644 vendor/symfony/console/DependencyInjection/AddConsoleCommandPass.php create mode 100644 vendor/symfony/console/Descriptor/ApplicationDescription.php create mode 100644 vendor/symfony/console/Descriptor/Descriptor.php create mode 100644 vendor/symfony/console/Descriptor/DescriptorInterface.php create mode 100644 vendor/symfony/console/Descriptor/JsonDescriptor.php create mode 100644 vendor/symfony/console/Descriptor/MarkdownDescriptor.php create mode 100644 vendor/symfony/console/Descriptor/ReStructuredTextDescriptor.php create mode 100644 vendor/symfony/console/Descriptor/TextDescriptor.php create mode 100644 vendor/symfony/console/Descriptor/XmlDescriptor.php create mode 100644 vendor/symfony/console/Event/ConsoleCommandEvent.php create mode 100644 vendor/symfony/console/Event/ConsoleErrorEvent.php create mode 100644 vendor/symfony/console/Event/ConsoleEvent.php create mode 100644 vendor/symfony/console/Event/ConsoleSignalEvent.php create mode 100644 vendor/symfony/console/Event/ConsoleTerminateEvent.php create mode 100644 vendor/symfony/console/EventListener/ErrorListener.php create mode 100644 vendor/symfony/console/Exception/CommandNotFoundException.php create mode 100644 vendor/symfony/console/Exception/ExceptionInterface.php create mode 100644 vendor/symfony/console/Exception/InvalidArgumentException.php create mode 100644 vendor/symfony/console/Exception/InvalidOptionException.php create mode 100644 vendor/symfony/console/Exception/LogicException.php create mode 100644 vendor/symfony/console/Exception/MissingInputException.php create mode 100644 vendor/symfony/console/Exception/NamespaceNotFoundException.php create mode 100644 vendor/symfony/console/Exception/RuntimeException.php create mode 100644 vendor/symfony/console/Formatter/NullOutputFormatter.php create mode 100644 vendor/symfony/console/Formatter/NullOutputFormatterStyle.php create mode 100644 vendor/symfony/console/Formatter/OutputFormatter.php create mode 100644 vendor/symfony/console/Formatter/OutputFormatterInterface.php create mode 100644 vendor/symfony/console/Formatter/OutputFormatterStyle.php create mode 100644 vendor/symfony/console/Formatter/OutputFormatterStyleInterface.php create mode 100644 vendor/symfony/console/Formatter/OutputFormatterStyleStack.php create mode 100644 vendor/symfony/console/Formatter/WrappableOutputFormatterInterface.php create mode 100644 vendor/symfony/console/Helper/DebugFormatterHelper.php create mode 100644 vendor/symfony/console/Helper/DescriptorHelper.php create mode 100644 vendor/symfony/console/Helper/Dumper.php create mode 100644 vendor/symfony/console/Helper/FormatterHelper.php create mode 100644 vendor/symfony/console/Helper/Helper.php create mode 100644 vendor/symfony/console/Helper/HelperInterface.php create mode 100644 vendor/symfony/console/Helper/HelperSet.php create mode 100644 vendor/symfony/console/Helper/InputAwareHelper.php create mode 100644 vendor/symfony/console/Helper/OutputWrapper.php create mode 100644 vendor/symfony/console/Helper/ProcessHelper.php create mode 100644 vendor/symfony/console/Helper/ProgressBar.php create mode 100644 vendor/symfony/console/Helper/ProgressIndicator.php create mode 100644 vendor/symfony/console/Helper/QuestionHelper.php create mode 100644 vendor/symfony/console/Helper/SymfonyQuestionHelper.php create mode 100644 vendor/symfony/console/Helper/Table.php create mode 100644 vendor/symfony/console/Helper/TableCell.php create mode 100644 vendor/symfony/console/Helper/TableCellStyle.php create mode 100644 vendor/symfony/console/Helper/TableRows.php create mode 100644 vendor/symfony/console/Helper/TableSeparator.php create mode 100644 vendor/symfony/console/Helper/TableStyle.php create mode 100644 vendor/symfony/console/Input/ArgvInput.php create mode 100644 vendor/symfony/console/Input/ArrayInput.php create mode 100644 vendor/symfony/console/Input/Input.php create mode 100644 vendor/symfony/console/Input/InputArgument.php create mode 100644 vendor/symfony/console/Input/InputAwareInterface.php create mode 100644 vendor/symfony/console/Input/InputDefinition.php create mode 100644 vendor/symfony/console/Input/InputInterface.php create mode 100644 vendor/symfony/console/Input/InputOption.php create mode 100644 vendor/symfony/console/Input/StreamableInputInterface.php create mode 100644 vendor/symfony/console/Input/StringInput.php create mode 100644 vendor/symfony/console/LICENSE create mode 100644 vendor/symfony/console/Logger/ConsoleLogger.php create mode 100644 vendor/symfony/console/Output/AnsiColorMode.php create mode 100644 vendor/symfony/console/Output/BufferedOutput.php create mode 100644 vendor/symfony/console/Output/ConsoleOutput.php create mode 100644 vendor/symfony/console/Output/ConsoleOutputInterface.php create mode 100644 vendor/symfony/console/Output/ConsoleSectionOutput.php create mode 100644 vendor/symfony/console/Output/NullOutput.php create mode 100644 vendor/symfony/console/Output/Output.php create mode 100644 vendor/symfony/console/Output/OutputInterface.php create mode 100644 vendor/symfony/console/Output/StreamOutput.php create mode 100644 vendor/symfony/console/Output/TrimmedBufferOutput.php create mode 100644 vendor/symfony/console/PATCHES.txt create mode 100644 vendor/symfony/console/Question/ChoiceQuestion.php create mode 100644 vendor/symfony/console/Question/ConfirmationQuestion.php create mode 100644 vendor/symfony/console/Question/Question.php create mode 100644 vendor/symfony/console/README.md create mode 100644 vendor/symfony/console/Resources/bin/hiddeninput.exe create mode 100644 vendor/symfony/console/Resources/completion.bash create mode 100644 vendor/symfony/console/Resources/completion.fish create mode 100644 vendor/symfony/console/Resources/completion.zsh create mode 100644 vendor/symfony/console/SignalRegistry/SignalRegistry.php create mode 100644 vendor/symfony/console/SingleCommandApplication.php create mode 100644 vendor/symfony/console/Style/OutputStyle.php create mode 100644 vendor/symfony/console/Style/StyleInterface.php create mode 100644 vendor/symfony/console/Style/SymfonyStyle.php create mode 100644 vendor/symfony/console/Terminal.php create mode 100644 vendor/symfony/console/Tester/ApplicationTester.php create mode 100644 vendor/symfony/console/Tester/CommandCompletionTester.php create mode 100644 vendor/symfony/console/Tester/CommandTester.php create mode 100644 vendor/symfony/console/Tester/Constraint/CommandIsSuccessful.php create mode 100644 vendor/symfony/console/Tester/TesterTrait.php create mode 100644 vendor/symfony/console/composer.json create mode 100644 vendor/symfony/deprecation-contracts/CHANGELOG.md create mode 100644 vendor/symfony/deprecation-contracts/LICENSE create mode 100644 vendor/symfony/deprecation-contracts/README.md create mode 100644 vendor/symfony/deprecation-contracts/composer.json create mode 100644 vendor/symfony/deprecation-contracts/function.php create mode 100644 vendor/symfony/filesystem/CHANGELOG.md create mode 100644 vendor/symfony/filesystem/Exception/ExceptionInterface.php create mode 100644 vendor/symfony/filesystem/Exception/FileNotFoundException.php create mode 100644 vendor/symfony/filesystem/Exception/IOException.php create mode 100644 vendor/symfony/filesystem/Exception/IOExceptionInterface.php create mode 100644 vendor/symfony/filesystem/Exception/InvalidArgumentException.php create mode 100644 vendor/symfony/filesystem/Exception/RuntimeException.php create mode 100644 vendor/symfony/filesystem/Filesystem.php create mode 100644 vendor/symfony/filesystem/LICENSE create mode 100644 vendor/symfony/filesystem/Path.php create mode 100644 vendor/symfony/filesystem/README.md create mode 100644 vendor/symfony/filesystem/composer.json create mode 100644 vendor/symfony/finder/CHANGELOG.md create mode 100644 vendor/symfony/finder/Comparator/Comparator.php create mode 100644 vendor/symfony/finder/Comparator/DateComparator.php create mode 100644 vendor/symfony/finder/Comparator/NumberComparator.php create mode 100644 vendor/symfony/finder/Exception/AccessDeniedException.php create mode 100644 vendor/symfony/finder/Exception/DirectoryNotFoundException.php create mode 100644 vendor/symfony/finder/Finder.php create mode 100644 vendor/symfony/finder/Gitignore.php create mode 100644 vendor/symfony/finder/Glob.php create mode 100644 vendor/symfony/finder/Iterator/CustomFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/DateRangeFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/DepthRangeFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/FileTypeFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/FilecontentFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/FilenameFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/LazyIterator.php create mode 100644 vendor/symfony/finder/Iterator/MultiplePcreFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/PathFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/RecursiveDirectoryIterator.php create mode 100644 vendor/symfony/finder/Iterator/SizeRangeFilterIterator.php create mode 100644 vendor/symfony/finder/Iterator/SortableIterator.php create mode 100644 vendor/symfony/finder/Iterator/VcsIgnoredFilterIterator.php create mode 100644 vendor/symfony/finder/LICENSE create mode 100644 vendor/symfony/finder/README.md create mode 100644 vendor/symfony/finder/SplFileInfo.php create mode 100644 vendor/symfony/finder/composer.json create mode 100644 vendor/symfony/options-resolver/CHANGELOG.md create mode 100644 vendor/symfony/options-resolver/Debug/OptionsResolverIntrospector.php create mode 100644 vendor/symfony/options-resolver/Exception/AccessException.php create mode 100644 vendor/symfony/options-resolver/Exception/ExceptionInterface.php create mode 100644 vendor/symfony/options-resolver/Exception/InvalidArgumentException.php create mode 100644 vendor/symfony/options-resolver/Exception/InvalidOptionsException.php create mode 100644 vendor/symfony/options-resolver/Exception/MissingOptionsException.php create mode 100644 vendor/symfony/options-resolver/Exception/NoConfigurationException.php create mode 100644 vendor/symfony/options-resolver/Exception/NoSuchOptionException.php create mode 100644 vendor/symfony/options-resolver/Exception/OptionDefinitionException.php create mode 100644 vendor/symfony/options-resolver/Exception/UndefinedOptionsException.php create mode 100644 vendor/symfony/options-resolver/LICENSE create mode 100644 vendor/symfony/options-resolver/OptionConfigurator.php create mode 100644 vendor/symfony/options-resolver/Options.php create mode 100644 vendor/symfony/options-resolver/OptionsResolver.php create mode 100644 vendor/symfony/options-resolver/README.md create mode 100644 vendor/symfony/options-resolver/composer.json create mode 100644 vendor/symfony/polyfill-mbstring/LICENSE create mode 100644 vendor/symfony/polyfill-mbstring/Mbstring.php create mode 100644 vendor/symfony/polyfill-mbstring/README.md create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/lowerCase.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/titleCaseRegexp.php create mode 100644 vendor/symfony/polyfill-mbstring/Resources/unidata/upperCase.php create mode 100644 vendor/symfony/polyfill-mbstring/bootstrap.php create mode 100644 vendor/symfony/polyfill-mbstring/bootstrap80.php create mode 100644 vendor/symfony/polyfill-mbstring/composer.json create mode 100644 vendor/symfony/polyfill-php80/LICENSE create mode 100644 vendor/symfony/polyfill-php80/Php80.php create mode 100644 vendor/symfony/polyfill-php80/PhpToken.php create mode 100644 vendor/symfony/polyfill-php80/README.md create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/Attribute.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/PhpToken.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/Stringable.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php create mode 100644 vendor/symfony/polyfill-php80/Resources/stubs/ValueError.php create mode 100644 vendor/symfony/polyfill-php80/bootstrap.php create mode 100644 vendor/symfony/polyfill-php80/composer.json create mode 100644 vendor/symfony/polyfill-php81/LICENSE create mode 100644 vendor/symfony/polyfill-php81/Php81.php create mode 100644 vendor/symfony/polyfill-php81/README.md create mode 100644 vendor/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php create mode 100644 vendor/symfony/polyfill-php81/bootstrap.php create mode 100644 vendor/symfony/polyfill-php81/composer.json create mode 100644 vendor/symfony/service-contracts/Attribute/Required.php create mode 100644 vendor/symfony/service-contracts/Attribute/SubscribedService.php create mode 100644 vendor/symfony/service-contracts/CHANGELOG.md create mode 100644 vendor/symfony/service-contracts/LICENSE create mode 100644 vendor/symfony/service-contracts/README.md create mode 100644 vendor/symfony/service-contracts/ResetInterface.php create mode 100644 vendor/symfony/service-contracts/ServiceLocatorTrait.php create mode 100644 vendor/symfony/service-contracts/ServiceProviderInterface.php create mode 100644 vendor/symfony/service-contracts/ServiceSubscriberInterface.php create mode 100644 vendor/symfony/service-contracts/ServiceSubscriberTrait.php create mode 100644 vendor/symfony/service-contracts/Test/ServiceLocatorTest.php create mode 100644 vendor/symfony/service-contracts/Test/ServiceLocatorTestCase.php create mode 100644 vendor/symfony/service-contracts/composer.json create mode 100644 vendor/symplify/coding-standard/LICENSE create mode 100644 vendor/symplify/coding-standard/composer.json create mode 100644 vendor/symplify/coding-standard/config/symplify.php create mode 100644 vendor/symplify/coding-standard/easy-ci.php create mode 100644 vendor/symplify/coding-standard/ecs.php create mode 100644 vendor/symplify/coding-standard/phpstan.neon create mode 100644 vendor/symplify/coding-standard/rector.php create mode 100644 vendor/symplify/coding-standard/src/DocBlock/UselessDocBlockCleaner.php create mode 100644 vendor/symplify/coding-standard/src/Enum/BlockBorderType.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/AbstractSymplifyFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Annotation/RemovePHPStormAnnotationFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayListItemNewlineFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayOpenerAndCloserNewlineFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/ArrayNotation/StandaloneLineInMultilineArrayFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Commenting/ParamReturnAndVarTagMalformsFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Commenting/RemoveUselessDefaultCommentFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/LineLength/LineLengthFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Spacing/MethodChainingNewlineFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Spacing/SpaceAfterCommaHereNowDocFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Spacing/StandaloneLineConstructorParamFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Spacing/StandaloneLinePromotedPropertyFixer.php create mode 100644 vendor/symplify/coding-standard/src/Fixer/Strict/BlankLineAfterStrictTypesFixer.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/ChainMethodCallAnalyzer.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/DocblockRelatedParamNamesResolver.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/FunctionCallNameMatcher.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/HeredocAnalyzer.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/Naming/MethodNameResolver.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/NewlineAnalyzer.php create mode 100644 vendor/symplify/coding-standard/src/TokenAnalyzer/ParamNewliner.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/ArrayAnalyzer.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/BlockFinder.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/CallAnalyzer.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/IndentDetector.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/TokenSkipper.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Arrays/ArrayItemNewliner.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Contract/DocBlock/MalformWorkerInterface.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVarMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVariableDocBlockMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingParamNameMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingVarNameMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameReferenceMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameTypoMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousReturnNameMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousVarNameMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SwitchedTypeAndNameMalformWorker.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Enum/LineKind.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Exception/MissingImplementationException.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Exception/TokenNotFoundException.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/TokenFinder.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/FirstLineLengthResolver.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthCloserTransformer.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthOpenerTransformer.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthResolver.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthTransformer.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensInliner.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensNewliner.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Traverser/ArrayBlockInfoFinder.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Traverser/TokenReverser.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/ValueObject/BlockInfo.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/ValueObject/LineLengthAndPosition.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/ValueObject/TokenKinds.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/ValueObject/Wrapper/FixerWrapper/ArrayWrapper.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/ValueObjectFactory/LineLengthAndPositionFactory.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Whitespace/IndentResolver.php create mode 100644 vendor/symplify/coding-standard/src/TokenRunner/Wrapper/FixerWrapper/ArrayWrapperFactory.php create mode 100644 vendor/symplify/coding-standard/src/ValueObject/BlockInfoMetadata.php create mode 100644 vendor/symplify/coding-standard/src/ValueObject/CodingStandardConfig.php create mode 100644 vendor/symplify/easy-parallel/LICENSE create mode 100644 vendor/symplify/easy-parallel/composer.json create mode 100644 vendor/symplify/easy-parallel/config/config.php create mode 100644 vendor/symplify/easy-parallel/easy-ci.php create mode 100644 vendor/symplify/easy-parallel/ecs.php create mode 100644 vendor/symplify/easy-parallel/phpstan.neon create mode 100644 vendor/symplify/easy-parallel/rector.php create mode 100644 vendor/symplify/easy-parallel/src/CommandLine/WorkerCommandLineFactory.php create mode 100644 vendor/symplify/easy-parallel/src/Contract/SerializableInterface.php create mode 100644 vendor/symplify/easy-parallel/src/CpuCoreCountProvider.php create mode 100644 vendor/symplify/easy-parallel/src/Enum/Action.php create mode 100644 vendor/symplify/easy-parallel/src/Enum/Content.php create mode 100644 vendor/symplify/easy-parallel/src/Enum/ReactCommand.php create mode 100644 vendor/symplify/easy-parallel/src/Enum/ReactEvent.php create mode 100644 vendor/symplify/easy-parallel/src/Exception/ParallelShouldNotHappenException.php create mode 100644 vendor/symplify/easy-parallel/src/FileSystem/FilePathNormalizer.php create mode 100644 vendor/symplify/easy-parallel/src/Reflection/CommandFromReflectionFactory.php create mode 100644 vendor/symplify/easy-parallel/src/ScheduleFactory.php create mode 100644 vendor/symplify/easy-parallel/src/ValueObject/EasyParallelConfig.php create mode 100644 vendor/symplify/easy-parallel/src/ValueObject/ParallelProcess.php create mode 100644 vendor/symplify/easy-parallel/src/ValueObject/ProcessPool.php create mode 100644 vendor/symplify/easy-parallel/src/ValueObject/Schedule.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/LICENSE create mode 100644 vendor/symplify/rule-doc-generator-contracts/composer.json create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Contract/Category/CategoryInfererInterface.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Contract/CodeSampleInterface.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Contract/ConfigurableRuleInterface.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Contract/DocumentedRuleInterface.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Contract/RuleCodeSamplePrinterInterface.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Exception/PoorDocumentationException.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/Exception/ShouldNotHappenException.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/AbstractCodeSample.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/CodeSample.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ComposerJsonAwareCodeSample.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ConfiguredCodeSample.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ExtraFileCodeSample.php create mode 100644 vendor/symplify/rule-doc-generator-contracts/src/ValueObject/RuleDefinition.php create mode 100644 vendor/webmozart/assert/CHANGELOG.md create mode 100644 vendor/webmozart/assert/LICENSE create mode 100644 vendor/webmozart/assert/README.md create mode 100644 vendor/webmozart/assert/composer.json create mode 100644 vendor/webmozart/assert/src/Assert.php create mode 100644 vendor/webmozart/assert/src/InvalidArgumentException.php create mode 100644 vendor/webmozart/assert/src/Mixin.php diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index bec95c4494f..00000000000 --- a/.editorconfig +++ /dev/null @@ -1,9 +0,0 @@ -root = true - -[*] -charset = utf-8 -end_of_line = lf -insert_final_newline = true -trim_trailing_whitespace = true -indent_style = space -indent_size = 4 diff --git a/.gitignore b/.gitignore index 8889565a17c..c4ddab031de 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ -/vendor +# we need the vendor composer.lock -/.phpunit.cache +.phpunit.result.cache # to keep local rector outside git repository diff --git a/bin/ecs b/bin/ecs index 7db94487b0a..8fb45334c9c 100755 --- a/bin/ecs +++ b/bin/ecs @@ -1,4 +1,5 @@ #!/usr/bin/env php -includeCwdVendorAutoloadIfExists(); $autoloadIncluder->loadIfNotLoadedYet(__DIR__ . '/../vendor/scoper-autoload.php'); $autoloadIncluder->autoloadProjectAutoloaderFile('/../../autoload.php'); $autoloadIncluder->includeDependencyOrRepositoryVendorAutoloadIfExists(); $autoloadIncluder->includePhpCodeSnifferAutoload(); - /** * Inspired by https://github.com/rectorphp/rector/pull/2373/files#diff-0fc04a2bb7928cac4ae339d5a8bf67f3 */ @@ -45,112 +39,91 @@ final class AutoloadIncluder // monorepo __DIR__ . '/../../../vendor', ]; - /** * @var string[] */ - private array $alreadyLoadedAutoloadFiles = []; - - public function includeCwdVendorAutoloadIfExists(): void + private $alreadyLoadedAutoloadFiles = []; + public function includeCwdVendorAutoloadIfExists() : void { - $cwdVendorAutoload = getcwd() . '/vendor/autoload.php'; - if (! is_file($cwdVendorAutoload)) { + $cwdVendorAutoload = \getcwd() . '/vendor/autoload.php'; + if (!\is_file($cwdVendorAutoload)) { return; } $this->loadIfNotLoadedYet($cwdVendorAutoload); } - - public function includeDependencyOrRepositoryVendorAutoloadIfExists(): void + public function includeDependencyOrRepositoryVendorAutoloadIfExists() : void { // ECS' vendor is already loaded - if (class_exists('Symplify\EasyCodingStandard\DependencyInjection\NewContainerFactory')) { + if (\class_exists('Symplify\\EasyCodingStandard\\DependencyInjection\\NewContainerFactory')) { return; } - $devVendorAutoload = __DIR__ . '/../vendor/autoload.php'; - if (! is_file($devVendorAutoload)) { + if (!\is_file($devVendorAutoload)) { return; } - $this->loadIfNotLoadedYet($devVendorAutoload); } - - public function autoloadProjectAutoloaderFile(string $file): void + public function autoloadProjectAutoloaderFile(string $file) : void { - $path = dirname(__DIR__) . $file; - if (! is_file($path)) { + $path = \dirname(__DIR__) . $file; + if (!\is_file($path)) { return; } $this->loadIfNotLoadedYet($path); } - - public function includePhpCodeSnifferAutoload(): void + public function includePhpCodeSnifferAutoload() : void { // 1. autoload foreach (self::POSSIBLE_AUTOLOAD_PATHS as $possibleAutoloadPath) { $possiblePhpCodeSnifferAutoloadPath = $possibleAutoloadPath . '/squizlabs/php_codesniffer/autoload.php'; - if (! is_file($possiblePhpCodeSnifferAutoloadPath)) { + if (!\is_file($possiblePhpCodeSnifferAutoloadPath)) { continue; } - require_once $possiblePhpCodeSnifferAutoloadPath; } - // initalize token with INT type, otherwise php-cs-fixer and php-parser breaks - if (! defined('T_MATCH')) { - define('T_MATCH', 5000); + if (!\defined('T_MATCH')) { + \define('T_MATCH', 5000); } - - if (! defined('T_READONLY')) { - define('T_READONLY', 5010); + if (!\defined('T_READONLY')) { + \define('T_READONLY', 5010); } - - if (! defined('T_ENUM')) { - define('T_ENUM', 5015); + if (!\defined('T_ENUM')) { + \define('T_ENUM', 5015); } - // for PHP_CodeSniffer - define('PHP_CODESNIFFER_CBF', false); - define('PHP_CODESNIFFER_VERBOSITY', 0); - + \define('PHP_CODESNIFFER_CBF', \false); + \define('PHP_CODESNIFFER_VERBOSITY', 0); new Tokens(); } - - public function loadIfNotLoadedYet(string $file): void + public function loadIfNotLoadedYet(string $file) : void { - if (! file_exists($file)) { + if (!\file_exists($file)) { return; } - - if (in_array($file, $this->alreadyLoadedAutoloadFiles, true)) { + if (\in_array($file, $this->alreadyLoadedAutoloadFiles, \true)) { return; } - - $realPath = realpath($file); - if (! is_string($realPath)) { + $realPath = \realpath($file); + if (!\is_string($realPath)) { return; } - $this->alreadyLoadedAutoloadFiles[] = $realPath; require_once $file; } } - try { $input = new ArgvInput(); $ecsContainerFactory = new EasyCodingStandardContainerFactory(); $container = $ecsContainerFactory->createFromFromInput($input); -} catch (Throwable $throwable) { +} catch (\Throwable $throwable) { $symfonyStyleFactory = new SymfonyStyleFactory(); $symfonyStyle = $symfonyStyleFactory->create(); - $symfonyStyle->error($throwable->getMessage()); $symfonyStyle->writeln($throwable->getTraceAsString()); exit(Command::FAILURE); } - /** @var EasyCodingStandardConsoleApplication $application */ $application = $container->get(EasyCodingStandardConsoleApplication::class); - $statusCode = $application->run(); exit($statusCode); diff --git a/build/target-repository/bootstrap.php b/bootstrap.php similarity index 100% rename from build/target-repository/bootstrap.php rename to bootstrap.php diff --git a/build/rector-downgrade-php-72.php b/build/rector-downgrade-php-72.php deleted file mode 100644 index a28f9eac4de..00000000000 --- a/build/rector-downgrade-php-72.php +++ /dev/null @@ -1,16 +0,0 @@ -parallel(); - $rectorConfig->sets([DowngradeLevelSetList::DOWN_TO_PHP_72]); - - $rectorConfig->skip([ - '*/Tests/*', - '*/tests/*', - ]); -}; diff --git a/build/target-repository/.gitignore b/build/target-repository/.gitignore deleted file mode 100644 index c4ddab031de..00000000000 --- a/build/target-repository/.gitignore +++ /dev/null @@ -1,10 +0,0 @@ -# we need the vendor -composer.lock - -.phpunit.result.cache - - -# to keep local rector outside git repository -rector-local - -php-scoper.phar diff --git a/build/target-repository/composer.json b/build/target-repository/composer.json deleted file mode 100644 index bb0f6349be3..00000000000 --- a/build/target-repository/composer.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "symplify/easy-coding-standard", - "description": "Use Coding Standard with 0-knowledge of PHP-CS-Fixer and PHP_CodeSniffer", - "license": "MIT", - "keywords": ["static analysis", "code style", "automation", "fixer"], - "bin": [ - "bin/ecs" - ], - "require": { - "php": ">=7.2" - }, - "autoload": { - "files": [ - "bootstrap.php" - ] - }, - "conflict": { - "symplify/coding-standard": "<11.3", - "squizlabs/php_codesniffer": "<3.6", - "friendsofphp/php-cs-fixer": "<3.0" - } -} diff --git a/composer.json b/composer.json index aff014af412..bb0f6349be3 100644 --- a/composer.json +++ b/composer.json @@ -1,95 +1,22 @@ { "name": "symplify/easy-coding-standard", - "description": "Use Coding Standard with 0-knowledge of PHP-CS-Fixer and PHP_CodeSniffer.", + "description": "Use Coding Standard with 0-knowledge of PHP-CS-Fixer and PHP_CodeSniffer", "license": "MIT", - "keywords": [ - "static analysis", - "code style", - "automation", - "fixer" - ], + "keywords": ["static analysis", "code style", "automation", "fixer"], "bin": [ "bin/ecs" ], "require": { - "php": ">=8.1", - "composer/xdebug-handler": "^3.0", - "friendsofphp/php-cs-fixer": "^3.22.0", - "illuminate/container": "^10.15", - "nette/utils": "^3.2", - "sebastian/diff": "^5.0", - "squizlabs/php_codesniffer": "^3.7.2", - "symfony/console": "^6.3", - "symfony/finder": "^6.3", - "symplify/coding-standard": "^12.0", - "symplify/easy-parallel": "^11.1", - "webmozart/assert": "^1.11" - }, - "require-dev": { - "cweagans/composer-patches": "^1.7", - "php-parallel-lint/php-parallel-lint": "^1.3", - "phpstan/extension-installer": "^1.2", - "phpstan/phpstan": "^1.10.19", - "phpstan/phpstan-phpunit": "^1.3", - "phpstan/phpstan-symfony": "^1.2", - "phpstan/phpstan-webmozart-assert": "^1.2", - "phpunit/phpunit": "^10.0", - "rector/rector": "^0.17.1", - "symplify/easy-ci": "^11.1", - "symplify/phpstan-extensions": "^11.2", - "symplify/vendor-patches": "^11.2", - "tomasvotruba/class-leak": "0.0.22.72", - "tracy/tracy": "^2.9" + "php": ">=7.2" }, "autoload": { - "psr-4": { - "Symplify\\EasyCodingStandard\\": [ - "src", - "packages" - ] - } - }, - "autoload-dev": { - "psr-4": { - "Symplify\\EasyCodingStandard\\Tests\\": [ - "tests", - "packages-tests" - ] - }, "files": [ - "tests/functions.php" + "bootstrap.php" ] }, - "config": { - "sort-packages": true, - "platform-check": false, - "allow-plugins": { - "cweagans/composer-patches": true, - "phpstan/extension-installer": true - } - }, - "scripts": { - "check-cs": "bin/ecs check --ansi", - "fix-cs": "bin/ecs check --fix --ansi", - "phpstan": "vendor/bin/phpstan analyse --ansi --error-format symplify", - "rector": "vendor/bin/rector process --dry-run --ansi" - }, - "replace": { - "symfony/polyfill-intl-grapheme": "*", - "symfony/polyfill-ctype": "*", - "symfony/polyfill-intl-normalizer": "*", - "symfony/event-dispatcher": "6.*", - "symfony/process": "6.*", - "symfony/stopwatch": "6.*", - "symfony/string": "6.*" - }, - "minimum-stability": "dev", - "prefer-stable": true, - "extra": { - "patches": { - "symfony/console": [ - "patches/symfony-console-helper-helper-php.patch" - ] - } + "conflict": { + "symplify/coding-standard": "<11.3", + "squizlabs/php_codesniffer": "<3.6", + "friendsofphp/php-cs-fixer": "<3.0" } -} \ No newline at end of file +} diff --git a/config/config.php b/config/config.php index 0ca047c7a21..9f7735ef4ba 100644 --- a/config/config.php +++ b/config/config.php @@ -1,28 +1,23 @@ indentation(Option::INDENTATION_SPACES); - $ecsConfig->lineEnding(PHP_EOL); - - $cacheDirectory = sys_get_temp_dir() . '/changed_files_detector'; + $ecsConfig->lineEnding(\PHP_EOL); + $cacheDirectory = \sys_get_temp_dir() . '/changed_files_detector'; if (StaticVersionResolver::PACKAGE_VERSION !== '@package_version@') { $cacheDirectory .= '_' . StaticVersionResolver::PACKAGE_VERSION; } - $ecsConfig->cacheDirectory($cacheDirectory); - // make cache individual per project - $cacheNamespace = str_replace(DIRECTORY_SEPARATOR, '_', getcwd()); + $cacheNamespace = \str_replace(\DIRECTORY_SEPARATOR, '_', \getcwd()); $ecsConfig->cacheNamespace($cacheNamespace); - $ecsConfig->parallel(); - $ecsConfig->paths([]); $ecsConfig->skip([]); $ecsConfig->fileExtensions(['php']); diff --git a/config/set/clean-code.php b/config/set/clean-code.php index eebafe6687c..fc8d07e408c 100644 --- a/config/set/clean-code.php +++ b/config/set/clean-code.php @@ -1,6 +1,7 @@ ruleWithConfiguration(ArraySyntaxFixer::class, [ - 'syntax' => 'short', - ]); - - $ecsConfig->rules([ - ParamReturnAndVarTagMalformsFixer::class, - NoUnusedImportsFixer::class, - OrderedImportsFixer::class, - NoEmptyStatementFixer::class, - ProtectedToPrivateFixer::class, - NoUnneededControlParenthesesFixer::class, - NoUnneededCurlyBracesFixer::class, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->ruleWithConfiguration(ArraySyntaxFixer::class, ['syntax' => 'short']); + $ecsConfig->rules([ParamReturnAndVarTagMalformsFixer::class, NoUnusedImportsFixer::class, OrderedImportsFixer::class, NoEmptyStatementFixer::class, ProtectedToPrivateFixer::class, NoUnneededControlParenthesesFixer::class, NoUnneededCurlyBracesFixer::class]); }; diff --git a/config/set/common.php b/config/set/common.php index 12d6f86f388..4c9d57fd9a4 100644 --- a/config/set/common.php +++ b/config/set/common.php @@ -1,19 +1,10 @@ sets([ - SetList::ARRAY, - SetList::COMMENTS, - SetList::CONTROL_STRUCTURES, - SetList::DOCBLOCK, - SetList::NAMESPACES, - SetList::PHPUNIT, - SetList::SPACES, - SetList::STRICT, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->sets([SetList::ARRAY, SetList::COMMENTS, SetList::CONTROL_STRUCTURES, SetList::DOCBLOCK, SetList::NAMESPACES, SetList::PHPUNIT, SetList::SPACES, SetList::STRICT]); }; diff --git a/config/set/common/array.php b/config/set/common/array.php index 7d4c4122402..d185c2f2771 100644 --- a/config/set/common/array.php +++ b/config/set/common/array.php @@ -1,6 +1,7 @@ rules([ - NoWhitespaceBeforeCommaInArrayFixer::class, - ArrayOpenerAndCloserNewlineFixer::class, - ArrayIndentationFixer::class, - TrimArraySpacesFixer::class, - WhitespaceAfterCommaInArrayFixer::class, - ArrayListItemNewlineFixer::class, - StandaloneLineInMultilineArrayFixer::class, - ]); - +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([NoWhitespaceBeforeCommaInArrayFixer::class, ArrayOpenerAndCloserNewlineFixer::class, ArrayIndentationFixer::class, TrimArraySpacesFixer::class, WhitespaceAfterCommaInArrayFixer::class, ArrayListItemNewlineFixer::class, StandaloneLineInMultilineArrayFixer::class]); // commas - $ecsConfig->ruleWithConfiguration(NoTrailingCommaInSinglelineFixer::class, [ - 'elements' => ['arguments', 'array_destructuring', 'array', 'group_import'], - ]); - - $ecsConfig->ruleWithConfiguration(TrailingCommaInMultilineFixer::class, [ - 'elements' => [TrailingCommaInMultilineFixer::ELEMENTS_ARRAYS], - ]); - - $ecsConfig->ruleWithConfiguration(ArraySyntaxFixer::class, [ - 'syntax' => 'short', - ]); + $ecsConfig->ruleWithConfiguration(NoTrailingCommaInSinglelineFixer::class, ['elements' => ['arguments', 'array_destructuring', 'array', 'group_import']]); + $ecsConfig->ruleWithConfiguration(TrailingCommaInMultilineFixer::class, ['elements' => [TrailingCommaInMultilineFixer::ELEMENTS_ARRAYS]]); + $ecsConfig->ruleWithConfiguration(ArraySyntaxFixer::class, ['syntax' => 'short']); }; diff --git a/config/set/common/comments.php b/config/set/common/comments.php index c4867389c85..ef434706e5e 100644 --- a/config/set/common/comments.php +++ b/config/set/common/comments.php @@ -1,10 +1,10 @@ rule(GitMergeConflictSniff::class); }; diff --git a/config/set/common/control-structures.php b/config/set/common/control-structures.php index 52d48864492..64499779d26 100644 --- a/config/set/common/control-structures.php +++ b/config/set/common/control-structures.php @@ -1,6 +1,7 @@ rules([ - PhpUnitMethodCasingFixer::class, - FunctionToConstantFixer::class, - ExplicitStringVariableFixer::class, - ExplicitIndirectVariableFixer::class, - NewWithBracesFixer::class, - StandardizeIncrementFixer::class, - SelfAccessorFixer::class, - MagicConstantCasingFixer::class, - AssignmentInConditionSniff::class, - NoUselessElseFixer::class, - SingleQuoteFixer::class, - OrderedClassElementsFixer::class, - ]); - - $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, [ - 'elements' => ['const', 'property'], - ]); - - $ecsConfig->ruleWithConfiguration(ClassDefinitionFixer::class, [ - 'single_line' => true, - ]); - - $ecsConfig->ruleWithConfiguration(YodaStyleFixer::class, [ - 'equal' => false, - 'identical' => false, - 'less_and_greater' => false, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([PhpUnitMethodCasingFixer::class, FunctionToConstantFixer::class, ExplicitStringVariableFixer::class, ExplicitIndirectVariableFixer::class, NewWithBracesFixer::class, StandardizeIncrementFixer::class, SelfAccessorFixer::class, MagicConstantCasingFixer::class, AssignmentInConditionSniff::class, NoUselessElseFixer::class, SingleQuoteFixer::class, OrderedClassElementsFixer::class]); + $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, ['elements' => ['const', 'property']]); + $ecsConfig->ruleWithConfiguration(ClassDefinitionFixer::class, ['single_line' => \true]); + $ecsConfig->ruleWithConfiguration(YodaStyleFixer::class, ['equal' => \false, 'identical' => \false, 'less_and_greater' => \false]); }; diff --git a/config/set/common/docblock.php b/config/set/common/docblock.php index a43e3d393b7..674bf5b48ab 100644 --- a/config/set/common/docblock.php +++ b/config/set/common/docblock.php @@ -1,6 +1,7 @@ rules([ - PhpdocLineSpanFixer::class, - NoTrailingWhitespaceInCommentFixer::class, - PhpdocTrimConsecutiveBlankLineSeparationFixer::class, - PhpdocTrimFixer::class, - NoEmptyPhpdocFixer::class, - PhpdocNoEmptyReturnFixer::class, - PhpdocIndentFixer::class, - PhpdocTypesFixer::class, - PhpdocReturnSelfReferenceFixer::class, - PhpdocVarWithoutNameFixer::class, - RemoveUselessDefaultCommentFixer::class, - ]); - - $ecsConfig->ruleWithConfiguration(NoSuperfluousPhpdocTagsFixer::class, [ - 'remove_inheritdoc' => true, - 'allow_mixed' => true, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([PhpdocLineSpanFixer::class, NoTrailingWhitespaceInCommentFixer::class, PhpdocTrimConsecutiveBlankLineSeparationFixer::class, PhpdocTrimFixer::class, NoEmptyPhpdocFixer::class, PhpdocNoEmptyReturnFixer::class, PhpdocIndentFixer::class, PhpdocTypesFixer::class, PhpdocReturnSelfReferenceFixer::class, PhpdocVarWithoutNameFixer::class, RemoveUselessDefaultCommentFixer::class]); + $ecsConfig->ruleWithConfiguration(NoSuperfluousPhpdocTagsFixer::class, ['remove_inheritdoc' => \true, 'allow_mixed' => \true]); }; diff --git a/config/set/common/namespaces.php b/config/set/common/namespaces.php index 34f7e69583f..1397a0dbd36 100644 --- a/config/set/common/namespaces.php +++ b/config/set/common/namespaces.php @@ -1,16 +1,12 @@ rules([ - NoUnusedImportsFixer::class, - OrderedImportsFixer::class, - SingleBlankLineBeforeNamespaceFixer::class, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([NoUnusedImportsFixer::class, OrderedImportsFixer::class, SingleBlankLineBeforeNamespaceFixer::class]); }; diff --git a/config/set/common/phpunit.php b/config/set/common/phpunit.php index 6cc850aafef..58b6f752a3a 100644 --- a/config/set/common/phpunit.php +++ b/config/set/common/phpunit.php @@ -1,11 +1,11 @@ rules([PhpUnitTestAnnotationFixer::class, PhpUnitSetUpTearDownVisibilityFixer::class]); }; diff --git a/config/set/common/spaces.php b/config/set/common/spaces.php index 294c5d06ea5..2e8ed4a84be 100644 --- a/config/set/common/spaces.php +++ b/config/set/common/spaces.php @@ -1,6 +1,7 @@ rules([ - StandaloneLinePromotedPropertyFixer::class, - BlankLineAfterOpeningTagFixer::class, - MethodChainingIndentationFixer::class, - NotOperatorWithSuccessorSpaceFixer::class, - CastSpacesFixer::class, - ClassAttributesSeparationFixer::class, - SingleTraitInsertPerStatementFixer::class, - NoBlankLinesAfterClassOpeningFixer::class, - NoSinglelineWhitespaceBeforeSemicolonsFixer::class, - PhpdocSingleLineVarSpacingFixer::class, - NoLeadingNamespaceWhitespaceFixer::class, - NoSpacesAroundOffsetFixer::class, - NoWhitespaceInBlankLineFixer::class, - ReturnTypeDeclarationFixer::class, - SpaceAfterSemicolonFixer::class, - TernaryOperatorSpacesFixer::class, - MethodArgumentSpaceFixer::class, - LanguageConstructSpacingSniff::class, - ]); - - $ecsConfig->ruleWithConfiguration(ClassAttributesSeparationFixer::class, [ - 'elements' => [ - 'const' => 'one', - 'property' => 'one', - 'method' => 'one', - ], - ]); - - $ecsConfig->ruleWithConfiguration(ConcatSpaceFixer::class, [ - 'spacing' => 'one', - ]); - - $ecsConfig->ruleWithConfiguration(SuperfluousWhitespaceSniff::class, [ - 'ignoreBlankLines' => false, - ]); - - $ecsConfig->ruleWithConfiguration(BinaryOperatorSpacesFixer::class, [ - 'operators' => [ - '=>' => 'single_space', - '=' => 'single_space', - ], - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([StandaloneLinePromotedPropertyFixer::class, BlankLineAfterOpeningTagFixer::class, MethodChainingIndentationFixer::class, NotOperatorWithSuccessorSpaceFixer::class, CastSpacesFixer::class, ClassAttributesSeparationFixer::class, SingleTraitInsertPerStatementFixer::class, NoBlankLinesAfterClassOpeningFixer::class, NoSinglelineWhitespaceBeforeSemicolonsFixer::class, PhpdocSingleLineVarSpacingFixer::class, NoLeadingNamespaceWhitespaceFixer::class, NoSpacesAroundOffsetFixer::class, NoWhitespaceInBlankLineFixer::class, ReturnTypeDeclarationFixer::class, SpaceAfterSemicolonFixer::class, TernaryOperatorSpacesFixer::class, MethodArgumentSpaceFixer::class, LanguageConstructSpacingSniff::class]); + $ecsConfig->ruleWithConfiguration(ClassAttributesSeparationFixer::class, ['elements' => ['const' => 'one', 'property' => 'one', 'method' => 'one']]); + $ecsConfig->ruleWithConfiguration(ConcatSpaceFixer::class, ['spacing' => 'one']); + $ecsConfig->ruleWithConfiguration(SuperfluousWhitespaceSniff::class, ['ignoreBlankLines' => \false]); + $ecsConfig->ruleWithConfiguration(BinaryOperatorSpacesFixer::class, ['operators' => ['=>' => 'single_space', '=' => 'single_space']]); }; diff --git a/config/set/common/strict.php b/config/set/common/strict.php index d85bea1a590..d1e76dc19a0 100644 --- a/config/set/common/strict.php +++ b/config/set/common/strict.php @@ -1,18 +1,13 @@ rules([ - StrictComparisonFixer::class, - IsNullFixer::class, - StrictParamFixer::class, - DeclareStrictTypesFixer::class, - ]); +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->rules([StrictComparisonFixer::class, IsNullFixer::class, StrictParamFixer::class, DeclareStrictTypesFixer::class]); }; diff --git a/config/set/doctrine-annotations.php b/config/set/doctrine-annotations.php index 01a624c9086..0d1dbb90d83 100644 --- a/config/set/doctrine-annotations.php +++ b/config/set/doctrine-annotations.php @@ -1,21 +1,14 @@ ruleWithConfiguration(DoctrineAnnotationIndentationFixer::class, [ - 'indent_mixed_lines' => true, - ]); - - $ecsConfig->ruleWithConfiguration(DoctrineAnnotationSpacesFixer::class, [ - 'after_array_assignments_equals' => false, - 'before_array_assignments_equals' => false, - ]); - +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->ruleWithConfiguration(DoctrineAnnotationIndentationFixer::class, ['indent_mixed_lines' => \true]); + $ecsConfig->ruleWithConfiguration(DoctrineAnnotationSpacesFixer::class, ['after_array_assignments_equals' => \false, 'before_array_assignments_equals' => \false]); $ecsConfig->rule(DoctrineAnnotationArrayAssignmentFixer::class); }; diff --git a/config/set/laravel.php b/config/set/laravel.php index 38353d82d24..c5761ced21d 100644 --- a/config/set/laravel.php +++ b/config/set/laravel.php @@ -1,6 +1,7 @@ rule(ArrayIndentationFixer::class); - $ecsConfig->rulesWithConfiguration([ - ArraySyntaxFixer::class => [ - 'syntax' => 'short', - ], - BinaryOperatorSpacesFixer::class => [ - 'default' => 'single_space', - ], - ]); + $ecsConfig->rulesWithConfiguration([ArraySyntaxFixer::class => ['syntax' => 'short'], BinaryOperatorSpacesFixer::class => ['default' => 'single_space']]); $ecsConfig->rules([BlankLineAfterNamespaceFixer::class, BlankLineAfterOpeningTagFixer::class]); - $ecsConfig->ruleWithConfiguration(BlankLineBeforeStatementFixer::class, [ - 'statements' => ['continue', 'return'], - ]); + $ecsConfig->ruleWithConfiguration(BlankLineBeforeStatementFixer::class, ['statements' => ['continue', 'return']]); $ecsConfig->rule(CastSpacesFixer::class); - $ecsConfig->rulesWithConfiguration([ - ClassAttributesSeparationFixer::class => [ - 'elements' => [ - 'const' => 'one', - 'method' => 'one', - 'property' => 'one', - 'trait_import' => 'none', - ], - ], - ClassDefinitionFixer::class => [ - 'multi_line_extends_each_single_line' => true, - 'single_item_single_line' => true, - 'single_line' => true, - ], - ]); + $ecsConfig->rulesWithConfiguration([ClassAttributesSeparationFixer::class => ['elements' => ['const' => 'one', 'method' => 'one', 'property' => 'one', 'trait_import' => 'none']], ClassDefinitionFixer::class => ['multi_line_extends_each_single_line' => \true, 'single_item_single_line' => \true, 'single_line' => \true]]); $ecsConfig->rules([CleanNamespaceFixer::class, CompactNullableTypehintFixer::class]); - $ecsConfig->rulesWithConfiguration([ - ConcatSpaceFixer::class => [ - 'spacing' => 'none', - ], - ConstantCaseFixer::class => [ - 'case' => 'lower', - ], - ]); + $ecsConfig->rulesWithConfiguration([ConcatSpaceFixer::class => ['spacing' => 'none'], ConstantCaseFixer::class => ['case' => 'lower']]); $ecsConfig->rule(ControlStructureBracesFixer::class); - $ecsConfig->rulesWithConfiguration([ - ControlStructureContinuationPositionFixer::class => [ - 'position' => 'same_line', - ], - CurlyBracesPositionFixer::class => [ - 'control_structures_opening_brace' => 'same_line', - 'functions_opening_brace' => 'next_line_unless_newline_at_signature_end', - 'anonymous_functions_opening_brace' => 'same_line', - 'classes_opening_brace' => 'next_line_unless_newline_at_signature_end', - 'anonymous_classes_opening_brace' => 'next_line_unless_newline_at_signature_end', - 'allow_single_line_empty_anonymous_classes' => false, - 'allow_single_line_anonymous_functions' => false, - ], - ]); - $ecsConfig->rules([ - DeclareEqualNormalizeFixer::class, - DeclareParenthesesFixer::class, - ElseifFixer::class, - EncodingFixer::class, - FullOpeningTagFixer::class, - FullyQualifiedStrictTypesFixer::class, - FunctionDeclarationFixer::class, - FunctionTypehintSpaceFixer::class, - GeneralPhpdocTagRenameFixer::class, - HeredocToNowdocFixer::class, - IncludeFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(IncrementStyleFixer::class, [ - 'style' => 'post', - ]); - $ecsConfig->rules([ - IndentationTypeFixer::class, - IntegerLiteralCaseFixer::class, - LambdaNotUsedImportFixer::class, - LinebreakAfterOpeningTagFixer::class, - LineEndingFixer::class, - ListSyntaxFixer::class, - LowercaseCastFixer::class, - LowercaseKeywordsFixer::class, - LowercaseStaticReferenceFixer::class, - MagicMethodCasingFixer::class, - MagicConstantCasingFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(MethodArgumentSpaceFixer::class, [ - 'on_multiline' => 'ignore', - ]); + $ecsConfig->rulesWithConfiguration([ControlStructureContinuationPositionFixer::class => ['position' => 'same_line'], CurlyBracesPositionFixer::class => ['control_structures_opening_brace' => 'same_line', 'functions_opening_brace' => 'next_line_unless_newline_at_signature_end', 'anonymous_functions_opening_brace' => 'same_line', 'classes_opening_brace' => 'next_line_unless_newline_at_signature_end', 'anonymous_classes_opening_brace' => 'next_line_unless_newline_at_signature_end', 'allow_single_line_empty_anonymous_classes' => \false, 'allow_single_line_anonymous_functions' => \false]]); + $ecsConfig->rules([DeclareEqualNormalizeFixer::class, DeclareParenthesesFixer::class, ElseifFixer::class, EncodingFixer::class, FullOpeningTagFixer::class, FullyQualifiedStrictTypesFixer::class, FunctionDeclarationFixer::class, FunctionTypehintSpaceFixer::class, GeneralPhpdocTagRenameFixer::class, HeredocToNowdocFixer::class, IncludeFixer::class]); + $ecsConfig->ruleWithConfiguration(IncrementStyleFixer::class, ['style' => 'post']); + $ecsConfig->rules([IndentationTypeFixer::class, IntegerLiteralCaseFixer::class, LambdaNotUsedImportFixer::class, LinebreakAfterOpeningTagFixer::class, LineEndingFixer::class, ListSyntaxFixer::class, LowercaseCastFixer::class, LowercaseKeywordsFixer::class, LowercaseStaticReferenceFixer::class, MagicMethodCasingFixer::class, MagicConstantCasingFixer::class]); + $ecsConfig->ruleWithConfiguration(MethodArgumentSpaceFixer::class, ['on_multiline' => 'ignore']); $ecsConfig->rule(MethodChainingIndentationFixer::class); - $ecsConfig->ruleWithConfiguration(MultilineWhitespaceBeforeSemicolonsFixer::class, [ - 'strategy' => 'no_multi_line', - ]); - $ecsConfig->rules([ - NativeFunctionCasingFixer::class, - NativeFunctionTypeDeclarationCasingFixer::class, - NoAliasFunctionsFixer::class, - NoAliasLanguageConstructCallFixer::class, - NoAlternativeSyntaxFixer::class, - NoBinaryStringFixer::class, - NoBlankLinesAfterClassOpeningFixer::class, - NoBlankLinesAfterPhpdocFixer::class, - NoClosingTagFixer::class, - NoEmptyPhpdocFixer::class, - NoEmptyStatementFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(NoExtraBlankLinesFixer::class, [ - 'tokens' => ['extra', 'throw', 'use'], - ]); + $ecsConfig->ruleWithConfiguration(MultilineWhitespaceBeforeSemicolonsFixer::class, ['strategy' => 'no_multi_line']); + $ecsConfig->rules([NativeFunctionCasingFixer::class, NativeFunctionTypeDeclarationCasingFixer::class, NoAliasFunctionsFixer::class, NoAliasLanguageConstructCallFixer::class, NoAlternativeSyntaxFixer::class, NoBinaryStringFixer::class, NoBlankLinesAfterClassOpeningFixer::class, NoBlankLinesAfterPhpdocFixer::class, NoClosingTagFixer::class, NoEmptyPhpdocFixer::class, NoEmptyStatementFixer::class]); + $ecsConfig->ruleWithConfiguration(NoExtraBlankLinesFixer::class, ['tokens' => ['extra', 'throw', 'use']]); $ecsConfig->rules([NoLeadingImportSlashFixer::class, NoLeadingNamespaceWhitespaceFixer::class]); - $ecsConfig->ruleWithConfiguration(NoMixedEchoPrintFixer::class, [ - 'use' => 'echo', - ]); - $ecsConfig->rules([ - NoMultilineWhitespaceAroundDoubleArrowFixer::class, - NoMultipleStatementsPerLineFixer::class, - NoShortBoolCastFixer::class, - NoSinglelineWhitespaceBeforeSemicolonsFixer::class, - NoSpacesAfterFunctionNameFixer::class, - NoSpaceAroundDoubleColonFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(NoSpacesAroundOffsetFixer::class, [ - 'positions' => ['inside', 'outside'], - ]); + $ecsConfig->ruleWithConfiguration(NoMixedEchoPrintFixer::class, ['use' => 'echo']); + $ecsConfig->rules([NoMultilineWhitespaceAroundDoubleArrowFixer::class, NoMultipleStatementsPerLineFixer::class, NoShortBoolCastFixer::class, NoSinglelineWhitespaceBeforeSemicolonsFixer::class, NoSpacesAfterFunctionNameFixer::class, NoSpaceAroundDoubleColonFixer::class]); + $ecsConfig->ruleWithConfiguration(NoSpacesAroundOffsetFixer::class, ['positions' => ['inside', 'outside']]); $ecsConfig->rule(NoSpacesInsideParenthesisFixer::class); - $ecsConfig->ruleWithConfiguration(NoSuperfluousPhpdocTagsFixer::class, [ - 'allow_mixed' => true, - 'allow_unused_params' => true, - ]); - $ecsConfig->rules([ - NoTrailingCommaInSinglelineFixer::class, - NoTrailingWhitespaceFixer::class, - NoTrailingWhitespaceInCommentFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(NoUnneededControlParenthesesFixer::class, [ - 'statements' => ['break', 'clone', 'continue', 'echo_print', 'return', 'switch_case', 'yield'], - ]); - $ecsConfig->rules([ - NoUnneededCurlyBracesFixer::class, - NoUnreachableDefaultArgumentValueFixer::class, - NoUnsetCastFixer::class, - NoUnusedImportsFixer::class, - NoUselessReturnFixer::class, - NoWhitespaceBeforeCommaInArrayFixer::class, - NoWhitespaceInBlankLineFixer::class, - NormalizeIndexBraceFixer::class, - NotOperatorWithSuccessorSpaceFixer::class, - ObjectOperatorWithoutWhitespaceFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(OrderedImportsFixer::class, [ - 'sort_algorithm' => 'alpha', - ]); - $ecsConfig->rules([ - PhpdocIndentFixer::class, - PhpdocInlineTagNormalizerFixer::class, - PhpdocNoAccessFixer::class, - PhpdocNoPackageFixer::class, - PhpdocNoUselessInheritdocFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(PhpdocOrderFixer::class, [ - 'order' => ['param', 'return', 'throws'], - ]); + $ecsConfig->ruleWithConfiguration(NoSuperfluousPhpdocTagsFixer::class, ['allow_mixed' => \true, 'allow_unused_params' => \true]); + $ecsConfig->rules([NoTrailingCommaInSinglelineFixer::class, NoTrailingWhitespaceFixer::class, NoTrailingWhitespaceInCommentFixer::class]); + $ecsConfig->ruleWithConfiguration(NoUnneededControlParenthesesFixer::class, ['statements' => ['break', 'clone', 'continue', 'echo_print', 'return', 'switch_case', 'yield']]); + $ecsConfig->rules([NoUnneededCurlyBracesFixer::class, NoUnreachableDefaultArgumentValueFixer::class, NoUnsetCastFixer::class, NoUnusedImportsFixer::class, NoUselessReturnFixer::class, NoWhitespaceBeforeCommaInArrayFixer::class, NoWhitespaceInBlankLineFixer::class, NormalizeIndexBraceFixer::class, NotOperatorWithSuccessorSpaceFixer::class, ObjectOperatorWithoutWhitespaceFixer::class]); + $ecsConfig->ruleWithConfiguration(OrderedImportsFixer::class, ['sort_algorithm' => 'alpha']); + $ecsConfig->rules([PhpdocIndentFixer::class, PhpdocInlineTagNormalizerFixer::class, PhpdocNoAccessFixer::class, PhpdocNoPackageFixer::class, PhpdocNoUselessInheritdocFixer::class]); + $ecsConfig->ruleWithConfiguration(PhpdocOrderFixer::class, ['order' => ['param', 'return', 'throws']]); $ecsConfig->rule(PhpdocScalarFixer::class); - $ecsConfig->ruleWithConfiguration(PhpdocSeparationFixer::class, [ - 'groups' => [ - ['deprecated', 'link', 'see', 'since'], - ['author', 'copyright', 'license'], - ['category', 'package', 'subpackage'], - ['property', 'property-read', 'property-write'], - ['param', 'return'], - ], - ]); + $ecsConfig->ruleWithConfiguration(PhpdocSeparationFixer::class, ['groups' => [['deprecated', 'link', 'see', 'since'], ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write'], ['param', 'return']]]); $ecsConfig->rule(PhpdocSingleLineVarSpacingFixer::class); - $ecsConfig->ruleWithConfiguration(PhpdocTagTypeFixer::class, [ - 'tags' => [ - 'inheritdoc' => 'inline', - ], - ]); + $ecsConfig->ruleWithConfiguration(PhpdocTagTypeFixer::class, ['tags' => ['inheritdoc' => 'inline']]); $ecsConfig->rules([PhpdocTrimFixer::class, PhpdocTypesFixer::class, PhpdocVarWithoutNameFixer::class]); - $ecsConfig->ruleWithConfiguration(ReturnTypeDeclarationFixer::class, [ - 'space_before' => 'none', - ]); - $ecsConfig->rules([ - SelfStaticAccessorFixer::class, - ShortScalarCastFixer::class, - SingleBlankLineAtEofFixer::class, - SingleBlankLineBeforeNamespaceFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, [ - 'elements' => ['const', 'property'], - ]); + $ecsConfig->ruleWithConfiguration(ReturnTypeDeclarationFixer::class, ['space_before' => 'none']); + $ecsConfig->rules([SelfStaticAccessorFixer::class, ShortScalarCastFixer::class, SingleBlankLineAtEofFixer::class, SingleBlankLineBeforeNamespaceFixer::class]); + $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, ['elements' => ['const', 'property']]); $ecsConfig->rules([SingleImportPerStatementFixer::class, SingleLineAfterImportsFixer::class]); - $ecsConfig->ruleWithConfiguration(SingleLineCommentStyleFixer::class, [ - 'comment_types' => ['hash'], - ]); - $ecsConfig->rules([ - SingleQuoteFixer::class, - SingleSpaceAroundConstructFixer::class, - SpaceAfterSemicolonFixer::class, - StandardizeNotEqualsFixer::class, - SwitchCaseSemicolonToColonFixer::class, - SwitchCaseSpaceFixer::class, - TernaryOperatorSpacesFixer::class, - ]); - $ecsConfig->ruleWithConfiguration(TrailingCommaInMultilineFixer::class, [ - 'elements' => ['arrays'], - ]); + $ecsConfig->ruleWithConfiguration(SingleLineCommentStyleFixer::class, ['comment_types' => ['hash']]); + $ecsConfig->rules([SingleQuoteFixer::class, SingleSpaceAroundConstructFixer::class, SpaceAfterSemicolonFixer::class, StandardizeNotEqualsFixer::class, SwitchCaseSemicolonToColonFixer::class, SwitchCaseSpaceFixer::class, TernaryOperatorSpacesFixer::class]); + $ecsConfig->ruleWithConfiguration(TrailingCommaInMultilineFixer::class, ['elements' => ['arrays']]); $ecsConfig->rules([TrimArraySpacesFixer::class, TypesSpacesFixer::class, UnaryOperatorSpacesFixer::class]); - $ecsConfig->ruleWithConfiguration(VisibilityRequiredFixer::class, [ - 'elements' => ['method', 'property'], - ]); + $ecsConfig->ruleWithConfiguration(VisibilityRequiredFixer::class, ['elements' => ['method', 'property']]); $ecsConfig->rule(WhitespaceAfterCommaInArrayFixer::class); - // any rules marked as 'false' are skipped $ecsConfig->skip([ PhpdocSummaryFixer::class, diff --git a/config/set/psr12.php b/config/set/psr12.php index a77b1606cfd..683fee73a7d 100644 --- a/config/set/psr12.php +++ b/config/set/psr12.php @@ -1,6 +1,7 @@ ruleWithConfiguration(OrderedImportsFixer::class, [ - 'imports_order' => ['class', 'function', 'const'], - ]); - - $ecsConfig->ruleWithConfiguration(DeclareEqualNormalizeFixer::class, [ - 'space' => 'none', - ]); - - $ecsConfig->ruleWithConfiguration(BracesFixer::class, [ - 'allow_single_line_closure' => false, - 'position_after_functions_and_oop_constructs' => 'next', - 'position_after_control_structures' => 'same', - 'position_after_anonymous_constructs' => 'same', - ]); - +return static function (ECSConfig $ecsConfig) : void { + $ecsConfig->ruleWithConfiguration(OrderedImportsFixer::class, ['imports_order' => ['class', 'function', 'const']]); + $ecsConfig->ruleWithConfiguration(DeclareEqualNormalizeFixer::class, ['space' => 'none']); + $ecsConfig->ruleWithConfiguration(BracesFixer::class, ['allow_single_line_closure' => \false, 'position_after_functions_and_oop_constructs' => 'next', 'position_after_control_structures' => 'same', 'position_after_anonymous_constructs' => 'same']); // split of BracesFixer in PHP CS Fixer 3.10 - https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/4884 - $ecsConfig->rules([ - ControlStructureBracesFixer::class, - CurlyBracesPositionFixer::class, - NoMultipleStatementsPerLineFixer::class, - DeclareParenthesesFixer::class, - ControlStructureContinuationPositionFixer::class, - StatementIndentationFixer::class, - SingleSpaceAfterConstructFixer::class, - ]); - - $ecsConfig->ruleWithConfiguration(VisibilityRequiredFixer::class, [ - 'elements' => ['const', 'method', 'property'], - ]); - - $ecsConfig->rules([ - BinaryOperatorSpacesFixer::class, - BlankLineAfterNamespaceFixer::class, - BlankLineAfterOpeningTagFixer::class, - ClassDefinitionFixer::class, - ConstantCaseFixer::class, - ElseifFixer::class, - EncodingFixer::class, - FullOpeningTagFixer::class, - FunctionDeclarationFixer::class, - IndentationTypeFixer::class, - LineEndingFixer::class, - LowercaseCastFixer::class, - LowercaseKeywordsFixer::class, - NewWithBracesFixer::class, - NoBlankLinesAfterClassOpeningFixer::class, - NoBreakCommentFixer::class, - NoClosingTagFixer::class, - NoLeadingImportSlashFixer::class, - NoSinglelineWhitespaceBeforeSemicolonsFixer::class, - NoSpacesAfterFunctionNameFixer::class, - NoSpacesInsideParenthesisFixer::class, - NoTrailingWhitespaceFixer::class, - NoTrailingWhitespaceInCommentFixer::class, - NoWhitespaceBeforeCommaInArrayFixer::class, - ReturnTypeDeclarationFixer::class, - ShortScalarCastFixer::class, - SingleBlankLineAtEofFixer::class, - SingleImportPerStatementFixer::class, - SingleLineAfterImportsFixer::class, - SwitchCaseSemicolonToColonFixer::class, - SwitchCaseSpaceFixer::class, - TernaryOperatorSpacesFixer::class, - UnaryOperatorSpacesFixer::class, - VisibilityRequiredFixer::class, - WhitespaceAfterCommaInArrayFixer::class, - ]); - - $ecsConfig->ruleWithConfiguration(MethodArgumentSpaceFixer::class, [ - 'on_multiline' => 'ensure_fully_multiline', - ]); - - $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, [ - 'elements' => ['property'], - ]); - - $ecsConfig->ruleWithConfiguration(ConcatSpaceFixer::class, [ - 'spacing' => 'one', - ]); - + $ecsConfig->rules([ControlStructureBracesFixer::class, CurlyBracesPositionFixer::class, NoMultipleStatementsPerLineFixer::class, DeclareParenthesesFixer::class, ControlStructureContinuationPositionFixer::class, StatementIndentationFixer::class, SingleSpaceAfterConstructFixer::class]); + $ecsConfig->ruleWithConfiguration(VisibilityRequiredFixer::class, ['elements' => ['const', 'method', 'property']]); + $ecsConfig->rules([BinaryOperatorSpacesFixer::class, BlankLineAfterNamespaceFixer::class, BlankLineAfterOpeningTagFixer::class, ClassDefinitionFixer::class, ConstantCaseFixer::class, ElseifFixer::class, EncodingFixer::class, FullOpeningTagFixer::class, FunctionDeclarationFixer::class, IndentationTypeFixer::class, LineEndingFixer::class, LowercaseCastFixer::class, LowercaseKeywordsFixer::class, NewWithBracesFixer::class, NoBlankLinesAfterClassOpeningFixer::class, NoBreakCommentFixer::class, NoClosingTagFixer::class, NoLeadingImportSlashFixer::class, NoSinglelineWhitespaceBeforeSemicolonsFixer::class, NoSpacesAfterFunctionNameFixer::class, NoSpacesInsideParenthesisFixer::class, NoTrailingWhitespaceFixer::class, NoTrailingWhitespaceInCommentFixer::class, NoWhitespaceBeforeCommaInArrayFixer::class, ReturnTypeDeclarationFixer::class, ShortScalarCastFixer::class, SingleBlankLineAtEofFixer::class, SingleImportPerStatementFixer::class, SingleLineAfterImportsFixer::class, SwitchCaseSemicolonToColonFixer::class, SwitchCaseSpaceFixer::class, TernaryOperatorSpacesFixer::class, UnaryOperatorSpacesFixer::class, VisibilityRequiredFixer::class, WhitespaceAfterCommaInArrayFixer::class]); + $ecsConfig->ruleWithConfiguration(MethodArgumentSpaceFixer::class, ['on_multiline' => 'ensure_fully_multiline']); + $ecsConfig->ruleWithConfiguration(SingleClassElementPerStatementFixer::class, ['elements' => ['property']]); + $ecsConfig->ruleWithConfiguration(ConcatSpaceFixer::class, ['spacing' => 'one']); $ecsConfig->skip([SingleImportPerStatementFixer::class]); }; diff --git a/config/set/symplify.php b/config/set/symplify.php index 56e3659a503..c14dbc608ab 100644 --- a/config/set/symplify.php +++ b/config/set/symplify.php @@ -1,6 +1,7 @@ rules([ // docblocks and comments RemovePHPStormAnnotationFixer::class, ParamReturnAndVarTagMalformsFixer::class, RemoveUselessDefaultCommentFixer::class, - // arrays ArrayListItemNewlineFixer::class, ArrayOpenerAndCloserNewlineFixer::class, StandaloneLinePromotedPropertyFixer::class, - // newlines MethodChainingNewlineFixer::class, SpaceAfterCommaHereNowDocFixer::class, BlankLineAfterStrictTypesFixer::class, - // line length LineLengthFixer::class, ]); - - $ecsConfig->ruleWithConfiguration(GeneralPhpdocAnnotationRemoveFixer::class, [ - 'annotations' => ['throws', 'author', 'package', 'group', 'covers', 'category'], - ]); + $ecsConfig->ruleWithConfiguration(GeneralPhpdocAnnotationRemoveFixer::class, ['annotations' => ['throws', 'author', 'package', 'group', 'covers', 'category']]); }; diff --git a/easy-ci.php b/easy-ci.php deleted file mode 100644 index e330e80db92..00000000000 --- a/easy-ci.php +++ /dev/null @@ -1,20 +0,0 @@ -excludeCheckPaths(['Fixture', 'Source', 'tests', 'stubs', 'templates']); - - $easyCIConfig->typesToSkip([ - // factory in config - \Symplify\EasyCodingStandard\Caching\CacheFactory::class, - \Symplify\EasyCodingStandard\FixerRunner\WhitespacesFixerConfigFactory::class, - \Symplify\EasyCodingStandard\Skipper\Contract\SkipVoterInterface::class, - \Symfony\Component\Console\Application::class, - \Symplify\EasyCodingStandard\Console\Style\EasyCodingStandardStyleFactory::class, - \Symplify\EasyCodingStandard\DependencyInjection\EasyCodingStandardContainerFactory::class, - \Symplify\EasyCodingStandard\ValueObject\Set\SetList::class, - ]); -}; diff --git a/ecs.php b/ecs.php deleted file mode 100644 index 1094edd8a58..00000000000 --- a/ecs.php +++ /dev/null @@ -1,20 +0,0 @@ -paths([ - __DIR__ . '/ecs.php', - __DIR__ . '/rector.php', - __DIR__ . '/config', - __DIR__ . '/src', - __DIR__ . '/packages', - __DIR__ . '/tests', - __DIR__ . '/packages-tests', - ]); - - $ecsConfig->sets([SetList::SYMPLIFY, SetList::COMMON, SetList::PSR_12]); -}; diff --git a/full_ecs_build.sh b/full_ecs_build.sh deleted file mode 100644 index c7ff86b9049..00000000000 --- a/full_ecs_build.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash - -# add patches -composer install --ansi - -# but skip dev dependencies -composer update --no-dev --ansi - -# remove tests and useless files, to make downgraded, scoped and deployed codebase as small as possible -rm -rf tests packages-tests packages/changed-files-detector/tests packages/configuration/tests packages/fixer-runner/tests packages/sniff-runner/tests packages/snippet-formatter/tests vendor/symfony/event-dispatcher vendor/symfony/event-dispatcher-contracts vendor/symfony/process vendor/symfony/stopwatch vendor/squizlabs/php_codesniffer/tests vendor/squizlabs/php_codesniffer/src/Standards/Generic/Tests vendor/squizlabs/php_codesniffer/src/Standards/MySource/Tests vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Tests vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Tests vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Tests vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Tests vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Tests vendor/squizlabs/php_codesniffer/src/Standards/Zend/Tests vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs vendor/squizlabs/php_codesniffer/src/Standards/MySource/Docs vendor/squizlabs/php_codesniffer/src/Standards/PEAR/Docs vendor/squizlabs/php_codesniffer/src/Standards/PSR1/Docs vendor/squizlabs/php_codesniffer/src/Standards/PSR12/Docs vendor/squizlabs/php_codesniffer/src/Standards/PSR2/Docs vendor/squizlabs/php_codesniffer/src/Standards/Squiz/Docs vendor/squizlabs/php_codesniffer/src/Standards/Zend/Docs vendor/squizlabs/php_codesniffer/src/Reports vendor/squizlabs/php_codesniffer/src/Filters vendor/squizlabs/php_codesniffer/src/Generators vendor/friendsofphp/php-cs-fixer/src/Linter vendor/friendsofphp/php-cs-fixer/src/Runner vendor/friendsofphp/php-cs-fixer/src/Documentation vendor/friendsofphp/php-cs-fixer/src/Cache vendor/friendsofphp/php-cs-fixer/src/Console/Output vendor/friendsofphp/php-cs-fixer/src/Console/Report vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate vendor/friendsofphp/php-cs-fixer/src/Console/Application.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/Documentation.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php - -# downgrade with rector -mkdir rector-local -composer require rector/rector --working-dir rector-local -rector-local/vendor/bin/rector process bin src packages vendor --config build/rector-downgrade-php-72.php --ansi - -# prefix -sh prefix-code.sh diff --git a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/ChangedFilesDetectorTest.php b/packages-tests/ChangedFilesDetector/ChangedFilesDetector/ChangedFilesDetectorTest.php deleted file mode 100644 index 2a39196a2ea..00000000000 --- a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/ChangedFilesDetectorTest.php +++ /dev/null @@ -1,58 +0,0 @@ -filePath = __DIR__ . '/Source/OneClass.php'; - - $this->changedFilesDetector = $this->make(ChangedFilesDetector::class); - $this->changedFilesDetector->changeConfigurationFile(__DIR__ . '/Source/easy-coding-standard.php'); - } - - public function testAddFile(): void - { - $this->assertFileHasChanged($this->filePath); - $this->assertFileHasChanged($this->filePath); - } - - public function testHasFileChanged(): void - { - $this->changedFilesDetector->addFilePath($this->filePath); - - $this->assertFileHasNotChanged($this->filePath); - } - - public function testInvalidateCacheOnConfigurationChange(): void - { - $this->changedFilesDetector->addFilePath($this->filePath); - $this->assertFileHasNotChanged($this->filePath); - - $this->changedFilesDetector->changeConfigurationFile(__DIR__ . '/Source/another-configuration.php'); - - $this->assertFileHasChanged($this->filePath); - } - - private function assertFileHasChanged(string $filePath): void - { - $this->assertTrue($this->changedFilesDetector->hasFileChanged($filePath)); - } - - private function assertFileHasNotChanged(string $filePath): void - { - $this->assertFalse($this->changedFilesDetector->hasFileChanged($filePath)); - } -} diff --git a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/OneClass.php b/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/OneClass.php deleted file mode 100644 index 5a5bbbbc52b..00000000000 --- a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/OneClass.php +++ /dev/null @@ -1,10 +0,0 @@ -skip(['configuration-2']); -}; diff --git a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/easy-coding-standard.php b/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/easy-coding-standard.php deleted file mode 100644 index 9bf17ac2fdd..00000000000 --- a/packages-tests/ChangedFilesDetector/ChangedFilesDetector/Source/easy-coding-standard.php +++ /dev/null @@ -1,9 +0,0 @@ -skip(['configuration-2']); -}; diff --git a/packages-tests/ChangedFilesDetector/FileHashComputer/FileHashComputerTest.php b/packages-tests/ChangedFilesDetector/FileHashComputer/FileHashComputerTest.php deleted file mode 100644 index 3d0a89d2979..00000000000 --- a/packages-tests/ChangedFilesDetector/FileHashComputer/FileHashComputerTest.php +++ /dev/null @@ -1,67 +0,0 @@ -fileHashComputer = $this->make(FileHashComputer::class); - $this->filesystem = $this->make(Filesystem::class); - } - - public function testInvalidateCacheOnConfigurationChange(): void - { - // A. create on another one with fixer - $this->filesystem->copy(__DIR__ . '/Source/first_config.php', self::INCLUDED_CONFIG_FILE, true); - - $fileOneHash = $this->fileHashComputer->computeConfig( - __DIR__ . '/Fixture/config-including-another-one.php' - ); - - // B. create on another one with no fixer - $this->filesystem->copy(__DIR__ . '/Source/empty_config.php', self::INCLUDED_CONFIG_FILE, true); - - $fileTwoHash = $this->fileHashComputer->computeConfig( - __DIR__ . '/Fixture/config-including-another-one.php' - ); - - $this->assertNotSame($fileOneHash, $fileTwoHash); - - $this->filesystem->remove(self::INCLUDED_CONFIG_FILE); - } - - public function testPhpFileHash(): void - { - $fileOne = __DIR__ . '/Source/SomeScannedClass.php'; - $fileOneHash = $this->fileHashComputer->compute($fileOne); - - $expectedFileOneHasn = md5_file($fileOne); - $this->assertSame($expectedFileOneHasn, $fileOneHash); - - $fileTwo = __DIR__ . '/Source/ChangedScannedClass.php'; - $fileTwoHash = $this->fileHashComputer->compute($fileTwo); - - $expectedFileTwoHash = md5_file($fileTwo); - $this->assertSame($expectedFileTwoHash, $fileTwoHash); - - $this->assertNotSame($fileOneHash, $fileTwoHash); - } -} diff --git a/packages-tests/ChangedFilesDetector/FileHashComputer/Fixture/config-including-another-one.php b/packages-tests/ChangedFilesDetector/FileHashComputer/Fixture/config-including-another-one.php deleted file mode 100644 index a69f16e65e2..00000000000 --- a/packages-tests/ChangedFilesDetector/FileHashComputer/Fixture/config-including-another-one.php +++ /dev/null @@ -1,9 +0,0 @@ -import(__DIR__ . '/another-one.php'); -}; diff --git a/packages-tests/ChangedFilesDetector/FileHashComputer/Source/ChangedScannedClass.php b/packages-tests/ChangedFilesDetector/FileHashComputer/Source/ChangedScannedClass.php deleted file mode 100644 index 5bd0cb704af..00000000000 --- a/packages-tests/ChangedFilesDetector/FileHashComputer/Source/ChangedScannedClass.php +++ /dev/null @@ -1,10 +0,0 @@ -rule(CombineConsecutiveIssetsFixer::class); -}; diff --git a/packages-tests/ChangedFilesDetector/FileHashComputer/Source/first_config.php b/packages-tests/ChangedFilesDetector/FileHashComputer/Source/first_config.php deleted file mode 100644 index 3a9278366c9..00000000000 --- a/packages-tests/ChangedFilesDetector/FileHashComputer/Source/first_config.php +++ /dev/null @@ -1,10 +0,0 @@ -rule(DeclareStrictTypesFixer::class); -}; diff --git a/packages-tests/FixerRunner/Application/FileProcessorSource/easy-coding-standard.php b/packages-tests/FixerRunner/Application/FileProcessorSource/easy-coding-standard.php deleted file mode 100644 index d12a4fe0379..00000000000 --- a/packages-tests/FixerRunner/Application/FileProcessorSource/easy-coding-standard.php +++ /dev/null @@ -1,22 +0,0 @@ -rule(NoTrailingCommaInSinglelineArrayFixer::class); - - $ecsConfig->rule(ArrayDeclarationSniff::class); - - // priority 100 - higher first - $ecsConfig->rule(EncodingFixer::class); - - // priority 98 - $ecsConfig->rule(FullOpeningTagFixer::class); -}; diff --git a/packages-tests/FixerRunner/Application/FileProcessorTest.php b/packages-tests/FixerRunner/Application/FileProcessorTest.php deleted file mode 100644 index 79fb32cc706..00000000000 --- a/packages-tests/FixerRunner/Application/FileProcessorTest.php +++ /dev/null @@ -1,33 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/FileProcessorSource/easy-coding-standard.php']); - $this->fixerFileProcessor = $this->make(FixerFileProcessor::class); - } - - public function testGetSortedCheckers(): void - { - $checkers = $this->fixerFileProcessor->getCheckers(); - - $this->assertCount(3, $this->fixerFileProcessor->getCheckers()); - - $this->assertInstanceOf(EncodingFixer::class, $checkers[0]); - $this->assertInstanceOf(FullOpeningTagFixer::class, $checkers[1]); - $this->assertInstanceOf(NoTrailingCommaInSinglelineArrayFixer::class, $checkers[2]); - } -} diff --git a/packages-tests/FixerRunner/DependencyInjection/FixerServiceRegistrationTest.php b/packages-tests/FixerRunner/DependencyInjection/FixerServiceRegistrationTest.php deleted file mode 100644 index 29f90bad3db..00000000000 --- a/packages-tests/FixerRunner/DependencyInjection/FixerServiceRegistrationTest.php +++ /dev/null @@ -1,45 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/easy-coding-standard.php']); - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - - $checkers = $fixerFileProcessor->getCheckers(); - $this->assertCount(2, $checkers); - - /** @var ArraySyntaxFixer $arraySyntaxFixer */ - $arraySyntaxFixer = $checkers[1]; - $this->assertInstanceOf(ArraySyntaxFixer::class, $arraySyntaxFixer); - - $arraySyntaxConfiguration = PrivatesAccessorHelper::getPropertyValue($arraySyntaxFixer, 'configuration'); - $this->assertSame([ - 'syntax' => 'short', - ], $arraySyntaxConfiguration); - - /** @var VisibilityRequiredFixer $visibilityRequiredFixer */ - $visibilityRequiredFixer = $checkers[0]; - $this->assertInstanceOf(VisibilityRequiredFixer::class, $visibilityRequiredFixer); - - $visibilityRequiredConfiguration = PrivatesAccessorHelper::getPropertyValue( - $visibilityRequiredFixer, - 'configuration' - ); - - $this->assertSame([ - 'elements' => ['property'], - ], $visibilityRequiredConfiguration); - } -} diff --git a/packages-tests/FixerRunner/DependencyInjection/config/easy-coding-standard.php b/packages-tests/FixerRunner/DependencyInjection/config/easy-coding-standard.php deleted file mode 100644 index 41980687827..00000000000 --- a/packages-tests/FixerRunner/DependencyInjection/config/easy-coding-standard.php +++ /dev/null @@ -1,17 +0,0 @@ -ruleWithConfiguration(ArraySyntaxFixer::class, [ - 'syntax' => 'short', - ]); - - $ecsConfig->ruleWithConfiguration(VisibilityRequiredFixer::class, [ - 'elements' => ['property'], - ]); -}; diff --git a/packages-tests/Skipper/FileSystem/Fixture/in/it/KeepThisFile.txt b/packages-tests/Skipper/FileSystem/Fixture/in/it/KeepThisFile.txt deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/packages-tests/Skipper/FileSystem/Fixture/path/in/it/KeepThisFile.txt b/packages-tests/Skipper/FileSystem/Fixture/path/in/it/KeepThisFile.txt deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/packages-tests/Skipper/FileSystem/Fixture/path/with/KeepThisFile.txt b/packages-tests/Skipper/FileSystem/Fixture/path/with/KeepThisFile.txt deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/packages-tests/Skipper/FileSystem/FnMatchPathNormalizerTest.php b/packages-tests/Skipper/FileSystem/FnMatchPathNormalizerTest.php deleted file mode 100644 index 676987b8f82..00000000000 --- a/packages-tests/Skipper/FileSystem/FnMatchPathNormalizerTest.php +++ /dev/null @@ -1,39 +0,0 @@ -fnMatchPathNormalizer = $this->make(FnMatchPathNormalizer::class); - } - - #[DataProvider('providePaths')] - public function testPaths(string $path, string $expectedNormalizedPath): void - { - $normalizedPath = $this->fnMatchPathNormalizer->normalizeForFnmatch($path); - $this->assertSame($expectedNormalizedPath, $normalizedPath); - } - - public static function providePaths(): Iterator - { - yield ['path/with/no/asterisk', 'path/with/no/asterisk']; - yield ['*path/with/asterisk/begin', '*path/with/asterisk/begin*']; - yield ['path/with/asterisk/end*', '*path/with/asterisk/end*']; - yield ['*path/with/asterisk/begin/and/end*', '*path/with/asterisk/begin/and/end*']; - yield [__DIR__ . '/Fixture/path/with/../in/it', __DIR__ . '/Fixture/path/in/it']; - yield [__DIR__ . '/Fixture/path/with/../../in/it', __DIR__ . '/Fixture/in/it']; - } -} diff --git a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/Fixture/existing_paths.txt b/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/Fixture/existing_paths.txt deleted file mode 100644 index a0cde59caf0..00000000000 --- a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/Fixture/existing_paths.txt +++ /dev/null @@ -1 +0,0 @@ -you diff --git a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/SkippedPathsResolverTest.php b/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/SkippedPathsResolverTest.php deleted file mode 100644 index 8edd4fe4af5..00000000000 --- a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/SkippedPathsResolverTest.php +++ /dev/null @@ -1,27 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/config.php']); - $this->skippedPathsResolver = $this->make(SkippedPathsResolver::class); - } - - public function test(): void - { - $skippedPaths = $this->skippedPathsResolver->resolve(); - $this->assertCount(2, $skippedPaths); - - $this->assertSame('*/Mask/*', $skippedPaths[1]); - } -} diff --git a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/config/config.php b/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/config/config.php deleted file mode 100644 index 83517f9994b..00000000000 --- a/packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/config/config.php +++ /dev/null @@ -1,14 +0,0 @@ -skip([ - // windows slashes - __DIR__ . '\non-existing-path', - __DIR__ . '/../Fixture', - '*\Mask\*', - ]); -}; diff --git a/packages-tests/Skipper/Skipper/Skip/Fixture/AlwaysSkippedPath/some_file.txt b/packages-tests/Skipper/Skipper/Skip/Fixture/AlwaysSkippedPath/some_file.txt deleted file mode 100644 index 2ef267e25bd..00000000000 --- a/packages-tests/Skipper/Skipper/Skip/Fixture/AlwaysSkippedPath/some_file.txt +++ /dev/null @@ -1 +0,0 @@ -some content diff --git a/packages-tests/Skipper/Skipper/Skip/Fixture/PathSkippedWithMask/another_file.txt b/packages-tests/Skipper/Skipper/Skip/Fixture/PathSkippedWithMask/another_file.txt deleted file mode 100644 index 7d73532226e..00000000000 --- a/packages-tests/Skipper/Skipper/Skip/Fixture/PathSkippedWithMask/another_file.txt +++ /dev/null @@ -1 +0,0 @@ -yes, you can diff --git a/packages-tests/Skipper/Skipper/Skip/Fixture/skip.php.inc b/packages-tests/Skipper/Skipper/Skip/Fixture/skip.php.inc deleted file mode 100644 index e0c851ce087..00000000000 --- a/packages-tests/Skipper/Skipper/Skip/Fixture/skip.php.inc +++ /dev/null @@ -1,17 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/config.php']); - $this->skipper = $this->make(Skipper::class); - } - - #[DataProvider('provideCheckerAndFile')] - #[DataProvider('provideCodeAndFile')] - #[DataProvider('provideMessageAndFile')] - #[DataProvider('provideAnythingAndFilePath')] - public function test(string $element, string $filePath, bool $expectedSkip): void - { - $resolvedSkip = $this->skipper->shouldSkipElementAndFilePath($element, $filePath); - $this->assertSame($expectedSkip, $resolvedSkip); - } - - public static function provideCheckerAndFile(): Iterator - { - yield [SomeClassToSkip::class, __DIR__ . '/Fixture', true]; - - yield [AnotherClassToSkip::class, __DIR__ . '/Fixture/someFile', true]; - yield [AnotherClassToSkip::class, __DIR__ . '/Fixture/someDirectory/anotherFile.php', true]; - yield [AnotherClassToSkip::class, __DIR__ . '/Fixture/someDirectory/anotherFile.php', true]; - - yield [NotSkippedClass::class, __DIR__ . '/Fixture/someFile', false]; - yield [NotSkippedClass::class, __DIR__ . '/Fixture/someOtherFile', false]; - } - - public static function provideCodeAndFile(): Iterator - { - yield [AnotherClassToSkip::class . '.someCode', __DIR__ . '/Fixture/someFile', true]; - yield [AnotherClassToSkip::class . '.someOtherCode', __DIR__ . '/Fixture/someDirectory/someFile', true]; - yield [AnotherClassToSkip::class . '.someAnotherCode', __DIR__ . '/Fixture/someDirectory/someFile', true]; - - yield ['someSniff.someForeignCode', __DIR__ . '/Fixture/someFile', false]; - yield ['someSniff.someOtherCode', __DIR__ . '/Fixture/someFile', false]; - } - - public static function provideMessageAndFile(): Iterator - { - yield ['some fishy code at line 5!', __DIR__ . '/Fixture/someFile', true]; - yield ['some another fishy code at line 5!', __DIR__ . '/Fixture/someDirectory/someFile.php', true]; - - yield [ - 'Cognitive complexity for method "foo" is 2 but has to be less than or equal to 1.', - __DIR__ . '/Fixture/skip.php.inc', - true, - ]; - yield [ - 'Cognitive complexity for method "bar" is 2 but has to be less than or equal to 1.', - __DIR__ . '/Fixture/skip.php.inc', - false, - ]; - } - - public static function provideAnythingAndFilePath(): Iterator - { - yield ['anything', __DIR__ . '/Fixture/AlwaysSkippedPath/some_file.txt', true]; - yield ['anything', __DIR__ . '/Fixture/PathSkippedWithMask/another_file.txt', true]; - } -} diff --git a/packages-tests/Skipper/Skipper/Skip/Source/AnotherClassToSkip.php b/packages-tests/Skipper/Skipper/Skip/Source/AnotherClassToSkip.php deleted file mode 100644 index f1572244a43..00000000000 --- a/packages-tests/Skipper/Skipper/Skip/Source/AnotherClassToSkip.php +++ /dev/null @@ -1,9 +0,0 @@ -skip([ - // classes - SomeClassToSkip::class, - - AnotherClassToSkip::class => ['Fixture/someFile', '*/someDirectory/*'], - - // code - AnotherClassToSkip::class . '.someCode' => null, - AnotherClassToSkip::class . '.someOtherCode' => ['*/someDirectory/*'], - AnotherClassToSkip::class . '.someAnotherCode' => ['someDirectory/*'], - - // file paths - __DIR__ . '/../Fixture/AlwaysSkippedPath', - '*\PathSkippedWithMask\*', - - // messages - 'some fishy code at line 5!' => null, - 'some another fishy code at line 5!' => ['someDirectory/*'], - 'Cognitive complexity for method "foo" is 2 but has to be less than or equal to 1.' => null, - ]); -}; diff --git a/packages-tests/Skipper/Skipper/Skipper/Fixture/Element/FifthElement.php b/packages-tests/Skipper/Skipper/Skipper/Fixture/Element/FifthElement.php deleted file mode 100644 index bf950b20f13..00000000000 --- a/packages-tests/Skipper/Skipper/Skipper/Fixture/Element/FifthElement.php +++ /dev/null @@ -1,9 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/config.php']); - $this->skipper = $this->make(Skipper::class); - } - - #[DataProvider('provideDataShouldSkipFileInfo')] - public function testSkipFileInfo(string $filePath, bool $expectedSkip): void - { - $resultSkip = $this->skipper->shouldSkipFilePath($filePath); - $this->assertSame($expectedSkip, $resultSkip); - } - - /** - * @return Iterator - */ - public static function provideDataShouldSkipFileInfo(): Iterator - { - yield [__DIR__ . '/Fixture/SomeRandom/file.txt', false]; - yield [__DIR__ . '/Fixture/SomeSkipped/any.txt', true]; - - $basenameCwd = basename(getcwd()); - if ($basenameCwd === 'easy-coding-standard') { - // split test inside packages/easy-coding-standard - yield ['packages-tests/Skipper/Skipper/Skipper/Fixture/SomeSkipped/any.txt', true]; - } else { - // from root symplify - yield [ - 'packages/easy-coding-standard/packages-tests/Skipper/Skipper/Skipper/Fixture/SomeSkipped/any.txt', - true, - ]; - } - } - - /** - * @param object|class-string $element - */ - #[DataProvider('provideDataShouldSkipElement')] - public function testSkipElement(string|object $element, bool $expectedSkip): void - { - $resultSkip = $this->skipper->shouldSkipElement($element); - $this->assertSame($expectedSkip, $resultSkip); - } - - /** - * @return Iterator[]|class-string[]|FifthElement[]> - */ - public static function provideDataShouldSkipElement(): Iterator - { - yield [ThreeMan::class, false]; - yield [SixthSense::class, true]; - yield [new FifthElement(), true]; - } -} diff --git a/packages-tests/Skipper/Skipper/Skipper/config/config.php b/packages-tests/Skipper/Skipper/Skipper/config/config.php deleted file mode 100644 index 7dd0c69821e..00000000000 --- a/packages-tests/Skipper/Skipper/Skipper/config/config.php +++ /dev/null @@ -1,18 +0,0 @@ -skip([ - // windows like path - '*\SomeSkipped\*', - - // elements - FifthElement::class, - SixthSense::class, - ]); -}; diff --git a/packages-tests/SniffRunner/Application/FixerSource/SomeFile.php b/packages-tests/SniffRunner/Application/FixerSource/SomeFile.php deleted file mode 100644 index 2064782a32e..00000000000 --- a/packages-tests/SniffRunner/Application/FixerSource/SomeFile.php +++ /dev/null @@ -1,10 +0,0 @@ -make(FileFactory::class); - - $this->file = $fileFactory->createFromFile(__DIR__ . '/FixerSource/SomeFile.php'); - $this->fixer = $this->make(Fixer::class); - } - - public function testStartFile(): void - { - $this->assertSame('', $this->fixer->getContents()); - - $this->file->parse(); - $this->fixer->startFile($this->file); - - $this->assertStringEqualsFile(__DIR__ . '/FixerSource/SomeFile.php', $this->fixer->getContents()); - } - - public function testTokenContent(): void - { - $this->file->parse(); - $this->fixer->startFile($this->file); - - $token = $this->fixer->getTokenContent(14); - $this->assertSame('\\', $token); - - $this->fixer->replaceToken(14, '_'); - $token = $this->fixer->getTokenContent(14); - $this->assertSame('_', $token); - - $this->assertStringNotEqualsFile(__DIR__ . '/FixerSource/SomeFile.php', $this->fixer->getContents()); - } - - public function testAddContent(): void - { - $this->file->parse(); - $this->fixer->startFile($this->file); - $this->fixer->beginChangeSet(); - - $this->fixer->addContentBefore(14, 'A'); - - $token = $this->fixer->getTokenContent(14); - $this->assertSame('A\\', $token); - - $this->fixer->addContent(14, 'B'); - $token = $this->fixer->getTokenContent(14); - $this->assertSame('A\\B', $token); - } - - public function testChangesets(): void - { - $this->file->parse(); - $this->fixer->startFile($this->file); - $this->fixer->beginChangeSet(); - - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('\\', $tokenContent); - - $this->fixer->addContentBefore(14, 'A'); - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('A\\', $tokenContent); - - // during the changeset, you are free to modify current token as you wish... - $this->fixer->addContent(14, 'B'); - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('A\\B', $tokenContent); - - // you can also rollback the changes... - $this->fixer->rollbackChangeset(); - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('\\', $tokenContent); - - $this->fixer->addContent(14, 'B'); - $this->fixer->endChangeSet(); - - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('\\B', $tokenContent); - - // ...that stops being the case after changeset is committed - $this->fixer->addContent(14, 'C'); - $tokenContent = $this->fixer->getTokenContent(14); - $this->assertSame('\\B', $tokenContent); - } - - public function testAddNewline(): void - { - $this->file->parse(); - $this->fixer->startFile($this->file); - $this->fixer->beginChangeSet(); - - $token = $this->fixer->getTokenContent(14); - $this->assertSame('\\', $token); - - $this->fixer->addNewline(14); - $token = $this->fixer->getTokenContent(14); - $this->assertSame('\\' . PHP_EOL, $token); - - $this->fixer->addNewlineBefore(14); - $token = $this->fixer->getTokenContent(14); - $this->assertSame(PHP_EOL . '\\' . PHP_EOL, $token); - } - - public function testSubstrToken(): void - { - $this->file->parse(); - $this->fixer->startFile($this->file); - $this->fixer->beginChangeSet(); - - $token = $this->fixer->getTokenContent(15); - $this->assertSame('EasyCodingStandard', $token); - - $this->fixer->substrToken(15, 0, 4); - $token = $this->fixer->getTokenContent(15); - $this->assertSame('Easy', $token); - - $this->fixer->substrToken(15, 3); - $token = $this->fixer->getTokenContent(15); - $this->assertSame('y', $token); - - $this->fixer->substrToken(17, 3, 0); - $token = $this->fixer->getTokenContent(17); - $this->assertSame('', $token); - } -} diff --git a/packages-tests/SniffRunner/DI/SniffServiceRegistrationTest.php b/packages-tests/SniffRunner/DI/SniffServiceRegistrationTest.php deleted file mode 100644 index 3a673a28b2e..00000000000 --- a/packages-tests/SniffRunner/DI/SniffServiceRegistrationTest.php +++ /dev/null @@ -1,24 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/ecs.php']); - $sniffFileProcessor = $this->make(SniffFileProcessor::class); - - /** @var LineLengthSniff $lineLengthSniff */ - $lineLengthSniff = $sniffFileProcessor->getCheckers()[0]; - - $this->assertSame(15, $lineLengthSniff->lineLimit); - $this->assertSame(55, $lineLengthSniff->absoluteLineLimit); - } -} diff --git a/packages-tests/SniffRunner/DI/Source/AnotherSniff.php b/packages-tests/SniffRunner/DI/Source/AnotherSniff.php deleted file mode 100644 index 03752bb5e7d..00000000000 --- a/packages-tests/SniffRunner/DI/Source/AnotherSniff.php +++ /dev/null @@ -1,24 +0,0 @@ -ruleWithConfiguration(AnotherSniff::class, [ - 'lineLimit' => 15, - 'absoluteLineLimit' => 55, - ]); -}; diff --git a/packages-tests/SniffRunner/File/FileFactorySource/SomeFile.php b/packages-tests/SniffRunner/File/FileFactorySource/SomeFile.php deleted file mode 100644 index 174d7fd709f..00000000000 --- a/packages-tests/SniffRunner/File/FileFactorySource/SomeFile.php +++ /dev/null @@ -1,3 +0,0 @@ -make(FileFactory::class); - - $file = $fileFactory->createFromFile(__DIR__ . '/FileFactorySource/SomeFile.php'); - - $this->assertInstanceOf(File::class, $file); - $this->assertInstanceOf(PhpCodeSnifferFile::class, $file); - $this->assertInstanceOf(Fixer::class, $file->fixer); - } -} diff --git a/packages-tests/SniffRunner/ValueObject/FileSource/SomeFile.php b/packages-tests/SniffRunner/ValueObject/FileSource/SomeFile.php deleted file mode 100644 index 174d7fd709f..00000000000 --- a/packages-tests/SniffRunner/ValueObject/FileSource/SomeFile.php +++ /dev/null @@ -1,3 +0,0 @@ -make(FileFactory::class); - - $file = $fileFactory->createFromFile(__DIR__ . '/FileSource/SomeFile.php'); - $file->processWithTokenListenersAndFilePath([], __DIR__ . '/FileSource/SomeFile.php', []); - } -} diff --git a/packages/Caching/Cache.php b/packages/Caching/Cache.php index 22e76d0fbf5..9d39d333c5c 100644 --- a/packages/Caching/Cache.php +++ b/packages/Caching/Cache.php @@ -1,40 +1,39 @@ fileCacheStorage = $fileCacheStorage; } - /** * @api */ - public function load(string $key, string $variableKey): ?string + public function load(string $key, string $variableKey) : ?string { return $this->fileCacheStorage->load($key, $variableKey); } - /** * @api */ - public function save(string $key, string $variableKey, string $data): void + public function save(string $key, string $variableKey, string $data) : void { $this->fileCacheStorage->save($key, $variableKey, $data); } - - public function clear(): void + public function clear() : void { $this->fileCacheStorage->clear(); } - - public function clean(string $cacheKey): void + public function clean(string $cacheKey) : void { $this->fileCacheStorage->clean($cacheKey); } diff --git a/packages/Caching/CacheFactory.php b/packages/Caching/CacheFactory.php index 805cb53b689..8586aacf437 100644 --- a/packages/Caching/CacheFactory.php +++ b/packages/Caching/CacheFactory.php @@ -1,38 +1,37 @@ fileSystem = $fileSystem; } - /** * @api */ - public function create(): Cache + public function create() : \Symplify\EasyCodingStandard\Caching\Cache { $cacheDirectory = SimpleParameterProvider::getStringParameter(Option::CACHE_DIRECTORY); - // ensure cache directory exists - if (! $this->fileSystem->exists($cacheDirectory)) { + if (!$this->fileSystem->exists($cacheDirectory)) { $this->fileSystem->mkdir($cacheDirectory); } - $fileCacheStorage = new FileCacheStorage($cacheDirectory, $this->fileSystem); - - return new Cache($fileCacheStorage); + return new \Symplify\EasyCodingStandard\Caching\Cache($fileCacheStorage); } } diff --git a/packages/Caching/ChangedFilesDetector.php b/packages/Caching/ChangedFilesDetector.php index a9fd26bc06c..508b8151f50 100644 --- a/packages/Caching/ChangedFilesDetector.php +++ b/packages/Caching/ChangedFilesDetector.php @@ -1,12 +1,10 @@ fileHashComputer = $fileHashComputer; + $this->cache = $cache; } - /** * @api For tests */ - public function changeConfigurationFile(string $configurationFile): void + public function changeConfigurationFile(string $configurationFile) : void { $this->storeConfigurationDataHash($this->fileHashComputer->computeConfig($configurationFile)); } - - public function addFilePath(string $filePath): void + public function addFilePath(string $filePath) : void { $cacheKey = $this->filePathToKey($filePath); $currentValue = $this->fileHashComputer->compute($filePath); $this->cache->save($cacheKey, self::FILE_HASH, $currentValue); } - - public function invalidateFilePath(string $filePath): void + public function invalidateFilePath(string $filePath) : void { $cacheKey = $this->filePathToKey($filePath); $this->cache->clean($cacheKey); } - - public function hasFileChanged(string $filePath): bool + public function hasFileChanged(string $filePath) : bool { $newFileHash = $this->fileHashComputer->compute($filePath); - $cacheKey = $this->filePathToKey($filePath); $cachedValue = $this->cache->load($cacheKey, self::FILE_HASH); - return $newFileHash !== $cachedValue; } - - public function clearCache(): void + public function clearCache() : void { // clear cache only for changed files group $this->cache->clear(); } - /** * For cache invalidation * * @param string[] $configFiles * @api */ - public function setUsedConfigs(array $configFiles): void + public function setUsedConfigs(array $configFiles) : void { if ($configFiles === []) { return; } - Assert::allString($configFiles); Assert::allFile($configFiles); - // the first config is core to all → if it was changed, just invalidate it $firstConfigFile = $configFiles[0]; $this->storeConfigurationDataHash($this->fileHashComputer->computeConfig($firstConfigFile)); } - - private function storeConfigurationDataHash(string $configurationHash): void + private function storeConfigurationDataHash(string $configurationHash) : void { $this->invalidateCacheIfConfigurationChanged($configurationHash); $this->cache->save(self::CONFIGURATION_HASH_KEY, self::FILE_HASH, $configurationHash); } - - private function filePathToKey(string $filePath): string + private function filePathToKey(string $filePath) : string { $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd($filePath); - - return sha1($relativeFilePath); + return \sha1($relativeFilePath); } - - private function invalidateCacheIfConfigurationChanged(string $configurationHash): void + private function invalidateCacheIfConfigurationChanged(string $configurationHash) : void { $cachedValue = $this->cache->load(self::CONFIGURATION_HASH_KEY, self::FILE_HASH); if ($cachedValue === null) { return; } - if ($configurationHash === $cachedValue) { return; } - $this->clearCache(); } } diff --git a/packages/Caching/FileHashComputer.php b/packages/Caching/FileHashComputer.php index baaeaeca01b..e32fee578c9 100644 --- a/packages/Caching/FileHashComputer.php +++ b/packages/Caching/FileHashComputer.php @@ -1,41 +1,34 @@ getBindings())); - + $fileHash = \sha1(Json::encode($ecsConfig->getBindings())); return $fileHash . SimpleParameterProvider::hash(); } - - public function compute(string $filePath): string + public function compute(string $filePath) : string { - $fileHash = md5_file($filePath); - if (! $fileHash) { - throw new FileNotFoundException(sprintf('File "%s" was not found', $fileHash)); + $fileHash = \md5_file($filePath); + if (!$fileHash) { + throw new FileNotFoundException(\sprintf('File "%s" was not found', $fileHash)); } - return $fileHash; } } diff --git a/packages/Caching/ValueObject/CacheFilePaths.php b/packages/Caching/ValueObject/CacheFilePaths.php index f7bb121cd89..e38dd2584f9 100644 --- a/packages/Caching/ValueObject/CacheFilePaths.php +++ b/packages/Caching/ValueObject/CacheFilePaths.php @@ -1,29 +1,40 @@ firstDirectory = $firstDirectory; + $this->secondDirectory = $secondDirectory; + $this->filePath = $filePath; } - - public function getFirstDirectory(): string + public function getFirstDirectory() : string { return $this->firstDirectory; } - - public function getSecondDirectory(): string + public function getSecondDirectory() : string { return $this->secondDirectory; } - - public function getFilePath(): string + public function getFilePath() : string { return $this->filePath; } diff --git a/packages/Caching/ValueObject/CacheItem.php b/packages/Caching/ValueObject/CacheItem.php index 5a1e698397d..795081d1945 100644 --- a/packages/Caching/ValueObject/CacheItem.php +++ b/packages/Caching/ValueObject/CacheItem.php @@ -1,7 +1,6 @@ variableKey = $variableKey; + $this->data = $data; } - /** * @param mixed[] $properties */ - public static function __set_state(array $properties): self + public static function __set_state(array $properties) : self { return new self($properties['variableKey'], $properties['data']); } - - public function isVariableKeyValid(string $variableKey): bool + public function isVariableKeyValid(string $variableKey) : bool { return $this->variableKey === $variableKey; } - - public function getData(): mixed + /** + * @return mixed + */ + public function getData() { return $this->data; } diff --git a/packages/Caching/ValueObject/Storage/FileCacheStorage.php b/packages/Caching/ValueObject/Storage/FileCacheStorage.php index 04256f1822a..93d4a21b08b 100644 --- a/packages/Caching/ValueObject/Storage/FileCacheStorage.php +++ b/packages/Caching/ValueObject/Storage/FileCacheStorage.php @@ -1,90 +1,79 @@ directory = $directory; + $this->fileSystem = $fileSystem; } - - public function load(string $key, string $variableKey): ?string + public function load(string $key, string $variableKey) : ?string { $cacheFilePaths = $this->getCacheFilePaths($key); $filePath = $cacheFilePaths->getFilePath(); - if (! is_file($filePath)) { + if (!\is_file($filePath)) { return null; } - - $cacheItem = require $filePath; - if (! $cacheItem instanceof CacheItem) { + $cacheItem = (require $filePath); + if (!$cacheItem instanceof CacheItem) { return null; } - - if (! $cacheItem->isVariableKeyValid($variableKey)) { + if (!$cacheItem->isVariableKeyValid($variableKey)) { return null; } - return $cacheItem->getData(); } - - public function save(string $key, string $variableKey, string $data): void + public function save(string $key, string $variableKey, string $data) : void { $cacheFilePaths = $this->getCacheFilePaths($key); $this->fileSystem->mkdir($cacheFilePaths->getFirstDirectory()); $this->fileSystem->mkdir($cacheFilePaths->getSecondDirectory()); - - $errorBefore = error_get_last(); - $exported = @var_export(new CacheItem($variableKey, $data), true); - $errorAfter = error_get_last(); - + $errorBefore = \error_get_last(); + $exported = @\var_export(new CacheItem($variableKey, $data), \true); + $errorAfter = \error_get_last(); if ($errorAfter !== null && $errorBefore !== $errorAfter) { - $errorMessage = sprintf( - 'Error occurred while saving item "%s" ("%s") to cache: "%s"', - $key, - $variableKey, - $errorAfter['message'] - ); - + $errorMessage = \sprintf('Error occurred while saving item "%s" ("%s") to cache: "%s"', $key, $variableKey, $errorAfter['message']); throw new ShouldNotHappenException($errorMessage); } - - $variableFileContent = sprintf("fileSystem->dumpFile($cacheFilePaths->getFilePath(), $variableFileContent); } - - public function clean(string $cacheKey): void + public function clean(string $cacheKey) : void { $cacheFilePaths = $this->getCacheFilePaths($cacheKey); - $this->fileSystem->remove($cacheFilePaths->getFilePath()); } - - public function clear(): void + public function clear() : void { $this->fileSystem->remove($this->directory); } - - private function getCacheFilePaths(string $key): CacheFilePaths + private function getCacheFilePaths(string $key) : CacheFilePaths { - $keyHash = sha1($key); - $firstDirectory = sprintf('%s/%s', $this->directory, substr($keyHash, 0, 2)); - $secondDirectory = sprintf('%s/%s', $firstDirectory, substr($keyHash, 2, 2)); - $filePath = sprintf('%s/%s.php', $secondDirectory, $keyHash); - + $keyHash = \sha1($key); + $firstDirectory = \sprintf('%s/%s', $this->directory, \substr($keyHash, 0, 2)); + $secondDirectory = \sprintf('%s/%s', $firstDirectory, \substr($keyHash, 2, 2)); + $filePath = \sprintf('%s/%s.php', $secondDirectory, $keyHash); return new CacheFilePaths($firstDirectory, $secondDirectory, $filePath); } } diff --git a/packages/FixerRunner/Application/FixerFileProcessor.php b/packages/FixerRunner/Application/FixerFileProcessor.php index c77aed309b8..7887541966b 100644 --- a/packages/FixerRunner/Application/FixerFileProcessor.php +++ b/packages/FixerRunner/Application/FixerFileProcessor.php @@ -1,10 +1,9 @@ fileToTokensParser = $fileToTokensParser; + $this->skipper = $skipper; + $this->differ = $differ; + $this->easyCodingStandardStyle = $easyCodingStandardStyle; + $this->filesystem = $filesystem; + $this->fileDiffFactory = $fileDiffFactory; $this->fixers = $this->sortFixers($fixers); } - /** * @return FixerInterface[] */ - public function getCheckers(): array + public function getCheckers() : array { return $this->fixers; } - /** * @return array{file_diffs?: FileDiff[]} */ - public function processFile(string $filePath, Configuration $configuration): array + public function processFile(string $filePath, Configuration $configuration) : array { $tokens = $this->fileToTokensParser->parseFromFilePath($filePath); - $appliedFixers = []; - foreach ($this->fixers as $fixer) { if ($this->processTokensByFixer($filePath, $tokens, $fixer)) { - $appliedFixers[] = $fixer::class; + $appliedFixers[] = \get_class($fixer); } } - if ($appliedFixers === []) { return []; } - $fileContents = FileSystem::read($filePath); $diff = $this->differ->diff($fileContents, $tokens->generateCode()); - // some fixer with feature overlap can null each other if ($diff === '') { return []; } - $fileDiffs = []; - // file has changed $fileDiffs[] = $this->fileDiffFactory->createFromDiffAndAppliedCheckers($filePath, $diff, $appliedFixers); - $tokenGeneratedCode = $tokens->generateCode(); if ($configuration->isFixer()) { $this->filesystem->dumpFile($filePath, $tokenGeneratedCode); } - Tokens::clearCache(); - - return [ - Bridge::FILE_DIFFS => $fileDiffs, - ]; + return [Bridge::FILE_DIFFS => $fileDiffs]; } - - public function processFileToString(string $filePath): string + public function processFileToString(string $filePath) : string { $tokens = $this->fileToTokensParser->parseFromFilePath($filePath); - $appliedFixers = []; foreach ($this->fixers as $fixer) { if ($this->processTokensByFixer($filePath, $tokens, $fixer)) { - $appliedFixers[] = $fixer::class; + $appliedFixers[] = \get_class($fixer); } } - $contents = FileSystem::read($filePath); if ($appliedFixers === []) { return $contents; } - $diff = $this->differ->diff($contents, $tokens->generateCode()); // some fixer with feature overlap can null each other if ($diff === '') { return $contents; } - return $tokens->generateCode(); } - /** * @param FixerInterface[] $fixers * @return FixerInterface[] */ - private function sortFixers(array $fixers): array + private function sortFixers(array $fixers) : array { - usort( - $fixers, - static fn (FixerInterface $firstFixer, FixerInterface $secondFixer): int => $secondFixer->getPriority() <=> $firstFixer->getPriority() - ); - + \usort($fixers, static function (FixerInterface $firstFixer, FixerInterface $secondFixer) : int { + return $secondFixer->getPriority() <=> $firstFixer->getPriority(); + }); return $fixers; } - /** * @param Tokens $tokens * @return bool If fixer applied */ - private function processTokensByFixer(string $filePath, Tokens $tokens, FixerInterface $fixer): bool + private function processTokensByFixer(string $filePath, Tokens $tokens, FixerInterface $fixer) : bool { if ($this->shouldSkip($filePath, $fixer, $tokens)) { - return false; + return \false; } - // show current fixer in --debug / -vvv if ($this->easyCodingStandardStyle->isDebug()) { - $this->easyCodingStandardStyle->writeln(' [fixer] ' . $fixer::class); + $this->easyCodingStandardStyle->writeln(' [fixer] ' . \get_class($fixer)); } - try { $fixer->fix(new SplFileInfo($filePath), $tokens); } catch (Throwable $throwable) { - throw new ShouldNotHappenException(sprintf( - 'Fixing of "%s" file by "%s" failed: %s in file %s on line %d', - $filePath, - $fixer::class, - $throwable->getMessage(), - $throwable->getFile(), - $throwable->getLine() - ), $throwable->getCode(), $throwable); + throw new ShouldNotHappenException(\sprintf('Fixing of "%s" file by "%s" failed: %s in file %s on line %d', $filePath, \get_class($fixer), $throwable->getMessage(), $throwable->getFile(), $throwable->getLine()), $throwable->getCode(), $throwable); } - - if (! $tokens->isChanged()) { - return false; + if (!$tokens->isChanged()) { + return \false; } - $tokens->clearChanged(); $tokens->clearEmptyTokens(); - - return true; + return \true; } - /** * @param Tokens $tokens */ - private function shouldSkip(string $filePath, FixerInterface $fixer, Tokens $tokens): bool + private function shouldSkip(string $filePath, FixerInterface $fixer, Tokens $tokens) : bool { if ($this->skipper->shouldSkipElementAndFilePath($fixer, $filePath)) { - return true; + return \true; } - - if (! $fixer->supports(new SplFileInfo($filePath))) { - return true; + if (!$fixer->supports(new SplFileInfo($filePath))) { + return \true; } - - return ! $fixer->isCandidate($tokens); + return !$fixer->isCandidate($tokens); } } diff --git a/packages/FixerRunner/Parser/FileToTokensParser.php b/packages/FixerRunner/Parser/FileToTokensParser.php index 467bf76756e..d7d4b6f5118 100644 --- a/packages/FixerRunner/Parser/FileToTokensParser.php +++ b/packages/FixerRunner/Parser/FileToTokensParser.php @@ -1,19 +1,17 @@ */ - public function parseFromFilePath(string $filePath): Tokens + public function parseFromFilePath(string $filePath) : Tokens { $fileContents = FileSystem::read($filePath); return Tokens::fromCode($fileContents); diff --git a/packages/FixerRunner/ValueObject/Spacing.php b/packages/FixerRunner/ValueObject/Spacing.php index aed915de5b7..1b3e66034f4 100644 --- a/packages/FixerRunner/ValueObject/Spacing.php +++ b/packages/FixerRunner/ValueObject/Spacing.php @@ -1,7 +1,6 @@ resolveIndentation(), $lineEnding); } - - private function resolveIndentation(): string + private function resolveIndentation() : string { $indentation = SimpleParameterProvider::getStringParameter(Option::INDENTATION); if ($this->isOneTab($indentation)) { return Spacing::ONE_TAB; } - if ($indentation === Spacing::TWO_SPACES) { return Spacing::TWO_SPACES; } - if ($this->isFourSpaces($indentation)) { return Spacing::FOUR_SPACES; } - - throw new WhitespaceConfigurationException(sprintf( - 'Value "%s" is not supported in "$ecsConfig->indentation(...)".%sUse one of: "%s".', - $indentation, - PHP_EOL, - implode('", "', self::ALLOWED_VALUES) - )); + throw new WhitespaceConfigurationException(\sprintf('Value "%s" is not supported in "$ecsConfig->indentation(...)".%sUse one of: "%s".', $indentation, \PHP_EOL, \implode('", "', self::ALLOWED_VALUES))); } - - private function isOneTab(string $indentation): bool + private function isOneTab(string $indentation) : bool { if ($indentation === 'tab') { - return true; + return \true; } - return $indentation === Spacing::ONE_TAB; } - - private function isFourSpaces(string $indentation): bool + private function isFourSpaces(string $indentation) : bool { if ($indentation === 'spaces') { - return true; + return \true; } - return $indentation === Spacing::FOUR_SPACES; } } diff --git a/packages/Parallel/Application/ParallelFileProcessor.php b/packages/Parallel/Application/ParallelFileProcessor.php index 48095b9c08f..990040f8266 100644 --- a/packages/Parallel/Application/ParallelFileProcessor.php +++ b/packages/Parallel/Application/ParallelFileProcessor.php @@ -1,17 +1,16 @@ workerCommandLineFactory = $workerCommandLineFactory; } - /** * @api * * @param callable(int $stepCount): void $postFileCallback Used for progress bar jump * @return array{coding_standard_errors: CodingStandardError[], file_diffs: FileDiff[], system_errors: SystemError[]|string[], system_errors_count: int} */ - public function check( - Schedule $schedule, - string $mainScript, - callable $postFileCallback, - ?string $projectConfigFile, - InputInterface $input - ): array { - $jobs = array_reverse($schedule->getJobs()); + public function check(Schedule $schedule, string $mainScript, callable $postFileCallback, ?string $projectConfigFile, InputInterface $input) : array + { + $jobs = \array_reverse($schedule->getJobs()); $streamSelectLoop = new StreamSelectLoop(); - // basic properties setup $numberOfProcesses = $schedule->getNumberOfProcesses(); - // initial counters $codingStandardErrors = []; $fileDiffs = []; $systemErrors = []; - $tcpServer = new TcpServer('127.0.0.1:0', $streamSelectLoop); $this->processPool = new ProcessPool($tcpServer); - - $tcpServer->on(ReactEvent::CONNECTION, function (ConnectionInterface $connection) use (&$jobs): void { - $inDecoder = new Decoder($connection, true, 512, 0, 4 * 1024 * 1024); + $tcpServer->on(ReactEvent::CONNECTION, function (ConnectionInterface $connection) use(&$jobs) : void { + $inDecoder = new Decoder($connection, \true, 512, 0, 4 * 1024 * 1024); $outEncoder = new Encoder($connection); - - $inDecoder->on(ReactEvent::DATA, function (array $data) use (&$jobs, $inDecoder, $outEncoder): void { + $inDecoder->on(ReactEvent::DATA, function (array $data) use(&$jobs, $inDecoder, $outEncoder) : void { $action = $data[ReactCommand::ACTION]; if ($action !== Action::HELLO) { return; } - $processIdentifier = $data[Option::PARALLEL_IDENTIFIER]; $parallelProcess = $this->processPool->getProcess($processIdentifier); $parallelProcess->bindConnection($inDecoder, $outEncoder); - if ($jobs === []) { $this->processPool->quitProcess($processIdentifier); return; } - - $job = array_pop($jobs); - $parallelProcess->request([ - ReactCommand::ACTION => Action::MAIN, - Content::FILES => $job, - ]); + $job = \array_pop($jobs); + $parallelProcess->request([ReactCommand::ACTION => Action::MAIN, Content::FILES => $job]); }); }); - /** @var string $serverAddress */ $serverAddress = $tcpServer->getAddress(); - /** @var int $serverPort */ - $serverPort = parse_url($serverAddress, PHP_URL_PORT); - + $serverPort = \parse_url($serverAddress, \PHP_URL_PORT); $systemErrorsCount = 0; - - $reachedSystemErrorsCountLimit = false; - - $handleErrorCallable = function (Throwable $throwable) use ( - &$systemErrors, - &$systemErrorsCount, - &$reachedSystemErrorsCountLimit - ): void { + $reachedSystemErrorsCountLimit = \false; + $handleErrorCallable = function (Throwable $throwable) use(&$systemErrors, &$systemErrorsCount, &$reachedSystemErrorsCountLimit) : void { $systemErrors[] = new SystemError($throwable->getLine(), $throwable->getMessage(), $throwable->getFile()); - ++$systemErrorsCount; - $reachedSystemErrorsCountLimit = true; + $reachedSystemErrorsCountLimit = \true; $this->processPool->quitAll(); }; - $timeoutInSeconds = SimpleParameterProvider::getIntParameter(Option::PARALLEL_TIMEOUT_IN_SECONDS); - for ($i = 0; $i < $numberOfProcesses; ++$i) { // nothing else to process, stop now if ($jobs === []) { break; } - $processIdentifier = Random::generate(); - $workerCommandLine = $this->workerCommandLineFactory->create( - $mainScript, - CheckCommand::class, - 'worker', - Option::PATHS, - $projectConfigFile, - $input, - $processIdentifier, - $serverPort, - ); - + $workerCommandLine = $this->workerCommandLineFactory->create($mainScript, CheckCommand::class, 'worker', Option::PATHS, $projectConfigFile, $input, $processIdentifier, $serverPort); $parallelProcess = new ParallelProcess($workerCommandLine, $streamSelectLoop, $timeoutInSeconds); $parallelProcess->start( // 1. callable on data - function (array $json) use ( - $parallelProcess, - &$systemErrors, - &$fileDiffs, - &$codingStandardErrors, - &$jobs, - $postFileCallback, - &$systemErrorsCount, - &$reachedInternalErrorsCountLimit, - $processIdentifier - ): void { + function (array $json) use($parallelProcess, &$systemErrors, &$fileDiffs, &$codingStandardErrors, &$jobs, $postFileCallback, &$systemErrorsCount, &$reachedInternalErrorsCountLimit, $processIdentifier) : void { // decode arrays to objects foreach ($json[Bridge::SYSTEM_ERRORS] as $jsonError) { - if (is_string($jsonError)) { + if (\is_string($jsonError)) { $systemErrors[] = 'System error: ' . $jsonError; continue; } - $systemErrors[] = SystemError::decode($jsonError); } - foreach ($json[Bridge::FILE_DIFFS] as $jsonError) { $fileDiffs[] = FileDiff::decode($jsonError); } - foreach ($json[Bridge::CODING_STANDARD_ERRORS] as $jsonError) { $codingStandardErrors[] = CodingStandardError::decode($jsonError); } - $postFileCallback($json[Bridge::FILES_COUNT]); - $systemErrorsCount += $json[Bridge::SYSTEM_ERRORS_COUNT]; if ($systemErrorsCount >= self::SYSTEM_ERROR_LIMIT) { - $reachedInternalErrorsCountLimit = true; + $reachedInternalErrorsCountLimit = \true; $this->processPool->quitAll(); } - if ($jobs === []) { $this->processPool->quitProcess($processIdentifier); return; } - - $job = array_pop($jobs); - $parallelProcess->request([ - ReactCommand::ACTION => Action::MAIN, - Content::FILES => $job, - ]); + $job = \array_pop($jobs); + $parallelProcess->request([ReactCommand::ACTION => Action::MAIN, Content::FILES => $job]); }, - // 2. callable on error $handleErrorCallable, - // 3. callable on exit - function ($exitCode, string $stdErr) use (&$systemErrors, $processIdentifier): void { + function ($exitCode, string $stdErr) use(&$systemErrors, $processIdentifier) : void { $this->processPool->tryQuitProcess($processIdentifier); if ($exitCode === Command::SUCCESS) { return; } - if ($exitCode === null) { return; } - $systemErrors[] = 'Child process error: ' . $stdErr; } ); - $this->processPool->attachProcess($processIdentifier, $parallelProcess); } - $streamSelectLoop->run(); - if ($reachedSystemErrorsCountLimit) { - $systemErrors[] = sprintf( - 'Reached system errors count limit of %d, exiting...', - self::SYSTEM_ERROR_LIMIT - ); + $systemErrors[] = \sprintf('Reached system errors count limit of %d, exiting...', self::SYSTEM_ERROR_LIMIT); } - - return [ - Bridge::CODING_STANDARD_ERRORS => $codingStandardErrors, - Bridge::FILE_DIFFS => $fileDiffs, - Bridge::SYSTEM_ERRORS => $systemErrors, - Bridge::SYSTEM_ERRORS_COUNT => count($systemErrors), - ]; + return [Bridge::CODING_STANDARD_ERRORS => $codingStandardErrors, Bridge::FILE_DIFFS => $fileDiffs, Bridge::SYSTEM_ERRORS => $systemErrors, Bridge::SYSTEM_ERRORS_COUNT => \count($systemErrors)]; } } diff --git a/packages/Parallel/ValueObject/Bridge.php b/packages/Parallel/ValueObject/Bridge.php index db2574e243e..02742914ce1 100644 --- a/packages/Parallel/ValueObject/Bridge.php +++ b/packages/Parallel/ValueObject/Bridge.php @@ -1,7 +1,6 @@ singleFileProcessor = $singleFileProcessor; + $this->parametersMerger = $parametersMerger; } - - public function run(Encoder $encoder, Decoder $decoder, Configuration $configuration): void + public function run(Encoder $encoder, Decoder $decoder, Configuration $configuration) : void { // 1. handle system error - $handleErrorCallback = static function (Throwable $throwable) use ($encoder): void { + $handleErrorCallback = static function (Throwable $throwable) use($encoder) : void { $systemErrors = new SystemError($throwable->getLine(), $throwable->getMessage(), $throwable->getFile()); - - $encoder->write([ - ReactCommand::ACTION => Action::RESULT, - Content::RESULT => [ - Bridge::SYSTEM_ERRORS => [$systemErrors], - Bridge::FILES_COUNT => 0, - Bridge::SYSTEM_ERRORS_COUNT => 1, - ], - ]); + $encoder->write([ReactCommand::ACTION => Action::RESULT, Content::RESULT => [Bridge::SYSTEM_ERRORS => [$systemErrors], Bridge::FILES_COUNT => 0, Bridge::SYSTEM_ERRORS_COUNT => 1]]); $encoder->end(); }; - $encoder->on(ReactEvent::ERROR, $handleErrorCallback); - // 2. collect diffs + errors from file processor - $decoder->on(ReactEvent::DATA, function (array $json) use ($encoder, $configuration): void { + $decoder->on(ReactEvent::DATA, function (array $json) use($encoder, $configuration) : void { $action = $json[ReactCommand::ACTION]; if ($action !== Action::MAIN) { return; } - $systemErrorsCount = 0; - /** @var string[] $filePaths */ $filePaths = $json[Content::FILES] ?? []; - $errorAndFileDiffs = []; $systemErrors = []; - foreach ($filePaths as $filePath) { try { - $currentErrorsAndFileDiffs = $this->singleFileProcessor->processFilePath( - $filePath, - $configuration - ); - - $errorAndFileDiffs = $this->parametersMerger->merge( - $errorAndFileDiffs, - $currentErrorsAndFileDiffs - ); + $currentErrorsAndFileDiffs = $this->singleFileProcessor->processFilePath($filePath, $configuration); + $errorAndFileDiffs = $this->parametersMerger->merge($errorAndFileDiffs, $currentErrorsAndFileDiffs); } catch (Throwable $throwable) { ++$systemErrorsCount; - - $errorMessage = sprintf('System error: "%s"', $throwable->getMessage()); + $errorMessage = \sprintf('System error: "%s"', $throwable->getMessage()); $errorMessage .= 'Run ECS with "--debug" option and post the report here: https://github.com/symplify/symplify/issues/new'; $systemErrors[] = new SystemError($throwable->getLine(), $errorMessage, $filePath); } } - /** * this invokes all listeners listening $decoder->on(...) @see ReactEvent::DATA */ - $encoder->write([ - ReactCommand::ACTION => Action::RESULT, - Content::RESULT => [ - Bridge::CODING_STANDARD_ERRORS => $errorAndFileDiffs[Bridge::CODING_STANDARD_ERRORS] ?? [], - Bridge::FILE_DIFFS => $errorAndFileDiffs[Bridge::FILE_DIFFS] ?? [], - Bridge::FILES_COUNT => count($filePaths), - Bridge::SYSTEM_ERRORS => $systemErrors, - Bridge::SYSTEM_ERRORS_COUNT => $systemErrorsCount, - ], - ]); + $encoder->write([ReactCommand::ACTION => Action::RESULT, Content::RESULT => [Bridge::CODING_STANDARD_ERRORS => $errorAndFileDiffs[Bridge::CODING_STANDARD_ERRORS] ?? [], Bridge::FILE_DIFFS => $errorAndFileDiffs[Bridge::FILE_DIFFS] ?? [], Bridge::FILES_COUNT => \count($filePaths), Bridge::SYSTEM_ERRORS => $systemErrors, Bridge::SYSTEM_ERRORS_COUNT => $systemErrorsCount]]); }); - $decoder->on(ReactEvent::ERROR, $handleErrorCallback); } } diff --git a/packages/Skipper/Contract/SkipVoterInterface.php b/packages/Skipper/Contract/SkipVoterInterface.php index 2918d8962e5..85d4b5c17ec 100644 --- a/packages/Skipper/Contract/SkipVoterInterface.php +++ b/packages/Skipper/Contract/SkipVoterInterface.php @@ -1,14 +1,17 @@ normalizePath($matchingPath); $normalizedFilePath = $this->normalizePath($filePath); - - if (fnmatch($normalizedMatchingPath, $normalizedFilePath)) { - return true; + if (\fnmatch($normalizedMatchingPath, $normalizedFilePath)) { + return \true; } - // in case of relative compare - return fnmatch('*/' . $normalizedMatchingPath, $normalizedFilePath); + return \fnmatch('*/' . $normalizedMatchingPath, $normalizedFilePath); } - - private function normalizePath(string $path): string + private function normalizePath(string $path) : string { - return str_replace('\\', '/', $path); + return \str_replace('\\', '/', $path); } } diff --git a/packages/Skipper/Matcher/FileInfoMatcher.php b/packages/Skipper/Matcher/FileInfoMatcher.php index 1c374512746..15073fb33da 100644 --- a/packages/Skipper/Matcher/FileInfoMatcher.php +++ b/packages/Skipper/Matcher/FileInfoMatcher.php @@ -1,60 +1,62 @@ fnMatchPathNormalizer = $fnMatchPathNormalizer; + $this->fnmatcher = $fnmatcher; } - /** * @param string[] $filePatterns + * @param \SplFileInfo|string $fileInfo */ - public function doesFileInfoMatchPatterns(SplFileInfo | string $fileInfo, array $filePatterns): bool + public function doesFileInfoMatchPatterns($fileInfo, array $filePatterns) : bool { foreach ($filePatterns as $filePattern) { if ($this->doesFileInfoMatchPattern($fileInfo, $filePattern)) { - return true; + return \true; } } - - return false; + return \false; } - /** * Supports both relative and absolute $file path. They differ for PHP-CS-Fixer and PHP_CodeSniffer. + * @param \SplFileInfo|string $file */ - private function doesFileInfoMatchPattern(SplFileInfo | string $file, string $ignoredPath): bool + private function doesFileInfoMatchPattern($file, string $ignoredPath) : bool { $filePath = $file instanceof SplFileInfo ? $file->getRealPath() : $file; - // in ecs.php, the path can be absolute if ($filePath === $ignoredPath) { - return true; + return \true; } - $ignoredPath = $this->fnMatchPathNormalizer->normalizeForFnmatch($ignoredPath); if ($ignoredPath === '') { - return false; + return \false; } - - if (str_starts_with($filePath, $ignoredPath)) { - return true; + if (\strncmp($filePath, $ignoredPath, \strlen($ignoredPath)) === 0) { + return \true; } - - if (str_ends_with($filePath, $ignoredPath)) { - return true; + if (\substr_compare($filePath, $ignoredPath, -\strlen($ignoredPath)) === 0) { + return \true; } - return $this->fnmatcher->match($ignoredPath, $filePath); } } diff --git a/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php b/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php index f19711a3b44..101aa1e0f94 100644 --- a/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php +++ b/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php @@ -1,47 +1,38 @@ */ - private array $skippedClassAndCodes = []; - + private $skippedClassAndCodes = []; /** * @return array */ - public function resolve(): array + public function resolve() : array { if ($this->skippedClassAndCodes !== []) { return $this->skippedClassAndCodes; } - $skip = SimpleParameterProvider::getArrayParameter(Option::SKIP); - foreach ($skip as $key => $value) { // e.g. [SomeClass::class] → shift values to [SomeClass::class => null] - if (is_int($key)) { + if (\is_int($key)) { $key = $value; $value = null; } - - if (substr_count((string) $key, '.') !== 1) { + if (\substr_count((string) $key, '.') !== 1) { continue; } - Assert::string($key); - $this->skippedClassAndCodes[$key] = $value; } - return $this->skippedClassAndCodes; } } diff --git a/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php b/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php index 9993da810cb..6a93d476424 100644 --- a/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php +++ b/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php @@ -1,48 +1,39 @@ */ - private array $skippedClasses = []; - + private $skippedClasses = []; /** * @return array */ - public function resolve(): array + public function resolve() : array { if ($this->skippedClasses !== []) { return $this->skippedClasses; } - $skip = SimpleParameterProvider::getArrayParameter(Option::SKIP); - foreach ($skip as $key => $value) { // e.g. [SomeClass::class] → shift values to [SomeClass::class => null] - if (is_int($key)) { + if (\is_int($key)) { $key = $value; $value = null; } - - if (! is_string($key)) { + if (!\is_string($key)) { continue; } - - if (! class_exists($key) && ! interface_exists($key)) { + if (!\class_exists($key) && !\interface_exists($key)) { continue; } - $this->skippedClasses[$key] = $value; } - return $this->skippedClasses; } } diff --git a/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php b/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php index 1af368c9da8..f1d3758b7da 100644 --- a/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php +++ b/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php @@ -1,48 +1,39 @@ */ - private array $skippedMessages = []; - + private $skippedMessages = []; /** * @return array */ - public function resolve(): array + public function resolve() : array { if ($this->skippedMessages !== []) { return $this->skippedMessages; } - $skip = SimpleParameterProvider::getArrayParameter(Option::SKIP); - foreach ($skip as $key => $value) { // e.g. [SomeClass::class] → shift values to [SomeClass::class => null] - if (is_int($key)) { + if (\is_int($key)) { $key = $value; $value = null; } - - if (! is_string($key)) { + if (!\is_string($key)) { continue; } - - if (substr_count($key, ' ') === 0) { + if (\substr_count($key, ' ') === 0) { continue; } - $this->skippedMessages[$key] = $value; } - return $this->skippedMessages; } } diff --git a/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php b/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php index cb841ef030a..d5a97d6b4b8 100644 --- a/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php +++ b/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php @@ -1,53 +1,50 @@ pathNormalizer = $pathNormalizer; } - /** * @return string[] */ - public function resolve(): array + public function resolve() : array { if ($this->skippedPaths !== []) { return $this->skippedPaths; } - $skip = SimpleParameterProvider::getArrayParameter(Option::SKIP); foreach ($skip as $key => $value) { - if (! is_int($key)) { + if (!\is_int($key)) { continue; } - - if (\str_contains((string) $value, '*')) { + if (\strpos((string) $value, '*') !== \false) { $this->skippedPaths[] = $this->pathNormalizer->normalizePath($value); continue; } - - if (file_exists($value)) { + if (\file_exists($value)) { $this->skippedPaths[] = $this->pathNormalizer->normalizePath($value); } } - return $this->skippedPaths; } } diff --git a/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php b/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php index 63a4eb6b5df..a32a5803f23 100644 --- a/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php +++ b/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php @@ -1,51 +1,59 @@ skippedClassAndCodesResolver = $skippedClassAndCodesResolver; + $this->fileInfoMatcher = $fileInfoMatcher; } - - public function match(string | object $element): bool + /** + * @param string|object $element + */ + public function match($element) : bool { - if (! is_string($element)) { - return false; + if (!\is_string($element)) { + return \false; } - - return substr_count($element, '.') === 1; + return \substr_count($element, '.') === 1; } - - public function shouldSkip(string | object $element, SplFileInfo | string $file): bool + /** + * @param string|object $element + * @param \SplFileInfo|string $file + */ + public function shouldSkip($element, $file) : bool { - if (is_object($element)) { - return false; + if (\is_object($element)) { + return \false; } - $skippedClassAndCodes = $this->skippedClassAndCodesResolver->resolve(); - if (! array_key_exists($element, $skippedClassAndCodes)) { - return false; + if (!\array_key_exists($element, $skippedClassAndCodes)) { + return \false; } - // skip regardless the path $skippedPaths = $skippedClassAndCodes[$element]; if ($skippedPaths === null) { - return true; + return \true; } - return $this->fileInfoMatcher->doesFileInfoMatchPatterns($file, $skippedPaths); } } diff --git a/packages/Skipper/SkipVoter/ClassSkipVoter.php b/packages/Skipper/SkipVoter/ClassSkipVoter.php index 2d2233c0461..2020dfe0ac3 100644 --- a/packages/Skipper/SkipVoter/ClassSkipVoter.php +++ b/packages/Skipper/SkipVoter/ClassSkipVoter.php @@ -1,32 +1,43 @@ skipSkipper = $skipSkipper; + $this->skippedClassResolver = $skippedClassResolver; } - - public function match(string | object $element): bool + /** + * @param string|object $element + */ + public function match($element) : bool { - if (is_object($element)) { - return true; + if (\is_object($element)) { + return \true; } - - return class_exists($element) || interface_exists($element); + return \class_exists($element) || \interface_exists($element); } - - public function shouldSkip(string | object $element, SplFileInfo | string $file): bool + /** + * @param string|object $element + * @param \SplFileInfo|string $file + */ + public function shouldSkip($element, $file) : bool { $skippedClasses = $this->skippedClassResolver->resolve(); return $this->skipSkipper->doesMatchSkip($element, $file, $skippedClasses); diff --git a/packages/Skipper/SkipVoter/MessageSkipVoter.php b/packages/Skipper/SkipVoter/MessageSkipVoter.php index 339fc8f3089..c066c3ca0b3 100644 --- a/packages/Skipper/SkipVoter/MessageSkipVoter.php +++ b/packages/Skipper/SkipVoter/MessageSkipVoter.php @@ -1,48 +1,56 @@ skippedMessagesResolver = $skippedMessagesResolver; + $this->fileInfoMatcher = $fileInfoMatcher; } - - public function match(string | object $element): bool + /** + * @param string|object $element + */ + public function match($element) : bool { - if (is_object($element)) { - return false; + if (\is_object($element)) { + return \false; } - - return substr_count($element, ' ') > 0; + return \substr_count($element, ' ') > 0; } - - public function shouldSkip(string | object $element, SplFileInfo | string $file): bool + /** + * @param string|object $element + * @param \SplFileInfo|string $file + */ + public function shouldSkip($element, $file) : bool { - if (is_object($element)) { - return false; + if (\is_object($element)) { + return \false; } - $skippedMessages = $this->skippedMessagesResolver->resolve(); - if (! array_key_exists($element, $skippedMessages)) { - return false; + if (!\array_key_exists($element, $skippedMessages)) { + return \false; } - // skip regardless the path $skippedPaths = $skippedMessages[$element]; if ($skippedPaths === null) { - return true; + return \true; } - return $this->fileInfoMatcher->doesFileInfoMatchPatterns($file, $skippedPaths); } } diff --git a/packages/Skipper/SkipVoter/PathSkipVoter.php b/packages/Skipper/SkipVoter/PathSkipVoter.php index 52d483ec39e..4cc0f9109c3 100644 --- a/packages/Skipper/SkipVoter/PathSkipVoter.php +++ b/packages/Skipper/SkipVoter/PathSkipVoter.php @@ -1,28 +1,40 @@ fileInfoMatcher = $fileInfoMatcher; + $this->skippedPathsResolver = $skippedPathsResolver; } - - public function match(string | object $element): bool + /** + * @param string|object $element + */ + public function match($element) : bool { - return true; + return \true; } - - public function shouldSkip(string | object $element, SplFileInfo | string $file): bool + /** + * @param string|object $element + * @param \SplFileInfo|string $file + */ + public function shouldSkip($element, $file) : bool { $skippedPaths = $this->skippedPathsResolver->resolve(); return $this->fileInfoMatcher->doesFileInfoMatchPatterns($file, $skippedPaths); diff --git a/packages/Skipper/Skipper/SkipSkipper.php b/packages/Skipper/Skipper/SkipSkipper.php index 71b66b8996b..3f6fa06a8db 100644 --- a/packages/Skipper/Skipper/SkipSkipper.php +++ b/packages/Skipper/Skipper/SkipSkipper.php @@ -1,42 +1,42 @@ fileInfoMatcher = $fileInfoMatcher; } - /** * @param array $skippedClasses + * @param object|string $checker + * @param \SplFileInfo|string $file */ - public function doesMatchSkip(object | string $checker, SplFileInfo | string $file, array $skippedClasses): bool + public function doesMatchSkip($checker, $file, array $skippedClasses) : bool { foreach ($skippedClasses as $skippedClass => $skippedFiles) { - if (! is_a($checker, $skippedClass, true)) { + if (!\is_a($checker, $skippedClass, \true)) { continue; } - // skip everywhere - if (! is_array($skippedFiles)) { - return true; + if (!\is_array($skippedFiles)) { + return \true; } - if ($this->fileInfoMatcher->doesFileInfoMatchPatterns($file, $skippedFiles)) { - return true; + return \true; } } - - return false; + return \false; } } diff --git a/packages/Skipper/Skipper/Skipper.php b/packages/Skipper/Skipper/Skipper.php index 52b3e2ef70f..5864f78b81e 100644 --- a/packages/Skipper/Skipper/Skipper.php +++ b/packages/Skipper/Skipper/Skipper.php @@ -1,7 +1,6 @@ skipVoters = [$classAndCodeSkipVoter, $classSkipVoter, $messageSkipVoter, $pathSkipVoter]; } - - public function shouldSkipElement(string | object $element): bool + /** + * @param string|object $element + */ + public function shouldSkipElement($element) : bool { return $this->shouldSkipElementAndFilePath($element, __FILE__); } - - public function shouldSkipFilePath(string $filePath): bool + public function shouldSkipFilePath(string $filePath) : bool { return $this->shouldSkipElementAndFilePath(self::FILE_ELEMENT, $filePath); } - - public function shouldSkipElementAndFilePath(string | object $element, string $filePath): bool + /** + * @param string|object $element + */ + public function shouldSkipElementAndFilePath($element, string $filePath) : bool { foreach ($this->skipVoters as $skipVoter) { - if (! $skipVoter->match($element)) { + if (!$skipVoter->match($element)) { continue; } - - if (! $skipVoter->shouldSkip($element, $filePath)) { + if (!$skipVoter->shouldSkip($element, $filePath)) { continue; } - - return true; + return \true; } - - return false; + return \false; } } diff --git a/packages/SniffRunner/Application/SniffFileProcessor.php b/packages/SniffRunner/Application/SniffFileProcessor.php index a5d83af833a..cabc68b7c3e 100644 --- a/packages/SniffRunner/Application/SniffFileProcessor.php +++ b/packages/SniffRunner/Application/SniffFileProcessor.php @@ -1,10 +1,9 @@ */ - private const ESCALATE_WARNINGS_SNIFF = [ - AssignmentInConditionSniff::class, - PropertyDeclarationSniff::class, - MethodDeclarationSniff::class, - CommentedOutCodeSniff::class, - UnusedFunctionParameterSniff::class, - ]; - + private const ESCALATE_WARNINGS_SNIFF = [AssignmentInConditionSniff::class, PropertyDeclarationSniff::class, MethodDeclarationSniff::class, CommentedOutCodeSniff::class, UnusedFunctionParameterSniff::class]; + /** + * @readonly + * @var \PHP_CodeSniffer\Fixer + */ + private $fixer; + /** + * @readonly + * @var \Symplify\EasyCodingStandard\SniffRunner\File\FileFactory + */ + private $fileFactory; + /** + * @readonly + * @var \PhpCsFixer\Differ\DifferInterface + */ + private $differ; + /** + * @readonly + * @var \Symplify\EasyCodingStandard\SniffRunner\DataCollector\SniffMetadataCollector + */ + private $sniffMetadataCollector; + /** + * @readonly + * @var \Symfony\Component\Filesystem\Filesystem + */ + private $filesystem; + /** + * @readonly + * @var \Symplify\EasyCodingStandard\Error\FileDiffFactory + */ + private $fileDiffFactory; /** * @var Sniff[] */ - private array $sniffs = []; - + private $sniffs = []; /** * @var array */ - private array $tokenListeners = []; - + private $tokenListeners = []; /** * @param Sniff[] $sniffs */ - public function __construct( - private readonly Fixer $fixer, - private readonly FileFactory $fileFactory, - private readonly DifferInterface $differ, - private readonly SniffMetadataCollector $sniffMetadataCollector, - private readonly \Symfony\Component\Filesystem\Filesystem $filesystem, - private readonly FileDiffFactory $fileDiffFactory, - array $sniffs - ) { + public function __construct(Fixer $fixer, FileFactory $fileFactory, DifferInterface $differ, SniffMetadataCollector $sniffMetadataCollector, \ECSPrefix202307\Symfony\Component\Filesystem\Filesystem $filesystem, FileDiffFactory $fileDiffFactory, array $sniffs) + { + $this->fixer = $fixer; + $this->fileFactory = $fileFactory; + $this->differ = $differ; + $this->sniffMetadataCollector = $sniffMetadataCollector; + $this->filesystem = $filesystem; + $this->fileDiffFactory = $fileDiffFactory; foreach ($sniffs as $sniff) { $this->addSniff($sniff); } } - /** * @return Sniff[] */ - public function getCheckers(): array + public function getCheckers() : array { return $this->sniffs; } - /** * @return array{file_diffs?: FileDiff[], coding_standard_errors?: CodingStandardError[]} */ - public function processFile(string $filePath, Configuration $configuration): array + public function processFile(string $filePath, Configuration $configuration) : array { $this->sniffMetadataCollector->reset(); - $errorsAndDiffs = []; - $file = $this->fileFactory->createFromFile($filePath); $this->fixFile($file, $this->fixer, $filePath, $this->tokenListeners, self::ESCALATE_WARNINGS_SNIFF); - // add coding standard errors $codingStandardErrors = $this->sniffMetadataCollector->getCodingStandardErrors(); if ($codingStandardErrors !== []) { $errorsAndDiffs[Bridge::CODING_STANDARD_ERRORS] = $codingStandardErrors; } - $fileContents = FileSystem::read($filePath); - // add diff if ($fileContents !== $this->fixer->getContents()) { $diff = $this->differ->diff($fileContents, $this->fixer->getContents()); - $appliedCheckers = $this->sniffMetadataCollector->getAppliedSniffs(); - - $fileDiff = $this->fileDiffFactory->createFromDiffAndAppliedCheckers( - $filePath, - $diff, - $appliedCheckers - ); - + $fileDiff = $this->fileDiffFactory->createFromDiffAndAppliedCheckers($filePath, $diff, $appliedCheckers); $errorsAndDiffs[Bridge::FILE_DIFFS][] = $fileDiff; } - if ($configuration->isFixer()) { $this->filesystem->dumpFile($file->getFilename(), $this->fixer->getContents()); } - return $errorsAndDiffs; } - /** * For tests or printing contenet */ - public function processFileToString(string $filePath): string + public function processFileToString(string $filePath) : string { $file = $this->fileFactory->createFromFile($filePath); $this->fixFile($file, $this->fixer, $filePath, $this->tokenListeners, []); - return $this->fixer->getContents(); } - - private function addSniff(Sniff $sniff): void + private function addSniff(Sniff $sniff) : void { $this->sniffs[] = $sniff; $tokens = $sniff->register(); @@ -136,7 +135,6 @@ private function addSniff(Sniff $sniff): void $this->tokenListeners[$token][] = $sniff; } } - /** * Mimics @see \PHP_CodeSniffer\Files\File::process() * @@ -145,27 +143,17 @@ private function addSniff(Sniff $sniff): void * @param array $tokenListeners * @param array> $reportSniffClassesWarnings */ - private function fixFile( - File $file, - Fixer $fixer, - string $filePath, - array $tokenListeners, - array $reportSniffClassesWarnings - ): void { + private function fixFile(File $file, Fixer $fixer, string $filePath, array $tokenListeners, array $reportSniffClassesWarnings) : void + { $previousContent = FileSystem::read($filePath); - $this->fixer->loops = 0; - do { // Only needed once file content has changed. $content = $previousContent; - // set property value - PrivatesAccessorHelper::setPropertyValue($fixer, 'inConflict', false); - + PrivatesAccessorHelper::setPropertyValue($fixer, 'inConflict', \false); $file->setContent($content); $file->processWithTokenListenersAndFilePath($tokenListeners, $filePath, $reportSniffClassesWarnings); - // fixed content $previousContent = $fixer->getContents(); ++$this->fixer->loops; diff --git a/packages/SniffRunner/DataCollector/SniffMetadataCollector.php b/packages/SniffRunner/DataCollector/SniffMetadataCollector.php index 11fdd57d064..bb8abfebc6e 100644 --- a/packages/SniffRunner/DataCollector/SniffMetadataCollector.php +++ b/packages/SniffRunner/DataCollector/SniffMetadataCollector.php @@ -1,55 +1,47 @@ */ - private array $appliedSniffs = []; - + private $appliedSniffs = []; /** * @var CodingStandardError[] */ - private array $codingStandardErrors = []; - + private $codingStandardErrors = []; /** * @param class-string|string $checkerClass */ - public function addAppliedSniff(string $checkerClass): void + public function addAppliedSniff(string $checkerClass) : void { $this->appliedSniffs[] = $checkerClass; } - /** * @return array|string> */ - public function getAppliedSniffs(): array + public function getAppliedSniffs() : array { return $this->appliedSniffs; } - - public function reset(): void + public function reset() : void { $this->appliedSniffs = []; $this->codingStandardErrors = []; } - - public function addCodingStandardError(CodingStandardError $codingStandardError): void + public function addCodingStandardError(CodingStandardError $codingStandardError) : void { $this->codingStandardErrors[] = $codingStandardError; } - /** * @return CodingStandardError[] */ - public function getCodingStandardErrors(): array + public function getCodingStandardErrors() : array { return $this->codingStandardErrors; } diff --git a/packages/SniffRunner/File/FileFactory.php b/packages/SniffRunner/File/FileFactory.php index 4e86d4d5be0..1590072fc95 100644 --- a/packages/SniffRunner/File/FileFactory.php +++ b/packages/SniffRunner/File/FileFactory.php @@ -1,42 +1,51 @@ fixer = $fixer; + $this->skipper = $skipper; + $this->sniffMetadataCollector = $sniffMetadataCollector; + $this->easyCodingStandardStyle = $easyCodingStandardStyle; } - - public function createFromFile(string $filePath): File + public function createFromFile(string $filePath) : File { $fileContents = FileSystem::read($filePath); $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd($filePath); - - return new File( - $relativeFilePath, - $fileContents, - $this->fixer, - $this->skipper, - $this->sniffMetadataCollector, - $this->easyCodingStandardStyle - ); + return new File($relativeFilePath, $fileContents, $this->fixer, $this->skipper, $this->sniffMetadataCollector, $this->easyCodingStandardStyle); } } diff --git a/packages/SniffRunner/ValueObject/Error/CodingStandardError.php b/packages/SniffRunner/ValueObject/Error/CodingStandardError.php index 0d6023b6f03..9a93033b3c8 100644 --- a/packages/SniffRunner/ValueObject/Error/CodingStandardError.php +++ b/packages/SniffRunner/ValueObject/Error/CodingStandardError.php @@ -1,70 +1,72 @@ line = $line; + $this->message = $message; + $this->checkerClass = $checkerClass; + $this->relativeFilePath = $relativeFilePath; } - - public function getLine(): int + public function getLine() : int { return $this->line; } - - public function getMessage(): string + public function getMessage() : string { return $this->message; } - - public function getCheckerClass(): string + public function getCheckerClass() : string { return $this->checkerClass; } - - public function getFileWithLine(): string + public function getFileWithLine() : string { return $this->relativeFilePath . ':' . $this->line; } - - public function getRelativeFilePath(): string + public function getRelativeFilePath() : string { return $this->relativeFilePath; } - /** * @return array{line: int, message: string, checker_class: string, relative_file_path: string} */ - public function jsonSerialize(): array + public function jsonSerialize() : array { - return [ - Name::LINE => $this->line, - Name::MESSAGE => $this->message, - Name::CHECKER_CLASS => $this->checkerClass, - Name::RELATIVE_FILE_PATH => $this->relativeFilePath, - ]; + return [Name::LINE => $this->line, Name::MESSAGE => $this->message, Name::CHECKER_CLASS => $this->checkerClass, Name::RELATIVE_FILE_PATH => $this->relativeFilePath]; } - /** * @param array{line: int, message: string, checker_class: string, relative_file_path: string} $json + * @return $this */ - public static function decode(array $json): self + public static function decode(array $json) : \ECSPrefix202307\Symplify\EasyParallel\Contract\SerializableInterface { - return new self( - $json[Name::LINE], - $json[Name::MESSAGE], - $json[Name::CHECKER_CLASS], - $json[Name::RELATIVE_FILE_PATH], - ); + return new self($json[Name::LINE], $json[Name::MESSAGE], $json[Name::CHECKER_CLASS], $json[Name::RELATIVE_FILE_PATH]); } } diff --git a/packages/SniffRunner/ValueObject/File.php b/packages/SniffRunner/ValueObject/File.php index b38ef28558c..72ab31708b3 100644 --- a/packages/SniffRunner/ValueObject/File.php +++ b/packages/SniffRunner/ValueObject/File.php @@ -1,7 +1,6 @@ */ - private array $tokenListeners = []; - - private ?string $filePath = null; - + private $tokenListeners = []; + /** + * @var string|null + */ + private $filePath; /** * @var array> */ - private array $reportSniffClassesWarnings = []; - - public function __construct( - string $path, - string $content, - Fixer $fixer, - private Skipper $skipper, - private SniffMetadataCollector $sniffMetadataCollector, - private EasyCodingStandardStyle $easyCodingStandardStyle - ) { + private $reportSniffClassesWarnings = []; + public function __construct(string $path, string $content, Fixer $fixer, Skipper $skipper, SniffMetadataCollector $sniffMetadataCollector, EasyCodingStandardStyle $easyCodingStandardStyle) + { + $this->skipper = $skipper; + $this->sniffMetadataCollector = $sniffMetadataCollector; + $this->easyCodingStandardStyle = $easyCodingStandardStyle; $this->path = $path; $this->content = $content; - // this property cannot be promoted as defined in constructor $this->fixer = $fixer; - $this->eolChar = Common::detectLineEndings($content); - // compat - if (! defined('PHP_CODESNIFFER_CBF')) { - define('PHP_CODESNIFFER_CBF', false); + if (!\defined('PHP_CODESNIFFER_CBF')) { + \define('PHP_CODESNIFFER_CBF', \false); } - // parent required - $this->config = new Config([], false); + $this->config = new Config([], \false); $this->config->tabWidth = 4; - $this->config->annotations = false; + $this->config->annotations = \false; $this->config->encoding = 'UTF-8'; } - /** * Mimics @see * https://github.com/squizlabs/PHP_CodeSniffer/blob/e4da24f399d71d1077f93114a72e305286020415/src/Files/File.php#L310 */ - public function process(): void + public function process() : void { $this->parse(); $this->fixer->startFile($this); - $currentFilePath = $this->filePath; - if (! is_string($currentFilePath)) { + if (!\is_string($currentFilePath)) { throw new ShouldNotHappenException(); } - foreach ($this->tokens as $stackPtr => $token) { - if (! isset($this->tokenListeners[$token['code']])) { + if (!isset($this->tokenListeners[$token['code']])) { continue; } - foreach ($this->tokenListeners[$token['code']] as $sniff) { if ($this->skipper->shouldSkipElementAndFilePath($sniff, $currentFilePath)) { continue; } - $this->reportActiveSniffClass($sniff); - $sniff->process($this, $stackPtr); } } - $this->fixedCount += $this->fixer->getFixCount(); } - /** * Delegate to addError(). * * @param mixed[] $data */ - public function addFixableError($error, $stackPtr, $code, $data = [], $severity = 0): bool + public function addFixableError($error, $stackPtr, $code, $data = [], $severity = 0) : bool { $fullyQualifiedCode = $this->resolveFullyQualifiedCode($code); $this->sniffMetadataCollector->addAppliedSniff($fullyQualifiedCode); - - return ! $this->shouldSkipError($error, $code, $data); + return !$this->shouldSkipError($error, $code, $data); } - /** * @param mixed[] $data */ - public function addError($error, $stackPtr, $code, $data = [], $severity = 0, $fixable = false): bool + public function addError($error, $stackPtr, $code, $data = [], $severity = 0, $fixable = \false) : bool { if ($this->shouldSkipError($error, $code, $data)) { - return false; + return \false; } - return parent::addError($error, $stackPtr, $code, $data, $severity, $fixable); } - /** * @param mixed $data * Allow only specific classes */ - public function addWarning($warning, $stackPtr, $code, $data = [], $severity = 0, $fixable = false): bool + public function addWarning($warning, $stackPtr, $code, $data = [], $severity = 0, $fixable = \false) : bool { if ($this->activeSniffClass === null) { throw new ShouldNotHappenException(); } - if ($this->shouldSkipClassWarnings($this->activeSniffClass)) { - return false; + return \false; } - return $this->addError($warning, $stackPtr, $code, $data, $severity, $fixable); } - /** * @param array> $reportSniffClassesWarnings * @param array $tokenListeners */ - public function processWithTokenListenersAndFilePath( - array $tokenListeners, - string $filePath, - array $reportSniffClassesWarnings - ): void { + public function processWithTokenListenersAndFilePath(array $tokenListeners, string $filePath, array $reportSniffClassesWarnings) : void + { $this->tokenListeners = $tokenListeners; $this->filePath = $filePath; $this->reportSniffClassesWarnings = $reportSniffClassesWarnings; $this->process(); } - /** * @param mixed $data * Delegated from addError(). */ - protected function addMessage( - $isError, - $message, - $line, - $column, - $sniffClassOrCode, - $data, - $severity, - $isFixable = false - ): bool { + protected function addMessage($isError, $message, $line, $column, $sniffClassOrCode, $data, $severity, $isFixable = \false) : bool + { // skip warnings - if (! $isError) { - return false; + if (!$isError) { + return \false; } - // hardcode skip the PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis\AssignmentInConditionSniff.FoundInWhileCondition // as the only code is passed and this rule does not make sense if ($sniffClassOrCode === 'FoundInWhileCondition') { - return false; + return \false; } - - $message = $data !== [] ? vsprintf($message, $data) : $message; - + $message = $data !== [] ? \vsprintf($message, $data) : $message; $checkerClass = $this->resolveFullyQualifiedCode($sniffClassOrCode); $codingStandardError = new CodingStandardError($line, $message, $checkerClass, $this->getFilename()); - $this->sniffMetadataCollector->addCodingStandardError($codingStandardError); - if ($isFixable) { return $isFixable; } - // do not add non-fixable errors twice return $this->fixer->loops === 0; } - - private function reportActiveSniffClass(Sniff $sniff): void + private function reportActiveSniffClass(Sniff $sniff) : void { // used in other places later - $this->activeSniffClass = $sniff::class; - - if (! $this->easyCodingStandardStyle->isDebug()) { + $this->activeSniffClass = \get_class($sniff); + if (!$this->easyCodingStandardStyle->isDebug()) { return; } - if ($this->previousActiveSniffClass === $this->activeSniffClass) { return; } - $this->easyCodingStandardStyle->writeln(' [sniff] ' . $this->activeSniffClass); $this->previousActiveSniffClass = $this->activeSniffClass; } - - private function resolveFullyQualifiedCode(string $sniffClassOrCode): string + private function resolveFullyQualifiedCode(string $sniffClassOrCode) : string { - if (class_exists($sniffClassOrCode)) { + if (\class_exists($sniffClassOrCode)) { return $sniffClassOrCode; } - return $this->activeSniffClass . '.' . $sniffClassOrCode; } - /** * @param string[] $data */ - private function shouldSkipError(string $error, string $code, array $data): bool + private function shouldSkipError(string $error, string $code, array $data) : bool { $fullyQualifiedCode = $this->resolveFullyQualifiedCode($code); - - if (! is_string($this->filePath)) { + if (!\is_string($this->filePath)) { throw new ShouldNotHappenException(); } - if ($this->skipper->shouldSkipElementAndFilePath($fullyQualifiedCode, $this->filePath)) { - return true; + return \true; } - - $message = $data !== [] ? vsprintf($error, $data) : $error; - + $message = $data !== [] ? \vsprintf($error, $data) : $error; return $this->skipper->shouldSkipElementAndFilePath($message, $this->filePath); } - - private function shouldSkipClassWarnings(string $sniffClass): bool + private function shouldSkipClassWarnings(string $sniffClass) : bool { foreach ($this->reportSniffClassesWarnings as $reportSniffClassWarning) { - if (is_a($sniffClass, $reportSniffClassWarning, true)) { - return false; + if (\is_a($sniffClass, $reportSniffClassWarning, \true)) { + return \false; } } - - return true; + return \true; } } diff --git a/phpstan.neon b/phpstan.neon deleted file mode 100644 index 0f664b759fe..00000000000 --- a/phpstan.neon +++ /dev/null @@ -1,50 +0,0 @@ -parameters: - level: 8 - - reportUnmatchedIgnoredErrors: false - - # requires exact closure types - checkMissingCallableSignature: true - - paths: - - src - - tests - - packages - - packages-tests - - ecs.php - - rector.php - - excludePaths: - # deprecated, to be removed - - scoper.php - - # tests - - '*/Source/*' - - '*/Fixture/*' - - bootstrapFiles: - - tests/bootstrap.php - - ignoreErrors: - # set above - - - path: packages/Parallel/Application/ParallelFileProcessor.php - message: '#Cannot call method (.*?)\(\) on Symplify\\EasyParallel\\ValueObject\\ProcessPool\|null#' - - - '#Method Symplify\\EasyCodingStandard\\Console\\Command\\ListCheckersCommand\:\:getObjectClasses\(\) should return array> but returns array\|class\-string>#' - - - '#Method Symplify\\EasyCodingStandard\\Application\\SingleFileProcessor\:\:processFilePath\(\) should return array\{file_diffs\?\: array, coding_standard_errors\?\: array\} but returns array<(.*?), array>#' - - - '#Method Symplify\\EasyCodingStandard\\FixerRunner\\Parser\\FileToTokensParser\:\:parseFromFilePath\(\) should return iterable&PhpCsFixer\\Tokenizer\\Tokens but returns PhpCsFixer\\Tokenizer\\Tokens#' - - - '#Parameter \#1 \$skips of method Symplify\\EasyCodingStandard\\Config\\ECSConfig\:\:skip\(\) expects array\|int, array\|string\|null>, array\|string\|null> given#' - - # false positive on custom config tets - - - message: '#Missing call to parent\:\:setUp\(\) method#' - paths: - - packages-tests/Skipper/Skipper/Skipper/SkipperTest.php - - packages-tests/Skipper/Skipper/Skip/SkipSkipperTest.php - - packages-tests/Skipper/SkipCriteriaResolver/SkippedPathsResolver/SkippedPathsResolverTest.php - - packages-tests/FixerRunner/Application/FileProcessorTest.ph - - src/Testing/PHPUnit/AbstractCheckerTestCase.php diff --git a/phpunit.xml b/phpunit.xml deleted file mode 100644 index daca3e2d35c..00000000000 --- a/phpunit.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - tests - packages-tests - - diff --git a/prefix-code.sh b/prefix-code.sh deleted file mode 100755 index 9ec05e594ee..00000000000 --- a/prefix-code.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env bash - -# inspired from https://github.com/rectorphp/rector/blob/main/build/build-rector-scoped.sh - -# see https://stackoverflow.com/questions/66644233/how-to-propagate-colors-from-bash-script-to-github-action?noredirect=1#comment117811853_66644233 -export TERM=xterm-color - -# show errors -set -e - -# script fails if trying to access to an undefined variable -set -u - - -# functions -note() -{ - MESSAGE=$1; - printf "\n"; - echo "\033[0;33m[NOTE] $MESSAGE\033[0m"; -} - -# --------------------------- - -# 2. scope it -note "Downloading php-scoper 0.17.5" -# @todo upgrade to 0.18.1 -wget https://github.com/humbug/php-scoper/releases/download/0.17.5/php-scoper.phar -N --no-verbose - - -note "Running php-scoper" - -# Work around possible PHP memory limits -php -d memory_limit=-1 php-scoper.phar add-prefix bin config src packages vendor composer.json --config scoper.php --force --ansi --output-dir scoped-code - -# the output code is in "/scoped-code", lets move it up -# the local directories have to be empty to move easily -rm -r bin config src packages vendor composer.json -mv scoped-code/* . - -note "Show prefixed files" -ls -l . - -note "Dumping Composer Autoload" -composer dump-autoload --ansi --classmap-authoritative --no-dev - -# make bin/ecs runnable without "php" -chmod 777 "bin/ecs" -chmod 777 "bin/ecs.php" - -note "Finished" diff --git a/build/target-repository/preload.php b/preload.php similarity index 100% rename from build/target-repository/preload.php rename to preload.php diff --git a/rector.php b/rector.php deleted file mode 100644 index 2b96968e062..00000000000 --- a/rector.php +++ /dev/null @@ -1,49 +0,0 @@ -sets([ - LevelSetList::UP_TO_PHP_81, - SetList::CODE_QUALITY, - SetList::DEAD_CODE, - SetList::CODING_STYLE, - SetList::TYPE_DECLARATION, - SetList::NAMING, - SetList::PRIVATIZATION, - SetList::EARLY_RETURN, - PHPUnitSetList::PHPUNIT_100, - PHPUnitSetList::PHPUNIT_CODE_QUALITY, - ]); - - $rectorConfig->paths([ - __DIR__ . '/ecs.php', - __DIR__ . '/rector.php', - __DIR__ . '/config', - __DIR__ . '/src', - __DIR__ . '/packages', - __DIR__ . '/config', - __DIR__ . '/tests', - __DIR__ . '/packages-tests', - ]); - - $rectorConfig->importNames(); - - $rectorConfig->bootstrapFiles([__DIR__ . '/tests/bootstrap.php']); - - $rectorConfig->skip([ - '*/Source/*', - '*/Fixture/*', - 'packages/SniffRunner/ValueObject/File.php', - RenameParamToMatchTypeRector::class => [ - __DIR__ . '/packages/FixerRunner/Application/FixerFileProcessor.php', - ], - ]); -}; diff --git a/scoper.php b/scoper.php deleted file mode 100644 index 26588af3c28..00000000000 --- a/scoper.php +++ /dev/null @@ -1,147 +0,0 @@ -format('Ym'); - -use Symplify\EasyCodingStandard\Application\Version\StaticVersionResolver; - -// excluding polyfills in generic way -// @see https://github.com/humbug/php-scoper/blob/cb23986d9309a10eaa284242f2169723af4e4a7e/docs/further-reading.md#further-reading - -$polyfillsBootstraps = array_map( - static fn (SplFileInfo $fileInfo) => $fileInfo->getPathname(), - iterator_to_array( - Finder::create() - ->files() - ->in(__DIR__ . '/vendor/symfony/polyfill-*') - ->name('bootstrap*.php'), - false, - ), -); - -$polyfillsStubs = array_map( - static fn (SplFileInfo $fileInfo) => $fileInfo->getPathname(), - iterator_to_array( - Finder::create() - ->files() - ->in(__DIR__ . '/vendor/symfony/polyfill-*/Resources/stubs') - ->name('*.php'), - false, - ), -); - -// see https://github.com/humbug/php-scoper -return [ - 'prefix' => 'ECSPrefix' . $timestamp, - - // excluded - 'exclude-namespaces' => [ - '#^Symplify\\\\EasyCodingStandard#', - '#^Symplify\\\\CodingStandard#', - '#^PhpCsFixer#', - '#^PHP_CodeSniffer#', - '#^Symfony\\\\Polyfill#', - ], - 'exclude-constants' => [ - // Symfony global constants - '#^SYMFONY\_[\p{L}_]+$#', - // TOKENS from code sniffer - https://github.com/symplify/easy-coding-standard/blob/main/vendor/squizlabs/php_codesniffer/src/Util/Tokens.php - '#^T_(.*?)#', - 'PHP_CODESNIFFER_CBF', - 'PHP_CODESNIFFER_VERBOSITY', - ], - 'expose-constants' => ['__ECS_RUNNING__'], - 'expose-functions' => ['u', 'b', 's', 'trigger_deprecation'], - - 'exclude-files' => [...$polyfillsBootstraps, ...$polyfillsStubs], - - // expose - 'expose-classes' => [ - 'Normalizer', - ], - - 'patchers' => [ - static function (string $filePath, string $prefix, string $content): string { - if (! \str_ends_with( - $filePath, - 'vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php', - )) { - return $content; - } - - // php-cs-fixer uses partial namespaces, that are only strings - should be kept untouched - // ref.: https://github.com/easy-coding-standard/easy-coding-standard/issues/91 - return str_replace([ - $prefix . '\\\\ORM\\\\Entity', - $prefix . '\\\\ORM\\\\Mapping\\\\Entity', - $prefix . '\\\\Mapping\\\\Entity', - $prefix . '\\\\ODM\\\\Document', - ], [ - 'ORM\\Entity', - 'ORM\\Mapping\\Entity', - 'Mapping\\Entity', - 'ODM\\Document', - ], $content); - }, - - static function (string $filePath, string $prefix, string $content): string { - if (! \str_ends_with( - $filePath, - 'vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php' - )) { - return $content; - } - - // PHP Code Sniffer and php-cs-fixer use different type, so both are compatible - // remove type, to allow string|int constants for token emulation - $content = str_replace('array_map(static function (int $id)', 'array_map(static function ($id)', $content); - - return str_replace('static fn (int $id)', 'static fn ($id)', $content); - }, - - static function (string $filePath, string $prefix, string $content): string { - if (! \str_ends_with($filePath, 'vendor/symfony/deprecation-contracts/function.php')) { - return $content; - } - - // comment out - return str_replace('@\trigger_', '// @\trigger_', $content); - }, - - // fixes https://github.com/symplify/symplify/issues/3205 - function (string $filePath, string $prefix, string $content): string { - if ( - ! str_ends_with($filePath, 'src/Testing/PHPUnit/AbstractCheckerTestCase.php') && - ! str_ends_with($filePath, 'src/Testing/PHPUnit/AbstractTestCase.php') - ) { - return $content; - } - - return Strings::replace( - $content, - '#' . $prefix . '\\\\PHPUnit\\\\Framework\\\\TestCase#', - 'PHPUnit\Framework\TestCase' - ); - }, - - // add static versions constant values - function (string $filePath, string $prefix, string $content): string { - if (! str_ends_with($filePath, 'src/Application/Version/StaticVersionResolver.php')) { - return $content; - } - - $releaseDateTime = StaticVersionResolver::resolverReleaseDateTime(); - - return strtr($content, [ - '@package_version@' => StaticVersionResolver::resolvePackageVersion(), - '@release_date@' => $releaseDateTime->format('Y-m-d H:i:s'), - ]); - }, - ], -]; diff --git a/src/Application/EasyCodingStandardApplication.php b/src/Application/EasyCodingStandardApplication.php index c68e37e7e02..dee179fb8bb 100644 --- a/src/Application/EasyCodingStandardApplication.php +++ b/src/Application/EasyCodingStandardApplication.php @@ -1,12 +1,11 @@ easyCodingStandardStyle = $easyCodingStandardStyle; + $this->sourceFinder = $sourceFinder; + $this->changedFilesDetector = $changedFilesDetector; + $this->fileFilter = $fileFilter; + $this->singleFileProcessor = $singleFileProcessor; + $this->scheduleFactory = $scheduleFactory; + $this->parallelFileProcessor = $parallelFileProcessor; + $this->cpuCoreCountProvider = $cpuCoreCountProvider; + $this->symfonyStyle = $symfonyStyle; + $this->parametersMerger = $parametersMerger; } - /** * @return array{coding_standard_errors?: CodingStandardError[], file_diffs?: FileDiff[], system_errors?: SystemError[]|string[], system_errors_count?: int} */ - public function run(Configuration $configuration, InputInterface $input): array + public function run(Configuration $configuration, InputInterface $input) : array { // 1. find files in sources $filePaths = $this->sourceFinder->find($configuration->getSources()); - // 2. clear cache if ($configuration->shouldClearCache()) { $this->changedFilesDetector->clearCache(); } else { $filePaths = $this->fileFilter->filterOnlyChangedFiles($filePaths); } - // no files found - $filesCount = count($filePaths); - + $filesCount = \count($filePaths); if ($filesCount === 0) { return []; } - if ($configuration->isParallel()) { - $schedule = $this->scheduleFactory->create( - $this->cpuCoreCountProvider->provide(), - SimpleParameterProvider::getIntParameter(Option::PARALLEL_JOB_SIZE), - SimpleParameterProvider::getIntParameter(Option::PARALLEL_MAX_NUMBER_OF_PROCESSES), - $filePaths - ); - + $schedule = $this->scheduleFactory->create($this->cpuCoreCountProvider->provide(), SimpleParameterProvider::getIntParameter(Option::PARALLEL_JOB_SIZE), SimpleParameterProvider::getIntParameter(Option::PARALLEL_MAX_NUMBER_OF_PROCESSES), $filePaths); // for progress bar - $isProgressBarStarted = false; - - $postFileCallback = function (int $stepCount) use ( - &$isProgressBarStarted, - $filePaths, - $configuration - ): void { - if (! $configuration->shouldShowProgressBar()) { + $isProgressBarStarted = \false; + $postFileCallback = function (int $stepCount) use(&$isProgressBarStarted, $filePaths, $configuration) : void { + if (!$configuration->shouldShowProgressBar()) { return; } - - if (! $isProgressBarStarted) { - $fileCount = count($filePaths); + if (!$isProgressBarStarted) { + $fileCount = \count($filePaths); $this->symfonyStyle->progressStart($fileCount); - $isProgressBarStarted = true; + $isProgressBarStarted = \true; } - $this->symfonyStyle->progressAdvance($stepCount); // running in parallel here → nothing else to do }; - $mainScript = $this->resolveCalledEcsBinary(); if ($mainScript === null) { throw new ShouldNotHappenException('[parallel] Main script was not found'); } - // mimics see https://github.com/phpstan/phpstan-src/commit/9124c66dcc55a222e21b1717ba5f60771f7dda92#diff-387b8f04e0db7a06678eb52ce0c0d0aff73e0d7d8fc5df834d0a5fbec198e5daR139 - return $this->parallelFileProcessor->check( - $schedule, - $mainScript, - $postFileCallback, - $configuration->getConfig(), - $input - ); + return $this->parallelFileProcessor->check($schedule, $mainScript, $postFileCallback, $configuration->getConfig(), $input); } - // process found files by each processors return $this->processFoundFiles($filePaths, $configuration); } - /** * @param string[] $filePaths * @return array{coding_standard_errors: CodingStandardError[], file_diffs: FileDiff[], system_errors: SystemError[], system_errors_count: int} */ - private function processFoundFiles(array $filePaths, Configuration $configuration): array + private function processFoundFiles(array $filePaths, Configuration $configuration) : array { - $fileCount = count($filePaths); - + $fileCount = \count($filePaths); // 3. start progress bar $this->outputProgressBarAndDebugInfo($fileCount, $configuration); - $errorsAndDiffs = []; - foreach ($filePaths as $filePath) { if ($this->easyCodingStandardStyle->isDebug()) { $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd($filePath); $this->easyCodingStandardStyle->writeln(' [file] ' . $relativeFilePath); } - try { $currentErrorsAndDiffs = $this->singleFileProcessor->processFilePath($filePath, $configuration); if ($currentErrorsAndDiffs !== []) { @@ -143,48 +158,35 @@ private function processFoundFiles(array $filePaths, Configuration $configuratio } } catch (ParseError $parseError) { $this->changedFilesDetector->invalidateFilePath($filePath); - $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd($filePath); - - $errorsAndDiffs[Bridge::SYSTEM_ERRORS][] = new SystemError( - $parseError->getLine(), - $parseError->getMessage(), - $relativeFilePath - ); + $errorsAndDiffs[Bridge::SYSTEM_ERRORS][] = new SystemError($parseError->getLine(), $parseError->getMessage(), $relativeFilePath); } - if ($configuration->shouldShowProgressBar()) { $this->easyCodingStandardStyle->progressAdvance(); } } - return $errorsAndDiffs; } - - private function outputProgressBarAndDebugInfo(int $fileInfoCount, Configuration $configuration): void + private function outputProgressBarAndDebugInfo(int $fileInfoCount, Configuration $configuration) : void { - if (! $configuration->shouldShowProgressBar()) { + if (!$configuration->shouldShowProgressBar()) { return; } - $this->easyCodingStandardStyle->progressStart($fileInfoCount); } - /** * Path to called "ecs" binary file, e.g. "vendor/bin/ecs" returns "vendor/bin/ecs" This is needed to re-call the * ecs binary in sub-process in the same location. */ - private function resolveCalledEcsBinary(): ?string + private function resolveCalledEcsBinary() : ?string { - if (! isset($_SERVER[self::ARGV][0])) { + if (!isset($_SERVER[self::ARGV][0])) { return null; } - $potentialEcsBinaryPath = $_SERVER[self::ARGV][0]; - if (! file_exists($potentialEcsBinaryPath)) { + if (!\file_exists($potentialEcsBinaryPath)) { return null; } - return $potentialEcsBinaryPath; } } diff --git a/src/Application/FileProcessorCollector.php b/src/Application/FileProcessorCollector.php index b0cb7267748..3e32a32a27a 100644 --- a/src/Application/FileProcessorCollector.php +++ b/src/Application/FileProcessorCollector.php @@ -1,20 +1,17 @@ fileProcessors[] = $sniffFileProcessor; $this->fileProcessors[] = $fixerFileProcessor; } - /** * @return FileProcessorInterface[] */ - public function getFileProcessors(): array + public function getFileProcessors() : array { return $this->fileProcessors; } diff --git a/src/Application/SingleFileProcessor.php b/src/Application/SingleFileProcessor.php index 0e2d20452b4..036111f5fab 100644 --- a/src/Application/SingleFileProcessor.php +++ b/src/Application/SingleFileProcessor.php @@ -1,7 +1,6 @@ skipper = $skipper; + $this->changedFilesDetector = $changedFilesDetector; + $this->fileProcessorCollector = $fileProcessorCollector; } - /** * @return array{file_diffs?: FileDiff[], coding_standard_errors?: CodingStandardError[]} */ - public function processFilePath(string $filePath, Configuration $configuration): array + public function processFilePath(string $filePath, Configuration $configuration) : array { if ($this->skipper->shouldSkipFilePath($filePath)) { return []; } - $errorsAndDiffs = []; - $this->changedFilesDetector->addFilePath($filePath); $fileProcessors = $this->fileProcessorCollector->getFileProcessors(); - foreach ($fileProcessors as $fileProcessor) { if ($fileProcessor->getCheckers() === []) { continue; } - $currentErrorsAndFileDiffs = $fileProcessor->processFile($filePath, $configuration); if ($currentErrorsAndFileDiffs === []) { continue; } - - $errorsAndDiffs = [...$errorsAndDiffs, ...$currentErrorsAndFileDiffs]; + $errorsAndDiffs = \array_merge($errorsAndDiffs, \is_array($currentErrorsAndFileDiffs) ? $currentErrorsAndFileDiffs : \iterator_to_array($currentErrorsAndFileDiffs)); } - // invalidate broken file, to analyse in next run too if ($errorsAndDiffs !== []) { $this->changedFilesDetector->invalidateFilePath($filePath); } - return $errorsAndDiffs; } } diff --git a/src/Application/Version/StaticVersionResolver.php b/src/Application/Version/StaticVersionResolver.php index 95c3cdc6781..241a5ed3134 100644 --- a/src/Application/Version/StaticVersionResolver.php +++ b/src/Application/Version/StaticVersionResolver.php @@ -1,12 +1,10 @@ |array, list|null> $skips */ - public function skip(array $skips): void + public function skip(array $skips) : void { SimpleParameterProvider::addParameter(Option::SKIP, $skips); } - /** * @param string[] $sets */ - public function sets(array $sets): void + public function sets(array $sets) : void { Assert::allString($sets); Assert::allFileExists($sets); - foreach ($sets as $set) { $this->import($set); } } - /** * @param class-string $checkerClass */ - public function rule(string $checkerClass): void + public function rule(string $checkerClass) : void { $this->assertCheckerClass($checkerClass); - // tag for autowiring of tagged_iterator() - $interfaceTag = is_a($checkerClass, Sniff::class, true) ? Sniff::class : FixerInterface::class; - + $interfaceTag = \is_a($checkerClass, Sniff::class, \true) ? Sniff::class : FixerInterface::class; $this->singleton($checkerClass); $this->tag($checkerClass, $interfaceTag); $this->autowireWhitespaceAwareFixer($checkerClass); } - /** * @param array> $checkerClasses */ - public function rules(array $checkerClasses): void + public function rules(array $checkerClasses) : void { $this->ensureCheckerClassesAreUnique($checkerClasses); - foreach ($checkerClasses as $checkerClass) { $this->rule($checkerClass); } } - /** * @param class-string $checkerClass * @param mixed[] $configuration */ - public function ruleWithConfiguration(string $checkerClass, array $configuration): void + public function ruleWithConfiguration(string $checkerClass, array $configuration) : void { $this->assertCheckerClass($checkerClass); - $this->singleton($checkerClass); - // tag for autowiring of tagged_iterator() - $interfaceTag = is_a($checkerClass, Sniff::class, true) ? Sniff::class : FixerInterface::class; + $interfaceTag = \is_a($checkerClass, Sniff::class, \true) ? Sniff::class : FixerInterface::class; $this->tag($checkerClass, $interfaceTag); - - if (is_a($checkerClass, FixerInterface::class, true)) { + if (\is_a($checkerClass, FixerInterface::class, \true)) { Assert::isAnyOf($checkerClass, [ConfigurableFixerInterface::class, ConfigurableRuleInterface::class]); - $this->extend($checkerClass, static function (ConfigurableFixerInterface $configurableFixer) use ( - $configuration - ): ConfigurableFixerInterface { + $this->extend($checkerClass, static function (ConfigurableFixerInterface $configurableFixer) use($configuration) : ConfigurableFixerInterface { $configurableFixer->configure($configuration); return $configurableFixer; }); } - - if (is_a($checkerClass, Sniff::class, true)) { - $this->extend($checkerClass, static function (Sniff $sniff) use ($configuration): Sniff { + if (\is_a($checkerClass, Sniff::class, \true)) { + $this->extend($checkerClass, static function (Sniff $sniff) use($configuration) : Sniff { foreach ($configuration as $propertyName => $value) { Assert::propertyExists($sniff, $propertyName); $sniff->{$propertyName} = $value; } - return $sniff; }); } } - /** * @param array, mixed[]> $rulesWithConfiguration */ - public function rulesWithConfiguration(array $rulesWithConfiguration): void + public function rulesWithConfiguration(array $rulesWithConfiguration) : void { Assert::allIsArray($rulesWithConfiguration); - foreach ($rulesWithConfiguration as $checkerClass => $configuration) { $this->ruleWithConfiguration($checkerClass, $configuration); } } - /** * @param Option::INDENTATION_* $indentation */ - public function indentation(string $indentation): void + public function indentation(string $indentation) : void { SimpleParameterProvider::setParameter(Option::INDENTATION, $indentation); } - - public function lineEnding(string $lineEnding): void + public function lineEnding(string $lineEnding) : void { SimpleParameterProvider::setParameter(Option::LINE_ENDING, $lineEnding); } - - public function cacheDirectory(string $cacheDirectory): void + public function cacheDirectory(string $cacheDirectory) : void { SimpleParameterProvider::setParameter(Option::CACHE_DIRECTORY, $cacheDirectory); } - - public function cacheNamespace(string $cacheNamespace): void + public function cacheNamespace(string $cacheNamespace) : void { SimpleParameterProvider::setParameter(Option::CACHE_NAMESPACE, $cacheNamespace); } - /** * @param string[] $fileExtensions */ - public function fileExtensions(array $fileExtensions): void + public function fileExtensions(array $fileExtensions) : void { Assert::allString($fileExtensions); - SimpleParameterProvider::addParameter(Option::FILE_EXTENSIONS, $fileExtensions); } - - public function parallel(int $seconds = 120, int $maxNumberOfProcess = 16, int $jobSize = 20): void + public function parallel(int $seconds = 120, int $maxNumberOfProcess = 16, int $jobSize = 20) : void { - SimpleParameterProvider::setParameter(Option::PARALLEL, true); - + SimpleParameterProvider::setParameter(Option::PARALLEL, \true); SimpleParameterProvider::setParameter(Option::PARALLEL_TIMEOUT_IN_SECONDS, $seconds); SimpleParameterProvider::setParameter(Option::PARALLEL_MAX_NUMBER_OF_PROCESSES, $maxNumberOfProcess); SimpleParameterProvider::setParameter(Option::PARALLEL_JOB_SIZE, $jobSize); } - /** * @api */ - public function disableParallel(): void + public function disableParallel() : void { - SimpleParameterProvider::setParameter(Option::PARALLEL, false); + SimpleParameterProvider::setParameter(Option::PARALLEL, \false); } - /** * @deprecated * @param array> $sniffClasses */ - public function reportSniffClassWarnings(array $sniffClasses): void + public function reportSniffClassWarnings(array $sniffClasses) : void { - echo sprintf( - 'The "%s()" is deprecated. Use default sniff class setup instead or add classes to ECS core to make them available for everyone', - __METHOD__ - ); + echo \sprintf('The "%s()" is deprecated. Use default sniff class setup instead or add classes to ECS core to make them available for everyone', __METHOD__); } - /** * @link https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/master/doc/ruleSets/index.rst * @param list $setNames */ - public function dynamicSets(array $setNames): void + public function dynamicSets(array $setNames) : void { $fixerFactory = new FixerFactory(); $fixerFactory->registerBuiltInFixers(); - - $ruleSet = new RuleSet(array_fill_keys($setNames, true)); + $ruleSet = new RuleSet(\array_fill_keys($setNames, \true)); $fixerFactory->useRuleSet($ruleSet); - /** @var FixerInterface $fixer */ foreach ($fixerFactory->getFixers() as $fixer) { $ruleConfiguration = $ruleSet->getRuleConfiguration($fixer->getName()); - if ($ruleConfiguration === null) { - $this->rule($fixer::class); + $this->rule(\get_class($fixer)); } else { - $this->ruleWithConfiguration($fixer::class, $ruleConfiguration); + $this->ruleWithConfiguration(\get_class($fixer), $ruleConfiguration); } } } - - public function import(string $setFilePath): void + public function import(string $setFilePath) : void { $self = $this; - - $closureFilePath = require $setFilePath; + $closureFilePath = (require $setFilePath); Assert::isCallable($closureFilePath); - $closureFilePath($self); } - /** * @param class-string $checkerClass */ - private function assertCheckerClass(string $checkerClass): void + private function assertCheckerClass(string $checkerClass) : void { Assert::classExists($checkerClass); Assert::isAnyOf($checkerClass, [Sniff::class, FixerInterface::class]); } - /** * @param string[] $checkerClasses */ - private function ensureCheckerClassesAreUnique(array $checkerClasses): void + private function ensureCheckerClassesAreUnique(array $checkerClasses) : void { // ensure all rules are registered exactly once - $checkerClassToCount = array_count_values($checkerClasses); - $duplicatedCheckerClassToCount = array_filter($checkerClassToCount, static fn (int $count): bool => $count > 1); - + $checkerClassToCount = \array_count_values($checkerClasses); + $duplicatedCheckerClassToCount = \array_filter($checkerClassToCount, static function (int $count) : bool { + return $count > 1; + }); if ($duplicatedCheckerClassToCount === []) { return; } - - $duplicatedCheckerClasses = array_flip($duplicatedCheckerClassToCount); - - $errorMessage = sprintf( - 'There are duplicated classes in $rectorConfig->rules(): "%s". Make them unique to avoid unexpected behavior.', - implode('", "', $duplicatedCheckerClasses) - ); + $duplicatedCheckerClasses = \array_flip($duplicatedCheckerClassToCount); + $errorMessage = \sprintf('There are duplicated classes in $rectorConfig->rules(): "%s". Make them unique to avoid unexpected behavior.', \implode('", "', $duplicatedCheckerClasses)); throw new InvalidArgumentException($errorMessage); } - /** * @param class-string $checkerClass */ - private function autowireWhitespaceAwareFixer(string $checkerClass): void + private function autowireWhitespaceAwareFixer(string $checkerClass) : void { - if (! is_a($checkerClass, WhitespacesAwareFixerInterface::class, true)) { + if (!\is_a($checkerClass, WhitespacesAwareFixerInterface::class, \true)) { return; } - - $this->extend( - $checkerClass, - static function ( - WhitespacesAwareFixerInterface $whitespacesAwareFixer, - Container $container - ): WhitespacesAwareFixerInterface { - $whitespacesFixerConfig = $container->make(WhitespacesFixerConfig::class); - $whitespacesAwareFixer->setWhitespacesConfig($whitespacesFixerConfig); - - return $whitespacesAwareFixer; - } - ); + $this->extend($checkerClass, static function (WhitespacesAwareFixerInterface $whitespacesAwareFixer, Container $container) : WhitespacesAwareFixerInterface { + $whitespacesFixerConfig = $container->make(WhitespacesFixerConfig::class); + $whitespacesAwareFixer->setWhitespacesConfig($whitespacesFixerConfig); + return $whitespacesAwareFixer; + }); } } diff --git a/src/Configuration/ConfigInitializer.php b/src/Configuration/ConfigInitializer.php index 08f22839942..36528c81dfc 100644 --- a/src/Configuration/ConfigInitializer.php +++ b/src/Configuration/ConfigInitializer.php @@ -1,76 +1,80 @@ fileProcessorCollector = $fileProcessorCollector; + $this->symfonyStyle = $symfonyStyle; + $this->initPathsResolver = $initPathsResolver; + $this->filesystem = $filesystem; } - - public function areSomeCheckersRegistered(): bool + public function areSomeCheckersRegistered() : bool { $fileProcessors = $this->fileProcessorCollector->getFileProcessors(); foreach ($fileProcessors as $fileProcessor) { if ($fileProcessor->getCheckers()) { - return true; + return \true; } } - - return false; + return \false; } - - public function createConfig(string $projectDirectory): void + public function createConfig(string $projectDirectory) : void { $doesConfigExist = $this->filesystem->exists($projectDirectory . '/ecs.php'); - // config already exists, nothing to add if ($doesConfigExist) { - $this->symfonyStyle->warning( - 'The "ecs.php" config already exists. Register rules or sets there to make it change the code.' - ); + $this->symfonyStyle->warning('The "ecs.php" config already exists. Register rules or sets there to make it change the code.'); return; } - $response = $this->symfonyStyle->ask('No "ecs.php" config found. Should we generate it for you?', 'yes'); if ($response !== 'yes') { // okay, nothing we can do return; } - $templateFileContents = FileSystem::read(__DIR__ . '/../../templates/ecs.php.dist'); - $projectPhpDirectories = $this->initPathsResolver->resolve($projectDirectory); $projectPhpDirectoriesContents = $this->createPathsString($projectPhpDirectories); - - $templateFileContents = str_replace('__PATHS__', $projectPhpDirectoriesContents, $templateFileContents); - + $templateFileContents = \str_replace('__PATHS__', $projectPhpDirectoriesContents, $templateFileContents); // write the contents :) - FileSystem::write(getcwd() . '/ecs.php', $templateFileContents); - + FileSystem::write(\getcwd() . '/ecs.php', $templateFileContents); $this->symfonyStyle->success('The config file was generated! Now re-run the command to make your code tidy'); } - /** * @param string[] $projectPhpDirectories */ - private function createPathsString(array $projectPhpDirectories): string + private function createPathsString(array $projectPhpDirectories) : string { $projectPhpDirectoriesContents = ''; foreach ($projectPhpDirectories as $projectPhpDirectory) { - $projectPhpDirectoriesContents .= " __DIR__ . '/" . $projectPhpDirectory . "'," . PHP_EOL; + $projectPhpDirectoriesContents .= " __DIR__ . '/" . $projectPhpDirectory . "'," . \PHP_EOL; } - - return rtrim($projectPhpDirectoriesContents); + return \rtrim($projectPhpDirectoriesContents); } } diff --git a/src/Configuration/ConfigurationFactory.php b/src/Configuration/ConfigurationFactory.php index 4c1fd1739df..51f419c1105 100644 --- a/src/Configuration/ConfigurationFactory.php +++ b/src/Configuration/ConfigurationFactory.php @@ -1,93 +1,67 @@ resolvePaths($input); - $isFixer = (bool) $input->getOption(Option::FIX); $shouldClearCache = (bool) $input->getOption(Option::CLEAR_CACHE); $showProgressBar = $this->canShowProgressBar($input); - $showErrorTable = ! (bool) $input->getOption(Option::NO_ERROR_TABLE); + $showErrorTable = !(bool) $input->getOption(Option::NO_ERROR_TABLE); $parallelPort = (string) $input->getOption(Option::PARALLEL_PORT); $parallelIdentifier = (string) $input->getOption(Option::PARALLEL_IDENTIFIER); - $outputFormat = (string) $input->getOption(Option::OUTPUT_FORMAT); - /** @var string|null $memoryLimit */ $memoryLimit = $input->getOption(Option::MEMORY_LIMIT); - $isParallel = SimpleParameterProvider::getBoolParameter(Option::PARALLEL); - $config = $input->getOption(Option::CONFIG); if ($config !== null) { $config = (string) $config; } - - return new Configuration( - $isFixer, - $shouldClearCache, - $showProgressBar, - $showErrorTable, - $paths, - $outputFormat, - $isParallel, - $config, - $parallelPort, - $parallelIdentifier, - $memoryLimit - ); + return new Configuration($isFixer, $shouldClearCache, $showProgressBar, $showErrorTable, $paths, $outputFormat, $isParallel, $config, $parallelPort, $parallelIdentifier, $memoryLimit); } - - private function canShowProgressBar(InputInterface $input): bool + private function canShowProgressBar(InputInterface $input) : bool { // --debug option shows more $debug = (bool) $input->getOption(Option::DEBUG); if ($debug) { - return false; + return \false; } - $notJsonOutput = $input->getOption(Option::OUTPUT_FORMAT) !== JsonOutputFormatter::NAME; - if (! $notJsonOutput) { - return false; + if (!$notJsonOutput) { + return \false; } - - return ! (bool) $input->getOption(Option::NO_PROGRESS_BAR); + return !(bool) $input->getOption(Option::NO_PROGRESS_BAR); } - /** * @param string[] $paths */ - private function ensurePathsExists(array $paths): void + private function ensurePathsExists(array $paths) : void { foreach ($paths as $path) { - if (file_exists($path)) { + if (\file_exists($path)) { continue; } - - throw new SourceNotFoundException(sprintf('Source "%s" does not exist.', $path)); + throw new SourceNotFoundException(\sprintf('Source "%s" does not exist.', $path)); } } - /** * @return string[] */ - private function resolvePaths(InputInterface $input): array + private function resolvePaths(InputInterface $input) : array { /** @var string[] $paths */ $paths = (array) $input->getArgument(Option::PATHS); @@ -95,22 +69,18 @@ private function resolvePaths(InputInterface $input): array // if not paths are provided from CLI, use the config ones $paths = SimpleParameterProvider::getArrayParameter(Option::PATHS); } - $this->ensurePathsExists($paths); - return $this->normalizePaths($paths); } - /** * @param string[] $paths * @return string[] */ - private function normalizePaths(array $paths): array + private function normalizePaths(array $paths) : array { foreach ($paths as $key => $path) { - $paths[$key] = rtrim($path, DIRECTORY_SEPARATOR); + $paths[$key] = \rtrim($path, \DIRECTORY_SEPARATOR); } - return $paths; } } diff --git a/src/Configuration/InitPathsResolver.php b/src/Configuration/InitPathsResolver.php index 2211c5b8dba..78a9120501f 100644 --- a/src/Configuration/InitPathsResolver.php +++ b/src/Configuration/InitPathsResolver.php @@ -1,51 +1,33 @@ directories() - ->depth(0) - // system files - ->notPath('#(vendor|var|stubs|temp|templates|tmp|e2e|bin|build|database|storage|migrations)#') - ->in($projectDirectory) - ->sortByName(); - + $rootDirectoryFinder = Finder::create()->directories()->depth(0)->notPath('#(vendor|var|stubs|temp|templates|tmp|e2e|bin|build|database|storage|migrations)#')->in($projectDirectory)->sortByName(); /** @var SplFileInfo[] $rootDirectoryFileInfos */ - $rootDirectoryFileInfos = iterator_to_array($rootDirectoryFinder); - + $rootDirectoryFileInfos = \iterator_to_array($rootDirectoryFinder); $projectDirectories = []; - foreach ($rootDirectoryFileInfos as $rootDirectoryFileInfo) { - if (! $this->hasDirectoryFileInfoPhpFiles($rootDirectoryFileInfo)) { + if (!$this->hasDirectoryFileInfoPhpFiles($rootDirectoryFileInfo)) { continue; } - $projectDirectories[] = $rootDirectoryFileInfo->getRelativePathname(); } - return $projectDirectories; } - - private function hasDirectoryFileInfoPhpFiles(SplFileInfo $rootDirectoryFileInfo): bool + private function hasDirectoryFileInfoPhpFiles(SplFileInfo $rootDirectoryFileInfo) : bool { // is directory with PHP files? - $phpFilesFinder = Finder::create() - ->files() - ->in($rootDirectoryFileInfo->getPathname()) - ->name('*.php'); - - return count($phpFilesFinder) !== 0; + $phpFilesFinder = Finder::create()->files()->in($rootDirectoryFileInfo->getPathname())->name('*.php'); + return \count($phpFilesFinder) !== 0; } } diff --git a/src/Console/Command/AbstractCheckCommand.php b/src/Console/Command/AbstractCheckCommand.php index a59aaab4bfa..76e959be8b2 100644 --- a/src/Console/Command/AbstractCheckCommand.php +++ b/src/Console/Command/AbstractCheckCommand.php @@ -1,18 +1,16 @@ addArgument( Option::PATHS, @@ -20,37 +18,13 @@ protected function configure(): void InputArgument::OPTIONAL | InputArgument::IS_ARRAY, 'The path(s) to be checked.' ); - $this->addOption(Option::FIX, null, null, 'Fix found violations.'); - $this->addOption(Option::CONFIG, 'c', InputOption::VALUE_REQUIRED, 'Path to config file'); - $this->addOption(Option::CLEAR_CACHE, null, null, 'Clear cache for already checked files.'); - - $this->addOption( - Option::NO_PROGRESS_BAR, - null, - InputOption::VALUE_NONE, - 'Hide progress bar. Useful e.g. for nicer CI output.' - ); - - $this->addOption( - Option::NO_ERROR_TABLE, - null, - InputOption::VALUE_NONE, - 'Hide error table. Useful e.g. for fast check of error count.' - ); - - $this->addOption( - Option::OUTPUT_FORMAT, - null, - InputOption::VALUE_REQUIRED, - 'Select output format', - ConsoleOutputFormatter::NAME - ); - + $this->addOption(Option::NO_PROGRESS_BAR, null, InputOption::VALUE_NONE, 'Hide progress bar. Useful e.g. for nicer CI output.'); + $this->addOption(Option::NO_ERROR_TABLE, null, InputOption::VALUE_NONE, 'Hide error table. Useful e.g. for fast check of error count.'); + $this->addOption(Option::OUTPUT_FORMAT, null, InputOption::VALUE_REQUIRED, 'Select output format', ConsoleOutputFormatter::NAME); $this->addOption(Option::MEMORY_LIMIT, null, InputOption::VALUE_REQUIRED, 'Memory limit for check'); - // for parallel run $this->addOption(Option::PARALLEL_PORT, null, InputOption::VALUE_REQUIRED); $this->addOption(Option::PARALLEL_IDENTIFIER, null, InputOption::VALUE_REQUIRED); diff --git a/src/Console/Command/CheckCommand.php b/src/Console/Command/CheckCommand.php index ef5fd4c1e5c..baff2c017ed 100644 --- a/src/Console/Command/CheckCommand.php +++ b/src/Console/Command/CheckCommand.php @@ -1,46 +1,65 @@ processedFileReporter = $processedFileReporter; + $this->memoryLimitter = $memoryLimitter; + $this->configInitializer = $configInitializer; + $this->easyCodingStandardApplication = $easyCodingStandardApplication; + $this->configurationFactory = $configurationFactory; parent::__construct(); } - - protected function configure(): void + protected function configure() : void { $this->setName('check'); $this->setDescription('Check coding standard in one or more directories.'); parent::configure(); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(InputInterface $input, OutputInterface $output) : int { - if (! $this->configInitializer->areSomeCheckersRegistered()) { - $this->configInitializer->createConfig(getcwd()); + if (!$this->configInitializer->areSomeCheckersRegistered()) { + $this->configInitializer->createConfig(\getcwd()); return self::SUCCESS; } - $configuration = $this->configurationFactory->createFromInput($input); $this->memoryLimitter->adjust($configuration); - $errorsAndDiffs = $this->easyCodingStandardApplication->run($configuration, $input); return $this->processedFileReporter->report($errorsAndDiffs, $configuration); } diff --git a/src/Console/Command/ListCheckersCommand.php b/src/Console/Command/ListCheckersCommand.php index 32177e3f43e..107fe4426fe 100644 --- a/src/Console/Command/ListCheckersCommand.php +++ b/src/Console/Command/ListCheckersCommand.php @@ -1,111 +1,106 @@ sniffFileProcessor = $sniffFileProcessor; + $this->fixerFileProcessor = $fixerFileProcessor; + $this->checkerListReporter = $checkerListReporter; + $this->skippedClassResolver = $skippedClassResolver; parent::__construct(); } - - protected function configure(): void + protected function configure() : void { $this->setName('list-checkers'); $this->setDescription('Shows loaded checkers'); - - $this->addOption( - Option::OUTPUT_FORMAT, - null, - InputOption::VALUE_REQUIRED, - 'Select output format', - ConsoleOutputFormatter::NAME - ); - + $this->addOption(Option::OUTPUT_FORMAT, null, InputOption::VALUE_REQUIRED, 'Select output format', ConsoleOutputFormatter::NAME); $this->addOption(Option::CONFIG, 'c', InputOption::VALUE_REQUIRED, 'Path to config file'); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(InputInterface $input, OutputInterface $output) : int { $outputFormat = $input->getOption(Option::OUTPUT_FORMAT); - // include skipped rules to avoid adding those too $skippedCheckers = $this->getSkippedCheckers(); - if ($outputFormat === 'json') { - $data = [ - 'sniffs' => $this->getSniffClasses(), - 'fixers' => $this->getFixerClasses(), - 'skipped-checkers' => $skippedCheckers, - ]; - - echo Json::encode($data, Json::PRETTY) . PHP_EOL; - + $data = ['sniffs' => $this->getSniffClasses(), 'fixers' => $this->getFixerClasses(), 'skipped-checkers' => $skippedCheckers]; + echo Json::encode($data, Json::PRETTY) . \PHP_EOL; return Command::SUCCESS; } - $this->checkerListReporter->report($this->getSniffClasses(), 'PHP_CodeSniffer'); $this->checkerListReporter->report($this->getFixerClasses(), 'PHP-CS-Fixer'); $this->checkerListReporter->report($skippedCheckers, 'Skipped Checkers'); - return self::SUCCESS; } - /** * @return array> */ - private function getFixerClasses(): array + private function getFixerClasses() : array { $fixers = $this->fixerFileProcessor->getCheckers(); return $this->getObjectClasses($fixers); } - /** * @return array> */ - private function getSniffClasses(): array + private function getSniffClasses() : array { $sniffs = $this->sniffFileProcessor->getCheckers(); return $this->getObjectClasses($sniffs); } - /** * @template TObject as Sniff|FixerInterface * @param TObject[] $checkers * @return array> */ - private function getObjectClasses(array $checkers): array + private function getObjectClasses(array $checkers) : array { - $objectClasses = array_map(static fn (object $fixer): string => $fixer::class, $checkers); - sort($objectClasses); - + $objectClasses = \array_map(static function (object $fixer) : string { + return \get_class($fixer); + }, $checkers); + \sort($objectClasses); return $objectClasses; } - /** * @return string[] */ - private function getSkippedCheckers(): array + private function getSkippedCheckers() : array { $skippedCheckers = []; foreach ($this->skippedClassResolver->resolve() as $checkerClass => $fileList) { @@ -113,10 +108,8 @@ private function getSkippedCheckers(): array if ($fileList !== null) { continue; } - $skippedCheckers[] = $checkerClass; } - return $skippedCheckers; } } diff --git a/src/Console/Command/WorkerCommand.php b/src/Console/Command/WorkerCommand.php index b59d1566464..bcb15fdfc74 100644 --- a/src/Console/Command/WorkerCommand.php +++ b/src/Console/Command/WorkerCommand.php @@ -1,22 +1,20 @@ workerRunner = $workerRunner; + $this->memoryLimitter = $memoryLimitter; + $this->configurationFactory = $configurationFactory; parent::__construct(); } - - protected function configure(): void + protected function configure() : void { $this->setName('worker'); $this->setDescription('[INTERNAL] Support for parallel process'); - parent::configure(); } - - protected function execute(InputInterface $input, OutputInterface $output): int + protected function execute(InputInterface $input, OutputInterface $output) : int { $configuration = $this->configurationFactory->createFromInput($input); $this->memoryLimitter->adjust($configuration); - $streamSelectLoop = new StreamSelectLoop(); $parallelIdentifier = $configuration->getParallelIdentifier(); - $tcpConnector = new TcpConnector($streamSelectLoop); - $promise = $tcpConnector->connect('127.0.0.1:' . $configuration->getParallelPort()); - $promise->then(function (ConnectionInterface $connection) use ($parallelIdentifier, $configuration): void { - $inDecoder = new Decoder($connection, true, 512, JSON_INVALID_UTF8_IGNORE); - $outEncoder = new Encoder($connection, JSON_INVALID_UTF8_IGNORE); - + $promise->then(function (ConnectionInterface $connection) use($parallelIdentifier, $configuration) : void { + $inDecoder = new Decoder($connection, \true, 512, \JSON_INVALID_UTF8_IGNORE); + $outEncoder = new Encoder($connection, \JSON_INVALID_UTF8_IGNORE); // handshake? - $outEncoder->write([ - ReactCommand::ACTION => Action::HELLO, - ReactCommand::IDENTIFIER => $parallelIdentifier, - ]); - + $outEncoder->write([ReactCommand::ACTION => Action::HELLO, ReactCommand::IDENTIFIER => $parallelIdentifier]); $this->workerRunner->run($outEncoder, $inDecoder, $configuration); }); - $streamSelectLoop->run(); - return self::SUCCESS; } } diff --git a/src/Console/EasyCodingStandardConsoleApplication.php b/src/Console/EasyCodingStandardConsoleApplication.php index 81ae157bcc8..55aaa8ef1e1 100644 --- a/src/Console/EasyCodingStandardConsoleApplication.php +++ b/src/Console/EasyCodingStandardConsoleApplication.php @@ -1,96 +1,67 @@ add($checkCommand); $this->add($workerCommand); $this->add($listCheckersCommand); - $this->setDefaultCommand('check'); } - - public function doRun(InputInterface $input, OutputInterface $output): int + public function doRun(InputInterface $input, OutputInterface $output) : int { // @fixes https://github.com/rectorphp/rector/issues/2205 $isXdebugAllowed = $input->hasParameterOption('--xdebug'); - if (! $isXdebugAllowed && ! defined('PHPUNIT_COMPOSER_INSTALL')) { + if (!$isXdebugAllowed && !\defined('ECSPrefix202307\\PHPUNIT_COMPOSER_INSTALL')) { $xdebugHandler = new XdebugHandler('ecs'); $xdebugHandler->check(); unset($xdebugHandler); } - // skip in this case, since generate content must be clear from meta-info if ($this->shouldPrintMetaInformation($input)) { $output->writeln($this->getLongVersion()); } - return parent::doRun($input, $output); } - - protected function getDefaultInputDefinition(): InputDefinition + protected function getDefaultInputDefinition() : InputDefinition { $inputDefinition = parent::getDefaultInputDefinition(); $this->addExtraOptions($inputDefinition); - return $inputDefinition; } - - private function shouldPrintMetaInformation(InputInterface $input): bool + private function shouldPrintMetaInformation(InputInterface $input) : bool { $hasNoArguments = $input->getFirstArgument() === null; $hasVersionOption = $input->hasParameterOption('--version'); - if ($hasVersionOption) { - return false; + return \false; } - if ($hasNoArguments) { - return false; + return \false; } - $outputFormat = $input->getParameterOption('--' . Option::OUTPUT_FORMAT); - return $outputFormat === ConsoleOutputFormatter::NAME; } - - private function addExtraOptions(InputDefinition $inputDefinition): void + private function addExtraOptions(InputDefinition $inputDefinition) : void { - $inputDefinition->addOption(new InputOption( - Option::XDEBUG, - null, - InputOption::VALUE_NONE, - 'Allow running xdebug' - )); - - $inputDefinition->addOption(new InputOption( - Option::DEBUG, - null, - InputOption::VALUE_NONE, - 'Run in debug mode (alias for "-vvv")' - )); + $inputDefinition->addOption(new InputOption(Option::XDEBUG, null, InputOption::VALUE_NONE, 'Allow running xdebug')); + $inputDefinition->addOption(new InputOption(Option::DEBUG, null, InputOption::VALUE_NONE, 'Run in debug mode (alias for "-vvv")')); } } diff --git a/src/Console/ExitCode.php b/src/Console/ExitCode.php index 42b26abfb6e..48335f33619 100644 --- a/src/Console/ExitCode.php +++ b/src/Console/ExitCode.php @@ -1,23 +1,19 @@ @@ -19,85 +17,68 @@ final class ColorConsoleDiffFormatter * @var string * @see https://regex101.com/r/ovLMDF/1 */ - private const PLUS_START_REGEX = '#^(\+.*)#'; - + private const PLUS_START_REGEX = '#^(\\+.*)#'; /** * @var string * @see https://regex101.com/r/xwywpa/1 */ - private const MINUT_START_REGEX = '#^(\-.*)#'; - + private const MINUT_START_REGEX = '#^(\\-.*)#'; /** * @var string * @see https://regex101.com/r/CMlwa8/1 */ private const AT_START_REGEX = '#^(@.*)#'; - /** * @var string * @see https://regex101.com/r/qduj2O/1 */ private const NEWLINES_REGEX = "#\n\r|\n#"; - - private readonly string $template; - + /** + * @readonly + * @var string + */ + private $template; public function __construct() { - $this->template = sprintf( - ' ---------- begin diff ----------%s%%s%s ----------- end diff -----------' . PHP_EOL, - PHP_EOL, - PHP_EOL - ); + $this->template = \sprintf(' ---------- begin diff ----------%s%%s%s ----------- end diff -----------' . \PHP_EOL, \PHP_EOL, \PHP_EOL); } - - public function format(string $diff): string + public function format(string $diff) : string { return $this->formatWithTemplate($diff, $this->template); } - - private function formatWithTemplate(string $diff, string $template): string + private function formatWithTemplate(string $diff, string $template) : string { - $escapedDiff = OutputFormatter::escape(rtrim($diff)); - + $escapedDiff = OutputFormatter::escape(\rtrim($diff)); $escapedDiffLines = Strings::split($escapedDiff, self::NEWLINES_REGEX); - // remove description of added + remove; obvious on diffs foreach ($escapedDiffLines as $key => $escapedDiffLine) { if ($escapedDiffLine === '--- Original') { unset($escapedDiffLines[$key]); } - if ($escapedDiffLine === '+++ New') { unset($escapedDiffLines[$key]); } } - - $coloredLines = array_map(function (string $string): string { + $coloredLines = \array_map(function (string $string) : string { $string = $this->makePlusLinesGreen($string); $string = $this->makeMinusLinesRed($string); $string = $this->makeAtNoteCyan($string); - if ($string === ' ') { return ''; } - return $string; }, $escapedDiffLines); - - return sprintf($template, implode(PHP_EOL, $coloredLines)); + return \sprintf($template, \implode(\PHP_EOL, $coloredLines)); } - - private function makePlusLinesGreen(string $string): string + private function makePlusLinesGreen(string $string) : string { return Strings::replace($string, self::PLUS_START_REGEX, '$1'); } - - private function makeMinusLinesRed(string $string): string + private function makeMinusLinesRed(string $string) : string { return Strings::replace($string, self::MINUT_START_REGEX, '$1'); } - - private function makeAtNoteCyan(string $string): string + private function makeAtNoteCyan(string $string) : string { return Strings::replace($string, self::AT_START_REGEX, '$1'); } diff --git a/src/Console/Output/ConsoleOutputFormatter.php b/src/Console/Output/ConsoleOutputFormatter.php index 91d2713a225..6ac84a9459c 100644 --- a/src/Console/Output/ConsoleOutputFormatter.php +++ b/src/Console/Output/ConsoleOutputFormatter.php @@ -1,7 +1,6 @@ easyCodingStandardStyle = $easyCodingStandardStyle; + $this->exitCodeResolver = $exitCodeResolver; } - /** * @return ExitCode::* */ - public function report(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): int + public function report(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration) : int { $this->reportFileDiffs($errorAndDiffResult->getFileDiffs()); - $this->easyCodingStandardStyle->newLine(1); - if ($errorAndDiffResult->getErrorCount() === 0 && $errorAndDiffResult->getFileDiffsCount() === 0) { $this->easyCodingStandardStyle->success('No errors found. Great job - your code is shiny in style!'); - return $this->exitCodeResolver->resolve($errorAndDiffResult, $configuration); } - $this->easyCodingStandardStyle->newLine(); - if ($configuration->isFixer()) { $this->printAfterFixerStatus($errorAndDiffResult, $configuration); } else { $this->printNoFixerStatus($errorAndDiffResult, $configuration); } - return $this->exitCodeResolver->resolve($errorAndDiffResult, $configuration); } - - public function getName(): string + public function getName() : string { return self::NAME; } - /** * @param FileDiff[] $fileDiffs */ - private function reportFileDiffs(array $fileDiffs): void + private function reportFileDiffs(array $fileDiffs) : void { if ($fileDiffs === []) { return; } - $this->easyCodingStandardStyle->newLine(1); - $i = 1; foreach ($fileDiffs as $fileDiff) { $this->easyCodingStandardStyle->newLine(2); - - $boldNumberedMessage = sprintf('%d) %s', $i, $fileDiff->getRelativeFilePath()); + $boldNumberedMessage = \sprintf('%d) %s', $i, $fileDiff->getRelativeFilePath()); $this->easyCodingStandardStyle->writeln($boldNumberedMessage); - ++$i; - $this->easyCodingStandardStyle->newLine(); $this->easyCodingStandardStyle->writeln($fileDiff->getDiffConsoleFormatted()); $this->easyCodingStandardStyle->newLine(); - $this->easyCodingStandardStyle->writeln('Applied checkers:'); $this->easyCodingStandardStyle->newLine(); $this->easyCodingStandardStyle->listing($fileDiff->getAppliedCheckers()); } } - - private function printAfterFixerStatus(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): void + private function printAfterFixerStatus(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration) : void { if ($configuration->shouldShowErrorTable()) { $this->easyCodingStandardStyle->printErrors($errorAndDiffResult->getErrors()); } - if ($errorAndDiffResult->getErrorCount() === 0) { - $successMessage = sprintf( - '%d error%s successfully fixed and no other errors found!', - $errorAndDiffResult->getFileDiffsCount(), - $errorAndDiffResult->getFileDiffsCount() === 1 ? '' : 's' - ); + $successMessage = \sprintf('%d error%s successfully fixed and no other errors found!', $errorAndDiffResult->getFileDiffsCount(), $errorAndDiffResult->getFileDiffsCount() === 1 ? '' : 's'); $this->easyCodingStandardStyle->success($successMessage); - return; } - $this->printSystemErrors($errorAndDiffResult); - - $this->printErrorMessageFromErrorCounts( - $errorAndDiffResult->getCodingStandardErrorCount(), - $errorAndDiffResult->getFileDiffsCount(), - $configuration - ); + $this->printErrorMessageFromErrorCounts($errorAndDiffResult->getCodingStandardErrorCount(), $errorAndDiffResult->getFileDiffsCount(), $configuration); } - - private function printNoFixerStatus(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): void + private function printNoFixerStatus(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration) : void { if ($configuration->shouldShowErrorTable()) { $errors = $errorAndDiffResult->getErrors(); @@ -121,62 +99,34 @@ private function printNoFixerStatus(ErrorAndDiffResult $errorAndDiffResult, Conf $this->easyCodingStandardStyle->printErrors($errors); } } - $this->printSystemErrors($errorAndDiffResult); - - $this->printErrorMessageFromErrorCounts( - $errorAndDiffResult->getCodingStandardErrorCount(), - $errorAndDiffResult->getFileDiffsCount(), - $configuration - ); + $this->printErrorMessageFromErrorCounts($errorAndDiffResult->getCodingStandardErrorCount(), $errorAndDiffResult->getFileDiffsCount(), $configuration); } - - private function printSystemErrors(ErrorAndDiffResult $errorAndDiffResult): void + private function printSystemErrors(ErrorAndDiffResult $errorAndDiffResult) : void { $systemErrors = $errorAndDiffResult->getSystemErrors(); foreach ($systemErrors as $systemError) { $this->easyCodingStandardStyle->newLine(); - if ($systemError instanceof SystemError) { - $this->easyCodingStandardStyle->error( - $systemError->getMessage() . ' in ' . $systemError->getFileWithLine() - ); + $this->easyCodingStandardStyle->error($systemError->getMessage() . ' in ' . $systemError->getFileWithLine()); } else { $this->easyCodingStandardStyle->error($systemError); } } } - - private function printErrorMessageFromErrorCounts( - int $codingStandardErrorCount, - int $fileDiffsCount, - Configuration $configuration - ): void { + private function printErrorMessageFromErrorCounts(int $codingStandardErrorCount, int $fileDiffsCount, Configuration $configuration) : void + { if ($codingStandardErrorCount !== 0) { - $errorMessage = sprintf( - 'Found %d error%s that need%s to be fixed manually.', - $codingStandardErrorCount, - $codingStandardErrorCount === 1 ? '' : 's', - $codingStandardErrorCount === 1 ? 's' : '' - ); + $errorMessage = \sprintf('Found %d error%s that need%s to be fixed manually.', $codingStandardErrorCount, $codingStandardErrorCount === 1 ? '' : 's', $codingStandardErrorCount === 1 ? 's' : ''); $this->easyCodingStandardStyle->error($errorMessage); } - if ($fileDiffsCount === 0) { return; } - if ($configuration->isFixer()) { return; } - - $fixableMessage = sprintf( - '%s%d %s fixable! Just add "--fix" to console command and rerun to apply.', - $codingStandardErrorCount !== 0 ? 'Good news is that ' : '', - $fileDiffsCount, - $fileDiffsCount === 1 ? 'error is' : 'errors are' - ); - + $fixableMessage = \sprintf('%s%d %s fixable! Just add "--fix" to console command and rerun to apply.', $codingStandardErrorCount !== 0 ? 'Good news is that ' : '', $fileDiffsCount, $fileDiffsCount === 1 ? 'error is' : 'errors are'); $this->easyCodingStandardStyle->warning($fixableMessage); } } diff --git a/src/Console/Output/ExitCodeResolver.php b/src/Console/Output/ExitCodeResolver.php index c81cd55b18f..85fc3177a50 100644 --- a/src/Console/Output/ExitCodeResolver.php +++ b/src/Console/Output/ExitCodeResolver.php @@ -1,28 +1,24 @@ getErrorCount() === 0 && $errorAndDiffResult->getFileDiffsCount() === 0) { return ExitCode::SUCCESS; } - if ($configuration->isFixer()) { return $errorAndDiffResult->getErrorCount() === 0 ? ExitCode::SUCCESS : ExitCode::FAILURE; } - return $errorAndDiffResult->getErrorCount() !== 0 || $errorAndDiffResult->getFileDiffsCount() !== 0 ? ExitCode::CHANGED_CODE_OR_FOUND_ERRORS : ExitCode::SUCCESS; } } diff --git a/src/Console/Output/JsonOutputFormatter.php b/src/Console/Output/JsonOutputFormatter.php index 264215fec8d..129934a93b4 100644 --- a/src/Console/Output/JsonOutputFormatter.php +++ b/src/Console/Output/JsonOutputFormatter.php @@ -1,16 +1,14 @@ easyCodingStandardStyle = $easyCodingStandardStyle; + $this->exitCodeResolver = $exitCodeResolver; } - /** * @return ExitCode::* */ - public function report(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration): int + public function report(ErrorAndDiffResult $errorAndDiffResult, Configuration $configuration) : int { $json = $this->createJsonContent($errorAndDiffResult); $this->easyCodingStandardStyle->writeln($json); - return $this->exitCodeResolver->resolve($errorAndDiffResult, $configuration); } - - public function getName(): string + public function getName() : string { return self::NAME; } - /** * @api */ - public function createJsonContent(ErrorAndDiffResult $errorAndDiffResult): string + public function createJsonContent(ErrorAndDiffResult $errorAndDiffResult) : string { $errorsArrayJson = $this->createBaseErrorsJson($errorAndDiffResult); - $codingStandardErrors = $errorAndDiffResult->getErrors(); foreach ($codingStandardErrors as $codingStandardError) { - $errorsArrayJson[self::FILES][$codingStandardError->getRelativeFilePath()]['errors'][] = [ - 'line' => $codingStandardError->getLine(), - 'file_path' => $codingStandardError->getRelativeFilePath(), - 'message' => $codingStandardError->getMessage(), - 'source_class' => $codingStandardError->getCheckerClass(), - ]; + $errorsArrayJson[self::FILES][$codingStandardError->getRelativeFilePath()]['errors'][] = ['line' => $codingStandardError->getLine(), 'file_path' => $codingStandardError->getRelativeFilePath(), 'message' => $codingStandardError->getMessage(), 'source_class' => $codingStandardError->getCheckerClass()]; } - $fileDiffs = $errorAndDiffResult->getFileDiffs(); foreach ($fileDiffs as $fileDiff) { - $errorsArrayJson[self::FILES][$fileDiff->getRelativeFilePath()]['diffs'][] = [ - 'diff' => $fileDiff->getDiff(), - 'applied_checkers' => $fileDiff->getAppliedCheckers(), - ]; + $errorsArrayJson[self::FILES][$fileDiff->getRelativeFilePath()]['diffs'][] = ['diff' => $fileDiff->getDiff(), 'applied_checkers' => $fileDiff->getAppliedCheckers()]; } - return Json::encode($errorsArrayJson, Json::PRETTY); } - /** * @return array{totals: array{errors: int, diffs: int}, files: string[]} */ - private function createBaseErrorsJson(ErrorAndDiffResult $errorAndDiffResult): array + private function createBaseErrorsJson(ErrorAndDiffResult $errorAndDiffResult) : array { - return [ - 'totals' => [ - 'errors' => $errorAndDiffResult->getErrorCount(), - 'diffs' => $errorAndDiffResult->getFileDiffsCount(), - ], - self::FILES => [], - ]; + return ['totals' => ['errors' => $errorAndDiffResult->getErrorCount(), 'diffs' => $errorAndDiffResult->getFileDiffsCount()], self::FILES => []]; } } diff --git a/src/Console/Output/OutputFormatterCollector.php b/src/Console/Output/OutputFormatterCollector.php index 08a99c42687..d0db9bcaab1 100644 --- a/src/Console/Output/OutputFormatterCollector.php +++ b/src/Console/Output/OutputFormatterCollector.php @@ -1,19 +1,16 @@ */ - private array $outputFormatters = []; - + private $outputFormatters = []; /** * @param OutputFormatterInterface[] $outputFormatters */ @@ -23,20 +20,13 @@ public function __construct(array $outputFormatters) $this->outputFormatters[$outputFormatter->getName()] = $outputFormatter; } } - - public function getByName(string $name): OutputFormatterInterface + public function getByName(string $name) : OutputFormatterInterface { if (isset($this->outputFormatters[$name])) { return $this->outputFormatters[$name]; } - - $outputFormatterKeys = array_keys($this->outputFormatters); - - $errorMessage = sprintf( - 'Output formatter "%s" not found. Use one of: "%s".', - $name, - implode('", "', $outputFormatterKeys) - ); + $outputFormatterKeys = \array_keys($this->outputFormatters); + $errorMessage = \sprintf('Output formatter "%s" not found. Use one of: "%s".', $name, \implode('", "', $outputFormatterKeys)); throw new OutputFormatterNotFoundException($errorMessage); } } diff --git a/src/Console/Reporter/CheckerListReporter.php b/src/Console/Reporter/CheckerListReporter.php index ae289df645d..43ef0c41719 100644 --- a/src/Console/Reporter/CheckerListReporter.php +++ b/src/Console/Reporter/CheckerListReporter.php @@ -1,33 +1,29 @@ symfonyStyle = $symfonyStyle; } - /** * @param string[] $checkerClasses */ - public function report(array $checkerClasses, string $type): void + public function report(array $checkerClasses, string $type) : void { if ($checkerClasses === []) { return; } - - $sectionMessage = sprintf( - '%d checker%s from %s:', - count($checkerClasses), - count($checkerClasses) === 1 ? '' : 's', - $type - ); + $sectionMessage = \sprintf('%d checker%s from %s:', \count($checkerClasses), \count($checkerClasses) === 1 ? '' : 's', $type); $this->symfonyStyle->section($sectionMessage); $this->symfonyStyle->listing($checkerClasses); } diff --git a/src/Console/Style/EasyCodingStandardStyle.php b/src/Console/Style/EasyCodingStandardStyle.php index bcd7ce7f61f..8621a1edae5 100644 --- a/src/Console/Style/EasyCodingStandardStyle.php +++ b/src/Console/Style/EasyCodingStandardStyle.php @@ -1,15 +1,13 @@ terminal = $terminal; parent::__construct($input, $output); } - /** * @param CodingStandardError[] $codingStandardErrors */ - public function printErrors(array $codingStandardErrors): void + public function printErrors(array $codingStandardErrors) : void { /** @var CodingStandardError $codingStandardError */ foreach ($codingStandardErrors as $codingStandardError) { $this->separator(); - $this->writeln(' ' . $codingStandardError->getFileWithLine()); - $this->separator(); - $message = $this->createMessageFromFileError($codingStandardError); $this->writeln(' ' . $message); - $this->separator(); - $this->newLine(); } } - - private function separator(): void + private function separator() : void { - $separator = str_repeat('-', $this->getTerminalWidth()); + $separator = \str_repeat('-', $this->getTerminalWidth()); $this->writeln(' ' . $separator); } - - private function createMessageFromFileError(CodingStandardError $codingStandardError): string + private function createMessageFromFileError(CodingStandardError $codingStandardError) : string { - $message = sprintf( - '%s%s Reported by: "%s"', - $codingStandardError->getMessage(), - PHP_EOL . PHP_EOL, - $codingStandardError->getCheckerClass() - ); + $message = \sprintf('%s%s Reported by: "%s"', $codingStandardError->getMessage(), \PHP_EOL . \PHP_EOL, $codingStandardError->getCheckerClass()); $message = $this->clearCrLfFromMessage($message); - return $this->wrapMessageSoItFitsTheColumnWidth($message); } - - private function getTerminalWidth(): int + private function getTerminalWidth() : int { return $this->terminal->getWidth() - self::BULGARIAN_CONSTANT; } - /** * This prevents message override in Windows system. */ - private function clearCrLfFromMessage(string $message): string + private function clearCrLfFromMessage(string $message) : string { - return str_replace("\r", '', $message); + return \str_replace("\r", '', $message); } - - private function wrapMessageSoItFitsTheColumnWidth(string $message): string + private function wrapMessageSoItFitsTheColumnWidth(string $message) : string { - return wordwrap($message, $this->getTerminalWidth(), PHP_EOL); + return \wordwrap($message, $this->getTerminalWidth(), \PHP_EOL); } } diff --git a/src/Console/Style/EasyCodingStandardStyleFactory.php b/src/Console/Style/EasyCodingStandardStyleFactory.php index 7789d8e311e..20fda338704 100644 --- a/src/Console/Style/EasyCodingStandardStyleFactory.php +++ b/src/Console/Style/EasyCodingStandardStyleFactory.php @@ -1,42 +1,41 @@ terminal = $terminal; } - /** * @api */ - public function create(): EasyCodingStandardStyle + public function create() : \Symplify\EasyCodingStandard\Console\Style\EasyCodingStandardStyle { $argvInput = new ArgvInput(); $consoleOutput = new ConsoleOutput(); - // --debug is called if ($argvInput->hasParameterOption('--debug')) { $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_DEBUG); } - // disable output for tests - if (defined('PHPUNIT_COMPOSER_INSTALL')) { + if (\defined('ECSPrefix202307\\PHPUNIT_COMPOSER_INSTALL')) { $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_QUIET); } - - return new EasyCodingStandardStyle($argvInput, $consoleOutput, $this->terminal); + return new \Symplify\EasyCodingStandard\Console\Style\EasyCodingStandardStyle($argvInput, $consoleOutput, $this->terminal); } } diff --git a/src/Console/Style/SymfonyStyleFactory.php b/src/Console/Style/SymfonyStyleFactory.php index 620f0bb0b9a..584ce745b4d 100644 --- a/src/Console/Style/SymfonyStyleFactory.php +++ b/src/Console/Style/SymfonyStyleFactory.php @@ -1,47 +1,40 @@ hasParameterOption('--debug')) { $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_DEBUG); } - // disable output for tests if ($this->isPHPUnitRun()) { $consoleOutput->setVerbosity(OutputInterface::VERBOSITY_QUIET); } - return new SymfonyStyle($argvInput, $consoleOutput); } - /** * Never ever used static methods if not neccesary, this is just handy for tests + src to prevent duplication. */ - private function isPHPUnitRun(): bool + private function isPHPUnitRun() : bool { - return defined('PHPUNIT_COMPOSER_INSTALL') || defined('__PHPUNIT_PHAR__'); + return \defined('ECSPrefix202307\\PHPUNIT_COMPOSER_INSTALL') || \defined('ECSPrefix202307\\__PHPUNIT_PHAR__'); } } diff --git a/src/Contract/Application/FileProcessorInterface.php b/src/Contract/Application/FileProcessorInterface.php index ebc1447d9b6..14390f292d7 100644 --- a/src/Contract/Application/FileProcessorInterface.php +++ b/src/Contract/Application/FileProcessorInterface.php @@ -1,24 +1,20 @@ getBindings()); - - return array_filter($serviceTypes, static function (string $serviceType): bool { - if (is_a($serviceType, FixerInterface::class, true)) { - return true; + $serviceTypes = \array_keys($container->getBindings()); + return \array_filter($serviceTypes, static function (string $serviceType) : bool { + if (\is_a($serviceType, FixerInterface::class, \true)) { + return \true; } - - return is_a($serviceType, Sniff::class, true); + return \is_a($serviceType, Sniff::class, \true); }); } - - public static function removeCheckerFromContainer(COntainer $container, string $checkerClass): void + public static function removeCheckerFromContainer(COntainer $container, string $checkerClass) : void { // remove instance $container->offsetUnset($checkerClass); - $tags = PrivatesAccessorHelper::getPropertyValue($container, 'tags'); - // nothing to remove if ($tags === []) { return; } - // remove from tags $checkerTagClasses = [FixerInterface::class, Sniff::class]; - foreach ($checkerTagClasses as $checkerTagClass) { foreach ($tags[$checkerTagClass] ?? [] as $key => $class) { if ($class !== $checkerClass) { continue; } - unset($tags[$checkerTagClass][$key]); } } - // update value PrivatesAccessorHelper::setPropertyValue($container, 'tags', $tags); } diff --git a/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php b/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php index 4df7b63838d..23fc1933d00 100644 --- a/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php @@ -1,10 +1,9 @@ isMatch($checkerTypes, $viceVersaMatchingCheckerGroup)) { + if (!$this->isMatch($checkerTypes, $viceVersaMatchingCheckerGroup)) { continue; } - - throw new ConflictingCheckersLoadedException(sprintf( - 'Checkers "%s" mutually exclude each other. Use only one of them or exclude the unwanted one in "$ecsConfig->skip(...)" in your config.', - implode('" and "', $viceVersaMatchingCheckerGroup) - )); + throw new ConflictingCheckersLoadedException(\sprintf('Checkers "%s" mutually exclude each other. Use only one of them or exclude the unwanted one in "$ecsConfig->skip(...)" in your config.', \implode('" and "', $viceVersaMatchingCheckerGroup))); } } - /** * @param mixed[] $checkers * @param string[] $matchingCheckerGroup */ - private function isMatch(array $checkers, array $matchingCheckerGroup): bool + private function isMatch(array $checkers, array $matchingCheckerGroup) : bool { - $checkers = array_flip($checkers); - $matchingCheckerGroup = array_flip($matchingCheckerGroup); - - $foundCheckers = array_intersect_key($matchingCheckerGroup, $checkers); - - return count($foundCheckers) === count($matchingCheckerGroup); + $checkers = \array_flip($checkers); + $matchingCheckerGroup = \array_flip($matchingCheckerGroup); + $foundCheckers = \array_intersect_key($matchingCheckerGroup, $checkers); + return \count($foundCheckers) === \count($matchingCheckerGroup); } } diff --git a/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php b/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php index b2f6ff2ecbb..d4560a1e191 100644 --- a/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php @@ -1,73 +1,61 @@ getExcludedCheckersFromSkipParameter(); - - foreach (array_keys($container->getBindings()) as $classType) { - if (! in_array($classType, $excludedCheckers, true)) { + foreach (\array_keys($container->getBindings()) as $classType) { + if (!\in_array($classType, $excludedCheckers, \true)) { continue; } - // remove service from container completely - CompilerPassHelper::removeCheckerFromContainer($container, $classType); + \Symplify\EasyCodingStandard\DependencyInjection\CompilerPass\CompilerPassHelper::removeCheckerFromContainer($container, $classType); } } - /** * @return array */ - private function getExcludedCheckersFromSkipParameter(): array + private function getExcludedCheckersFromSkipParameter() : array { $excludedCheckers = []; - $skip = SimpleParameterProvider::getArrayParameter(Option::SKIP); - foreach ($skip as $key => $value) { $excludedChecker = $this->matchFullClassSkip($key, $value); if ($excludedChecker === null) { continue; } - $excludedCheckers[] = $excludedChecker; } - - return array_unique($excludedCheckers); + return \array_unique($excludedCheckers); } - /** * @return class-string|null + * @param int|string $key + * @param mixed $value */ - private function matchFullClassSkip(int|string $key, mixed $value): ?string + private function matchFullClassSkip($key, $value) : ?string { // "SomeClass::class" => null - if (is_string($key) && class_exists($key) && $value === null) { + if (\is_string($key) && \class_exists($key) && $value === null) { return $key; } - // "SomeClass::class" - if (! is_int($key)) { + if (!\is_int($key)) { return null; } - - if (! is_string($value)) { + if (!\is_string($value)) { return null; } - - if (! class_exists($value)) { + if (!\class_exists($value)) { return null; } - return $value; } } diff --git a/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php b/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php index 23bb209421e..2556b6c30c1 100644 --- a/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php +++ b/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php @@ -1,10 +1,9 @@ resolveCheckersToRemove($checkerTypes); if ($checkersToRemove === []) { return; } - - foreach (array_keys($container->getBindings()) as $type) { - if (! in_array($type, $checkersToRemove, true)) { + foreach (\array_keys($container->getBindings()) as $type) { + if (!\in_array($type, $checkersToRemove, \true)) { continue; } - - CompilerPassHelper::removeCheckerFromContainer($container, $type); + \Symplify\EasyCodingStandard\DependencyInjection\CompilerPass\CompilerPassHelper::removeCheckerFromContainer($container, $type); } } - /** * @param string[] $checkers * @return string[] */ - private function resolveCheckersToRemove(array $checkers): array + private function resolveCheckersToRemove(array $checkers) : array { - $checkers = array_flip($checkers); - + $checkers = \array_flip($checkers); $checkersToRemove = []; foreach (self::DUPLICATED_CHECKER_GROUPS as $matchingCheckerGroup) { - if (! $this->isMatch($checkers, $matchingCheckerGroup)) { + if (!$this->isMatch($checkers, $matchingCheckerGroup)) { continue; } - - array_shift($matchingCheckerGroup); - - $checkersToRemove = [...$checkersToRemove, ...$matchingCheckerGroup]; + \array_shift($matchingCheckerGroup); + $checkersToRemove = \array_merge($checkersToRemove, \is_array($matchingCheckerGroup) ? $matchingCheckerGroup : \iterator_to_array($matchingCheckerGroup)); } - return $checkersToRemove; } - /** * @param string[] $checkers * @param string[] $matchingCheckerGroup */ - private function isMatch(array $checkers, array $matchingCheckerGroup): bool + private function isMatch(array $checkers, array $matchingCheckerGroup) : bool { - $matchingCheckerGroupKeys = array_flip($matchingCheckerGroup); - $matchingCheckers = array_intersect_key($matchingCheckerGroupKeys, $checkers); - - return count($matchingCheckers) === count($matchingCheckerGroup); + $matchingCheckerGroupKeys = \array_flip($matchingCheckerGroup); + $matchingCheckers = \array_intersect_key($matchingCheckerGroupKeys, $checkers); + return \count($matchingCheckers) === \count($matchingCheckerGroup); } } diff --git a/src/DependencyInjection/EasyCodingStandardContainerFactory.php b/src/DependencyInjection/EasyCodingStandardContainerFactory.php index a7c48d6b121..285cb218b4b 100644 --- a/src/DependencyInjection/EasyCodingStandardContainerFactory.php +++ b/src/DependencyInjection/EasyCodingStandardContainerFactory.php @@ -1,45 +1,38 @@ hasParameterOption(['--config', '-c'])) { $commandLineConfigFile = $argvInput->getParameterOption(['--config', '-c']); - if (is_string($commandLineConfigFile) && file_exists($commandLineConfigFile)) { + if (\is_string($commandLineConfigFile) && \file_exists($commandLineConfigFile)) { // must be realpath, so container builder knows the location - $inputConfigFiles[] = (string) realpath($commandLineConfigFile); + $inputConfigFiles[] = (string) \realpath($commandLineConfigFile); } - } elseif (file_exists($rootECSConfig)) { + } elseif (\file_exists($rootECSConfig)) { $inputConfigFiles[] = $rootECSConfig; } - $container = $newContainerFactory->create($inputConfigFiles); - if ($inputConfigFiles !== []) { // for cache invalidation on config change /** @var ChangedFilesDetector $changedFilesDetector */ $changedFilesDetector = $container->make(ChangedFilesDetector::class); $changedFilesDetector->setUsedConfigs($inputConfigFiles); } - return $container; } } diff --git a/src/DependencyInjection/NewContainerFactory.php b/src/DependencyInjection/NewContainerFactory.php index 11f36ba6c42..3a4c0347e99 100644 --- a/src/DependencyInjection/NewContainerFactory.php +++ b/src/DependencyInjection/NewContainerFactory.php @@ -1,11 +1,10 @@ loadPHPCodeSnifferConstants(); - $ecsConfig = new ECSConfig(); - // make sure these services have shared instance created just once, as use setters throughout the project $ecsConfig->singleton(ChangedFilesDetector::class); $ecsConfig->singleton(SniffMetadataCollector::class); @@ -61,161 +57,108 @@ public function create(array $configFiles = []): Container $ecsConfig->singleton(ParallelFileProcessor::class); $ecsConfig->singleton(Skipper::class); $ecsConfig->singleton(SkipSkipper::class); - // console $ecsConfig->singleton(EasyCodingStandardStyle::class, static function (Container $container) { $easyCodingStandardStyleFactory = $container->make(EasyCodingStandardStyleFactory::class); return $easyCodingStandardStyleFactory->create(); }); - $ecsConfig->singleton(SymfonyStyle::class, static function (Container $container) { $symfonyStyleFactory = $container->make(SymfonyStyleFactory::class); return $symfonyStyleFactory->create(); }); - $ecsConfig->singleton(Fixer::class); - // whitespace - $ecsConfig->singleton(WhitespacesFixerConfig::class, static function (): WhitespacesFixerConfig { + $ecsConfig->singleton(WhitespacesFixerConfig::class, static function () : WhitespacesFixerConfig { $whitespacesFixerConfigFactory = new WhitespacesFixerConfigFactory(); return $whitespacesFixerConfigFactory->create(); }); - // caching $ecsConfig->singleton(Cache::class, static function (Container $container) { $cacheFactory = $container->make(CacheFactory::class); return $cacheFactory->create(); }); - // output $ecsConfig->singleton(ConsoleOutputFormatter::class); $ecsConfig->tag(ConsoleOutputFormatter::class, OutputFormatterInterface::class); - $ecsConfig->singleton(JsonOutputFormatter::class); $ecsConfig->tag(JsonOutputFormatter::class, OutputFormatterInterface::class); - - $ecsConfig->singleton( - OutputFormatterCollector::class, - static function (Container $container): OutputFormatterCollector { - /** @var RewindableGenerator $outputFormattersRewindableGenerator */ - $outputFormattersRewindableGenerator = $container->tagged(OutputFormatterInterface::class); - return new OutputFormatterCollector(iterator_to_array( - $outputFormattersRewindableGenerator->getIterator() - )); - } - ); - - $ecsConfig->singleton(DifferInterface::class, static fn (): DifferInterface => new UnifiedDiffer()); - - $ecsConfig->singleton(FixerFileProcessor::class, function (Container $container): FixerFileProcessor { + $ecsConfig->singleton(OutputFormatterCollector::class, static function (Container $container) : OutputFormatterCollector { + /** @var RewindableGenerator $outputFormattersRewindableGenerator */ + $outputFormattersRewindableGenerator = $container->tagged(OutputFormatterInterface::class); + return new OutputFormatterCollector(\iterator_to_array($outputFormattersRewindableGenerator->getIterator())); + }); + $ecsConfig->singleton(DifferInterface::class, static function () : DifferInterface { + return new UnifiedDiffer(); + }); + $ecsConfig->singleton(FixerFileProcessor::class, function (Container $container) : FixerFileProcessor { $fixers = $this->getTaggedServicesArray($container, FixerInterface::class); - - return new FixerFileProcessor( - $container->make(FileToTokensParser::class), - $container->make(Skipper::class), - $container->make(DifferInterface::class), - $container->make(EasyCodingStandardStyle::class), - $container->make(Filesystem::class), - $container->make(FileDiffFactory::class), - $fixers - ); + return new FixerFileProcessor($container->make(FileToTokensParser::class), $container->make(Skipper::class), $container->make(DifferInterface::class), $container->make(EasyCodingStandardStyle::class), $container->make(Filesystem::class), $container->make(FileDiffFactory::class), $fixers); }); - - $ecsConfig->singleton(SniffFileProcessor::class, function (Container $container): SniffFileProcessor { + $ecsConfig->singleton(SniffFileProcessor::class, function (Container $container) : SniffFileProcessor { $sniffs = $this->getTaggedServicesArray($container, Sniff::class); - - return new SniffFileProcessor( - $container->make(Fixer::class), - $container->make(FileFactory::class), - $container->make(DifferInterface::class), - $container->make(SniffMetadataCollector::class), - $container->make(Filesystem::class), - $container->make(FileDiffFactory::class), - $sniffs, - ); + return new SniffFileProcessor($container->make(Fixer::class), $container->make(FileFactory::class), $container->make(DifferInterface::class), $container->make(SniffMetadataCollector::class), $container->make(Filesystem::class), $container->make(FileDiffFactory::class), $sniffs); }); - // load default config first - $configFiles = array_merge([__DIR__ . '/../../config/config.php'], $configFiles); - + $configFiles = \array_merge([__DIR__ . '/../../config/config.php'], $configFiles); foreach ($configFiles as $configFile) { - $configClosure = require $configFile; + $configClosure = (require $configFile); Assert::isCallable($configClosure); - $configClosure($ecsConfig); } - // compiler passes-like - $ecsConfig->beforeResolving( - FixerFileProcessor::class, - static function ($object, $misc, ECSConfig $ecsConfig): void { - $removeExcludedCheckersCompilerPass = new RemoveExcludedCheckersCompilerPass(); - $removeExcludedCheckersCompilerPass->process($ecsConfig); - } - ); - - $hasRunAfterResolving = false; - - $ecsConfig->afterResolving(static function ($object, ECSConfig $ecsConfig) use (&$hasRunAfterResolving): void { + $ecsConfig->beforeResolving(FixerFileProcessor::class, static function ($object, $misc, ECSConfig $ecsConfig) : void { + $removeExcludedCheckersCompilerPass = new RemoveExcludedCheckersCompilerPass(); + $removeExcludedCheckersCompilerPass->process($ecsConfig); + }); + $hasRunAfterResolving = \false; + $ecsConfig->afterResolving(static function ($object, ECSConfig $ecsConfig) use(&$hasRunAfterResolving) : void { // run just once if ($hasRunAfterResolving) { return; } - $removeMutualCheckersCompilerPass = new RemoveMutualCheckersCompilerPass(); $removeMutualCheckersCompilerPass->process($ecsConfig); - $conflictingCheckersCompilerPass = new ConflictingCheckersCompilerPass(); $conflictingCheckersCompilerPass->process($ecsConfig); - - $hasRunAfterResolving = true; + $hasRunAfterResolving = \true; }); - return $ecsConfig; } - /** * These are require for PHP_CodeSniffer to run */ - private function loadPHPCodeSnifferConstants(): void + private function loadPHPCodeSnifferConstants() : void { - if (! defined('PHP_CODESNIFFER_VERBOSITY')) { + if (!\defined('PHP_CODESNIFFER_VERBOSITY')) { // initalize token with INT type, otherwise php-cs-fixer and php-parser breaks - if (! defined('T_MATCH')) { - define('T_MATCH', 5000); + if (!\defined('T_MATCH')) { + \define('T_MATCH', 5000); } - - if (! defined('T_READONLY')) { - define('T_READONLY', 5010); + if (!\defined('T_READONLY')) { + \define('T_READONLY', 5010); } - - if (! defined('T_ENUM')) { - define('T_ENUM', 5015); + if (!\defined('T_ENUM')) { + \define('T_ENUM', 5015); } - // for PHP_CodeSniffer - define('PHP_CODESNIFFER_CBF', false); - define('PHP_CODESNIFFER_VERBOSITY', 0); - + \define('PHP_CODESNIFFER_CBF', \false); + \define('PHP_CODESNIFFER_VERBOSITY', 0); new Tokens(); } } - /** * @template TType of object * @param class-string $type * @return TType[] */ - private function getTaggedServicesArray(Container $container, string $type): array + private function getTaggedServicesArray(Container $container, string $type) : array { /** @var RewindableGenerator|TType[] $rewindableGenerator */ $rewindableGenerator = $container->tagged($type); - // turn generator to array - if (! is_array($rewindableGenerator)) { - return iterator_to_array($rewindableGenerator->getIterator()); + if (!\is_array($rewindableGenerator)) { + return \iterator_to_array($rewindableGenerator->getIterator()); } - // return array return $rewindableGenerator; } diff --git a/src/DependencyInjection/SimpleParameterProvider.php b/src/DependencyInjection/SimpleParameterProvider.php index f18724e8a1c..cbf22f26992 100644 --- a/src/DependencyInjection/SimpleParameterProvider.php +++ b/src/DependencyInjection/SimpleParameterProvider.php @@ -1,69 +1,80 @@ */ - private static array $parameters = []; - - public static function addParameter(string $key, mixed $value): void + private static $parameters = []; + /** + * @param mixed $value + */ + public static function addParameter(string $key, $value) : void { - if (is_array($value)) { - $mergedParameters = array_merge(self::$parameters[$key] ?? [], $value); + if (\is_array($value)) { + $mergedParameters = \array_merge(self::$parameters[$key] ?? [], $value); self::$parameters[$key] = $mergedParameters; } else { self::$parameters[$key][] = $value; } } - - public static function setParameter(string $key, mixed $value): void + /** + * @param mixed $value + */ + public static function setParameter(string $key, $value) : void { self::$parameters[$key] = $value; } - /** * @return mixed[] */ - public static function getArrayParameter(string $key): array + public static function getArrayParameter(string $key) : array { $parameter = self::$parameters[$key] ?? []; Assert::isArray($parameter); - - if (array_is_list($parameter)) { + $arrayIsList = function (array $array) : bool { + if (\function_exists('array_is_list')) { + return \array_is_list($array); + } + if ($array === []) { + return \true; + } + $current_key = 0; + foreach ($array as $key => $noop) { + if ($key !== $current_key) { + return \false; + } + ++$current_key; + } + return \true; + }; + if ($arrayIsList($parameter)) { // remove duplicates - return array_values(array_unique($parameter)); + return \array_values(\array_unique($parameter)); } - return $parameter; } - - public static function getStringParameter(string $key): string + public static function getStringParameter(string $key) : string { return self::$parameters[$key]; } - - public static function getIntParameter(string $key): int + public static function getIntParameter(string $key) : int { return self::$parameters[$key]; } - - public static function getBoolParameter(string $key): bool + public static function getBoolParameter(string $key) : bool { return self::$parameters[$key]; } - /** * For cache invalidation */ - public static function hash(): string + public static function hash() : string { - return sha1(serialize(self::$parameters)); + return \sha1(\serialize(self::$parameters)); } } diff --git a/src/Error/FileDiffFactory.php b/src/Error/FileDiffFactory.php index 722550d332b..26f56363040 100644 --- a/src/Error/FileDiffFactory.php +++ b/src/Error/FileDiffFactory.php @@ -1,7 +1,6 @@ colorConsoleDiffFormatter = $colorConsoleDiffFormatter; } - /** * @param array|string> $appliedCheckers */ - public function createFromDiffAndAppliedCheckers( - string $filePath, - string $diff, - array $appliedCheckers - ): FileDiff { + public function createFromDiffAndAppliedCheckers(string $filePath, string $diff, array $appliedCheckers) : FileDiff + { $consoleFormattedDiff = $this->colorConsoleDiffFormatter->format($diff); - $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd($filePath); - return new FileDiff($relativeFilePath, $diff, $consoleFormattedDiff, $appliedCheckers); } } diff --git a/src/Exception/Configuration/ConflictingCheckersLoadedException.php b/src/Exception/Configuration/ConflictingCheckersLoadedException.php index dc5e26b19a8..009237aabaa 100644 --- a/src/Exception/Configuration/ConflictingCheckersLoadedException.php +++ b/src/Exception/Configuration/ConflictingCheckersLoadedException.php @@ -1,11 +1,9 @@ changedFilesDetector = $changedFilesDetector; } - /** * @param string[] $filePaths * @return string[] */ - public function filterOnlyChangedFiles(array $filePaths): array + public function filterOnlyChangedFiles(array $filePaths) : array { - return array_filter( - $filePaths, - fn (string $filePath): bool => $this->changedFilesDetector->hasFileChanged($filePath) - ); + return \array_filter($filePaths, function (string $filePath) : bool { + return $this->changedFilesDetector->hasFileChanged($filePath); + }); } } diff --git a/src/FileSystem/PathNormalizer.php b/src/FileSystem/PathNormalizer.php index b949835d6be..80d2ee34a17 100644 --- a/src/FileSystem/PathNormalizer.php +++ b/src/FileSystem/PathNormalizer.php @@ -1,11 +1,9 @@ normalizePathParts($pathParts, $scheme); - - $pathStart = ($scheme !== self::SCHEME_UNDEFINED ? $scheme . '://' : ''); - return $pathStart . $pathRoot . implode($directorySeparator, $normalizedPathParts); + $pathStart = $scheme !== self::SCHEME_UNDEFINED ? $scheme . '://' : ''; + return $pathStart . $pathRoot . \implode($directorySeparator, $normalizedPathParts); } - /** * @param string[] $pathParts * @return string[] */ - private function normalizePathParts(array $pathParts, string $scheme): array + private function normalizePathParts(array $pathParts, string $scheme) : array { $normalizedPathParts = []; - foreach ($pathParts as $pathPart) { if ($pathPart === '.') { continue; } - if ($pathPart !== '..') { $normalizedPathParts[] = $pathPart; continue; } - /** @var string $removedPart */ - $removedPart = array_pop($normalizedPathParts); + $removedPart = \array_pop($normalizedPathParts); if ($scheme !== 'phar') { continue; } - - if (! \str_ends_with($removedPart, '.phar')) { + if (\substr_compare($removedPart, '.phar', -\strlen('.phar')) !== 0) { continue; } - $scheme = self::SCHEME_UNDEFINED; } - return $normalizedPathParts; } } diff --git a/src/FileSystem/StaticRelativeFilePathHelper.php b/src/FileSystem/StaticRelativeFilePathHelper.php index 5a0c027d8ce..ef563154a2c 100644 --- a/src/FileSystem/StaticRelativeFilePathHelper.php +++ b/src/FileSystem/StaticRelativeFilePathHelper.php @@ -1,18 +1,15 @@ makePathRelative((string) realpath($filePath), getcwd()); - - return rtrim($relativeFilePathFromCwd, '/'); + $relativeFilePathFromCwd = $filesystem->makePathRelative((string) \realpath($filePath), \getcwd()); + return \rtrim($relativeFilePathFromCwd, '/'); } } diff --git a/src/Finder/SourceFinder.php b/src/Finder/SourceFinder.php index 6f23d3f84f2..123869b8a7d 100644 --- a/src/Finder/SourceFinder.php +++ b/src/Finder/SourceFinder.php @@ -1,14 +1,12 @@ fileExtensions = SimpleParameterProvider::getArrayParameter(Option::FILE_EXTENSIONS); } - /** * @param string[] $source * @return string[] */ - public function find(array $source): array + public function find(array $source) : array { $filePaths = []; foreach ($source as $singleSource) { - if (is_file($singleSource)) { + if (\is_file($singleSource)) { $filePaths[] = $singleSource; } else { $filesInDirectory = $this->processDirectory($singleSource); - $filePaths = array_merge($filePaths, $filesInDirectory); + $filePaths = \array_merge($filePaths, $filesInDirectory); } } - - ksort($filePaths); - + \ksort($filePaths); return $filePaths; } - /** * @return string[] */ - private function processDirectory(string $directory): array + private function processDirectory(string $directory) : array { $normalizedFileExtensions = $this->normalizeFileExtensions($this->fileExtensions); - - $finder = Finder::create() - ->files() - ->name($normalizedFileExtensions) - ->in($directory) - ->exclude('vendor') - // skip empty files - ->size('> 0') - ->sortByName(); - - $filePaths = array_keys(iterator_to_array($finder)); + $finder = Finder::create()->files()->name($normalizedFileExtensions)->in($directory)->exclude('vendor')->size('> 0')->sortByName(); + $filePaths = \array_keys(\iterator_to_array($finder)); Assert::allString($filePaths); - return $filePaths; } - /** * @param string[] $fileExtensions * @return string[] */ - private function normalizeFileExtensions(array $fileExtensions): array + private function normalizeFileExtensions(array $fileExtensions) : array { $normalizedFileExtensions = []; - foreach ($fileExtensions as $fileExtension) { $normalizedFileExtensions[] = '*.' . $fileExtension; } - return $normalizedFileExtensions; } } diff --git a/src/MemoryLimitter.php b/src/MemoryLimitter.php index 0a1cfa56646..b15c4127beb 100644 --- a/src/MemoryLimitter.php +++ b/src/MemoryLimitter.php @@ -1,13 +1,11 @@ getMemoryLimit(); if ($memoryLimit === null) { return; } - $this->validateMemoryLimitFormat($memoryLimit); - - $memorySetResult = ini_set('memory_limit', $memoryLimit); - - if ($memorySetResult === false) { - $errorMessage = sprintf('Memory limit "%s" cannot be set.', $memoryLimit); + $memorySetResult = \ini_set('memory_limit', $memoryLimit); + if ($memorySetResult === \false) { + $errorMessage = \sprintf('Memory limit "%s" cannot be set.', $memoryLimit); throw new InitializationException($errorMessage); } } - - private function validateMemoryLimitFormat(string $memoryLimit): void + private function validateMemoryLimitFormat(string $memoryLimit) : void { $memoryLimitFormatMatch = Strings::match($memoryLimit, self::VALID_MEMORY_LIMIT_REGEX); if ($memoryLimitFormatMatch !== null) { return; } - - $errorMessage = sprintf('Invalid memory limit format "%s".', $memoryLimit); + $errorMessage = \sprintf('Invalid memory limit format "%s".', $memoryLimit); throw new InitializationException($errorMessage); } } diff --git a/src/Reporter/ProcessedFileReporter.php b/src/Reporter/ProcessedFileReporter.php index fac5c7767f7..7166dd9f394 100644 --- a/src/Reporter/ProcessedFileReporter.php +++ b/src/Reporter/ProcessedFileReporter.php @@ -1,7 +1,6 @@ outputFormatterCollector = $outputFormatterCollector; } - /** * @param array{system_errors?: SystemError[]|string[], file_diffs?: FileDiff[], coding_standard_errors?: CodingStandardError[], system_errors_count?: int} $errorsAndDiffs * @return ExitCode::* */ - public function report(array $errorsAndDiffs, Configuration $configuration): int + public function report(array $errorsAndDiffs, Configuration $configuration) : int { $outputFormat = $configuration->getOutputFormat(); $outputFormatter = $this->outputFormatterCollector->getByName($outputFormat); - /** @var SystemError[]|string[] $systemErrors */ $systemErrors = $errorsAndDiffs[Bridge::SYSTEM_ERRORS] ?? []; - /** @var FileDiff[] $fileDiffs */ $fileDiffs = $errorsAndDiffs[Bridge::FILE_DIFFS] ?? []; - /** @var CodingStandardError[] $codingStandardErrors */ $codingStandardErrors = $errorsAndDiffs[Bridge::CODING_STANDARD_ERRORS] ?? []; - $errorAndDiffResult = new ErrorAndDiffResult($codingStandardErrors, $fileDiffs, $systemErrors); return $outputFormatter->report($errorAndDiffResult, $configuration); } diff --git a/src/Testing/Contract/ConfigAwareInterface.php b/src/Testing/Contract/ConfigAwareInterface.php index a86c6cb2ff9..d2a8a639a95 100644 --- a/src/Testing/Contract/ConfigAwareInterface.php +++ b/src/Testing/Contract/ConfigAwareInterface.php @@ -1,10 +1,9 @@ autoloadCodeSniffer(); - $configs = $this->getValidatedConfigs(); $this->createContainerWithConfigs($configs); - $this->fixerFileProcessor = $this->make(FixerFileProcessor::class); $this->sniffFileProcessor = $this->make(SniffFileProcessor::class); } - - protected function doTestFile(string $filePath): void + protected function doTestFile(string $filePath) : void { $this->ensureSomeCheckersAreRegistered(); - $fileContents = FileSystem::read($filePath); - // before and after case - we want to see a change - if (\str_contains($fileContents, '-----')) { + if (\strpos($fileContents, '-----') !== \false) { [$inputContents, $expectedContents] = Strings::split($fileContents, self::SPLIT_LINE_REGEX); } else { // no change, part before and after are the same $inputContents = $fileContents; $expectedContents = $fileContents; } - - $inputFilePath = sys_get_temp_dir() . '/ecs_tests/' . md5((string) $inputContents) . '.php'; + $inputFilePath = \sys_get_temp_dir() . '/ecs_tests/' . \md5((string) $inputContents) . '.php'; FileSystem::write($inputFilePath, $inputContents); - // 1. process php-cs-fixer if ($this->fixerFileProcessor->getCheckers() !== []) { $processedFileContent = $this->fixerFileProcessor->processFileToString($inputFilePath); @@ -78,44 +67,35 @@ protected function doTestFile(string $filePath): void $this->assertEquals($expectedContents, $processedFileContent); } } - - protected static function yieldFiles(string $directory, string $suffix = '*.php.inc'): Iterator + protected static function yieldFiles(string $directory, string $suffix = '*.php.inc') : Iterator { - return FixtureFinder::yieldDataProviderFiles($directory, $suffix); + return \Symplify\EasyCodingStandard\Testing\PHPUnit\FixtureFinder::yieldDataProviderFiles($directory, $suffix); } - - private function autoloadCodeSniffer(): void + private function autoloadCodeSniffer() : void { foreach (self::POSSIBLE_CODE_SNIFFER_AUTOLOAD_PATHS as $possibleCodeSnifferAutoloadPath) { - if (! file_exists($possibleCodeSnifferAutoloadPath)) { + if (!\file_exists($possibleCodeSnifferAutoloadPath)) { continue; } - require_once $possibleCodeSnifferAutoloadPath; return; } } - - private function ensureSomeCheckersAreRegistered(): void + private function ensureSomeCheckersAreRegistered() : void { - $totalCheckersLoaded = count($this->sniffFileProcessor->getCheckers()) - + count($this->fixerFileProcessor->getCheckers()); - + $totalCheckersLoaded = \count($this->sniffFileProcessor->getCheckers()) + \count($this->fixerFileProcessor->getCheckers()); if ($totalCheckersLoaded > 0) { return; } - throw new ShouldNotHappenException('No fixers nor sniffers were found. Registers them in your config.'); } - /** * @return string[] */ - private function getValidatedConfigs(): array + private function getValidatedConfigs() : array { $config = $this->provideConfig(); Assert::fileExists($config); - return [$config]; } } diff --git a/src/Testing/PHPUnit/AbstractTestCase.php b/src/Testing/PHPUnit/AbstractTestCase.php index a52f9a99bba..1147105f781 100644 --- a/src/Testing/PHPUnit/AbstractTestCase.php +++ b/src/Testing/PHPUnit/AbstractTestCase.php @@ -1,46 +1,41 @@ container = $newContainerFactory->create(); } - /** * @param string[] $configs */ - protected function createContainerWithConfigs(array $configs): void + protected function createContainerWithConfigs(array $configs) : void { Assert::allString($configs); Assert::allFile($configs); - $newContainerFactory = new NewContainerFactory(); $this->container = $newContainerFactory->create($configs); } - /** * @template TObject as object * * @param class-string $class * @return TObject */ - protected function make(string $class): object + protected function make(string $class) : object { Assert::notNull($this->container); - return $this->container->make($class); } } diff --git a/src/Testing/PHPUnit/FixtureFinder.php b/src/Testing/PHPUnit/FixtureFinder.php index 2887760b66c..d9412342a13 100644 --- a/src/Testing/PHPUnit/FixtureFinder.php +++ b/src/Testing/PHPUnit/FixtureFinder.php @@ -1,12 +1,10 @@ > */ - public static function yieldDataProviderFiles(string $directory, string $suffix = '*.php.inc'): Iterator + public static function yieldDataProviderFiles(string $directory, string $suffix = '*.php.inc') : Iterator { $finder = Finder::create()->in($directory)->files()->name($suffix); - $fileInfos = iterator_to_array($finder); - - $filePaths = array_keys($fileInfos); + $fileInfos = \iterator_to_array($finder); + $filePaths = \array_keys($fileInfos); foreach ($filePaths as $filePath) { - yield [$filePath]; + (yield [$filePath]); } } } diff --git a/src/Utils/ParametersMerger.php b/src/Utils/ParametersMerger.php index f4696e46b59..54148c3916c 100644 --- a/src/Utils/ParametersMerger.php +++ b/src/Utils/ParametersMerger.php @@ -1,7 +1,6 @@ mergeLeftToRightWithCallable( - $left, - $right, - fn ($leftValue, $rightValue) => $this->merge($leftValue, $rightValue) - ); + if (\is_array($left) && \is_array($right)) { + return $this->mergeLeftToRightWithCallable($left, $right, function ($leftValue, $rightValue) { + return $this->merge($leftValue, $rightValue); + }); } - if ($left !== null) { return $left; } - - if (! is_array($right)) { + if (!\is_array($right)) { return $left; } - return $right; } - /** * The same as above, just with the case if both values being non-array, it will combined them to array: * * $this->mergeWithCombine(1, 2); // [1, 2] + * @param mixed $left + * @param mixed $right + * @return mixed */ - public function mergeWithCombine(mixed $left, mixed $right): mixed + public function mergeWithCombine($left, $right) { - if (is_array($left) && is_array($right)) { - return $this->mergeLeftToRightWithCallable( - $left, - $right, - fn ($leftValue, $rightValue) => $this->mergeWithCombine($leftValue, $rightValue) - ); + if (\is_array($left) && \is_array($right)) { + return $this->mergeLeftToRightWithCallable($left, $right, function ($leftValue, $rightValue) { + return $this->mergeWithCombine($leftValue, $rightValue); + }); } - - if ($left === null && is_array($right)) { + if ($left === null && \is_array($right)) { return $right; } - - if (! empty($right) && (array) $left !== (array) $right) { + if (!empty($right) && (array) $left !== (array) $right) { return $this->mergeWithCombine((array) $right, (array) $left); } - return $left; } - /** * @param array $left * @param array $right * @param callable(mixed $first, mixed $seccond): mixed[] $mergeCallback * @return mixed[] */ - private function mergeLeftToRightWithCallable(array $left, array $right, callable $mergeCallback): array + private function mergeLeftToRightWithCallable(array $left, array $right, callable $mergeCallback) : array { foreach ($left as $key => $val) { - if (is_int($key)) { + if (\is_int($key)) { // prevent duplicated values in unindexed arrays - if (! in_array($val, $right, true)) { + if (!\in_array($val, $right, \true)) { $right[] = $val; } } else { if (isset($right[$key])) { $val = $mergeCallback($val, $right[$key]); } - $right[$key] = $val; } } - return $right; } } diff --git a/src/Utils/PrivatesAccessorHelper.php b/src/Utils/PrivatesAccessorHelper.php index 604d8e61ed0..197f3a2df49 100644 --- a/src/Utils/PrivatesAccessorHelper.php +++ b/src/Utils/PrivatesAccessorHelper.php @@ -1,28 +1,29 @@ setAccessible(true); - + $reflectionProperty->setAccessible(\true); return $reflectionProperty->getValue($object); } - - public static function setPropertyValue(object $object, string $propertyName, mixed $value): void + /** + * @param mixed $value + */ + public static function setPropertyValue(object $object, string $propertyName, $value) : void { $reflectionProperty = new ReflectionProperty($object, $propertyName); // this is needed for PHP 7.2 downgrade code - $reflectionProperty->setAccessible(true); - + $reflectionProperty->setAccessible(\true); $reflectionProperty->setValue($object, $value); } } diff --git a/src/ValueObject/Configuration.php b/src/ValueObject/Configuration.php index 3d458cf8b61..32e408ecee8 100644 --- a/src/ValueObject/Configuration.php +++ b/src/ValueObject/Configuration.php @@ -1,85 +1,127 @@ isFixer = $isFixer; + $this->shouldClearCache = $shouldClearCache; + $this->showProgressBar = $showProgressBar; + $this->showErrorTable = $showErrorTable; + $this->sources = $sources; + $this->outputFormat = $outputFormat; + $this->isParallel = $isParallel; + $this->config = $config; + $this->parallelPort = $parallelPort; + $this->parallelIdentifier = $parallelIdentifier; + $this->memoryLimit = $memoryLimit; } - - public function isFixer(): bool + public function isFixer() : bool { return $this->isFixer; } - - public function shouldClearCache(): bool + public function shouldClearCache() : bool { return $this->shouldClearCache; } - - public function shouldShowProgressBar(): bool + public function shouldShowProgressBar() : bool { return $this->showProgressBar; } - - public function shouldShowErrorTable(): bool + public function shouldShowErrorTable() : bool { return $this->showErrorTable; } - /** * @return string[] */ - public function getSources(): array + public function getSources() : array { return $this->sources; } - - public function getOutputFormat(): string + public function getOutputFormat() : string { return $this->outputFormat; } - - public function isParallel(): bool + public function isParallel() : bool { return $this->isParallel; } - - public function getConfig(): ?string + public function getConfig() : ?string { return $this->config; } - - public function getParallelPort(): ?string + public function getParallelPort() : ?string { return $this->parallelPort; } - - public function getParallelIdentifier(): ?string + public function getParallelIdentifier() : ?string { return $this->parallelIdentifier; } - - public function getMemoryLimit(): ?string + public function getMemoryLimit() : ?string { return $this->memoryLimit; } diff --git a/src/ValueObject/Error/ErrorAndDiffResult.php b/src/ValueObject/Error/ErrorAndDiffResult.php index 64d994af3d2..e4b3513842a 100644 --- a/src/ValueObject/Error/ErrorAndDiffResult.php +++ b/src/ValueObject/Error/ErrorAndDiffResult.php @@ -1,105 +1,88 @@ + * @readonly + */ + private $systemErrors; /** * @var CodingStandardError[] */ - private array $codingStandardErrors = []; - + private $codingStandardErrors = []; /** * @var FileDiff[] */ - private array $fileDiffs = []; - + private $fileDiffs = []; /** * @param CodingStandardError[] $codingStandardErrors * @param FileDiff[] $fileDiffs * @param array $systemErrors */ - public function __construct( - array $codingStandardErrors, - array $fileDiffs, - private readonly array $systemErrors - ) { + public function __construct(array $codingStandardErrors, array $fileDiffs, array $systemErrors) + { + $this->systemErrors = $systemErrors; $this->codingStandardErrors = $this->sortByFileAndLine($codingStandardErrors); $this->fileDiffs = $this->sortByFilePath($fileDiffs); } - - public function getErrorCount(): int + public function getErrorCount() : int { - return $this->getCodingStandardErrorCount() + count($this->systemErrors); + return $this->getCodingStandardErrorCount() + \count($this->systemErrors); } - - public function getCodingStandardErrorCount(): int + public function getCodingStandardErrorCount() : int { - return count($this->codingStandardErrors); + return \count($this->codingStandardErrors); } - - public function getFileDiffsCount(): int + public function getFileDiffsCount() : int { - return count($this->fileDiffs); + return \count($this->fileDiffs); } - /** * @return CodingStandardError[] */ - public function getErrors(): array + public function getErrors() : array { return $this->codingStandardErrors; } - /** * @return array */ - public function getSystemErrors(): array + public function getSystemErrors() : array { return $this->systemErrors; } - /** * @return FileDiff[] */ - public function getFileDiffs(): array + public function getFileDiffs() : array { return $this->fileDiffs; } - /** * @param CodingStandardError[] $errorMessages * @return CodingStandardError[] */ - private function sortByFileAndLine(array $errorMessages): array + private function sortByFileAndLine(array $errorMessages) : array { - usort( - $errorMessages, - static fn (CodingStandardError $firstCodingStandardError, CodingStandardError $secondCodingStandardError): int => [ - $firstCodingStandardError->getRelativeFilePath(), - $firstCodingStandardError->getLine(), - ] - <=> [$secondCodingStandardError->getRelativeFilePath(), $secondCodingStandardError->getLine()] - ); - + \usort($errorMessages, static function (CodingStandardError $firstCodingStandardError, CodingStandardError $secondCodingStandardError) : int { + return [$firstCodingStandardError->getRelativeFilePath(), $firstCodingStandardError->getLine()] <=> [$secondCodingStandardError->getRelativeFilePath(), $secondCodingStandardError->getLine()]; + }); return $errorMessages; } - /** * @param FileDiff[] $fileDiffs * @return FileDiff[] */ - private function sortByFilePath(array $fileDiffs): array + private function sortByFilePath(array $fileDiffs) : array { - uasort( - $fileDiffs, - static fn (FileDiff $firstFileDiff, FileDiff $secondFileDiff): int => $firstFileDiff->getRelativeFilePath() <=> $secondFileDiff->getRelativeFilePath() - ); - + \uasort($fileDiffs, static function (\Symplify\EasyCodingStandard\ValueObject\Error\FileDiff $firstFileDiff, \Symplify\EasyCodingStandard\ValueObject\Error\FileDiff $secondFileDiff) : int { + return $firstFileDiff->getRelativeFilePath() <=> $secondFileDiff->getRelativeFilePath(); + }); return $fileDiffs; } } diff --git a/src/ValueObject/Error/FileDiff.php b/src/ValueObject/Error/FileDiff.php index c876bcea140..6059ca5e90d 100644 --- a/src/ValueObject/Error/FileDiff.php +++ b/src/ValueObject/Error/FileDiff.php @@ -1,76 +1,77 @@ | string)> + */ + private $appliedCheckers; /** * @param array|string> $appliedCheckers */ - public function __construct( - private readonly string $relativeFilePath, - private readonly string $diff, - private readonly string $consoleFormattedDiff, - private array $appliedCheckers - ) { + public function __construct(string $relativeFilePath, string $diff, string $consoleFormattedDiff, array $appliedCheckers) + { + $this->relativeFilePath = $relativeFilePath; + $this->diff = $diff; + $this->consoleFormattedDiff = $consoleFormattedDiff; + $this->appliedCheckers = $appliedCheckers; } - - public function getDiff(): string + public function getDiff() : string { return $this->diff; } - - public function getDiffConsoleFormatted(): string + public function getDiffConsoleFormatted() : string { return $this->consoleFormattedDiff; } - /** * @return array|string> */ - public function getAppliedCheckers(): array + public function getAppliedCheckers() : array { - $this->appliedCheckers = array_unique($this->appliedCheckers); - sort($this->appliedCheckers); - + $this->appliedCheckers = \array_unique($this->appliedCheckers); + \sort($this->appliedCheckers); return $this->appliedCheckers; } - - public function getRelativeFilePath(): string + public function getRelativeFilePath() : string { return $this->relativeFilePath; } - /** * @return array{relative_file_path: string, diff: string, diff_console_formatted: string, applied_checkers: string[]} */ - public function jsonSerialize(): array + public function jsonSerialize() : array { - return [ - Name::RELATIVE_FILE_PATH => $this->relativeFilePath, - Name::DIFF => $this->diff, - Name::DIFF_CONSOLE_FORMATTED => $this->consoleFormattedDiff, - Name::APPLIED_CHECKERS => $this->getAppliedCheckers(), - ]; + return [Name::RELATIVE_FILE_PATH => $this->relativeFilePath, Name::DIFF => $this->diff, Name::DIFF_CONSOLE_FORMATTED => $this->consoleFormattedDiff, Name::APPLIED_CHECKERS => $this->getAppliedCheckers()]; } - /** * @param array{relative_file_path: string, diff: string, diff_console_formatted: string, applied_checkers: string[]} $json + * @return $this */ - public static function decode(array $json): self + public static function decode(array $json) : \ECSPrefix202307\Symplify\EasyParallel\Contract\SerializableInterface { - return new self( - $json[Name::RELATIVE_FILE_PATH], - $json[Name::DIFF], - $json[Name::DIFF_CONSOLE_FORMATTED], - $json[Name::APPLIED_CHECKERS], - ); + return new self($json[Name::RELATIVE_FILE_PATH], $json[Name::DIFF], $json[Name::DIFF_CONSOLE_FORMATTED], $json[Name::APPLIED_CHECKERS]); } } diff --git a/src/ValueObject/Error/SystemError.php b/src/ValueObject/Error/SystemError.php index 0d5a464c58d..861f8700691 100644 --- a/src/ValueObject/Error/SystemError.php +++ b/src/ValueObject/Error/SystemError.php @@ -1,47 +1,53 @@ line = $line; + $this->message = $message; + $this->relativeFilePath = $relativeFilePath; } - - public function getMessage(): string + public function getMessage() : string { return $this->message; } - - public function getFileWithLine(): string + public function getFileWithLine() : string { return $this->relativeFilePath . ':' . $this->line; } - /** * @return array{line: int, message: string, relative_file_path: string} */ - public function jsonSerialize(): array + public function jsonSerialize() : array { - return [ - Name::LINE => $this->line, - Name::MESSAGE => $this->message, - Name::RELATIVE_FILE_PATH => $this->relativeFilePath, - ]; + return [Name::LINE => $this->line, Name::MESSAGE => $this->message, Name::RELATIVE_FILE_PATH => $this->relativeFilePath]; } - /** * @param array{line: int, message: string, relative_file_path: string} $json + * @return $this */ - public static function decode(array $json): self + public static function decode(array $json) : \ECSPrefix202307\Symplify\EasyParallel\Contract\SerializableInterface { return new self($json[Name::LINE], $json[Name::MESSAGE], $json[Name::RELATIVE_FILE_PATH]); } diff --git a/src/ValueObject/Option.php b/src/ValueObject/Option.php index 6ea4daab6c8..34a9b59b208 100644 --- a/src/ValueObject/Option.php +++ b/src/ValueObject/Option.php @@ -1,7 +1,6 @@ colorConsoleDiffFormatter = new ColorConsoleDiffFormatter(); - } - - #[DataProvider('provideData')] - public function test(string $content, string $expectedFormatedFileContent): void - { - $formattedContent = $this->colorConsoleDiffFormatter->format($content); - - $this->assertStringEqualsFile($expectedFormatedFileContent, $formattedContent); - } - - public static function provideData(): Iterator - { - yield ['...', __DIR__ . '/Fixture/expected_dots.txt']; - - yield ["-old\n+new", __DIR__ . '/Fixture/expected_old_new.txt']; - - yield [ - FileSystem::read(__DIR__ . '/Fixture/with_full_diff_by_phpunit.diff'), - __DIR__ . '/Fixture/expected_with_full_diff_by_phpunit.diff', - ]; - } -} diff --git a/tests/Console/Formatter/Fixture/expected_dots.txt b/tests/Console/Formatter/Fixture/expected_dots.txt deleted file mode 100644 index b2b41e62e78..00000000000 --- a/tests/Console/Formatter/Fixture/expected_dots.txt +++ /dev/null @@ -1,3 +0,0 @@ - ---------- begin diff ---------- -... - ----------- end diff ----------- diff --git a/tests/Console/Formatter/Fixture/expected_old_new.txt b/tests/Console/Formatter/Fixture/expected_old_new.txt deleted file mode 100644 index 20fc7471b0b..00000000000 --- a/tests/Console/Formatter/Fixture/expected_old_new.txt +++ /dev/null @@ -1,4 +0,0 @@ - ---------- begin diff ---------- --old -+new - ----------- end diff ----------- diff --git a/tests/Console/Formatter/Fixture/expected_with_full_diff_by_phpunit.diff b/tests/Console/Formatter/Fixture/expected_with_full_diff_by_phpunit.diff deleted file mode 100644 index b2b41e62e78..00000000000 --- a/tests/Console/Formatter/Fixture/expected_with_full_diff_by_phpunit.diff +++ /dev/null @@ -1,3 +0,0 @@ - ---------- begin diff ---------- -... - ----------- end diff ----------- diff --git a/tests/Console/Formatter/Fixture/with_full_diff_by_phpunit.diff b/tests/Console/Formatter/Fixture/with_full_diff_by_phpunit.diff deleted file mode 100644 index 58d1e099586..00000000000 --- a/tests/Console/Formatter/Fixture/with_full_diff_by_phpunit.diff +++ /dev/null @@ -1,3 +0,0 @@ ---- Original -+++ New -... diff --git a/tests/Console/Output/Fixture/expected_json_output.json b/tests/Console/Output/Fixture/expected_json_output.json deleted file mode 100644 index aa73c5623da..00000000000 --- a/tests/Console/Output/Fixture/expected_json_output.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "totals": { - "errors": 0, - "diffs": 2 - }, - "files": { - "%s/Console/Output/Source/RandomFile.php": { - "diffs": [ - { - "diff": "some diff", - "applied_checkers": [ - "Symplify\\CodingStandard\\Fixer\\LineLength\\LineLengthFixer" - ] - }, - { - "diff": "some other diff", - "applied_checkers": [ - "Symplify\\CodingStandard\\Fixer\\LineLength\\LineLengthFixer" - ] - } - ] - } - } -} diff --git a/tests/Console/Output/Fixture/expected_plain.json b/tests/Console/Output/Fixture/expected_plain.json deleted file mode 100644 index bd2fcd9b4f1..00000000000 --- a/tests/Console/Output/Fixture/expected_plain.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "totals": { - "errors": 0, - "diffs": 0 - }, - "files": [] -} diff --git a/tests/Console/Output/JsonOutputFormatterTest.php b/tests/Console/Output/JsonOutputFormatterTest.php deleted file mode 100644 index 754789bc52d..00000000000 --- a/tests/Console/Output/JsonOutputFormatterTest.php +++ /dev/null @@ -1,56 +0,0 @@ -jsonOutputFormatter = $this->make(JsonOutputFormatter::class); - $this->colorConsoleDiffFormatter = $this->make(ColorConsoleDiffFormatter::class); - } - - public function test(): void - { - $relativeFilePath = StaticRelativeFilePathHelper::resolveFromCwd(__DIR__ . '/Source/RandomFile.php'); - - $fileDiffs = []; - - $diff = 'some diff'; - $fileDiffs[] = new FileDiff( - $relativeFilePath, - $diff, - $this->colorConsoleDiffFormatter->format($diff), - [LineLengthFixer::class] - ); - - $diff = 'some other diff'; - $fileDiffs[] = new FileDiff( - $relativeFilePath, - $diff, - $this->colorConsoleDiffFormatter->format($diff), - [LineLengthFixer::class] - ); - - $errorAndDiffResult = new ErrorAndDiffResult([], $fileDiffs, []); - - $jsonContent = $this->jsonOutputFormatter->createJsonContent($errorAndDiffResult); - $this->assertStringMatchesFormatFile(__DIR__ . '/Fixture/expected_json_output.json', $jsonContent . PHP_EOL); - } -} diff --git a/tests/Console/Output/Source/RandomFile.php b/tests/Console/Output/Source/RandomFile.php deleted file mode 100644 index d28237dae28..00000000000 --- a/tests/Console/Output/Source/RandomFile.php +++ /dev/null @@ -1,9 +0,0 @@ -import(__DIR__ . '/simple-config.php'); - $ecsConfig->rule(ClassDefinitionFixer::class); -}; diff --git a/tests/DependencyInjection/ConfigurationFileSource/simple-config.php b/tests/DependencyInjection/ConfigurationFileSource/simple-config.php deleted file mode 100644 index b9314b1b166..00000000000 --- a/tests/DependencyInjection/ConfigurationFileSource/simple-config.php +++ /dev/null @@ -1,10 +0,0 @@ -rule(ArrayIndentSniff::class); -}; diff --git a/tests/DependencyInjection/ConfigurationFileTest.php b/tests/DependencyInjection/ConfigurationFileTest.php deleted file mode 100644 index 7d4ccf3b6dd..00000000000 --- a/tests/DependencyInjection/ConfigurationFileTest.php +++ /dev/null @@ -1,34 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/ConfigurationFileSource/empty-config.php']); - - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - $this->assertCount(0, $fixerFileProcessor->getCheckers()); - - $sniffFileProcessor = $this->make(SniffFileProcessor::class); - $this->assertCount(0, $sniffFileProcessor->getCheckers()); - } - - public function testIncludeConfig(): void - { - $this->createContainerWithConfigs([__DIR__ . '/ConfigurationFileSource/include-another-config.php']); - - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - $this->assertCount(1, $fixerFileProcessor->getCheckers()); - - $sniffFileProcessor = $this->make(SniffFileProcessor::class); - $this->assertCount(1, $sniffFileProcessor->getCheckers()); - } -} diff --git a/tests/DependencyInjection/ConflictingCheckers/ConflictingCheckersTest.php b/tests/DependencyInjection/ConflictingCheckers/ConflictingCheckersTest.php deleted file mode 100644 index 053ba139891..00000000000 --- a/tests/DependencyInjection/ConflictingCheckers/ConflictingCheckersTest.php +++ /dev/null @@ -1,22 +0,0 @@ -expectException(ConflictingCheckersLoadedException::class); - - $this->createContainerWithConfigs([__DIR__ . '/config/config.php']); - - // invoke afterResolver() checks - $this->make(FixerFileProcessor::class); - } -} diff --git a/tests/DependencyInjection/ConflictingCheckers/config/config.php b/tests/DependencyInjection/ConflictingCheckers/config/config.php deleted file mode 100644 index 2ddc687fffe..00000000000 --- a/tests/DependencyInjection/ConflictingCheckers/config/config.php +++ /dev/null @@ -1,12 +0,0 @@ -rule(LowerCaseConstantSniff::class); - $ecsConfig->rule(UpperCaseConstantSniff::class); -}; diff --git a/tests/DependencyInjection/ExcludedCheckers/ExcludedCheckersTest.php b/tests/DependencyInjection/ExcludedCheckers/ExcludedCheckersTest.php deleted file mode 100644 index 2e3a1639499..00000000000 --- a/tests/DependencyInjection/ExcludedCheckers/ExcludedCheckersTest.php +++ /dev/null @@ -1,19 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/config.php']); - - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - $this->assertCount(0, $fixerFileProcessor->getCheckers()); - } -} diff --git a/tests/DependencyInjection/ExcludedCheckers/config/config.php b/tests/DependencyInjection/ExcludedCheckers/config/config.php deleted file mode 100644 index 3b1ad921909..00000000000 --- a/tests/DependencyInjection/ExcludedCheckers/config/config.php +++ /dev/null @@ -1,12 +0,0 @@ -skip([NoUnusedImportsFixer::class]); - - $ecsConfig->rule(NoUnusedImportsFixer::class); -}; diff --git a/tests/DependencyInjection/MutualExcludedCheckers/MutualExcludedCheckersTest.php b/tests/DependencyInjection/MutualExcludedCheckers/MutualExcludedCheckersTest.php deleted file mode 100644 index 4bc45c3d04f..00000000000 --- a/tests/DependencyInjection/MutualExcludedCheckers/MutualExcludedCheckersTest.php +++ /dev/null @@ -1,23 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/config/config.php']); - - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - $this->assertCount(2, $fixerFileProcessor->getCheckers()); - - $sniffFileProcessor = $this->make(SniffFileProcessor::class); - $this->assertCount(0, $sniffFileProcessor->getCheckers()); - } -} diff --git a/tests/DependencyInjection/MutualExcludedCheckers/config/config.php b/tests/DependencyInjection/MutualExcludedCheckers/config/config.php deleted file mode 100644 index a46c8a9e9d3..00000000000 --- a/tests/DependencyInjection/MutualExcludedCheckers/config/config.php +++ /dev/null @@ -1,18 +0,0 @@ -rule(IndentationTypeFixer::class); - $ecsConfig->rule(DisallowTabIndentSniff::class); - - // See https://github.com/symplify/symplify/issues/1702 - $ecsConfig->rule(IncludeFixer::class); - $ecsConfig->rule(LanguageConstructSpacingSniff::class); -}; diff --git a/tests/Error/ErrorCollector/ErrorCollectorSource/ConstantWithoutPublicDeclaration.php.inc b/tests/Error/ErrorCollector/ErrorCollectorSource/ConstantWithoutPublicDeclaration.php.inc deleted file mode 100644 index 7e08ef03220..00000000000 --- a/tests/Error/ErrorCollector/ErrorCollectorSource/ConstantWithoutPublicDeclaration.php.inc +++ /dev/null @@ -1,10 +0,0 @@ -assertEquals('', ''); - } -} diff --git a/tests/Error/ErrorCollector/FixerFileProcessorTest.php b/tests/Error/ErrorCollector/FixerFileProcessorTest.php deleted file mode 100644 index 4f3e771c3e6..00000000000 --- a/tests/Error/ErrorCollector/FixerFileProcessorTest.php +++ /dev/null @@ -1,33 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/FixerRunnerSource/phpunit-fixer-config.php']); - - $fixerFileProcessor = $this->make(FixerFileProcessor::class); - - $configuration = new Configuration(); - - $errorsAndFileDiffs = $fixerFileProcessor->processFile( - __DIR__ . '/ErrorCollectorSource/NotPsr2Class.php.inc', - $configuration - ); - - $this->assertArrayNotHasKey(Bridge::CODING_STANDARD_ERRORS, $errorsAndFileDiffs); - $this->assertArrayHasKey(Bridge::FILE_DIFFS, $errorsAndFileDiffs); - - $fileDiffs = $errorsAndFileDiffs[Bridge::FILE_DIFFS]; - $this->assertCount(1, $fileDiffs); - } -} diff --git a/tests/Error/ErrorCollector/FixerRunnerSource/easy-coding-standard.php b/tests/Error/ErrorCollector/FixerRunnerSource/easy-coding-standard.php deleted file mode 100644 index 5dcd006206e..00000000000 --- a/tests/Error/ErrorCollector/FixerRunnerSource/easy-coding-standard.php +++ /dev/null @@ -1,15 +0,0 @@ -ruleWithConfiguration(VisibilityRequiredFixer::class, [ - 'elements' => ['const', 'property', 'method'], - ]); - - $ecsConfig->rule(SingleBlankLineAtEofFixer::class); -}; diff --git a/tests/Error/ErrorCollector/FixerRunnerSource/phpunit-fixer-config.php b/tests/Error/ErrorCollector/FixerRunnerSource/phpunit-fixer-config.php deleted file mode 100644 index a14cefd25ee..00000000000 --- a/tests/Error/ErrorCollector/FixerRunnerSource/phpunit-fixer-config.php +++ /dev/null @@ -1,10 +0,0 @@ -rule(PhpUnitStrictFixer::class); -}; diff --git a/tests/Error/ErrorCollector/SniffFileProcessorTest.php b/tests/Error/ErrorCollector/SniffFileProcessorTest.php deleted file mode 100644 index a14fe4a562a..00000000000 --- a/tests/Error/ErrorCollector/SniffFileProcessorTest.php +++ /dev/null @@ -1,38 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/SniffRunnerSource/easy-coding-standard.php']); - - $sniffFileProcessor = $this->make(SniffFileProcessor::class); - - $changedFilesDetector = $this->make(ChangedFilesDetector::class); - $changedFilesDetector->clearCache(); - - $errorsAndFileDiffs = $sniffFileProcessor->processFile( - __DIR__ . '/ErrorCollectorSource/NotPsr2Class.php.inc', - new Configuration(), - ); - - /** @var FileDiff[] $fileDiffs */ - $fileDiffs = $errorsAndFileDiffs['file_diffs'] ?? []; - $this->assertCount(1, $fileDiffs); - - /** @var CodingStandardError[] $codingStandardErrors */ - $codingStandardErrors = $errorsAndFileDiffs['coding_standard_errors'] ?? []; - $this->assertCount(0, $codingStandardErrors); - } -} diff --git a/tests/Error/ErrorCollector/SniffRunnerSource/easy-coding-standard.php b/tests/Error/ErrorCollector/SniffRunnerSource/easy-coding-standard.php deleted file mode 100644 index b9314b1b166..00000000000 --- a/tests/Error/ErrorCollector/SniffRunnerSource/easy-coding-standard.php +++ /dev/null @@ -1,10 +0,0 @@ -rule(ArrayIndentSniff::class); -}; diff --git a/tests/FileSystem/PathNormalizerTest.php b/tests/FileSystem/PathNormalizerTest.php deleted file mode 100644 index a7e7a764b83..00000000000 --- a/tests/FileSystem/PathNormalizerTest.php +++ /dev/null @@ -1,37 +0,0 @@ -pathNormalizer = new PathNormalizer(); - } - - #[DataProvider('provideData')] - public function test(string $inputPath, string $expectedNormalizedPath): void - { - $normalizedPath = $this->pathNormalizer->normalizePath($inputPath); - $this->assertSame($expectedNormalizedPath, $normalizedPath); - } - - /** - * @return Iterator - */ - public static function provideData(): Iterator - { - // based on Linux - yield ['/any/path', '/any/path']; - yield ['\any\path', '/any/path']; - } -} diff --git a/tests/Finder/SourceFinderSource/Source/SomeClass.php b/tests/Finder/SourceFinderSource/Source/SomeClass.php deleted file mode 100644 index 7c9b7287b93..00000000000 --- a/tests/Finder/SourceFinderSource/Source/SomeClass.php +++ /dev/null @@ -1,9 +0,0 @@ -make(SourceFinder::class); - $foundFiles = $sourceFinder->find([__DIR__ . '/SourceFinderSource/Source']); - $this->assertCount(1, $foundFiles); - - $foundFiles = $sourceFinder->find([__DIR__ . '/SourceFinderSource/Source/SomeClass.php.inc']); - $this->assertCount(1, $foundFiles); - } -} diff --git a/tests/Indentation/IndentationTest.php b/tests/Indentation/IndentationTest.php deleted file mode 100644 index 7cd9fb45371..00000000000 --- a/tests/Indentation/IndentationTest.php +++ /dev/null @@ -1,48 +0,0 @@ -createContainerWithConfigs([__DIR__ . '/Source/config-with-spaces-indentation.php']); - - $indentationTypeFixer = $this->make(IndentationTypeFixer::class); - $this->assertInstanceOf(WhitespacesAwareFixerInterface::class, $indentationTypeFixer); - - /** @var WhitespacesFixerConfig $whitespacesFixerConfig */ - $whitespacesFixerConfig = PrivatesAccessorHelper::getPropertyValue( - $indentationTypeFixer, - 'whitespacesConfig' - ); - - $this->assertSame(' ', $whitespacesFixerConfig->getIndent()); - $this->assertSame("\n", $whitespacesFixerConfig->getLineEnding()); - } - - public function testTabs(): void - { - $this->createContainerWithConfigs([__DIR__ . '/Source/config-with-tabs-indentation.php']); - - $indentationTypeFixer = $this->make(IndentationTypeFixer::class); - $this->assertInstanceOf(WhitespacesAwareFixerInterface::class, $indentationTypeFixer); - - /** @var WhitespacesFixerConfig $whitespacesFixerConfig */ - $whitespacesFixerConfig = PrivatesAccessorHelper::getPropertyValue( - $indentationTypeFixer, - 'whitespacesConfig', - ); - - $this->assertSame(' ', $whitespacesFixerConfig->getIndent()); - $this->assertSame("\n", $whitespacesFixerConfig->getLineEnding()); - } -} diff --git a/tests/Indentation/Source/config-with-spaces-indentation.php b/tests/Indentation/Source/config-with-spaces-indentation.php deleted file mode 100644 index c225ded6bce..00000000000 --- a/tests/Indentation/Source/config-with-spaces-indentation.php +++ /dev/null @@ -1,12 +0,0 @@ -rule(IndentationTypeFixer::class); - $ecsConfig->indentation(Option::INDENTATION_SPACES); -}; diff --git a/tests/Indentation/Source/config-with-tabs-indentation.php b/tests/Indentation/Source/config-with-tabs-indentation.php deleted file mode 100644 index 0e96e087f20..00000000000 --- a/tests/Indentation/Source/config-with-tabs-indentation.php +++ /dev/null @@ -1,12 +0,0 @@ -rule(IndentationTypeFixer::class); - $ecsConfig->indentation(Option::INDENTATION_TAB); -}; diff --git a/tests/Set/Array/ArrayTest.php b/tests/Set/Array/ArrayTest.php deleted file mode 100644 index fc122760da2..00000000000 --- a/tests/Set/Array/ArrayTest.php +++ /dev/null @@ -1,28 +0,0 @@ -doTestFile($filePath); - } - - public static function provideData(): Iterator - { - return self::yieldFiles(__DIR__ . '/Fixture'); - } - - public function provideConfig(): string - { - return __DIR__ . '/config.php'; - } -} diff --git a/tests/Set/Array/Fixture/nested_array.php.inc b/tests/Set/Array/Fixture/nested_array.php.inc deleted file mode 100644 index 4fe7e93bde3..00000000000 --- a/tests/Set/Array/Fixture/nested_array.php.inc +++ /dev/null @@ -1,19 +0,0 @@ - ['keyA' => 'valueA']]; - -?> ------ - [ - 'keyA' => 'valueA', - ], -]; - -?> diff --git a/tests/Set/Array/Fixture/nested_array_complex.php.inc b/tests/Set/Array/Fixture/nested_array_complex.php.inc deleted file mode 100644 index 4f8029f8dff..00000000000 --- a/tests/Set/Array/Fixture/nested_array_complex.php.inc +++ /dev/null @@ -1,22 +0,0 @@ - ['keyA1' => 'valueA1'], 'keyB' => ['keyB1' => 'valueB1']]; - -?> ------ - [ - 'keyA1' => 'valueA1', - ], - 'keyB' => [ - 'keyB1' => 'valueB1', - ], -]; - -?> diff --git a/tests/Set/Array/config.php b/tests/Set/Array/config.php deleted file mode 100644 index 97acbc80fba..00000000000 --- a/tests/Set/Array/config.php +++ /dev/null @@ -1,10 +0,0 @@ -sets([SetList::ARRAY]); -}; diff --git a/tests/Set/Psr12/Fixture/fixture.php.inc b/tests/Set/Psr12/Fixture/fixture.php.inc deleted file mode 100644 index 1a8a5d979ad..00000000000 --- a/tests/Set/Psr12/Fixture/fixture.php.inc +++ /dev/null @@ -1,282 +0,0 @@ -getVersion() === 'PSR12' && $respected->lineLengthRecommendeations() === false) { - bar(); - } - - $moreThan = 1; - $statement = 'per line'; - - if ($a === $b) { - bar(); - } elseif ($a > $b) { - $foo->bar($arg1); - } else { - BazClass::bar($arg2, $arg3); - } - } - - final public static function bar() - { - // method body - } - - CONST LOWER_CONSTANTS = 1; - - ABSTRACT STATIC PUBLIC FUNCTION lowercaseReservedKeywords(CALLABLE $a) - { - GLOBAL $test; - RETURN PRINT CLONE ARRAY() AND NEW stdClass OR $g INSTANCEOF stdClass XOR 4; - LIST($test) = EVAL(''); - UNSET($test); - TRUE AND FALSE; - (STRING) 1; - (BOOLEAN) 1; - (INTEGER) 1; - - ECHO FUNCTION () USE ($array) { - - }; - - FOR ($i = 1; $i++; $i > 100) { - WHILE (0) { - SWITCH ($test) { - CASE 1: - BREAK; - } - } - } - } -} - -class Foo - extends SomeRediculouslySuperfluouslyLongClassNameThatShouldNeverExistInTheRealWorldMeantToTestOverflow - implements SomeInterface, SomeOtherInterface, YetAnotherInterface { - - public function someBody() - { - } - use SomeTrait, SomeOtherTrait; - const SomeConst = 1; - use A, B, C { - B::smallTalk insteadof A; - A::bigTalk insteadof C; - C::mediumTalk as FooBar; - } - - protected$doo=4; - private $derp; - protected $doo; - public $derpity; - var $noVisibility; - static $staticNoVisibility; - -} - -class Foo { - use SomeTrait; -} - -class Foo extends ExtendedClass implements - SomeInterface, SomeOtherInterface, - YetAnotherInterface { - - public function someMethod () { } - - public function fooBarBaz ($arg1,& $arg2 ,$arg3=[]) - { - // method body - } - - public final function finalMethod() - { - } - - public static function staticMethod() - { - } - - public static final function staticMethod() - { - } - - public abstract function abstractMethod(); - -} - -declare( ticks = 1 ) -{ - echo 1; -} - -function fooBarBaz($arg1,& $arg2 ,$arg3=[]){ - // function body -} - -factoryFunction ( $arg1 , $arg2 )->method ($arg1,$arg2); - -factoryFunction( $arg1, - $arg2, $arg3); - -factoryFunction($arg1, $arg2, [ - 1, - 2, - 3 -], $arg4); - -?> ------ -getVersion() === 'PSR12' && $respected->lineLengthRecommendeations() === false) { - bar(); - } - - $moreThan = 1; - $statement = 'per line'; - - if ($a === $b) { - bar(); - } elseif ($a > $b) { - $foo->bar($arg1); - } else { - BazClass::bar($arg2, $arg3); - } - } - - final public static function bar() - { - // method body - } - - public const LOWER_CONSTANTS = 1; - - abstract public static function lowercaseReservedKeywords(callable $a) - { - global $test; - return print clone array() and new stdClass() or $g instanceof stdClass xor 4; - list($test) = eval(''); - unset($test); - true and false; - (string) 1; - (bool) 1; - (int) 1; - - echo function () use ($array) { - }; - - for ($i = 1; $i++; $i > 100) { - while (0) { - switch ($test) { - case 1: - break; - } - } - } - } -} - -class Foo extends SomeRediculouslySuperfluouslyLongClassNameThatShouldNeverExistInTheRealWorldMeantToTestOverflow implements SomeInterface, SomeOtherInterface, YetAnotherInterface -{ - public function someBody() - { - } - use SomeTrait, SomeOtherTrait; - public const SomeConst = 1; - use A, B, C { - B::smallTalk insteadof A; - A::bigTalk insteadof C; - C::mediumTalk as FooBar; - } - - protected $doo = 4; - private $derp; - protected $doo; - public $derpity; - public $noVisibility; - public static $staticNoVisibility; -} - -class Foo -{ - use SomeTrait; -} - -class Foo extends ExtendedClass implements - SomeInterface, - SomeOtherInterface, - YetAnotherInterface -{ - public function someMethod() - { - } - - public function fooBarBaz($arg1, &$arg2, $arg3 = []) - { - // method body - } - - final public function finalMethod() - { - } - - public static function staticMethod() - { - } - - final public static function staticMethod() - { - } - - abstract public function abstractMethod(); -} - -declare(ticks=1) { - echo 1; -} - -function fooBarBaz($arg1, &$arg2, $arg3 = []) -{ - // function body -} - -factoryFunction($arg1, $arg2)->method($arg1, $arg2); - -factoryFunction( - $arg1, - $arg2, - $arg3 -); - -factoryFunction($arg1, $arg2, [ - 1, - 2, - 3 -], $arg4); diff --git a/tests/Set/Psr12/Fixture/fixture2.php.inc b/tests/Set/Psr12/Fixture/fixture2.php.inc deleted file mode 100644 index a6eb12e94da..00000000000 --- a/tests/Set/Psr12/Fixture/fixture2.php.inc +++ /dev/null @@ -1,253 +0,0 @@ -$value ){ -} -foreach($simple as $key=>$value) -{ -} - -try -{ - // try body -} -catch(FirstThrowableType $e) -{ - // catch body -} -catch(OtherThrowableType $e) -{ - // catch body -}finally{ - // finally body -} - -/** Operators */ - -// Arithmetic -$result=-$a+$b-( +$c*$d )/ $e%($f**$g); - -// Comparison -((!$a==$b) === ($c!=$d))<>( ($e<$f)<=>($g>$h)); - -// Assignment -$a=$b+=$c -= $d.=$e=&$f; - -// Bitwise -$b&$c|~$d^$f<<$g>>$h; - -// Logical -$a and$b or !$c xor$d&&$e||$f; - -// String -$a.$b; - -// Single pipe try/catch operator -try { -} catch (Exception|Error $a) { -} - -/** Closures */ -function( $a , $b )use($c){}; - -function () use ( $a ) { } ; - -function ($a, $b) -{}; - -function ($a, $b) -{ - // Body - - -}; - -$closureWithArgs = function ($arg1, $arg2) -{ - // body -}; - -$closureWithArgsAndVars = function( $arg1 ,$arg2 ) -use( $var1, $var2 ){ - // body -}; - -/** Anonymous Classes */ -new class( - $a,$b,$c -) extends SomeExtendedClass implements - \ArrayAccess, - \Countable { - // Body -}; - -?> ------ - $value) { -} -foreach ($simple as $key => $value) { -} - -try { - // try body -} catch (FirstThrowableType $e) { - // catch body -} catch (OtherThrowableType $e) { - // catch body -} finally { - // finally body -} - -/** Operators */ - -// Arithmetic -$result = -$a + $b - (+$c * $d) / $e % ($f ** $g); - -// Comparison -((!$a == $b) === ($c != $d)) <> (($e < $f) <=> ($g > $h)); - -// Assignment -$a = $b += $c -= $d .= $e = &$f; - -// Bitwise -$b & $c | ~$d ^ $f << $g >> $h; - -// Logical -$a and $b or !$c xor $d && $e || $f; - -// String -$a . $b; - -// Single pipe try/catch operator -try { -} catch (Exception|Error $a) { -} - -/** Closures */ -function ($a, $b) use ($c) { -}; - -function () use ($a) { -}; - -function ($a, $b) { -}; - -function ($a, $b) { - // Body -}; - -$closureWithArgs = function ($arg1, $arg2) { - // body -}; - -$closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) { - // body -}; - -/** Anonymous Classes */ -new class($a, $b, $c) extends SomeExtendedClass implements - \ArrayAccess, - \Countable { - // Body -}; diff --git a/tests/Set/Psr12/Psr12Test.php b/tests/Set/Psr12/Psr12Test.php deleted file mode 100644 index b4e029aa1be..00000000000 --- a/tests/Set/Psr12/Psr12Test.php +++ /dev/null @@ -1,29 +0,0 @@ -doTestFile($filePath); - } - - public static function provideData(): Iterator - { - return self::yieldFiles(__DIR__ . '/Fixture'); - } - - public function provideConfig(): string - { - return SetList::PSR_12; - } -} diff --git a/tests/Testing/PHPUnit/Fixture/another_file.php.inc b/tests/Testing/PHPUnit/Fixture/another_file.php.inc deleted file mode 100644 index 3d8cf3b04eb..00000000000 --- a/tests/Testing/PHPUnit/Fixture/another_file.php.inc +++ /dev/null @@ -1,3 +0,0 @@ -assertCount(2, iterator_to_array($iterator)); - } -} diff --git a/tests/bootstrap.php b/tests/bootstrap.php deleted file mode 100644 index fd0d308748e..00000000000 --- a/tests/bootstrap.php +++ /dev/null @@ -1,6 +0,0 @@ -realpath = \realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = \fopen($this->realpath, $mode); + $this->position = 0; + return (bool) $this->handle; + } + public function stream_read($count) + { + $data = \fread($this->handle, $count); + if ($this->position === 0) { + $data = \preg_replace('{^#!.*\\r?\\n}', '', $data); + } + $this->position += \strlen($data); + return $data; + } + public function stream_cast($castAs) + { + return $this->handle; + } + public function stream_close() + { + \fclose($this->handle); + } + public function stream_lock($operation) + { + return $operation ? \flock($this->handle, $operation) : \true; + } + public function stream_seek($offset, $whence) + { + if (0 === \fseek($this->handle, $offset, $whence)) { + $this->position = \ftell($this->handle); + return \true; + } + return \false; + } + public function stream_tell() + { + return $this->position; + } + public function stream_eof() + { + return \feof($this->handle); + } + public function stream_stat() + { + return array(); + } + public function stream_set_option($option, $arg1, $arg2) + { + return \true; + } + public function url_stat($path, $flags) + { + $path = \substr($path, 17); + if (\file_exists($path)) { + return \stat($path); + } + return \false; + } + } + } + if (\function_exists('stream_get_wrappers') && \in_array('phpvfscomposer', \stream_get_wrappers(), \true) || \function_exists('stream_wrapper_register') && \stream_wrapper_register('phpvfscomposer', 'ECSPrefix202307\\Composer\\BinProxyWrapper')) { + return include "phpvfscomposer://" . __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/php-cs-fixer'; + } +} +return include __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/php-cs-fixer'; diff --git a/vendor/bin/phpcbf b/vendor/bin/phpcbf new file mode 100644 index 00000000000..4345d6b6a56 --- /dev/null +++ b/vendor/bin/phpcbf @@ -0,0 +1,94 @@ +#!/usr/bin/env php +realpath = \realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = \fopen($this->realpath, $mode); + $this->position = 0; + return (bool) $this->handle; + } + public function stream_read($count) + { + $data = \fread($this->handle, $count); + if ($this->position === 0) { + $data = \preg_replace('{^#!.*\\r?\\n}', '', $data); + } + $this->position += \strlen($data); + return $data; + } + public function stream_cast($castAs) + { + return $this->handle; + } + public function stream_close() + { + \fclose($this->handle); + } + public function stream_lock($operation) + { + return $operation ? \flock($this->handle, $operation) : \true; + } + public function stream_seek($offset, $whence) + { + if (0 === \fseek($this->handle, $offset, $whence)) { + $this->position = \ftell($this->handle); + return \true; + } + return \false; + } + public function stream_tell() + { + return $this->position; + } + public function stream_eof() + { + return \feof($this->handle); + } + public function stream_stat() + { + return array(); + } + public function stream_set_option($option, $arg1, $arg2) + { + return \true; + } + public function url_stat($path, $flags) + { + $path = \substr($path, 17); + if (\file_exists($path)) { + return \stat($path); + } + return \false; + } + } + } + if (\function_exists('stream_get_wrappers') && \in_array('phpvfscomposer', \stream_get_wrappers(), \true) || \function_exists('stream_wrapper_register') && \stream_wrapper_register('phpvfscomposer', 'ECSPrefix202307\\Composer\\BinProxyWrapper')) { + return include "phpvfscomposer://" . __DIR__ . '/..' . '/squizlabs/php_codesniffer/bin/phpcbf'; + } +} +return include __DIR__ . '/..' . '/squizlabs/php_codesniffer/bin/phpcbf'; diff --git a/vendor/bin/phpcs b/vendor/bin/phpcs new file mode 100644 index 00000000000..47617b10212 --- /dev/null +++ b/vendor/bin/phpcs @@ -0,0 +1,94 @@ +#!/usr/bin/env php +realpath = \realpath($opened_path) ?: $opened_path; + $opened_path = $this->realpath; + $this->handle = \fopen($this->realpath, $mode); + $this->position = 0; + return (bool) $this->handle; + } + public function stream_read($count) + { + $data = \fread($this->handle, $count); + if ($this->position === 0) { + $data = \preg_replace('{^#!.*\\r?\\n}', '', $data); + } + $this->position += \strlen($data); + return $data; + } + public function stream_cast($castAs) + { + return $this->handle; + } + public function stream_close() + { + \fclose($this->handle); + } + public function stream_lock($operation) + { + return $operation ? \flock($this->handle, $operation) : \true; + } + public function stream_seek($offset, $whence) + { + if (0 === \fseek($this->handle, $offset, $whence)) { + $this->position = \ftell($this->handle); + return \true; + } + return \false; + } + public function stream_tell() + { + return $this->position; + } + public function stream_eof() + { + return \feof($this->handle); + } + public function stream_stat() + { + return array(); + } + public function stream_set_option($option, $arg1, $arg2) + { + return \true; + } + public function url_stat($path, $flags) + { + $path = \substr($path, 17); + if (\file_exists($path)) { + return \stat($path); + } + return \false; + } + } + } + if (\function_exists('stream_get_wrappers') && \in_array('phpvfscomposer', \stream_get_wrappers(), \true) || \function_exists('stream_wrapper_register') && \stream_wrapper_register('phpvfscomposer', 'ECSPrefix202307\\Composer\\BinProxyWrapper')) { + return include "phpvfscomposer://" . __DIR__ . '/..' . '/squizlabs/php_codesniffer/bin/phpcs'; + } +} +return include __DIR__ . '/..' . '/squizlabs/php_codesniffer/bin/phpcs'; diff --git a/vendor/clue/ndjson-react/CHANGELOG.md b/vendor/clue/ndjson-react/CHANGELOG.md new file mode 100644 index 00000000000..bc4faf69393 --- /dev/null +++ b/vendor/clue/ndjson-react/CHANGELOG.md @@ -0,0 +1,75 @@ +# Changelog + +## 1.3.0 (2022-12-23) + +* Feature: Add support for PHP 8.1 and PHP 8.2. + (#31 by @clue and #30 by @SimonFring) + +* Feature: Check type of incoming `data` before trying to decode NDJSON. + (#29 by @SimonFrings) + +* Improve documentation and examples and update to new [default loop](https://reactphp.org/event-loop/#loop). + (#26 by @clue, #27 by @SimonFrings and #25 by @PaulRotmann) + +* Improve test suite, report failed assertions and ensure 100% code coverage. + (#32 and #33 by @clue and #28 by @SimonFrings) + +## 1.2.0 (2020-12-09) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Add PHP 8 support, update to PHPUnit 9 and simplify test setup. + (#18 by @clue and #19, #22 and #23 by @SimonFrings) + +## 1.1.0 (2020-02-04) + +* Feature: Improve error reporting and add parsing error message to Exception and + ignore `JSON_THROW_ON_ERROR` option (available as of PHP 7.3). + (#14 by @clue) + +* Feature: Add bechmarking script and import all global function references. + (#16 by @clue) + +* Improve documentation and add NDJSON format description and + add support / sponsorship info. + (#12 and #17 by @clue) + +* Improve test suite to run tests on PHP 7.4 and simplify test matrix and + apply minor code style adjustments to make phpstan happy. + (#13 and #15 by @clue) + +## 1.0.0 (2018-05-17) + +* First stable release, now following SemVer + +* Improve documentation and usage examples + +> Contains no other changes, so it's actually fully compatible with the v0.1.2 release. + +## 0.1.2 (2018-05-11) + +* Feature: Limit buffer size to 64 KiB by default. + (#10 by @clue) + +* Feature: Forward compatiblity with EventLoop v0.5 and upcoming v1.0. + (#8 by @clue) + +* Fix: Return bool `false` if encoding fails due to invalid value to pause source. + (#9 by @clue) + +* Improve test suite by supporting PHPUnit v6 and test against legacy PHP 5.3 through PHP 7.2. + (#7 by @clue) + +* Update project homepage. + (#11 by @clue) + +## 0.1.1 (2017-05-22) + +* Feature: Forward compatibility with Stream v0.7, v0.6, v0.5 and upcoming v1.0 (while keeping BC) + (#6 by @thklein) + +* Improved test suite by adding PHPUnit to `require-dev` + (#5 by @thklein) + +## 0.1.0 (2016-11-24) + +* First tagged release diff --git a/vendor/clue/ndjson-react/LICENSE b/vendor/clue/ndjson-react/LICENSE new file mode 100644 index 00000000000..7baae8e9a5b --- /dev/null +++ b/vendor/clue/ndjson-react/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Christian Lück + +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. diff --git a/vendor/clue/ndjson-react/README.md b/vendor/clue/ndjson-react/README.md new file mode 100644 index 00000000000..0ca4eabe1e8 --- /dev/null +++ b/vendor/clue/ndjson-react/README.md @@ -0,0 +1,365 @@ +# clue/reactphp-ndjson + +[![CI status](https://github.com/clue/reactphp-ndjson/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-ndjson/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/clue/ndjson-react?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/ndjson-react) +[![code coverage](https://img.shields.io/badge/code%20coverage-100%25-success)](#tests) + +Streaming newline-delimited JSON ([NDJSON](http://ndjson.org/)) parser and encoder for [ReactPHP](https://reactphp.org/). + +[NDJSON](http://ndjson.org/) can be used to store multiple JSON records in a +file to store any kind of (uniform) structured data, such as a list of user +objects or log entries. It uses a simple newline character between each +individual record and as such can be both used for efficient persistence and +simple append-style operations. This also allows it to be used in a streaming +context, such as a simple inter-process communication (IPC) protocol or for a +remote procedure call (RPC) mechanism. This library provides a simple +streaming API to process very large NDJSON files with thousands or even millions +of rows efficiently without having to load the whole file into memory at once. + +* **Standard interfaces** - + Allows easy integration with existing higher-level components by implementing + ReactPHP's standard streaming interfaces. +* **Lightweight, SOLID design** - + Provides a thin abstraction that is [*just good enough*](https://en.wikipedia.org/wiki/Principle_of_good_enough) + and does not get in your way. + Builds on top of well-tested components and well-established concepts instead of reinventing the wheel. +* **Good test coverage** - + Comes with an [automated tests suite](#tests) and is regularly tested in the *real world*. + +**Table of contents** + +* [Support us](#support-us) +* [NDJSON format](#ndjson-format) +* [Usage](#usage) + * [Decoder](#decoder) + * [Encoder](#encoder) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Support us + +We invest a lot of time developing, maintaining, and updating our awesome +open-source projects. You can help us sustain this high-quality of our work by +[becoming a sponsor on GitHub](https://github.com/sponsors/clue). Sponsors get +numerous benefits in return, see our [sponsoring page](https://github.com/sponsors/clue) +for details. + +Let's take these projects to the next level together! 🚀 + +## NDJSON format + +NDJSON ("Newline-Delimited JSON" or sometimes referred to as "JSON lines") is a +very simple text-based format for storing a large number of records, such as a +list of user records or log entries. + +```JSON +{"name":"Alice","age":30,"comment":"Yes, I like cheese"} +{"name":"Bob","age":50,"comment":"Hello\nWorld!"} +``` + +If you understand JSON and you're now looking at this newline-delimited JSON for +the first time, you should already know everything you need to know to +understand NDJSON: As the name implies, this format essentially consists of +individual lines where each individual line is any valid JSON text and each line +is delimited with a newline character. + +This example uses a list of user objects where each user has some arbitrary +properties. This can easily be adjusted for many different use cases, such as +storing for example products instead of users, assigning additional properties +or having a significantly larger number of records. You can edit NDJSON files in +any text editor or use them in a streaming context where individual records +should be processed. Unlike normal JSON files, adding a new log entry to this +NDJSON file does not require modification of this file's structure (note there's +no "outer array" to be modified). This makes it a perfect fit for a streaming +context, for line-oriented CLI tools (such as `grep` and others) or for a logging +context where you want to append records at a later time. Additionally, this +also allows it to be used in a streaming context, such as a simple inter-process +communication (IPC) protocol or for a remote procedure call (RPC) mechanism. + +The newline character at the end of each line allows for some really simple +*framing* (detecting individual records). While each individual line is valid +JSON, the complete file as a whole is technically no longer valid JSON, because +it contains multiple JSON texts. This implies that for example calling PHP's +`json_decode()` on this complete input would fail because it would try to parse +multiple records at once. Likewise, using "pretty printing" JSON +(`JSON_PRETTY_PRINT`) is not allowed because each JSON text is limited to exactly +one line. On the other hand, values containing newline characters (such as the +`comment` property in the above example) do not cause issues because each newline +within a JSON string will be represented by a `\n` instead. + +One common alternative to NDJSON would be Comma-Separated Values (CSV). +If you want to process CSV files, you may want to take a look at the related +project [clue/reactphp-csv](https://github.com/clue/reactphp-csv) instead: + +``` +name,age,comment +Alice,30,"Yes, I like cheese" +Bob,50,"Hello +World!" +``` + +CSV may look slightly simpler, but this simplicity comes at a price. CSV is +limited to untyped, two-dimensional data, so there's no standard way of storing +any nested structures or to differentiate a boolean value from a string or +integer. Field names are sometimes used, sometimes they're not +(application-dependant). Inconsistent handling for fields that contain +separators such as `,` or spaces or line breaks (see the `comment` field above) +introduce additional complexity and its text encoding is usually undefined, +Unicode (or UTF-8) is unlikely to be supported and CSV files often use ISO +8859-1 encoding or some variant (again application-dependant). + +While NDJSON helps avoiding many of CSV's shortcomings, it is still a +(relatively) young format while CSV files have been used in production systems +for decades. This means that if you want to interface with an existing system, +you may have to rely on the format that's already supported. If you're building +a new system, using NDJSON is an excellent choice as it provides a flexible way +to process individual records using a common text-based format that can include +any kind of structured data. + +## Usage + +### Decoder + +The `Decoder` (parser) class can be used to make sure you only get back +complete, valid JSON elements when reading from a stream. +It wraps a given +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) +and exposes its data through the same interface, but emits the JSON elements +as parsed values instead of just chunks of strings: + +``` +{"name":"test","active":true} +{"name":"hello w\u00f6rld","active":true} +``` + +```php +$stdin = new React\Stream\ReadableResourceStream(STDIN); + +$ndjson = new Clue\React\NDJson\Decoder($stdin); + +$ndjson->on('data', function ($data) { + // $data is a parsed element from the JSON stream + // line 1: $data = (object)array('name' => 'test', 'active' => true); + // line 2: $data = (object)array('name' => 'hello wörld', 'active' => true); + var_dump($data); +}); +``` + +ReactPHP's streams emit chunks of data strings and make no assumption about their lengths. +These chunks do not necessarily represent complete JSON elements, as an +element may be broken up into multiple chunks. +This class reassembles these elements by buffering incomplete ones. + +The `Decoder` supports the same optional parameters as the underlying +[`json_decode()`](https://www.php.net/manual/en/function.json-decode.php) function. +This means that, by default, JSON objects will be emitted as a `stdClass`. +This behavior can be controlled through the optional constructor parameters: + +```php +$ndjson = new Clue\React\NDJson\Decoder($stdin, true); + +$ndjson->on('data', function ($data) { + // JSON objects will be emitted as assoc arrays now +}); +``` + +Additionally, the `Decoder` limits the maximum buffer size (maximum line +length) to avoid buffer overflows due to malformed user input. Usually, there +should be no need to change this value, unless you know you're dealing with some +unreasonably long lines. It accepts an additional argument if you want to change +this from the default of 64 KiB: + +```php +$ndjson = new Clue\React\NDJson\Decoder($stdin, false, 512, 0, 64 * 1024); +``` + +If the underlying stream emits an `error` event or the plain stream contains +any data that does not represent a valid NDJson stream, +it will emit an `error` event and then `close` the input stream: + +```php +$ndjson->on('error', function (Exception $error) { + // an error occured, stream will close next +}); +``` + +If the underlying stream emits an `end` event, it will flush any incomplete +data from the buffer, thus either possibly emitting a final `data` event +followed by an `end` event on success or an `error` event for +incomplete/invalid JSON data as above: + +```php +$ndjson->on('end', function () { + // stream successfully ended, stream will close next +}); +``` + +If either the underlying stream or the `Decoder` is closed, it will forward +the `close` event: + +```php +$ndjson->on('close', function () { + // stream closed + // possibly after an "end" event or due to an "error" event +}); +``` + +The `close(): void` method can be used to explicitly close the `Decoder` and +its underlying stream: + +```php +$ndjson->close(); +``` + +The `pipe(WritableStreamInterface $dest, array $options = array(): WritableStreamInterface` +method can be used to forward all data to the given destination stream. +Please note that the `Decoder` emits decoded/parsed data events, while many +(most?) writable streams expect only data chunks: + +```php +$ndjson->pipe($logger); +``` + +For more details, see ReactPHP's +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface). + +### Encoder + +The `Encoder` (serializer) class can be used to make sure anything you write to +a stream ends up as valid JSON elements in the resulting NDJSON stream. +It wraps a given +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface) +and accepts its data through the same interface, but handles any data as complete +JSON elements instead of just chunks of strings: + +```php +$stdout = new React\Stream\WritableResourceStream(STDOUT); + +$ndjson = new Clue\React\NDJson\Encoder($stdout); + +$ndjson->write(array('name' => 'test', 'active' => true)); +$ndjson->write(array('name' => 'hello wörld', 'active' => true)); +``` +``` +{"name":"test","active":true} +{"name":"hello w\u00f6rld","active":true} +``` + +The `Encoder` supports the same parameters as the underlying +[`json_encode()`](https://www.php.net/manual/en/function.json-encode.php) function. +This means that, by default, Unicode characters will be escaped in the output. +This behavior can be controlled through the optional constructor parameters: + +```php +$ndjson = new Clue\React\NDJson\Encoder($stdout, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + +$ndjson->write('hello wörld'); +``` +``` +"hello wörld" +``` + +Note that trying to pass the `JSON_PRETTY_PRINT` option will yield an +`InvalidArgumentException` because it is not compatible with NDJSON. + +If the underlying stream emits an `error` event or the given data contains +any data that can not be represented as a valid NDJSON stream, +it will emit an `error` event and then `close` the input stream: + +```php +$ndjson->on('error', function (Exception $error) { + // an error occured, stream will close next +}); +``` + +If either the underlying stream or the `Encoder` is closed, it will forward +the `close` event: + +```php +$ndjson->on('close', function () { + // stream closed + // possibly after an "end" event or due to an "error" event +}); +``` + +The `end(mixed $data = null): void` method can be used to optionally emit +any final data and then soft-close the `Encoder` and its underlying stream: + +```php +$ndjson->end(); +``` + +The `close(): void` method can be used to explicitly close the `Encoder` and +its underlying stream: + +```php +$ndjson->close(); +``` + +For more details, see ReactPHP's +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface). + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require clue/ndjson-react:^1.3 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +This project is released under the permissive [MIT license](LICENSE). + +> Did you know that I offer custom development services and issuing invoices for + sponsorships of releases and for contributions? Contact me (@clue) for details. + +## More + +* If you want to learn more about processing streams of data, refer to the documentation of + the underlying [react/stream](https://github.com/reactphp/stream) component. + +* If you want to process compressed NDJSON files (`.ndjson.gz` file extension), + you may want to use [clue/reactphp-zlib](https://github.com/clue/reactphp-zlib) + on the compressed input stream before passing the decompressed stream to the NDJSON decoder. + +* If you want to create compressed NDJSON files (`.ndjson.gz` file extension), + you may want to use [clue/reactphp-zlib](https://github.com/clue/reactphp-zlib) + on the resulting NDJSON encoder output stream before passing the compressed + stream to the file output stream. + +* If you want to concurrently process the records from your NDJSON stream, + you may want to use [clue/reactphp-flux](https://github.com/clue/reactphp-flux) + to concurrently process many (but not too many) records at once. + +* If you want to process structured data in the more common text-based format, + you may want to use [clue/reactphp-csv](https://github.com/clue/reactphp-csv) + to process Comma-Separated-Values (CSV) files (`.csv` file extension). diff --git a/vendor/clue/ndjson-react/composer.json b/vendor/clue/ndjson-react/composer.json new file mode 100644 index 00000000000..a0691f5d799 --- /dev/null +++ b/vendor/clue/ndjson-react/composer.json @@ -0,0 +1,38 @@ +{ + "name": "clue\/ndjson-react", + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "keywords": [ + "NDJSON", + "newline", + "JSON", + "jsonlines", + "streaming", + "ReactPHP" + ], + "homepage": "https:\/\/github.com\/clue\/reactphp-ndjson", + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering" + } + ], + "require": { + "php": ">=5.3", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react\/event-loop": "^1.2" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Clue\\React\\NDJson\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Clue\\Tests\\React\\NDJson\\": "tests\/" + } + } +} \ No newline at end of file diff --git a/vendor/clue/ndjson-react/src/Decoder.php b/vendor/clue/ndjson-react/src/Decoder.php new file mode 100644 index 00000000000..ddcf7b2ee5e --- /dev/null +++ b/vendor/clue/ndjson-react/src/Decoder.php @@ -0,0 +1,140 @@ +input = $input; + if (!$input->isReadable()) { + $this->close(); + return; + } + $this->assoc = $assoc; + $this->depth = $depth; + $this->options = $options; + $this->maxlength = $maxlength; + $this->input->on('data', array($this, 'handleData')); + $this->input->on('end', array($this, 'handleEnd')); + $this->input->on('error', array($this, 'handleError')); + $this->input->on('close', array($this, 'close')); + } + public function isReadable() + { + return !$this->closed; + } + public function close() + { + if ($this->closed) { + return; + } + $this->closed = \true; + $this->buffer = ''; + $this->input->close(); + $this->emit('close'); + $this->removeAllListeners(); + } + public function pause() + { + $this->input->pause(); + } + public function resume() + { + $this->input->resume(); + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + Util::pipe($this, $dest, $options); + return $dest; + } + /** @internal */ + public function handleData($data) + { + if (!\is_string($data)) { + $this->handleError(new \UnexpectedValueException('Expected stream to emit string, but got ' . \gettype($data))); + return; + } + $this->buffer .= $data; + // keep parsing while a newline has been found + while (($newline = \strpos($this->buffer, "\n")) !== \false && $newline <= $this->maxlength) { + // read data up until newline and remove from buffer + $data = (string) \substr($this->buffer, 0, $newline); + $this->buffer = (string) \substr($this->buffer, $newline + 1); + // decode data with options given in ctor + // @codeCoverageIgnoreStart + if ($this->options === 0) { + $data = \json_decode($data, $this->assoc, $this->depth); + } else { + \assert(\PHP_VERSION_ID >= 50400); + $data = \json_decode($data, $this->assoc, $this->depth, $this->options); + } + // @codeCoverageIgnoreEnd + // abort stream if decoding failed + if ($data === null && \json_last_error() !== \JSON_ERROR_NONE) { + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID > 50500) { + $errstr = \json_last_error_msg(); + } elseif (\json_last_error() === \JSON_ERROR_SYNTAX) { + $errstr = 'Syntax error'; + } else { + $errstr = 'Unknown error'; + } + // @codeCoverageIgnoreEnd + return $this->handleError(new \RuntimeException('Unable to decode JSON: ' . $errstr, \json_last_error())); + } + $this->emit('data', array($data)); + } + if (isset($this->buffer[$this->maxlength])) { + $this->handleError(new \OverflowException('Buffer size exceeded')); + } + } + /** @internal */ + public function handleEnd() + { + if ($this->buffer !== '') { + $this->handleData("\n"); + } + if (!$this->closed) { + $this->emit('end'); + $this->close(); + } + } + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + $this->close(); + } +} diff --git a/vendor/clue/ndjson-react/src/Encoder.php b/vendor/clue/ndjson-react/src/Encoder.php new file mode 100644 index 00000000000..5b669916a31 --- /dev/null +++ b/vendor/clue/ndjson-react/src/Encoder.php @@ -0,0 +1,122 @@ +output = $output; + if (!$output->isWritable()) { + $this->close(); + return; + } + $this->options = $options; + $this->depth = $depth; + $this->output->on('drain', array($this, 'handleDrain')); + $this->output->on('error', array($this, 'handleError')); + $this->output->on('close', array($this, 'close')); + } + public function write($data) + { + if ($this->closed) { + return \false; + } + // we have to handle PHP warnings for legacy PHP < 5.5 + // certain values (such as INF etc.) emit a warning, but still encode successfully + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID < 50500) { + $errstr = null; + \set_error_handler(function ($_, $error) use(&$errstr) { + $errstr = $error; + }); + // encode data with options given in ctor (depth not supported) + $data = \json_encode($data, $this->options); + // always check error code and match missing error messages + \restore_error_handler(); + $errno = \json_last_error(); + if (\defined('JSON_ERROR_UTF8') && $errno === \JSON_ERROR_UTF8) { + // const JSON_ERROR_UTF8 added in PHP 5.3.3, but no error message assigned in legacy PHP < 5.5 + // this overrides PHP 5.3.14 only: https://3v4l.org/IGP8Z#v5314 + $errstr = 'Malformed UTF-8 characters, possibly incorrectly encoded'; + } elseif ($errno !== \JSON_ERROR_NONE && $errstr === null) { + // error number present, but no error message applicable + $errstr = 'Unknown error'; + } + // abort stream if encoding fails + if ($errno !== \JSON_ERROR_NONE || $errstr !== null) { + $this->handleError(new \RuntimeException('Unable to encode JSON: ' . $errstr, $errno)); + return \false; + } + } else { + // encode data with options given in ctor + $data = \json_encode($data, $this->options, $this->depth); + // abort stream if encoding fails + if ($data === \false && \json_last_error() !== \JSON_ERROR_NONE) { + $this->handleError(new \RuntimeException('Unable to encode JSON: ' . \json_last_error_msg(), \json_last_error())); + return \false; + } + } + // @codeCoverageIgnoreEnd + return $this->output->write($data . "\n"); + } + public function end($data = null) + { + if ($data !== null) { + $this->write($data); + } + $this->output->end(); + } + public function isWritable() + { + return !$this->closed; + } + public function close() + { + if ($this->closed) { + return; + } + $this->closed = \true; + $this->output->close(); + $this->emit('close'); + $this->removeAllListeners(); + } + /** @internal */ + public function handleDrain() + { + $this->emit('drain'); + } + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + $this->close(); + } +} diff --git a/vendor/composer/ClassLoader.php b/vendor/composer/ClassLoader.php new file mode 100644 index 00000000000..7824d8f7eaf --- /dev/null +++ b/vendor/composer/ClassLoader.php @@ -0,0 +1,579 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see https://www.php-fig.org/psr/psr-0/ + * @see https://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + /** @var \Closure(string):void */ + private static $includeFile; + + /** @var string|null */ + private $vendorDir; + + // PSR-4 + /** + * @var array> + */ + private $prefixLengthsPsr4 = array(); + /** + * @var array> + */ + private $prefixDirsPsr4 = array(); + /** + * @var list + */ + private $fallbackDirsPsr4 = array(); + + // PSR-0 + /** + * List of PSR-0 prefixes + * + * Structured as array('F (first letter)' => array('Foo\Bar (full prefix)' => array('path', 'path2'))) + * + * @var array>> + */ + private $prefixesPsr0 = array(); + /** + * @var list + */ + private $fallbackDirsPsr0 = array(); + + /** @var bool */ + private $useIncludePath = false; + + /** + * @var array + */ + private $classMap = array(); + + /** @var bool */ + private $classMapAuthoritative = false; + + /** + * @var array + */ + private $missingClasses = array(); + + /** @var string|null */ + private $apcuPrefix; + + /** + * @var array + */ + private static $registeredLoaders = array(); + + /** + * @param string|null $vendorDir + */ + public function __construct($vendorDir = null) + { + $this->vendorDir = $vendorDir; + self::initializeIncludeClosure(); + } + + /** + * @return array> + */ + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); + } + + return array(); + } + + /** + * @return array> + */ + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + /** + * @return list + */ + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + /** + * @return list + */ + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + /** + * @return array Array of classname => path + */ + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + * + * @return void + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + * + * @return void + */ + public function add($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + $paths = (array) $paths; + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $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] = $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param list|string $paths The PSR-0 base directories + * + * @return void + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param list|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + * + * @return void + */ + 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; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + * + * @return void + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + * + * @return void + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + * + * @return void + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + * + * @return void + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + + if (null === $this->vendorDir) { + return; + } + + if ($prepend) { + self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; + } else { + unset(self::$registeredLoaders[$this->vendorDir]); + self::$registeredLoaders[$this->vendorDir] = $this; + } + } + + /** + * Unregisters this instance as an autoloader. + * + * @return void + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + + if (null !== $this->vendorDir) { + unset(self::$registeredLoaders[$this->vendorDir]); + } + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return true|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + $includeFile = self::$includeFile; + $includeFile($file); + + return true; + } + + return null; + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + 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'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + /** + * Returns the currently registered loaders keyed by their corresponding vendor directories. + * + * @return array + */ + public static function getRegisteredLoaders() + { + return self::$registeredLoaders; + } + + /** + * @param string $class + * @param string $ext + * @return string|false + */ + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $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; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $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; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } + + /** + * @return void + */ + private static function initializeIncludeClosure() + { + if (self::$includeFile !== null) { + return; + } + + /** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + * + * @param string $file + * @return void + */ + self::$includeFile = \Closure::bind(static function($file) { + include $file; + }, null, null); + } +} diff --git a/vendor/composer/InstalledVersions.php b/vendor/composer/InstalledVersions.php new file mode 100644 index 00000000000..fdfb717bffd --- /dev/null +++ b/vendor/composer/InstalledVersions.php @@ -0,0 +1,313 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer; + +use ECSPrefix202307\Composer\Autoload\ClassLoader; +use ECSPrefix202307\Composer\Semver\VersionParser; +/** + * This class is copied in every Composer installed project and available to all + * + * See also https://getcomposer.org/doc/07-runtime.md#installed-versions + * + * To require its presence, you can require `composer-runtime-api ^2.0` + * + * @final + */ +class InstalledVersions +{ + /** + * @var mixed[]|null + * @psalm-var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array}|array{}|null + */ + private static $installed; + /** + * @var bool|null + */ + private static $canGetVendors; + /** + * @var array[] + * @psalm-var array}> + */ + private static $installedByVendor = array(); + /** + * Returns a list of all package names which are present, either by being installed, replaced or provided + * + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackages() + { + $packages = array(); + foreach (self::getInstalled() as $installed) { + $packages[] = \array_keys($installed['versions']); + } + if (1 === \count($packages)) { + return $packages[0]; + } + return \array_keys(\array_flip(\call_user_func_array('array_merge', $packages))); + } + /** + * Returns a list of all package names with a specific type e.g. 'library' + * + * @param string $type + * @return string[] + * @psalm-return list + */ + public static function getInstalledPackagesByType($type) + { + $packagesByType = array(); + foreach (self::getInstalled() as $installed) { + foreach ($installed['versions'] as $name => $package) { + if (isset($package['type']) && $package['type'] === $type) { + $packagesByType[] = $name; + } + } + } + return $packagesByType; + } + /** + * Checks whether the given package is installed + * + * This also returns true if the package name is provided or replaced by another package + * + * @param string $packageName + * @param bool $includeDevRequirements + * @return bool + */ + public static function isInstalled($packageName, $includeDevRequirements = \true) + { + foreach (self::getInstalled() as $installed) { + if (isset($installed['versions'][$packageName])) { + return $includeDevRequirements || !isset($installed['versions'][$packageName]['dev_requirement']) || $installed['versions'][$packageName]['dev_requirement'] === \false; + } + } + return \false; + } + /** + * Checks whether the given package satisfies a version constraint + * + * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: + * + * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') + * + * @param VersionParser $parser Install composer/semver to have access to this class and functionality + * @param string $packageName + * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package + * @return bool + */ + public static function satisfies(VersionParser $parser, $packageName, $constraint) + { + $constraint = $parser->parseConstraints((string) $constraint); + $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); + return $provided->matches($constraint); + } + /** + * Returns a version constraint representing all the range(s) which are installed for a given package + * + * It is easier to use this via isInstalled() with the $constraint argument if you need to check + * whether a given version of a package is installed, and not just whether it exists + * + * @param string $packageName + * @return string Version constraint usable with composer/semver + */ + public static function getVersionRanges($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + $ranges = array(); + if (isset($installed['versions'][$packageName]['pretty_version'])) { + $ranges[] = $installed['versions'][$packageName]['pretty_version']; + } + if (\array_key_exists('aliases', $installed['versions'][$packageName])) { + $ranges = \array_merge($ranges, $installed['versions'][$packageName]['aliases']); + } + if (\array_key_exists('replaced', $installed['versions'][$packageName])) { + $ranges = \array_merge($ranges, $installed['versions'][$packageName]['replaced']); + } + if (\array_key_exists('provided', $installed['versions'][$packageName])) { + $ranges = \array_merge($ranges, $installed['versions'][$packageName]['provided']); + } + return \implode(' || ', $ranges); + } + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + if (!isset($installed['versions'][$packageName]['version'])) { + return null; + } + return $installed['versions'][$packageName]['version']; + } + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present + */ + public static function getPrettyVersion($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + if (!isset($installed['versions'][$packageName]['pretty_version'])) { + return null; + } + return $installed['versions'][$packageName]['pretty_version']; + } + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference + */ + public static function getReference($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + if (!isset($installed['versions'][$packageName]['reference'])) { + return null; + } + return $installed['versions'][$packageName]['reference']; + } + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + /** + * @param string $packageName + * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as install path. Packages of type metapackages also have a null install path. + */ + public static function getInstallPath($packageName) + { + foreach (self::getInstalled() as $installed) { + if (!isset($installed['versions'][$packageName])) { + continue; + } + return isset($installed['versions'][$packageName]['install_path']) ? $installed['versions'][$packageName]['install_path'] : null; + } + throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); + } + /** + * @return array + * @psalm-return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool} + */ + public static function getRootPackage() + { + $installed = self::getInstalled(); + return $installed[0]['root']; + } + /** + * Returns the raw installed.php data for custom implementations + * + * @deprecated Use getAllRawData() instead which returns all datasets for all autoloaders present in the process. getRawData only returns the first dataset loaded, which may not be what you expect. + * @return array[] + * @psalm-return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} + */ + public static function getRawData() + { + @\trigger_error('getRawData only returns the first dataset loaded, which may not be what you expect. Use getAllRawData() instead which returns all datasets for all autoloaders present in the process.', \E_USER_DEPRECATED); + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (\substr(__DIR__, -8, 1) !== 'C') { + self::$installed = (include __DIR__ . '/installed.php'); + } else { + self::$installed = array(); + } + } + return self::$installed; + } + /** + * Returns the raw data of all installed.php which are currently loaded for custom implementations + * + * @return array[] + * @psalm-return list}> + */ + public static function getAllRawData() + { + return self::getInstalled(); + } + /** + * Lets you reload the static array from another file + * + * This is only useful for complex integrations in which a project needs to use + * this class but then also needs to execute another project's autoloader in process, + * and wants to ensure both projects have access to their version of installed.php. + * + * A typical case would be PHPUnit, where it would need to make sure it reads all + * the data it needs from this class, then call reload() with + * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure + * the project in which it runs can then also use this class safely, without + * interference between PHPUnit's dependencies and the project's dependencies. + * + * @param array[] $data A vendor/composer/installed.php data set + * @return void + * + * @psalm-param array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $data + */ + public static function reload($data) + { + self::$installed = $data; + self::$installedByVendor = array(); + } + /** + * @return array[] + * @psalm-return list}> + */ + private static function getInstalled() + { + if (null === self::$canGetVendors) { + self::$canGetVendors = \method_exists('ECSPrefix202307\\Composer\\Autoload\\ClassLoader', 'getRegisteredLoaders'); + } + $installed = array(); + if (self::$canGetVendors) { + foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { + if (isset(self::$installedByVendor[$vendorDir])) { + $installed[] = self::$installedByVendor[$vendorDir]; + } elseif (\is_file($vendorDir . '/composer/installed.php')) { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = (require $vendorDir . '/composer/installed.php'); + $installed[] = self::$installedByVendor[$vendorDir] = $required; + if (null === self::$installed && \strtr($vendorDir . '/composer', '\\', '/') === \strtr(__DIR__, '\\', '/')) { + self::$installed = $installed[\count($installed) - 1]; + } + } + } + } + if (null === self::$installed) { + // only require the installed.php file if this file is loaded from its dumped location, + // and not from its source location in the composer/composer package, see https://github.com/composer/composer/issues/9937 + if (\substr(__DIR__, -8, 1) !== 'C') { + /** @var array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array} $required */ + $required = (require __DIR__ . '/installed.php'); + self::$installed = $required; + } else { + self::$installed = array(); + } + } + if (self::$installed !== array()) { + $installed[] = self::$installed; + } + return $installed; + } +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 00000000000..f27399a042d --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +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. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 00000000000..afe161c743b --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,1249 @@ + $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', + 'ECSPrefix202307\\Clue\\React\\NDJson\\Decoder' => $vendorDir . '/clue/ndjson-react/src/Decoder.php', + 'ECSPrefix202307\\Clue\\React\\NDJson\\Encoder' => $vendorDir . '/clue/ndjson-react/src/Encoder.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllResult' => $vendorDir . '/composer/pcre/src/MatchAllResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllStrictGroupsResult' => $vendorDir . '/composer/pcre/src/MatchAllStrictGroupsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllWithOffsetsResult' => $vendorDir . '/composer/pcre/src/MatchAllWithOffsetsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchResult' => $vendorDir . '/composer/pcre/src/MatchResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchStrictGroupsResult' => $vendorDir . '/composer/pcre/src/MatchStrictGroupsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchWithOffsetsResult' => $vendorDir . '/composer/pcre/src/MatchWithOffsetsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\PcreException' => $vendorDir . '/composer/pcre/src/PcreException.php', + 'ECSPrefix202307\\Composer\\Pcre\\Preg' => $vendorDir . '/composer/pcre/src/Preg.php', + 'ECSPrefix202307\\Composer\\Pcre\\Regex' => $vendorDir . '/composer/pcre/src/Regex.php', + 'ECSPrefix202307\\Composer\\Pcre\\ReplaceResult' => $vendorDir . '/composer/pcre/src/ReplaceResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\UnexpectedNullMatchException' => $vendorDir . '/composer/pcre/src/UnexpectedNullMatchException.php', + 'ECSPrefix202307\\Composer\\Semver\\Comparator' => $vendorDir . '/composer/semver/src/Comparator.php', + 'ECSPrefix202307\\Composer\\Semver\\CompilingMatcher' => $vendorDir . '/composer/semver/src/CompilingMatcher.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\Bound' => $vendorDir . '/composer/semver/src/Constraint/Bound.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\Constraint' => $vendorDir . '/composer/semver/src/Constraint/Constraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\ConstraintInterface' => $vendorDir . '/composer/semver/src/Constraint/ConstraintInterface.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MatchAllConstraint' => $vendorDir . '/composer/semver/src/Constraint/MatchAllConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MatchNoneConstraint' => $vendorDir . '/composer/semver/src/Constraint/MatchNoneConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MultiConstraint' => $vendorDir . '/composer/semver/src/Constraint/MultiConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Interval' => $vendorDir . '/composer/semver/src/Interval.php', + 'ECSPrefix202307\\Composer\\Semver\\Intervals' => $vendorDir . '/composer/semver/src/Intervals.php', + 'ECSPrefix202307\\Composer\\Semver\\Semver' => $vendorDir . '/composer/semver/src/Semver.php', + 'ECSPrefix202307\\Composer\\Semver\\VersionParser' => $vendorDir . '/composer/semver/src/VersionParser.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\PhpConfig' => $vendorDir . '/composer/xdebug-handler/src/PhpConfig.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\Process' => $vendorDir . '/composer/xdebug-handler/src/Process.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\Status' => $vendorDir . '/composer/xdebug-handler/src/Status.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\XdebugHandler' => $vendorDir . '/composer/xdebug-handler/src/XdebugHandler.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationException' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationRegistry' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Attribute' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Attributes' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Enum' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\NamedArgumentConstructor' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Required' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Target' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\DocLexer' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\DocParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\ImplicitlyIgnoredAnnotationNames' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\IndexedReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\PhpParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\PsrCachedReader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Reader' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\TokenParser' => $vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\AbstractLexer' => $vendorDir . '/doctrine/lexer/src/AbstractLexer.php', + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\Token' => $vendorDir . '/doctrine/lexer/src/Token.php', + 'ECSPrefix202307\\Evenement\\EventEmitter' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitter.php', + 'ECSPrefix202307\\Evenement\\EventEmitterInterface' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitterInterface.php', + 'ECSPrefix202307\\Evenement\\EventEmitterTrait' => $vendorDir . '/evenement/evenement/src/Evenement/EventEmitterTrait.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\CpuCoreCounter' => $vendorDir . '/fidry/cpu-core-counter/src/CpuCoreCounter.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Diagnoser' => $vendorDir . '/fidry/cpu-core-counter/src/Diagnoser.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Executor\\ProcOpenExecutor' => $vendorDir . '/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Executor\\ProcessExecutor' => $vendorDir . '/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\CpuCoreFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\CpuInfoFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\DummyCpuCoreFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\FinderRegistry' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/FinderRegistry.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\HwLogicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\HwPhysicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\LscpuLogicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\LscpuPhysicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NProcFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/NProcFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NProcessorFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NullCpuCoreFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\OnlyOnOSFamilyFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\ProcOpenBasedFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\SkipOnOSFamilyFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\WmicLogicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\WmicPhysicalFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\_NProcessorFinder' => $vendorDir . '/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\NumberOfCpuCoreNotFound' => $vendorDir . '/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php', + 'ECSPrefix202307\\Illuminate\\Container\\BoundMethod' => $vendorDir . '/illuminate/container/BoundMethod.php', + 'ECSPrefix202307\\Illuminate\\Container\\Container' => $vendorDir . '/illuminate/container/Container.php', + 'ECSPrefix202307\\Illuminate\\Container\\ContextualBindingBuilder' => $vendorDir . '/illuminate/container/ContextualBindingBuilder.php', + 'ECSPrefix202307\\Illuminate\\Container\\EntryNotFoundException' => $vendorDir . '/illuminate/container/EntryNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Container\\RewindableGenerator' => $vendorDir . '/illuminate/container/RewindableGenerator.php', + 'ECSPrefix202307\\Illuminate\\Container\\Util' => $vendorDir . '/illuminate/container/Util.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Access\\Authorizable' => $vendorDir . '/illuminate/contracts/Auth/Access/Authorizable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Access\\Gate' => $vendorDir . '/illuminate/contracts/Auth/Access/Gate.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Authenticatable' => $vendorDir . '/illuminate/contracts/Auth/Authenticatable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\CanResetPassword' => $vendorDir . '/illuminate/contracts/Auth/CanResetPassword.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Factory' => $vendorDir . '/illuminate/contracts/Auth/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Guard' => $vendorDir . '/illuminate/contracts/Auth/Guard.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Middleware\\AuthenticatesRequests' => $vendorDir . '/illuminate/contracts/Auth/Middleware/AuthenticatesRequests.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\MustVerifyEmail' => $vendorDir . '/illuminate/contracts/Auth/MustVerifyEmail.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\PasswordBroker' => $vendorDir . '/illuminate/contracts/Auth/PasswordBroker.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\PasswordBrokerFactory' => $vendorDir . '/illuminate/contracts/Auth/PasswordBrokerFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\StatefulGuard' => $vendorDir . '/illuminate/contracts/Auth/StatefulGuard.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\SupportsBasicAuth' => $vendorDir . '/illuminate/contracts/Auth/SupportsBasicAuth.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\UserProvider' => $vendorDir . '/illuminate/contracts/Auth/UserProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\Broadcaster' => $vendorDir . '/illuminate/contracts/Broadcasting/Broadcaster.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\Factory' => $vendorDir . '/illuminate/contracts/Broadcasting/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\HasBroadcastChannel' => $vendorDir . '/illuminate/contracts/Broadcasting/HasBroadcastChannel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBeUnique' => $vendorDir . '/illuminate/contracts/Broadcasting/ShouldBeUnique.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast' => $vendorDir . '/illuminate/contracts/Broadcasting/ShouldBroadcast.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBroadcastNow' => $vendorDir . '/illuminate/contracts/Broadcasting/ShouldBroadcastNow.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Bus\\Dispatcher' => $vendorDir . '/illuminate/contracts/Bus/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Bus\\QueueingDispatcher' => $vendorDir . '/illuminate/contracts/Bus/QueueingDispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Factory' => $vendorDir . '/illuminate/contracts/Cache/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Lock' => $vendorDir . '/illuminate/contracts/Cache/Lock.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\LockProvider' => $vendorDir . '/illuminate/contracts/Cache/LockProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\LockTimeoutException' => $vendorDir . '/illuminate/contracts/Cache/LockTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Repository' => $vendorDir . '/illuminate/contracts/Cache/Repository.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Store' => $vendorDir . '/illuminate/contracts/Cache/Store.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Config\\Repository' => $vendorDir . '/illuminate/contracts/Config/Repository.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Application' => $vendorDir . '/illuminate/contracts/Console/Application.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Isolatable' => $vendorDir . '/illuminate/contracts/Console/Isolatable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Kernel' => $vendorDir . '/illuminate/contracts/Console/Kernel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\PromptsForMissingInput' => $vendorDir . '/illuminate/contracts/Console/PromptsForMissingInput.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\BindingResolutionException' => $vendorDir . '/illuminate/contracts/Container/BindingResolutionException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\CircularDependencyException' => $vendorDir . '/illuminate/contracts/Container/CircularDependencyException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\Container' => $vendorDir . '/illuminate/contracts/Container/Container.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\ContextualBindingBuilder' => $vendorDir . '/illuminate/contracts/Container/ContextualBindingBuilder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cookie\\Factory' => $vendorDir . '/illuminate/contracts/Cookie/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cookie\\QueueingFactory' => $vendorDir . '/illuminate/contracts/Cookie/QueueingFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\Builder' => $vendorDir . '/illuminate/contracts/Database/Eloquent/Builder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\Castable' => $vendorDir . '/illuminate/contracts/Database/Eloquent/Castable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\CastsAttributes' => $vendorDir . '/illuminate/contracts/Database/Eloquent/CastsAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\CastsInboundAttributes' => $vendorDir . '/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\DeviatesCastableAttributes' => $vendorDir . '/illuminate/contracts/Database/Eloquent/DeviatesCastableAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\SerializesCastableAttributes' => $vendorDir . '/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\SupportsPartialRelations' => $vendorDir . '/illuminate/contracts/Database/Eloquent/SupportsPartialRelations.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Events\\MigrationEvent' => $vendorDir . '/illuminate/contracts/Database/Events/MigrationEvent.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\ModelIdentifier' => $vendorDir . '/illuminate/contracts/Database/ModelIdentifier.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\Builder' => $vendorDir . '/illuminate/contracts/Database/Query/Builder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\ConditionExpression' => $vendorDir . '/illuminate/contracts/Database/Query/ConditionExpression.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\Expression' => $vendorDir . '/illuminate/contracts/Database/Query/Expression.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Debug\\ExceptionHandler' => $vendorDir . '/illuminate/contracts/Debug/ExceptionHandler.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\DecryptException' => $vendorDir . '/illuminate/contracts/Encryption/DecryptException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\EncryptException' => $vendorDir . '/illuminate/contracts/Encryption/EncryptException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\Encrypter' => $vendorDir . '/illuminate/contracts/Encryption/Encrypter.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\StringEncrypter' => $vendorDir . '/illuminate/contracts/Encryption/StringEncrypter.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Events\\Dispatcher' => $vendorDir . '/illuminate/contracts/Events/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Cloud' => $vendorDir . '/illuminate/contracts/Filesystem/Cloud.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Factory' => $vendorDir . '/illuminate/contracts/Filesystem/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\FileNotFoundException' => $vendorDir . '/illuminate/contracts/Filesystem/FileNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Filesystem' => $vendorDir . '/illuminate/contracts/Filesystem/Filesystem.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\LockTimeoutException' => $vendorDir . '/illuminate/contracts/Filesystem/LockTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\Application' => $vendorDir . '/illuminate/contracts/Foundation/Application.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\CachesConfiguration' => $vendorDir . '/illuminate/contracts/Foundation/CachesConfiguration.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\CachesRoutes' => $vendorDir . '/illuminate/contracts/Foundation/CachesRoutes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\ExceptionRenderer' => $vendorDir . '/illuminate/contracts/Foundation/ExceptionRenderer.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\MaintenanceMode' => $vendorDir . '/illuminate/contracts/Foundation/MaintenanceMode.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Hashing\\Hasher' => $vendorDir . '/illuminate/contracts/Hashing/Hasher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Http\\Kernel' => $vendorDir . '/illuminate/contracts/Http/Kernel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Attachable' => $vendorDir . '/illuminate/contracts/Mail/Attachable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Factory' => $vendorDir . '/illuminate/contracts/Mail/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\MailQueue' => $vendorDir . '/illuminate/contracts/Mail/MailQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Mailable' => $vendorDir . '/illuminate/contracts/Mail/Mailable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Mailer' => $vendorDir . '/illuminate/contracts/Mail/Mailer.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Notifications\\Dispatcher' => $vendorDir . '/illuminate/contracts/Notifications/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Notifications\\Factory' => $vendorDir . '/illuminate/contracts/Notifications/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\CursorPaginator' => $vendorDir . '/illuminate/contracts/Pagination/CursorPaginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\LengthAwarePaginator' => $vendorDir . '/illuminate/contracts/Pagination/LengthAwarePaginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\Paginator' => $vendorDir . '/illuminate/contracts/Pagination/Paginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pipeline\\Hub' => $vendorDir . '/illuminate/contracts/Pipeline/Hub.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pipeline\\Pipeline' => $vendorDir . '/illuminate/contracts/Pipeline/Pipeline.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Process\\InvokedProcess' => $vendorDir . '/illuminate/contracts/Process/InvokedProcess.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Process\\ProcessResult' => $vendorDir . '/illuminate/contracts/Process/ProcessResult.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ClearableQueue' => $vendorDir . '/illuminate/contracts/Queue/ClearableQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\EntityNotFoundException' => $vendorDir . '/illuminate/contracts/Queue/EntityNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\EntityResolver' => $vendorDir . '/illuminate/contracts/Queue/EntityResolver.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Factory' => $vendorDir . '/illuminate/contracts/Queue/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Job' => $vendorDir . '/illuminate/contracts/Queue/Job.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Monitor' => $vendorDir . '/illuminate/contracts/Queue/Monitor.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Queue' => $vendorDir . '/illuminate/contracts/Queue/Queue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\QueueableCollection' => $vendorDir . '/illuminate/contracts/Queue/QueueableCollection.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\QueueableEntity' => $vendorDir . '/illuminate/contracts/Queue/QueueableEntity.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeEncrypted' => $vendorDir . '/illuminate/contracts/Queue/ShouldBeEncrypted.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeUnique' => $vendorDir . '/illuminate/contracts/Queue/ShouldBeUnique.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing' => $vendorDir . '/illuminate/contracts/Queue/ShouldBeUniqueUntilProcessing.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldQueue' => $vendorDir . '/illuminate/contracts/Queue/ShouldQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Connection' => $vendorDir . '/illuminate/contracts/Redis/Connection.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Connector' => $vendorDir . '/illuminate/contracts/Redis/Connector.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Factory' => $vendorDir . '/illuminate/contracts/Redis/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\LimiterTimeoutException' => $vendorDir . '/illuminate/contracts/Redis/LimiterTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\BindingRegistrar' => $vendorDir . '/illuminate/contracts/Routing/BindingRegistrar.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\Registrar' => $vendorDir . '/illuminate/contracts/Routing/Registrar.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\ResponseFactory' => $vendorDir . '/illuminate/contracts/Routing/ResponseFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\UrlGenerator' => $vendorDir . '/illuminate/contracts/Routing/UrlGenerator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\UrlRoutable' => $vendorDir . '/illuminate/contracts/Routing/UrlRoutable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Session\\Middleware\\AuthenticatesSessions' => $vendorDir . '/illuminate/contracts/Session/Middleware/AuthenticatesSessions.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Session\\Session' => $vendorDir . '/illuminate/contracts/Session/Session.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Arrayable' => $vendorDir . '/illuminate/contracts/Support/Arrayable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\CanBeEscapedWhenCastToString' => $vendorDir . '/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\DeferrableProvider' => $vendorDir . '/illuminate/contracts/Support/DeferrableProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\DeferringDisplayableValue' => $vendorDir . '/illuminate/contracts/Support/DeferringDisplayableValue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Htmlable' => $vendorDir . '/illuminate/contracts/Support/Htmlable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Jsonable' => $vendorDir . '/illuminate/contracts/Support/Jsonable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\MessageBag' => $vendorDir . '/illuminate/contracts/Support/MessageBag.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\MessageProvider' => $vendorDir . '/illuminate/contracts/Support/MessageProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Renderable' => $vendorDir . '/illuminate/contracts/Support/Renderable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Responsable' => $vendorDir . '/illuminate/contracts/Support/Responsable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\ValidatedData' => $vendorDir . '/illuminate/contracts/Support/ValidatedData.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\HasLocalePreference' => $vendorDir . '/illuminate/contracts/Translation/HasLocalePreference.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\Loader' => $vendorDir . '/illuminate/contracts/Translation/Loader.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\Translator' => $vendorDir . '/illuminate/contracts/Translation/Translator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\DataAwareRule' => $vendorDir . '/illuminate/contracts/Validation/DataAwareRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Factory' => $vendorDir . '/illuminate/contracts/Validation/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ImplicitRule' => $vendorDir . '/illuminate/contracts/Validation/ImplicitRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\InvokableRule' => $vendorDir . '/illuminate/contracts/Validation/InvokableRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Rule' => $vendorDir . '/illuminate/contracts/Validation/Rule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\UncompromisedVerifier' => $vendorDir . '/illuminate/contracts/Validation/UncompromisedVerifier.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidatesWhenResolved' => $vendorDir . '/illuminate/contracts/Validation/ValidatesWhenResolved.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidationRule' => $vendorDir . '/illuminate/contracts/Validation/ValidationRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Validator' => $vendorDir . '/illuminate/contracts/Validation/Validator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidatorAwareRule' => $vendorDir . '/illuminate/contracts/Validation/ValidatorAwareRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\Engine' => $vendorDir . '/illuminate/contracts/View/Engine.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\Factory' => $vendorDir . '/illuminate/contracts/View/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\View' => $vendorDir . '/illuminate/contracts/View/View.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\ViewCompilationException' => $vendorDir . '/illuminate/contracts/View/ViewCompilationException.php', + 'ECSPrefix202307\\Nette\\ArgumentOutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\DeprecatedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\DirectoryNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\FileNotFoundException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\HtmlStringable' => $vendorDir . '/nette/utils/src/HtmlStringable.php', + 'ECSPrefix202307\\Nette\\IOException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\InvalidArgumentException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\InvalidStateException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\Iterators\\CachingIterator' => $vendorDir . '/nette/utils/src/Iterators/CachingIterator.php', + 'ECSPrefix202307\\Nette\\Iterators\\Mapper' => $vendorDir . '/nette/utils/src/Iterators/Mapper.php', + 'ECSPrefix202307\\Nette\\Localization\\ITranslator' => $vendorDir . '/nette/utils/src/compatibility.php', + 'ECSPrefix202307\\Nette\\Localization\\Translator' => $vendorDir . '/nette/utils/src/Translator.php', + 'ECSPrefix202307\\Nette\\MemberAccessException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\NotImplementedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\NotSupportedException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\OutOfRangeException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\SmartObject' => $vendorDir . '/nette/utils/src/SmartObject.php', + 'ECSPrefix202307\\Nette\\StaticClass' => $vendorDir . '/nette/utils/src/StaticClass.php', + 'ECSPrefix202307\\Nette\\UnexpectedValueException' => $vendorDir . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\ArrayHash' => $vendorDir . '/nette/utils/src/Utils/ArrayHash.php', + 'ECSPrefix202307\\Nette\\Utils\\ArrayList' => $vendorDir . '/nette/utils/src/Utils/ArrayList.php', + 'ECSPrefix202307\\Nette\\Utils\\Arrays' => $vendorDir . '/nette/utils/src/Utils/Arrays.php', + 'ECSPrefix202307\\Nette\\Utils\\AssertionException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Callback' => $vendorDir . '/nette/utils/src/Utils/Callback.php', + 'ECSPrefix202307\\Nette\\Utils\\DateTime' => $vendorDir . '/nette/utils/src/Utils/DateTime.php', + 'ECSPrefix202307\\Nette\\Utils\\FileSystem' => $vendorDir . '/nette/utils/src/Utils/FileSystem.php', + 'ECSPrefix202307\\Nette\\Utils\\Floats' => $vendorDir . '/nette/utils/src/Utils/Floats.php', + 'ECSPrefix202307\\Nette\\Utils\\Helpers' => $vendorDir . '/nette/utils/src/Utils/Helpers.php', + 'ECSPrefix202307\\Nette\\Utils\\Html' => $vendorDir . '/nette/utils/src/Utils/Html.php', + 'ECSPrefix202307\\Nette\\Utils\\IHtmlString' => $vendorDir . '/nette/utils/src/compatibility.php', + 'ECSPrefix202307\\Nette\\Utils\\Image' => $vendorDir . '/nette/utils/src/Utils/Image.php', + 'ECSPrefix202307\\Nette\\Utils\\ImageException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Json' => $vendorDir . '/nette/utils/src/Utils/Json.php', + 'ECSPrefix202307\\Nette\\Utils\\JsonException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\ObjectHelpers' => $vendorDir . '/nette/utils/src/Utils/ObjectHelpers.php', + 'ECSPrefix202307\\Nette\\Utils\\ObjectMixin' => $vendorDir . '/nette/utils/src/Utils/ObjectMixin.php', + 'ECSPrefix202307\\Nette\\Utils\\Paginator' => $vendorDir . '/nette/utils/src/Utils/Paginator.php', + 'ECSPrefix202307\\Nette\\Utils\\Random' => $vendorDir . '/nette/utils/src/Utils/Random.php', + 'ECSPrefix202307\\Nette\\Utils\\Reflection' => $vendorDir . '/nette/utils/src/Utils/Reflection.php', + 'ECSPrefix202307\\Nette\\Utils\\RegexpException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Strings' => $vendorDir . '/nette/utils/src/Utils/Strings.php', + 'ECSPrefix202307\\Nette\\Utils\\Type' => $vendorDir . '/nette/utils/src/Utils/Type.php', + 'ECSPrefix202307\\Nette\\Utils\\UnknownImageFileException' => $vendorDir . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Validators' => $vendorDir . '/nette/utils/src/Utils/Validators.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheException' => $vendorDir . '/psr/cache/src/CacheException.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheItemInterface' => $vendorDir . '/psr/cache/src/CacheItemInterface.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheItemPoolInterface' => $vendorDir . '/psr/cache/src/CacheItemPoolInterface.php', + 'ECSPrefix202307\\Psr\\Cache\\InvalidArgumentException' => $vendorDir . '/psr/cache/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Psr\\Container\\ContainerExceptionInterface' => $vendorDir . '/psr/container/src/ContainerExceptionInterface.php', + 'ECSPrefix202307\\Psr\\Container\\ContainerInterface' => $vendorDir . '/psr/container/src/ContainerInterface.php', + 'ECSPrefix202307\\Psr\\Container\\NotFoundExceptionInterface' => $vendorDir . '/psr/container/src/NotFoundExceptionInterface.php', + 'ECSPrefix202307\\Psr\\Log\\AbstractLogger' => $vendorDir . '/psr/log/src/AbstractLogger.php', + 'ECSPrefix202307\\Psr\\Log\\InvalidArgumentException' => $vendorDir . '/psr/log/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Psr\\Log\\LogLevel' => $vendorDir . '/psr/log/src/LogLevel.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerAwareInterface' => $vendorDir . '/psr/log/src/LoggerAwareInterface.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerAwareTrait' => $vendorDir . '/psr/log/src/LoggerAwareTrait.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerInterface' => $vendorDir . '/psr/log/src/LoggerInterface.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerTrait' => $vendorDir . '/psr/log/src/LoggerTrait.php', + 'ECSPrefix202307\\Psr\\Log\\NullLogger' => $vendorDir . '/psr/log/src/NullLogger.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\CacheException' => $vendorDir . '/psr/simple-cache/src/CacheException.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\CacheInterface' => $vendorDir . '/psr/simple-cache/src/CacheInterface.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\InvalidArgumentException' => $vendorDir . '/psr/simple-cache/src/InvalidArgumentException.php', + 'ECSPrefix202307\\React\\Cache\\ArrayCache' => $vendorDir . '/react/cache/src/ArrayCache.php', + 'ECSPrefix202307\\React\\Cache\\CacheInterface' => $vendorDir . '/react/cache/src/CacheInterface.php', + 'ECSPrefix202307\\React\\ChildProcess\\Process' => $vendorDir . '/react/child-process/src/Process.php', + 'ECSPrefix202307\\React\\Dns\\BadServerException' => $vendorDir . '/react/dns/src/BadServerException.php', + 'ECSPrefix202307\\React\\Dns\\Config\\Config' => $vendorDir . '/react/dns/src/Config/Config.php', + 'ECSPrefix202307\\React\\Dns\\Config\\HostsFile' => $vendorDir . '/react/dns/src/Config/HostsFile.php', + 'ECSPrefix202307\\React\\Dns\\Model\\Message' => $vendorDir . '/react/dns/src/Model/Message.php', + 'ECSPrefix202307\\React\\Dns\\Model\\Record' => $vendorDir . '/react/dns/src/Model/Record.php', + 'ECSPrefix202307\\React\\Dns\\Protocol\\BinaryDumper' => $vendorDir . '/react/dns/src/Protocol/BinaryDumper.php', + 'ECSPrefix202307\\React\\Dns\\Protocol\\Parser' => $vendorDir . '/react/dns/src/Protocol/Parser.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CachingExecutor' => $vendorDir . '/react/dns/src/Query/CachingExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CancellationException' => $vendorDir . '/react/dns/src/Query/CancellationException.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CoopExecutor' => $vendorDir . '/react/dns/src/Query/CoopExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\ExecutorInterface' => $vendorDir . '/react/dns/src/Query/ExecutorInterface.php', + 'ECSPrefix202307\\React\\Dns\\Query\\FallbackExecutor' => $vendorDir . '/react/dns/src/Query/FallbackExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\HostsFileExecutor' => $vendorDir . '/react/dns/src/Query/HostsFileExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\Query' => $vendorDir . '/react/dns/src/Query/Query.php', + 'ECSPrefix202307\\React\\Dns\\Query\\RetryExecutor' => $vendorDir . '/react/dns/src/Query/RetryExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\SelectiveTransportExecutor' => $vendorDir . '/react/dns/src/Query/SelectiveTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TcpTransportExecutor' => $vendorDir . '/react/dns/src/Query/TcpTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TimeoutException' => $vendorDir . '/react/dns/src/Query/TimeoutException.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TimeoutExecutor' => $vendorDir . '/react/dns/src/Query/TimeoutExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\UdpTransportExecutor' => $vendorDir . '/react/dns/src/Query/UdpTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\RecordNotFoundException' => $vendorDir . '/react/dns/src/RecordNotFoundException.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\Factory' => $vendorDir . '/react/dns/src/Resolver/Factory.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\Resolver' => $vendorDir . '/react/dns/src/Resolver/Resolver.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\ResolverInterface' => $vendorDir . '/react/dns/src/Resolver/ResolverInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtEvLoop' => $vendorDir . '/react/event-loop/src/ExtEvLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtEventLoop' => $vendorDir . '/react/event-loop/src/ExtEventLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtLibevLoop' => $vendorDir . '/react/event-loop/src/ExtLibevLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtLibeventLoop' => $vendorDir . '/react/event-loop/src/ExtLibeventLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtUvLoop' => $vendorDir . '/react/event-loop/src/ExtUvLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\Factory' => $vendorDir . '/react/event-loop/src/Factory.php', + 'ECSPrefix202307\\React\\EventLoop\\Loop' => $vendorDir . '/react/event-loop/src/Loop.php', + 'ECSPrefix202307\\React\\EventLoop\\LoopInterface' => $vendorDir . '/react/event-loop/src/LoopInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\SignalsHandler' => $vendorDir . '/react/event-loop/src/SignalsHandler.php', + 'ECSPrefix202307\\React\\EventLoop\\StreamSelectLoop' => $vendorDir . '/react/event-loop/src/StreamSelectLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\Tick\\FutureTickQueue' => $vendorDir . '/react/event-loop/src/Tick/FutureTickQueue.php', + 'ECSPrefix202307\\React\\EventLoop\\TimerInterface' => $vendorDir . '/react/event-loop/src/TimerInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\Timer\\Timer' => $vendorDir . '/react/event-loop/src/Timer/Timer.php', + 'ECSPrefix202307\\React\\EventLoop\\Timer\\Timers' => $vendorDir . '/react/event-loop/src/Timer/Timers.php', + 'ECSPrefix202307\\React\\Promise\\Deferred' => $vendorDir . '/react/promise/src/Deferred.php', + 'ECSPrefix202307\\React\\Promise\\Exception\\CompositeException' => $vendorDir . '/react/promise/src/Exception/CompositeException.php', + 'ECSPrefix202307\\React\\Promise\\Exception\\LengthException' => $vendorDir . '/react/promise/src/Exception/LengthException.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\CancellationQueue' => $vendorDir . '/react/promise/src/Internal/CancellationQueue.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\FulfilledPromise' => $vendorDir . '/react/promise/src/Internal/FulfilledPromise.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\RejectedPromise' => $vendorDir . '/react/promise/src/Internal/RejectedPromise.php', + 'ECSPrefix202307\\React\\Promise\\Promise' => $vendorDir . '/react/promise/src/Promise.php', + 'ECSPrefix202307\\React\\Promise\\PromiseInterface' => $vendorDir . '/react/promise/src/PromiseInterface.php', + 'ECSPrefix202307\\React\\Socket\\Connection' => $vendorDir . '/react/socket/src/Connection.php', + 'ECSPrefix202307\\React\\Socket\\ConnectionInterface' => $vendorDir . '/react/socket/src/ConnectionInterface.php', + 'ECSPrefix202307\\React\\Socket\\Connector' => $vendorDir . '/react/socket/src/Connector.php', + 'ECSPrefix202307\\React\\Socket\\ConnectorInterface' => $vendorDir . '/react/socket/src/ConnectorInterface.php', + 'ECSPrefix202307\\React\\Socket\\DnsConnector' => $vendorDir . '/react/socket/src/DnsConnector.php', + 'ECSPrefix202307\\React\\Socket\\FdServer' => $vendorDir . '/react/socket/src/FdServer.php', + 'ECSPrefix202307\\React\\Socket\\FixedUriConnector' => $vendorDir . '/react/socket/src/FixedUriConnector.php', + 'ECSPrefix202307\\React\\Socket\\HappyEyeBallsConnectionBuilder' => $vendorDir . '/react/socket/src/HappyEyeBallsConnectionBuilder.php', + 'ECSPrefix202307\\React\\Socket\\HappyEyeBallsConnector' => $vendorDir . '/react/socket/src/HappyEyeBallsConnector.php', + 'ECSPrefix202307\\React\\Socket\\LimitingServer' => $vendorDir . '/react/socket/src/LimitingServer.php', + 'ECSPrefix202307\\React\\Socket\\SecureConnector' => $vendorDir . '/react/socket/src/SecureConnector.php', + 'ECSPrefix202307\\React\\Socket\\SecureServer' => $vendorDir . '/react/socket/src/SecureServer.php', + 'ECSPrefix202307\\React\\Socket\\Server' => $vendorDir . '/react/socket/src/Server.php', + 'ECSPrefix202307\\React\\Socket\\ServerInterface' => $vendorDir . '/react/socket/src/ServerInterface.php', + 'ECSPrefix202307\\React\\Socket\\SocketServer' => $vendorDir . '/react/socket/src/SocketServer.php', + 'ECSPrefix202307\\React\\Socket\\StreamEncryption' => $vendorDir . '/react/socket/src/StreamEncryption.php', + 'ECSPrefix202307\\React\\Socket\\TcpConnector' => $vendorDir . '/react/socket/src/TcpConnector.php', + 'ECSPrefix202307\\React\\Socket\\TcpServer' => $vendorDir . '/react/socket/src/TcpServer.php', + 'ECSPrefix202307\\React\\Socket\\TimeoutConnector' => $vendorDir . '/react/socket/src/TimeoutConnector.php', + 'ECSPrefix202307\\React\\Socket\\UnixConnector' => $vendorDir . '/react/socket/src/UnixConnector.php', + 'ECSPrefix202307\\React\\Socket\\UnixServer' => $vendorDir . '/react/socket/src/UnixServer.php', + 'ECSPrefix202307\\React\\Stream\\CompositeStream' => $vendorDir . '/react/stream/src/CompositeStream.php', + 'ECSPrefix202307\\React\\Stream\\DuplexResourceStream' => $vendorDir . '/react/stream/src/DuplexResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\DuplexStreamInterface' => $vendorDir . '/react/stream/src/DuplexStreamInterface.php', + 'ECSPrefix202307\\React\\Stream\\ReadableResourceStream' => $vendorDir . '/react/stream/src/ReadableResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\ReadableStreamInterface' => $vendorDir . '/react/stream/src/ReadableStreamInterface.php', + 'ECSPrefix202307\\React\\Stream\\ThroughStream' => $vendorDir . '/react/stream/src/ThroughStream.php', + 'ECSPrefix202307\\React\\Stream\\Util' => $vendorDir . '/react/stream/src/Util.php', + 'ECSPrefix202307\\React\\Stream\\WritableResourceStream' => $vendorDir . '/react/stream/src/WritableResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\WritableStreamInterface' => $vendorDir . '/react/stream/src/WritableStreamInterface.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\ConfigurationException' => $vendorDir . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Exception' => $vendorDir . '/sebastian/diff/src/Exception/Exception.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\InvalidArgumentException' => $vendorDir . '/sebastian/diff/src/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => $vendorDir . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => $vendorDir . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => $vendorDir . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Application' => $vendorDir . '/symfony/console/Application.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Attribute\\AsCommand' => $vendorDir . '/symfony/console/Attribute/AsCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CI\\GithubActionReporter' => $vendorDir . '/symfony/console/CI/GithubActionReporter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Color' => $vendorDir . '/symfony/console/Color.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\CommandLoaderInterface' => $vendorDir . '/symfony/console/CommandLoader/CommandLoaderInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\ContainerCommandLoader' => $vendorDir . '/symfony/console/CommandLoader/ContainerCommandLoader.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\FactoryCommandLoader' => $vendorDir . '/symfony/console/CommandLoader/FactoryCommandLoader.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\Command' => $vendorDir . '/symfony/console/Command/Command.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\CompleteCommand' => $vendorDir . '/symfony/console/Command/CompleteCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\DumpCompletionCommand' => $vendorDir . '/symfony/console/Command/DumpCompletionCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\HelpCommand' => $vendorDir . '/symfony/console/Command/HelpCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\LazyCommand' => $vendorDir . '/symfony/console/Command/LazyCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\ListCommand' => $vendorDir . '/symfony/console/Command/ListCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\LockableTrait' => $vendorDir . '/symfony/console/Command/LockableTrait.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\SignalableCommandInterface' => $vendorDir . '/symfony/console/Command/SignalableCommandInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\CompletionInput' => $vendorDir . '/symfony/console/Completion/CompletionInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\CompletionSuggestions' => $vendorDir . '/symfony/console/Completion/CompletionSuggestions.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\BashCompletionOutput' => $vendorDir . '/symfony/console/Completion/Output/BashCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\CompletionOutputInterface' => $vendorDir . '/symfony/console/Completion/Output/CompletionOutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\FishCompletionOutput' => $vendorDir . '/symfony/console/Completion/Output/FishCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\ZshCompletionOutput' => $vendorDir . '/symfony/console/Completion/Output/ZshCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Suggestion' => $vendorDir . '/symfony/console/Completion/Suggestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\ConsoleEvents' => $vendorDir . '/symfony/console/ConsoleEvents.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Cursor' => $vendorDir . '/symfony/console/Cursor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\DependencyInjection\\AddConsoleCommandPass' => $vendorDir . '/symfony/console/DependencyInjection/AddConsoleCommandPass.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => $vendorDir . '/symfony/console/Descriptor/ApplicationDescription.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\Descriptor' => $vendorDir . '/symfony/console/Descriptor/Descriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => $vendorDir . '/symfony/console/Descriptor/DescriptorInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => $vendorDir . '/symfony/console/Descriptor/JsonDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => $vendorDir . '/symfony/console/Descriptor/MarkdownDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\ReStructuredTextDescriptor' => $vendorDir . '/symfony/console/Descriptor/ReStructuredTextDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => $vendorDir . '/symfony/console/Descriptor/TextDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => $vendorDir . '/symfony/console/Descriptor/XmlDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\EventListener\\ErrorListener' => $vendorDir . '/symfony/console/EventListener/ErrorListener.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => $vendorDir . '/symfony/console/Event/ConsoleCommandEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleErrorEvent' => $vendorDir . '/symfony/console/Event/ConsoleErrorEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleEvent' => $vendorDir . '/symfony/console/Event/ConsoleEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleSignalEvent' => $vendorDir . '/symfony/console/Event/ConsoleSignalEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => $vendorDir . '/symfony/console/Event/ConsoleTerminateEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => $vendorDir . '/symfony/console/Exception/CommandNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/console/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/console/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\InvalidOptionException' => $vendorDir . '/symfony/console/Exception/InvalidOptionException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\LogicException' => $vendorDir . '/symfony/console/Exception/LogicException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\MissingInputException' => $vendorDir . '/symfony/console/Exception/MissingInputException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\NamespaceNotFoundException' => $vendorDir . '/symfony/console/Exception/NamespaceNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\RuntimeException' => $vendorDir . '/symfony/console/Exception/RuntimeException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\NullOutputFormatter' => $vendorDir . '/symfony/console/Formatter/NullOutputFormatter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\NullOutputFormatterStyle' => $vendorDir . '/symfony/console/Formatter/NullOutputFormatterStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatter' => $vendorDir . '/symfony/console/Formatter/OutputFormatter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => $vendorDir . '/symfony/console/Formatter/OutputFormatterStyleStack.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\WrappableOutputFormatterInterface' => $vendorDir . '/symfony/console/Formatter/WrappableOutputFormatterInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => $vendorDir . '/symfony/console/Helper/DebugFormatterHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\DescriptorHelper' => $vendorDir . '/symfony/console/Helper/DescriptorHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Dumper' => $vendorDir . '/symfony/console/Helper/Dumper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\FormatterHelper' => $vendorDir . '/symfony/console/Helper/FormatterHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Helper' => $vendorDir . '/symfony/console/Helper/Helper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\HelperInterface' => $vendorDir . '/symfony/console/Helper/HelperInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\HelperSet' => $vendorDir . '/symfony/console/Helper/HelperSet.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\InputAwareHelper' => $vendorDir . '/symfony/console/Helper/InputAwareHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\OutputWrapper' => $vendorDir . '/symfony/console/Helper/OutputWrapper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProcessHelper' => $vendorDir . '/symfony/console/Helper/ProcessHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProgressBar' => $vendorDir . '/symfony/console/Helper/ProgressBar.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProgressIndicator' => $vendorDir . '/symfony/console/Helper/ProgressIndicator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\QuestionHelper' => $vendorDir . '/symfony/console/Helper/QuestionHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => $vendorDir . '/symfony/console/Helper/SymfonyQuestionHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Table' => $vendorDir . '/symfony/console/Helper/Table.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableCell' => $vendorDir . '/symfony/console/Helper/TableCell.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableCellStyle' => $vendorDir . '/symfony/console/Helper/TableCellStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableRows' => $vendorDir . '/symfony/console/Helper/TableRows.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableSeparator' => $vendorDir . '/symfony/console/Helper/TableSeparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableStyle' => $vendorDir . '/symfony/console/Helper/TableStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\ArgvInput' => $vendorDir . '/symfony/console/Input/ArgvInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\ArrayInput' => $vendorDir . '/symfony/console/Input/ArrayInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\Input' => $vendorDir . '/symfony/console/Input/Input.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputArgument' => $vendorDir . '/symfony/console/Input/InputArgument.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputAwareInterface' => $vendorDir . '/symfony/console/Input/InputAwareInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputDefinition' => $vendorDir . '/symfony/console/Input/InputDefinition.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputInterface' => $vendorDir . '/symfony/console/Input/InputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputOption' => $vendorDir . '/symfony/console/Input/InputOption.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\StreamableInputInterface' => $vendorDir . '/symfony/console/Input/StreamableInputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\StringInput' => $vendorDir . '/symfony/console/Input/StringInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Logger\\ConsoleLogger' => $vendorDir . '/symfony/console/Logger/ConsoleLogger.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\AnsiColorMode' => $vendorDir . '/symfony/console/Output/AnsiColorMode.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\BufferedOutput' => $vendorDir . '/symfony/console/Output/BufferedOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleOutput' => $vendorDir . '/symfony/console/Output/ConsoleOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => $vendorDir . '/symfony/console/Output/ConsoleOutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleSectionOutput' => $vendorDir . '/symfony/console/Output/ConsoleSectionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\NullOutput' => $vendorDir . '/symfony/console/Output/NullOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\Output' => $vendorDir . '/symfony/console/Output/Output.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\OutputInterface' => $vendorDir . '/symfony/console/Output/OutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\StreamOutput' => $vendorDir . '/symfony/console/Output/StreamOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\TrimmedBufferOutput' => $vendorDir . '/symfony/console/Output/TrimmedBufferOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\ChoiceQuestion' => $vendorDir . '/symfony/console/Question/ChoiceQuestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => $vendorDir . '/symfony/console/Question/ConfirmationQuestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\Question' => $vendorDir . '/symfony/console/Question/Question.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\SignalRegistry\\SignalRegistry' => $vendorDir . '/symfony/console/SignalRegistry/SignalRegistry.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\SingleCommandApplication' => $vendorDir . '/symfony/console/SingleCommandApplication.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\OutputStyle' => $vendorDir . '/symfony/console/Style/OutputStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\StyleInterface' => $vendorDir . '/symfony/console/Style/StyleInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\SymfonyStyle' => $vendorDir . '/symfony/console/Style/SymfonyStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Terminal' => $vendorDir . '/symfony/console/Terminal.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\ApplicationTester' => $vendorDir . '/symfony/console/Tester/ApplicationTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\CommandCompletionTester' => $vendorDir . '/symfony/console/Tester/CommandCompletionTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\CommandTester' => $vendorDir . '/symfony/console/Tester/CommandTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\Constraint\\CommandIsSuccessful' => $vendorDir . '/symfony/console/Tester/Constraint/CommandIsSuccessful.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\TesterTrait' => $vendorDir . '/symfony/console/Tester/TesterTrait.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => $vendorDir . '/symfony/filesystem/Exception/FileNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\IOException' => $vendorDir . '/symfony/filesystem/Exception/IOException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => $vendorDir . '/symfony/filesystem/Exception/IOExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/filesystem/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\RuntimeException' => $vendorDir . '/symfony/filesystem/Exception/RuntimeException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Filesystem' => $vendorDir . '/symfony/filesystem/Filesystem.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Path' => $vendorDir . '/symfony/filesystem/Path.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\Comparator' => $vendorDir . '/symfony/finder/Comparator/Comparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\DateComparator' => $vendorDir . '/symfony/finder/Comparator/DateComparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\NumberComparator' => $vendorDir . '/symfony/finder/Comparator/NumberComparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => $vendorDir . '/symfony/finder/Exception/AccessDeniedException.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Exception\\DirectoryNotFoundException' => $vendorDir . '/symfony/finder/Exception/DirectoryNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Finder' => $vendorDir . '/symfony/finder/Finder.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Gitignore' => $vendorDir . '/symfony/finder/Gitignore.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Glob' => $vendorDir . '/symfony/finder/Glob.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => $vendorDir . '/symfony/finder/Iterator/CustomFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DateRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/DepthRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => $vendorDir . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FileTypeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilecontentFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => $vendorDir . '/symfony/finder/Iterator/FilenameFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\LazyIterator' => $vendorDir . '/symfony/finder/Iterator/LazyIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => $vendorDir . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => $vendorDir . '/symfony/finder/Iterator/PathFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => $vendorDir . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => $vendorDir . '/symfony/finder/Iterator/SizeRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\SortableIterator' => $vendorDir . '/symfony/finder/Iterator/SortableIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\VcsIgnoredFilterIterator' => $vendorDir . '/symfony/finder/Iterator/VcsIgnoredFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\SplFileInfo' => $vendorDir . '/symfony/finder/SplFileInfo.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Debug\\OptionsResolverIntrospector' => $vendorDir . '/symfony/options-resolver/Debug/OptionsResolverIntrospector.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\AccessException' => $vendorDir . '/symfony/options-resolver/Exception/AccessException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/options-resolver/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\InvalidArgumentException' => $vendorDir . '/symfony/options-resolver/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/InvalidOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\MissingOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/MissingOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\NoConfigurationException' => $vendorDir . '/symfony/options-resolver/Exception/NoConfigurationException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\NoSuchOptionException' => $vendorDir . '/symfony/options-resolver/Exception/NoSuchOptionException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\OptionDefinitionException' => $vendorDir . '/symfony/options-resolver/Exception/OptionDefinitionException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException' => $vendorDir . '/symfony/options-resolver/Exception/UndefinedOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\OptionConfigurator' => $vendorDir . '/symfony/options-resolver/OptionConfigurator.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Options' => $vendorDir . '/symfony/options-resolver/Options.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\OptionsResolver' => $vendorDir . '/symfony/options-resolver/OptionsResolver.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\Attribute\\Required' => $vendorDir . '/symfony/service-contracts/Attribute/Required.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\Attribute\\SubscribedService' => $vendorDir . '/symfony/service-contracts/Attribute/SubscribedService.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ResetInterface' => $vendorDir . '/symfony/service-contracts/ResetInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceLocatorTrait' => $vendorDir . '/symfony/service-contracts/ServiceLocatorTrait.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceProviderInterface' => $vendorDir . '/symfony/service-contracts/ServiceProviderInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => $vendorDir . '/symfony/service-contracts/ServiceSubscriberTrait.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\CommandLine\\WorkerCommandLineFactory' => $vendorDir . '/symplify/easy-parallel/src/CommandLine/WorkerCommandLineFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Contract\\SerializableInterface' => $vendorDir . '/symplify/easy-parallel/src/Contract/SerializableInterface.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\CpuCoreCountProvider' => $vendorDir . '/symplify/easy-parallel/src/CpuCoreCountProvider.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\Action' => $vendorDir . '/symplify/easy-parallel/src/Enum/Action.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\Content' => $vendorDir . '/symplify/easy-parallel/src/Enum/Content.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\ReactCommand' => $vendorDir . '/symplify/easy-parallel/src/Enum/ReactCommand.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\ReactEvent' => $vendorDir . '/symplify/easy-parallel/src/Enum/ReactEvent.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Exception\\ParallelShouldNotHappenException' => $vendorDir . '/symplify/easy-parallel/src/Exception/ParallelShouldNotHappenException.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\FileSystem\\FilePathNormalizer' => $vendorDir . '/symplify/easy-parallel/src/FileSystem/FilePathNormalizer.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Reflection\\CommandFromReflectionFactory' => $vendorDir . '/symplify/easy-parallel/src/Reflection/CommandFromReflectionFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ScheduleFactory' => $vendorDir . '/symplify/easy-parallel/src/ScheduleFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\EasyParallelConfig' => $vendorDir . '/symplify/easy-parallel/src/ValueObject/EasyParallelConfig.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\ParallelProcess' => $vendorDir . '/symplify/easy-parallel/src/ValueObject/ParallelProcess.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\ProcessPool' => $vendorDir . '/symplify/easy-parallel/src/ValueObject/ProcessPool.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\Schedule' => $vendorDir . '/symplify/easy-parallel/src/ValueObject/Schedule.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\Category\\CategoryInfererInterface' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Contract/Category/CategoryInfererInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\CodeSampleInterface' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Contract/CodeSampleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\ConfigurableRuleInterface' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Contract/ConfigurableRuleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\DocumentedRuleInterface' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Contract/DocumentedRuleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\RuleCodeSamplePrinterInterface' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Contract/RuleCodeSamplePrinterInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Exception\\PoorDocumentationException' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Exception/PoorDocumentationException.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Exception\\ShouldNotHappenException' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/Exception/ShouldNotHappenException.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\AbstractCodeSample' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/AbstractCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\CodeSample' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/CodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ComposerJsonAwareCodeSample' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ComposerJsonAwareCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ConfiguredCodeSample' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ConfiguredCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ExtraFileCodeSample' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ExtraFileCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\RuleDefinition' => $vendorDir . '/symplify/rule-doc-generator-contracts/src/ValueObject/RuleDefinition.php', + 'ECSPrefix202307\\Webmozart\\Assert\\Assert' => $vendorDir . '/webmozart/assert/src/Assert.php', + 'ECSPrefix202307\\Webmozart\\Assert\\InvalidArgumentException' => $vendorDir . '/webmozart/assert/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Webmozart\\Assert\\Mixin' => $vendorDir . '/webmozart/assert/src/Mixin.php', + 'PhpCsFixer\\AbstractDoctrineAnnotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php', + 'PhpCsFixer\\AbstractFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractFixer.php', + 'PhpCsFixer\\AbstractFopenFlagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php', + 'PhpCsFixer\\AbstractFunctionReferenceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php', + 'PhpCsFixer\\AbstractNoUselessElseFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php', + 'PhpCsFixer\\AbstractPhpdocToTypeDeclarationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php', + 'PhpCsFixer\\AbstractPhpdocTypesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php', + 'PhpCsFixer\\AbstractProxyFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php', + 'PhpCsFixer\\Cache\\Cache' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/Cache.php', + 'PhpCsFixer\\Cache\\CacheInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php', + 'PhpCsFixer\\Cache\\CacheManagerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php', + 'PhpCsFixer\\Cache\\Directory' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/Directory.php', + 'PhpCsFixer\\Cache\\DirectoryInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php', + 'PhpCsFixer\\Cache\\FileCacheManager' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php', + 'PhpCsFixer\\Cache\\FileHandler' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php', + 'PhpCsFixer\\Cache\\FileHandlerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php', + 'PhpCsFixer\\Cache\\NullCacheManager' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php', + 'PhpCsFixer\\Cache\\Signature' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/Signature.php', + 'PhpCsFixer\\Cache\\SignatureInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php', + 'PhpCsFixer\\Config' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Config.php', + 'PhpCsFixer\\ConfigInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ConfigInterface.php', + 'PhpCsFixer\\ConfigurationException\\InvalidConfigurationException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\InvalidFixerConfigurationException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\InvalidForEnvFixerConfigurationException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\RequiredFixerConfigurationException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php', + 'PhpCsFixer\\Console\\Application' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Application.php', + 'PhpCsFixer\\Console\\Command\\DescribeCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php', + 'PhpCsFixer\\Console\\Command\\DescribeNameNotFoundException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php', + 'PhpCsFixer\\Console\\Command\\DocumentationCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php', + 'PhpCsFixer\\Console\\Command\\FixCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php', + 'PhpCsFixer\\Console\\Command\\FixCommandExitStatusCalculator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php', + 'PhpCsFixer\\Console\\Command\\HelpCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php', + 'PhpCsFixer\\Console\\Command\\ListFilesCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php', + 'PhpCsFixer\\Console\\Command\\ListSetsCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php', + 'PhpCsFixer\\Console\\Command\\SelfUpdateCommand' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php', + 'PhpCsFixer\\Console\\ConfigurationResolver' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php', + 'PhpCsFixer\\Console\\Output\\ErrorOutput' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php', + 'PhpCsFixer\\Console\\Output\\OutputContext' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php', + 'PhpCsFixer\\Console\\Output\\Progress\\DotsOutput' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php', + 'PhpCsFixer\\Console\\Output\\Progress\\NullOutput' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputFactory' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputType' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\CheckstyleReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\GitlabReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\JsonReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\JunitReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReportSummary' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReporterFactory' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReporterInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\TextReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\XmlReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\JsonReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReportSummary' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReporterFactory' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReporterInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\TextReporter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php', + 'PhpCsFixer\\Console\\SelfUpdate\\GithubClient' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php', + 'PhpCsFixer\\Console\\SelfUpdate\\GithubClientInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php', + 'PhpCsFixer\\Console\\SelfUpdate\\NewVersionChecker' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php', + 'PhpCsFixer\\Console\\SelfUpdate\\NewVersionCheckerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php', + 'PhpCsFixer\\Console\\WarningsDetector' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php', + 'PhpCsFixer\\Differ\\DiffConsoleFormatter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php', + 'PhpCsFixer\\Differ\\DifferInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php', + 'PhpCsFixer\\Differ\\FullDiffer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php', + 'PhpCsFixer\\Differ\\NullDiffer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php', + 'PhpCsFixer\\Differ\\UnifiedDiffer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php', + 'PhpCsFixer\\DocBlock\\Annotation' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php', + 'PhpCsFixer\\DocBlock\\DocBlock' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php', + 'PhpCsFixer\\DocBlock\\Line' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/Line.php', + 'PhpCsFixer\\DocBlock\\ShortDescription' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php', + 'PhpCsFixer\\DocBlock\\Tag' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php', + 'PhpCsFixer\\DocBlock\\TagComparator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php', + 'PhpCsFixer\\DocBlock\\TypeExpression' => $vendorDir . '/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php', + 'PhpCsFixer\\Doctrine\\Annotation\\Token' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php', + 'PhpCsFixer\\Doctrine\\Annotation\\Tokens' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php', + 'PhpCsFixer\\Documentation\\DocumentationLocator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php', + 'PhpCsFixer\\Documentation\\FixerDocumentGenerator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php', + 'PhpCsFixer\\Documentation\\ListDocumentGenerator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Documentation/ListDocumentGenerator.php', + 'PhpCsFixer\\Documentation\\RstUtils' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php', + 'PhpCsFixer\\Documentation\\RuleSetDocumentationGenerator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Documentation/RuleSetDocumentationGenerator.php', + 'PhpCsFixer\\Error\\Error' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Error/Error.php', + 'PhpCsFixer\\Error\\ErrorsManager' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php', + 'PhpCsFixer\\FileReader' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FileReader.php', + 'PhpCsFixer\\FileRemoval' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FileRemoval.php', + 'PhpCsFixer\\Finder' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Finder.php', + 'PhpCsFixer\\FixerConfiguration\\AliasedFixerOption' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\AliasedFixerOptionBuilder' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php', + 'PhpCsFixer\\FixerConfiguration\\AllowedValueSubset' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php', + 'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOption' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOptionInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php', + 'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolver' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php', + 'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOption' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOptionBuilder' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOptionInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php', + 'PhpCsFixer\\FixerConfiguration\\InvalidOptionsForEnvException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php', + 'PhpCsFixer\\FixerDefinition\\CodeSample' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php', + 'PhpCsFixer\\FixerDefinition\\CodeSampleInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSample' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php', + 'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSampleInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\FixerDefinition' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php', + 'PhpCsFixer\\FixerDefinition\\FixerDefinitionInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSample' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSampleInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecification' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificationInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php', + 'PhpCsFixer\\FixerFactory' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerFactory.php', + 'PhpCsFixer\\FixerFileProcessedEvent' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php', + 'PhpCsFixer\\FixerNameValidator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/FixerNameValidator.php', + 'PhpCsFixer\\Fixer\\AbstractIncrementOperatorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php', + 'PhpCsFixer\\Fixer\\AbstractPhpUnitFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\ArrayPushFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\BacktickToShellExecFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\EregToPregFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\MbStrFunctionsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\ModernizeStrposFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoAliasFunctionsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoAliasLanguageConstructCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoMixedEchoPrintFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\PowToExponentiationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\RandomApiMigrationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\SetTypeToCastFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\ArraySyntaxFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoMultilineWhitespaceAroundDoubleArrowFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoTrailingCommaInSinglelineArrayFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoWhitespaceBeforeCommaInArrayFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NormalizeIndexBraceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\TrimArraySpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\WhitespaceAfterCommaInArrayFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\YieldFromArrayToYieldsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\BracesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\CurlyBracesPositionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\EncodingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NoMultipleStatementsPerLineFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NoTrailingCommaInSinglelineFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NonPrintableCharacterFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\OctalNotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\PsrAutoloadingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\SingleLineEmptyBodyFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\ClassReferenceNameCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\ConstantCaseFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\IntegerLiteralCaseFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\LowercaseKeywordsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\LowercaseStaticReferenceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\MagicConstantCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\MagicMethodCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\NativeFunctionCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\NativeFunctionTypeDeclarationCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\CastSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\LowercaseCastFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\ModernizeTypesCastingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\NoShortBoolCastFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\NoUnsetCastFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\ShortScalarCastFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ClassAttributesSeparationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ClassDefinitionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalClassFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalInternalClassFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalPublicMethodForAbstractClassFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoBlankLinesAfterClassOpeningFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoNullPropertyInitializationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoPhp4ConstructorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoUnneededFinalMethodFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedClassElementsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedInterfacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTraitsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTypesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ProtectedToPrivateFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SelfAccessorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SelfStaticAccessorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SingleClassElementPerStatementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SingleTraitInsertPerStatementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\VisibilityRequiredFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php', + 'PhpCsFixer\\Fixer\\ClassUsage\\DateTimeImmutableFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\CommentToPhpdocFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\HeaderCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\MultilineCommentOpeningClosingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\NoEmptyCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\NoTrailingWhitespaceInCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentSpacingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentStyleFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php', + 'PhpCsFixer\\Fixer\\ConfigurableFixerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php', + 'PhpCsFixer\\Fixer\\ConstantNotation\\NativeConstantInvocationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ControlStructureBracesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ControlStructureContinuationPositionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ElseifFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\EmptyLoopBodyFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\EmptyLoopConditionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\IncludeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoAlternativeSyntaxFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoBreakCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoSuperfluousElseifFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoTrailingCommaInListCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededControlParenthesesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededCurlyBracesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUselessElseFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SimplifiedIfReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSemicolonToColonFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchContinueToBreakFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\TrailingCommaInMultilineFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\YodaStyleFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php', + 'PhpCsFixer\\Fixer\\DeprecatedFixerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationArrayAssignmentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationBracesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationIndentationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php', + 'PhpCsFixer\\Fixer\\FixerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\CombineNestedDirnameFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\DateTimeCreateFromFormatCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagOrderFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionDeclarationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionTypehintSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\ImplodeCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\LambdaNotUsedImportFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\MethodArgumentSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NativeFunctionInvocationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoSpacesAfterFunctionNameFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoTrailingCommaInSinglelineFunctionCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoUnreachableDefaultArgumentValueFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoUselessSprintfFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NullableTypeDeclarationForDefaultNullValueFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToParamTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToPropertyTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToReturnTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\RegularCallableCallFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\ReturnTypeDeclarationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\SingleLineThrowFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\StaticLambdaFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\UseArrowFunctionsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\VoidReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php', + 'PhpCsFixer\\Fixer\\Import\\FullyQualifiedStrictTypesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php', + 'PhpCsFixer\\Fixer\\Import\\GlobalNamespaceImportFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php', + 'PhpCsFixer\\Fixer\\Import\\GroupImportFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoLeadingImportSlashFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoUnneededImportAliasFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoUnusedImportsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php', + 'PhpCsFixer\\Fixer\\Import\\OrderedImportsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php', + 'PhpCsFixer\\Fixer\\Import\\SingleImportPerStatementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\Import\\SingleLineAfterImportsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php', + 'PhpCsFixer\\Fixer\\Indentation' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ClassKeywordRemoveFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveIssetsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveUnsetsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareEqualNormalizeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareParenthesesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DirConstantFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ErrorSuppressionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ExplicitIndirectVariableFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\FunctionToConstantFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\GetClassToClassKeywordFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\IsNullFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\NoUnsetOnPropertyFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\NullableTypeDeclarationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAfterConstructFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAroundConstructFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php', + 'PhpCsFixer\\Fixer\\ListNotation\\ListSyntaxFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLineAfterNamespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLinesBeforeNamespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\CleanNamespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\NoBlankLinesBeforeNamespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\NoLeadingNamespaceWhitespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\SingleBlankLineBeforeNamespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\Naming\\NoHomoglyphNamesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\AssignNullCoalescingToCoalesceEqualFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\BinaryOperatorSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\ConcatSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\IncrementStyleFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\LogicalOperatorsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NewWithBracesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoSpaceAroundDoubleColonFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoUselessConcatOperatorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoUselessNullsafeOperatorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSuccessorSpaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\ObjectOperatorWithoutWhitespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\OperatorLinebreakFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\StandardizeIncrementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\StandardizeNotEqualsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryOperatorSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryToElvisOperatorFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryToNullCoalescingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\UnaryOperatorSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\BlankLineAfterOpeningTagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\EchoTagSyntaxFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\FullOpeningTagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\LinebreakAfterOpeningTagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\NoClosingTagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitConstructFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderNameFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderReturnTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderStaticFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertInternalTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitExpectationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitFqcnAnnotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitInternalClassFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMethodCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockShortWillReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNamespacedFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNoExpectationAnnotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSetUpTearDownVisibilityFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSizeClassFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitStrictFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTargetVersion' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestAnnotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestCaseStaticMethodCallsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestClassRequiresCoversFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\AlignMultilineCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocAnnotationRemoveFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocTagRenameFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoBlankLinesAfterPhpdocFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoEmptyPhpdocFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoSuperfluousPhpdocTagsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAddMissingParamAnnotationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAlignFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAnnotationWithoutDotFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocIndentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagNormalizerFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocLineSpanFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAccessFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAliasTagFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoEmptyReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoPackageFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoUselessInheritdocFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderByValueFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocParamOrderFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocReturnSelfReferenceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocScalarFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSeparationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSingleLineVarSpacingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSummaryFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagCasingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocToCommentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimConsecutiveBlankLineSeparationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesOrderFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarAnnotationCorrectOrderFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarWithoutNameFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\NoUselessReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\ReturnAssignmentFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\SimplifiedNullReturnFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\MultilineWhitespaceBeforeSemicolonsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\NoEmptyStatementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\NoSinglelineWhitespaceBeforeSemicolonsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\SemicolonAfterInstructionFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\SpaceAfterSemicolonFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\DeclareStrictTypesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\StrictComparisonFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\StrictParamFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\EscapeImplicitBackslashesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\ExplicitStringVariableFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\HeredocToNowdocFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\NoBinaryStringFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\NoTrailingWhitespaceInStringFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\SimpleToComplexStringVariableFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\SingleQuoteFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\StringLengthToEmptyFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\StringLineEndingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\ArrayIndentationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBeforeStatementFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBetweenImportGroupsFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\CompactNullableTypehintFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\HeredocIndentationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\IndentationTypeFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\LineEndingFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\MethodChainingIndentationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoExtraBlankLinesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesAroundOffsetFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesInsideParenthesisFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoTrailingWhitespaceFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoWhitespaceInBlankLineFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\SingleBlankLineAtEofFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\StatementIndentationFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\TypeDeclarationSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\TypesSpacesFixer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php', + 'PhpCsFixer\\Fixer\\WhitespacesAwareFixerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php', + 'PhpCsFixer\\Indicator\\PhpUnitTestCaseIndicator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php', + 'PhpCsFixer\\Linter\\CachingLinter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php', + 'PhpCsFixer\\Linter\\Linter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/Linter.php', + 'PhpCsFixer\\Linter\\LinterInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php', + 'PhpCsFixer\\Linter\\LintingException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/LintingException.php', + 'PhpCsFixer\\Linter\\LintingResultInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php', + 'PhpCsFixer\\Linter\\ProcessLinter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php', + 'PhpCsFixer\\Linter\\ProcessLinterProcessBuilder' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php', + 'PhpCsFixer\\Linter\\ProcessLintingResult' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php', + 'PhpCsFixer\\Linter\\TokenizerLinter' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php', + 'PhpCsFixer\\Linter\\TokenizerLintingResult' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php', + 'PhpCsFixer\\Linter\\UnavailableLinterException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php', + 'PhpCsFixer\\PharChecker' => $vendorDir . '/friendsofphp/php-cs-fixer/src/PharChecker.php', + 'PhpCsFixer\\PharCheckerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php', + 'PhpCsFixer\\Preg' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Preg.php', + 'PhpCsFixer\\PregException' => $vendorDir . '/friendsofphp/php-cs-fixer/src/PregException.php', + 'PhpCsFixer\\RuleSet\\AbstractMigrationSetDescription' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php', + 'PhpCsFixer\\RuleSet\\AbstractRuleSetDescription' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php', + 'PhpCsFixer\\RuleSet\\RuleSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php', + 'PhpCsFixer\\RuleSet\\RuleSetDescriptionInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php', + 'PhpCsFixer\\RuleSet\\RuleSetInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php', + 'PhpCsFixer\\RuleSet\\RuleSets' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php', + 'PhpCsFixer\\RuleSet\\Sets\\DoctrineAnnotationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERCS1x0RiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERCS1x0Set' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP54MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP73MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP81MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP82MigrationSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit100MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit30MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit32MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit35MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit43MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit48MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit50MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit52MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit54MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit55MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit56MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit57MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit60MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit75MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit84MigrationRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR12RiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR12Set' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR1Set' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR2Set' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerSet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\SymfonyRiskySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\SymfonySet' => $vendorDir . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php', + 'PhpCsFixer\\Runner\\FileCachingLintingIterator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php', + 'PhpCsFixer\\Runner\\FileFilterIterator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php', + 'PhpCsFixer\\Runner\\FileLintingIterator' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php', + 'PhpCsFixer\\Runner\\Runner' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Runner/Runner.php', + 'PhpCsFixer\\StdinFileInfo' => $vendorDir . '/friendsofphp/php-cs-fixer/src/StdinFileInfo.php', + 'PhpCsFixer\\Tokenizer\\AbstractTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php', + 'PhpCsFixer\\Tokenizer\\AbstractTypeTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\AlternativeSyntaxAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\AbstractControlCaseStructuresAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\ArgumentAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\CaseAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\DataProviderAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\DefaultAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\EnumAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\MatchAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceUseAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\StartEndTokenAwareAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\SwitchAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\TypeAnalysis' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ArgumentsAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\AttributeAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\BlocksAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ClassyAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\CommentsAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ControlCaseStructuresAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\DataProviderAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\FunctionsAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\GotoLabelAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\NamespaceUsesAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\NamespacesAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\RangeAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ReferenceAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\WhitespacesAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\CT' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php', + 'PhpCsFixer\\Tokenizer\\CodeHasher' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php', + 'PhpCsFixer\\Tokenizer\\Token' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php', + 'PhpCsFixer\\Tokenizer\\Tokens' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php', + 'PhpCsFixer\\Tokenizer\\TokensAnalyzer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\TransformerInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ArrayTypehintTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\AttributeTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\BraceClassInstantiationTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ClassConstantTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ConstructorPromotionTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\CurlyBraceTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\DisjunctiveNormalFormTypeParenthesisTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\FirstClassCallableTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ImportTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NameQualifiedTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NamedArgumentTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NamespaceOperatorTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NullableTypeTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ReturnRefTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\SquareBraceTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeAlternationTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeColonTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeIntersectionTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\UseTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\WhitespacyCommentTransformer' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformers' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformers.php', + 'PhpCsFixer\\ToolInfo' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ToolInfo.php', + 'PhpCsFixer\\ToolInfoInterface' => $vendorDir . '/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php', + 'PhpCsFixer\\Utils' => $vendorDir . '/friendsofphp/php-cs-fixer/src/Utils.php', + 'PhpCsFixer\\WhitespacesFixerConfig' => $vendorDir . '/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php', + 'PhpCsFixer\\WordMatcher' => $vendorDir . '/friendsofphp/php-cs-fixer/src/WordMatcher.php', + 'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => $vendorDir . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php', + 'Symfony\\Polyfill\\Php80\\Php80' => $vendorDir . '/symfony/polyfill-php80/Php80.php', + 'Symfony\\Polyfill\\Php80\\PhpToken' => $vendorDir . '/symfony/polyfill-php80/PhpToken.php', + 'Symfony\\Polyfill\\Php81\\Php81' => $vendorDir . '/symfony/polyfill-php81/Php81.php', + 'Symplify\\CodingStandard\\DocBlock\\UselessDocBlockCleaner' => $vendorDir . '/symplify/coding-standard/src/DocBlock/UselessDocBlockCleaner.php', + 'Symplify\\CodingStandard\\Enum\\BlockBorderType' => $vendorDir . '/symplify/coding-standard/src/Enum/BlockBorderType.php', + 'Symplify\\CodingStandard\\Fixer\\AbstractSymplifyFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/AbstractSymplifyFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Annotation\\RemovePHPStormAnnotationFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Annotation/RemovePHPStormAnnotationFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\ArrayListItemNewlineFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayListItemNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\ArrayOpenerAndCloserNewlineFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayOpenerAndCloserNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\StandaloneLineInMultilineArrayFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/ArrayNotation/StandaloneLineInMultilineArrayFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Commenting\\ParamReturnAndVarTagMalformsFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Commenting/ParamReturnAndVarTagMalformsFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Commenting\\RemoveUselessDefaultCommentFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Commenting/RemoveUselessDefaultCommentFixer.php', + 'Symplify\\CodingStandard\\Fixer\\LineLength\\LineLengthFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/LineLength/LineLengthFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\MethodChainingNewlineFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Spacing/MethodChainingNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\SpaceAfterCommaHereNowDocFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Spacing/SpaceAfterCommaHereNowDocFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\StandaloneLineConstructorParamFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Spacing/StandaloneLineConstructorParamFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\StandaloneLinePromotedPropertyFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Spacing/StandaloneLinePromotedPropertyFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Strict\\BlankLineAfterStrictTypesFixer' => $vendorDir . '/symplify/coding-standard/src/Fixer/Strict/BlankLineAfterStrictTypesFixer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\ChainMethodCallAnalyzer' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/ChainMethodCallAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\DocblockRelatedParamNamesResolver' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/DocblockRelatedParamNamesResolver.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\FunctionCallNameMatcher' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/FunctionCallNameMatcher.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\HeredocAnalyzer' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/HeredocAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\Naming\\MethodNameResolver' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/Naming/MethodNameResolver.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\NewlineAnalyzer' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/NewlineAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\ParamNewliner' => $vendorDir . '/symplify/coding-standard/src/TokenAnalyzer/ParamNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\ArrayAnalyzer' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/ArrayAnalyzer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\BlockFinder' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/BlockFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\CallAnalyzer' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/CallAnalyzer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\IndentDetector' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/IndentDetector.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\TokenSkipper' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/TokenSkipper.php', + 'Symplify\\CodingStandard\\TokenRunner\\Arrays\\ArrayItemNewliner' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Arrays/ArrayItemNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Contract\\DocBlock\\MalformWorkerInterface' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Contract/DocBlock/MalformWorkerInterface.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\InlineVarMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVarMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\InlineVariableDocBlockMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVariableDocBlockMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\MissingParamNameMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingParamNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\MissingVarNameMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingVarNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\ParamNameReferenceMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameReferenceMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\ParamNameTypoMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameTypoMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SuperfluousReturnNameMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousReturnNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SuperfluousVarNameMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousVarNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SwitchedTypeAndNameMalformWorker' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SwitchedTypeAndNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\Enum\\LineKind' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Enum/LineKind.php', + 'Symplify\\CodingStandard\\TokenRunner\\Exception\\MissingImplementationException' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Exception/MissingImplementationException.php', + 'Symplify\\CodingStandard\\TokenRunner\\Exception\\TokenNotFoundException' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Exception/TokenNotFoundException.php', + 'Symplify\\CodingStandard\\TokenRunner\\TokenFinder' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/TokenFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\FirstLineLengthResolver' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/FirstLineLengthResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthCloserTransformer' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthCloserTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthOpenerTransformer' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthOpenerTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthResolver' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthTransformer' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\TokensInliner' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensInliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\TokensNewliner' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Traverser\\ArrayBlockInfoFinder' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Traverser/ArrayBlockInfoFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Traverser\\TokenReverser' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Traverser/TokenReverser.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObjectFactory\\LineLengthAndPositionFactory' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/ValueObjectFactory/LineLengthAndPositionFactory.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\BlockInfo' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/ValueObject/BlockInfo.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\LineLengthAndPosition' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/ValueObject/LineLengthAndPosition.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\TokenKinds' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/ValueObject/TokenKinds.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\Wrapper\\FixerWrapper\\ArrayWrapper' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/ValueObject/Wrapper/FixerWrapper/ArrayWrapper.php', + 'Symplify\\CodingStandard\\TokenRunner\\Whitespace\\IndentResolver' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Whitespace/IndentResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Wrapper\\FixerWrapper\\ArrayWrapperFactory' => $vendorDir . '/symplify/coding-standard/src/TokenRunner/Wrapper/FixerWrapper/ArrayWrapperFactory.php', + 'Symplify\\CodingStandard\\ValueObject\\BlockInfoMetadata' => $vendorDir . '/symplify/coding-standard/src/ValueObject/BlockInfoMetadata.php', + 'Symplify\\CodingStandard\\ValueObject\\CodingStandardConfig' => $vendorDir . '/symplify/coding-standard/src/ValueObject/CodingStandardConfig.php', + 'Symplify\\EasyCodingStandard\\Application\\EasyCodingStandardApplication' => $baseDir . '/src/Application/EasyCodingStandardApplication.php', + 'Symplify\\EasyCodingStandard\\Application\\FileProcessorCollector' => $baseDir . '/src/Application/FileProcessorCollector.php', + 'Symplify\\EasyCodingStandard\\Application\\SingleFileProcessor' => $baseDir . '/src/Application/SingleFileProcessor.php', + 'Symplify\\EasyCodingStandard\\Application\\Version\\StaticVersionResolver' => $baseDir . '/src/Application/Version/StaticVersionResolver.php', + 'Symplify\\EasyCodingStandard\\Caching\\Cache' => $baseDir . '/packages/Caching/Cache.php', + 'Symplify\\EasyCodingStandard\\Caching\\CacheFactory' => $baseDir . '/packages/Caching/CacheFactory.php', + 'Symplify\\EasyCodingStandard\\Caching\\ChangedFilesDetector' => $baseDir . '/packages/Caching/ChangedFilesDetector.php', + 'Symplify\\EasyCodingStandard\\Caching\\FileHashComputer' => $baseDir . '/packages/Caching/FileHashComputer.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\CacheFilePaths' => $baseDir . '/packages/Caching/ValueObject/CacheFilePaths.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\CacheItem' => $baseDir . '/packages/Caching/ValueObject/CacheItem.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\Storage\\FileCacheStorage' => $baseDir . '/packages/Caching/ValueObject/Storage/FileCacheStorage.php', + 'Symplify\\EasyCodingStandard\\Config\\ECSConfig' => $baseDir . '/src/Config/ECSConfig.php', + 'Symplify\\EasyCodingStandard\\Configuration\\ConfigInitializer' => $baseDir . '/src/Configuration/ConfigInitializer.php', + 'Symplify\\EasyCodingStandard\\Configuration\\ConfigurationFactory' => $baseDir . '/src/Configuration/ConfigurationFactory.php', + 'Symplify\\EasyCodingStandard\\Configuration\\InitPathsResolver' => $baseDir . '/src/Configuration/InitPathsResolver.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\AbstractCheckCommand' => $baseDir . '/src/Console/Command/AbstractCheckCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\CheckCommand' => $baseDir . '/src/Console/Command/CheckCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\ListCheckersCommand' => $baseDir . '/src/Console/Command/ListCheckersCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\WorkerCommand' => $baseDir . '/src/Console/Command/WorkerCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\EasyCodingStandardConsoleApplication' => $baseDir . '/src/Console/EasyCodingStandardConsoleApplication.php', + 'Symplify\\EasyCodingStandard\\Console\\ExitCode' => $baseDir . '/src/Console/ExitCode.php', + 'Symplify\\EasyCodingStandard\\Console\\Formatter\\ColorConsoleDiffFormatter' => $baseDir . '/src/Console/Formatter/ColorConsoleDiffFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\ConsoleOutputFormatter' => $baseDir . '/src/Console/Output/ConsoleOutputFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\ExitCodeResolver' => $baseDir . '/src/Console/Output/ExitCodeResolver.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\JsonOutputFormatter' => $baseDir . '/src/Console/Output/JsonOutputFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\OutputFormatterCollector' => $baseDir . '/src/Console/Output/OutputFormatterCollector.php', + 'Symplify\\EasyCodingStandard\\Console\\Reporter\\CheckerListReporter' => $baseDir . '/src/Console/Reporter/CheckerListReporter.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\EasyCodingStandardStyle' => $baseDir . '/src/Console/Style/EasyCodingStandardStyle.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\EasyCodingStandardStyleFactory' => $baseDir . '/src/Console/Style/EasyCodingStandardStyleFactory.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\SymfonyStyleFactory' => $baseDir . '/src/Console/Style/SymfonyStyleFactory.php', + 'Symplify\\EasyCodingStandard\\Contract\\Application\\FileProcessorInterface' => $baseDir . '/src/Contract/Application/FileProcessorInterface.php', + 'Symplify\\EasyCodingStandard\\Contract\\Console\\Output\\OutputFormatterInterface' => $baseDir . '/src/Contract/Console/Output/OutputFormatterInterface.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\CompilerPassHelper' => $baseDir . '/src/DependencyInjection/CompilerPass/CompilerPassHelper.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\ConflictingCheckersCompilerPass' => $baseDir . '/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\RemoveExcludedCheckersCompilerPass' => $baseDir . '/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\RemoveMutualCheckersCompilerPass' => $baseDir . '/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\EasyCodingStandardContainerFactory' => $baseDir . '/src/DependencyInjection/EasyCodingStandardContainerFactory.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\NewContainerFactory' => $baseDir . '/src/DependencyInjection/NewContainerFactory.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\SimpleParameterProvider' => $baseDir . '/src/DependencyInjection/SimpleParameterProvider.php', + 'Symplify\\EasyCodingStandard\\Error\\FileDiffFactory' => $baseDir . '/src/Error/FileDiffFactory.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\ConflictingCheckersLoadedException' => $baseDir . '/src/Exception/Configuration/ConflictingCheckersLoadedException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\FileNotFoundException' => $baseDir . '/src/Exception/Configuration/FileNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\InitializationException' => $baseDir . '/src/Exception/Configuration/InitializationException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\OutputFormatterNotFoundException' => $baseDir . '/src/Exception/Configuration/OutputFormatterNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\SourceNotFoundException' => $baseDir . '/src/Exception/Configuration/SourceNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\WhitespaceConfigurationException' => $baseDir . '/src/Exception/Configuration/WhitespaceConfigurationException.php', + 'Symplify\\EasyCodingStandard\\Exception\\ShouldNotHappenException' => $baseDir . '/src/Exception/ShouldNotHappenException.php', + 'Symplify\\EasyCodingStandard\\Exception\\VersionException' => $baseDir . '/src/Exception/VersionException.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\FileFilter' => $baseDir . '/src/FileSystem/FileFilter.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\PathNormalizer' => $baseDir . '/src/FileSystem/PathNormalizer.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\StaticRelativeFilePathHelper' => $baseDir . '/src/FileSystem/StaticRelativeFilePathHelper.php', + 'Symplify\\EasyCodingStandard\\Finder\\SourceFinder' => $baseDir . '/src/Finder/SourceFinder.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\Application\\FixerFileProcessor' => $baseDir . '/packages/FixerRunner/Application/FixerFileProcessor.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\Parser\\FileToTokensParser' => $baseDir . '/packages/FixerRunner/Parser/FileToTokensParser.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\ValueObject\\Spacing' => $baseDir . '/packages/FixerRunner/ValueObject/Spacing.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\WhitespacesFixerConfigFactory' => $baseDir . '/packages/FixerRunner/WhitespacesFixerConfigFactory.php', + 'Symplify\\EasyCodingStandard\\MemoryLimitter' => $baseDir . '/src/MemoryLimitter.php', + 'Symplify\\EasyCodingStandard\\Parallel\\Application\\ParallelFileProcessor' => $baseDir . '/packages/Parallel/Application/ParallelFileProcessor.php', + 'Symplify\\EasyCodingStandard\\Parallel\\ValueObject\\Bridge' => $baseDir . '/packages/Parallel/ValueObject/Bridge.php', + 'Symplify\\EasyCodingStandard\\Parallel\\ValueObject\\Name' => $baseDir . '/packages/Parallel/ValueObject/Name.php', + 'Symplify\\EasyCodingStandard\\Parallel\\WorkerRunner' => $baseDir . '/packages/Parallel/WorkerRunner.php', + 'Symplify\\EasyCodingStandard\\Reporter\\ProcessedFileReporter' => $baseDir . '/src/Reporter/ProcessedFileReporter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Contract\\SkipVoterInterface' => $baseDir . '/packages/Skipper/Contract/SkipVoterInterface.php', + 'Symplify\\EasyCodingStandard\\Skipper\\FileSystem\\FnMatchPathNormalizer' => $baseDir . '/packages/Skipper/FileSystem/FnMatchPathNormalizer.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Fnmatcher' => $baseDir . '/packages/Skipper/Fnmatcher.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Matcher\\FileInfoMatcher' => $baseDir . '/packages/Skipper/Matcher/FileInfoMatcher.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedClassAndCodesResolver' => $baseDir . '/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedClassResolver' => $baseDir . '/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedMessagesResolver' => $baseDir . '/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedPathsResolver' => $baseDir . '/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\ClassAndCodeSkipVoter' => $baseDir . '/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\ClassSkipVoter' => $baseDir . '/packages/Skipper/SkipVoter/ClassSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\MessageSkipVoter' => $baseDir . '/packages/Skipper/SkipVoter/MessageSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\PathSkipVoter' => $baseDir . '/packages/Skipper/SkipVoter/PathSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Skipper\\SkipSkipper' => $baseDir . '/packages/Skipper/Skipper/SkipSkipper.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Skipper\\Skipper' => $baseDir . '/packages/Skipper/Skipper/Skipper.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\Application\\SniffFileProcessor' => $baseDir . '/packages/SniffRunner/Application/SniffFileProcessor.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\DataCollector\\SniffMetadataCollector' => $baseDir . '/packages/SniffRunner/DataCollector/SniffMetadataCollector.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\File\\FileFactory' => $baseDir . '/packages/SniffRunner/File/FileFactory.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\ValueObject\\Error\\CodingStandardError' => $baseDir . '/packages/SniffRunner/ValueObject/Error/CodingStandardError.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\ValueObject\\File' => $baseDir . '/packages/SniffRunner/ValueObject/File.php', + 'Symplify\\EasyCodingStandard\\Testing\\Contract\\ConfigAwareInterface' => $baseDir . '/src/Testing/Contract/ConfigAwareInterface.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\AbstractCheckerTestCase' => $baseDir . '/src/Testing/PHPUnit/AbstractCheckerTestCase.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\AbstractTestCase' => $baseDir . '/src/Testing/PHPUnit/AbstractTestCase.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\FixtureFinder' => $baseDir . '/src/Testing/PHPUnit/FixtureFinder.php', + 'Symplify\\EasyCodingStandard\\Utils\\ParametersMerger' => $baseDir . '/src/Utils/ParametersMerger.php', + 'Symplify\\EasyCodingStandard\\Utils\\PrivatesAccessorHelper' => $baseDir . '/src/Utils/PrivatesAccessorHelper.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Configuration' => $baseDir . '/src/ValueObject/Configuration.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\ErrorAndDiffResult' => $baseDir . '/src/ValueObject/Error/ErrorAndDiffResult.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\FileDiff' => $baseDir . '/src/ValueObject/Error/FileDiff.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\SystemError' => $baseDir . '/src/ValueObject/Error/SystemError.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Option' => $baseDir . '/src/ValueObject/Option.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Set\\SetList' => $baseDir . '/src/ValueObject/Set/SetList.php', + 'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', +); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 00000000000..16ea41236bc --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,14 @@ + $vendorDir . '/react/promise/src/functions_include.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => $vendorDir . '/symfony/polyfill-mbstring/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => $vendorDir . '/symfony/deprecation-contracts/function.php', + 'a4a119a56e50fbb293281d9a48007e0e' => $vendorDir . '/symfony/polyfill-php80/bootstrap.php', + '23c18046f52bef3eea034657bafda50f' => $vendorDir . '/symfony/polyfill-php81/bootstrap.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 00000000000..15a2ff3ad6d --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,9 @@ + array($baseDir . '/src', $baseDir . '/packages'), + 'Symplify\\CodingStandard\\' => array($vendorDir . '/symplify/coding-standard/src'), + 'Symfony\\Polyfill\\Php81\\' => array($vendorDir . '/symfony/polyfill-php81'), + 'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'), + 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), + 'PhpCsFixer\\' => array($vendorDir . '/friendsofphp/php-cs-fixer/src'), + 'ECSPrefix202307\\Webmozart\\Assert\\' => array($vendorDir . '/webmozart/assert/src'), + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\' => array($vendorDir . '/symplify/rule-doc-generator-contracts/src'), + 'ECSPrefix202307\\Symplify\\EasyParallel\\' => array($vendorDir . '/symplify/easy-parallel/src'), + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\' => array($vendorDir . '/symfony/service-contracts'), + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\' => array($vendorDir . '/symfony/options-resolver'), + 'ECSPrefix202307\\Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'), + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'), + 'ECSPrefix202307\\Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'), + 'ECSPrefix202307\\React\\Stream\\' => array($vendorDir . '/react/stream/src'), + 'ECSPrefix202307\\React\\Socket\\' => array($vendorDir . '/react/socket/src'), + 'ECSPrefix202307\\React\\Promise\\' => array($vendorDir . '/react/promise/src'), + 'ECSPrefix202307\\React\\EventLoop\\' => array($vendorDir . '/react/event-loop/src'), + 'ECSPrefix202307\\React\\Dns\\' => array($vendorDir . '/react/dns/src'), + 'ECSPrefix202307\\React\\ChildProcess\\' => array($vendorDir . '/react/child-process/src'), + 'ECSPrefix202307\\React\\Cache\\' => array($vendorDir . '/react/cache/src'), + 'ECSPrefix202307\\Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'), + 'ECSPrefix202307\\Psr\\Log\\' => array($vendorDir . '/psr/log/src'), + 'ECSPrefix202307\\Psr\\Container\\' => array($vendorDir . '/psr/container/src'), + 'ECSPrefix202307\\Psr\\Cache\\' => array($vendorDir . '/psr/cache/src'), + 'ECSPrefix202307\\Illuminate\\Contracts\\' => array($vendorDir . '/illuminate/contracts'), + 'ECSPrefix202307\\Illuminate\\Container\\' => array($vendorDir . '/illuminate/container'), + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\' => array($vendorDir . '/fidry/cpu-core-counter/src'), + 'ECSPrefix202307\\Evenement\\' => array($vendorDir . '/evenement/evenement/src/Evenement'), + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\' => array($vendorDir . '/doctrine/lexer/src'), + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\' => array($vendorDir . '/doctrine/annotations/lib/Doctrine/Common/Annotations'), + 'ECSPrefix202307\\Composer\\XdebugHandler\\' => array($vendorDir . '/composer/xdebug-handler/src'), + 'ECSPrefix202307\\Composer\\Semver\\' => array($vendorDir . '/composer/semver/src'), + 'ECSPrefix202307\\Composer\\Pcre\\' => array($vendorDir . '/composer/pcre/src'), + 'ECSPrefix202307\\Clue\\React\\NDJson\\' => array($vendorDir . '/clue/ndjson-react/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 00000000000..4e92597ddc0 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,49 @@ +setClassMapAuthoritative(true); + $loader->register(true); + + $filesToLoad = \Composer\Autoload\ComposerStaticInit24ab6383ac11570ff93fe409c40ede8c::$files; + $requireFile = \Closure::bind(static function ($fileIdentifier, $file) { + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + + require $file; + } + }, null, null); + foreach ($filesToLoad as $fileIdentifier => $file) { + $requireFile($fileIdentifier, $file); + } + + return $loader; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 00000000000..def1176ff88 --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,1460 @@ + __DIR__ . '/..' . '/react/promise/src/functions_include.php', + '0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php', + '6e3fae29631ef280660b3cdad06f25a8' => __DIR__ . '/..' . '/symfony/deprecation-contracts/function.php', + 'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php', + '23c18046f52bef3eea034657bafda50f' => __DIR__ . '/..' . '/symfony/polyfill-php81/bootstrap.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'S' => + array ( + 'Symplify\\EasyCodingStandard\\' => 28, + 'Symplify\\CodingStandard\\' => 24, + 'Symfony\\Polyfill\\Php81\\' => 23, + 'Symfony\\Polyfill\\Php80\\' => 23, + 'Symfony\\Polyfill\\Mbstring\\' => 26, + ), + 'P' => + array ( + 'PhpCsFixer\\' => 11, + ), + 'E' => + array ( + 'ECSPrefix202307\\Webmozart\\Assert\\' => 33, + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\' => 42, + 'ECSPrefix202307\\Symplify\\EasyParallel\\' => 38, + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\' => 42, + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\' => 50, + 'ECSPrefix202307\\Symfony\\Component\\Finder\\' => 41, + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\' => 45, + 'ECSPrefix202307\\Symfony\\Component\\Console\\' => 42, + 'ECSPrefix202307\\React\\Stream\\' => 29, + 'ECSPrefix202307\\React\\Socket\\' => 29, + 'ECSPrefix202307\\React\\Promise\\' => 30, + 'ECSPrefix202307\\React\\EventLoop\\' => 32, + 'ECSPrefix202307\\React\\Dns\\' => 26, + 'ECSPrefix202307\\React\\ChildProcess\\' => 35, + 'ECSPrefix202307\\React\\Cache\\' => 28, + 'ECSPrefix202307\\Psr\\SimpleCache\\' => 32, + 'ECSPrefix202307\\Psr\\Log\\' => 24, + 'ECSPrefix202307\\Psr\\Container\\' => 30, + 'ECSPrefix202307\\Psr\\Cache\\' => 26, + 'ECSPrefix202307\\Illuminate\\Contracts\\' => 37, + 'ECSPrefix202307\\Illuminate\\Container\\' => 37, + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\' => 37, + 'ECSPrefix202307\\Evenement\\' => 26, + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\' => 38, + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\' => 44, + 'ECSPrefix202307\\Composer\\XdebugHandler\\' => 39, + 'ECSPrefix202307\\Composer\\Semver\\' => 32, + 'ECSPrefix202307\\Composer\\Pcre\\' => 30, + 'ECSPrefix202307\\Clue\\React\\NDJson\\' => 34, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Symplify\\EasyCodingStandard\\' => + array ( + 0 => __DIR__ . '/../..' . '/src', + 1 => __DIR__ . '/../..' . '/packages', + ), + 'Symplify\\CodingStandard\\' => + array ( + 0 => __DIR__ . '/..' . '/symplify/coding-standard/src', + ), + 'Symfony\\Polyfill\\Php81\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php81', + ), + 'Symfony\\Polyfill\\Php80\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php80', + ), + 'Symfony\\Polyfill\\Mbstring\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', + ), + 'PhpCsFixer\\' => + array ( + 0 => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src', + ), + 'ECSPrefix202307\\Webmozart\\Assert\\' => + array ( + 0 => __DIR__ . '/..' . '/webmozart/assert/src', + ), + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\' => + array ( + 0 => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src', + ), + 'ECSPrefix202307\\Symplify\\EasyParallel\\' => + array ( + 0 => __DIR__ . '/..' . '/symplify/easy-parallel/src', + ), + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/service-contracts', + ), + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/options-resolver', + ), + 'ECSPrefix202307\\Symfony\\Component\\Finder\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/finder', + ), + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/filesystem', + ), + 'ECSPrefix202307\\Symfony\\Component\\Console\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/console', + ), + 'ECSPrefix202307\\React\\Stream\\' => + array ( + 0 => __DIR__ . '/..' . '/react/stream/src', + ), + 'ECSPrefix202307\\React\\Socket\\' => + array ( + 0 => __DIR__ . '/..' . '/react/socket/src', + ), + 'ECSPrefix202307\\React\\Promise\\' => + array ( + 0 => __DIR__ . '/..' . '/react/promise/src', + ), + 'ECSPrefix202307\\React\\EventLoop\\' => + array ( + 0 => __DIR__ . '/..' . '/react/event-loop/src', + ), + 'ECSPrefix202307\\React\\Dns\\' => + array ( + 0 => __DIR__ . '/..' . '/react/dns/src', + ), + 'ECSPrefix202307\\React\\ChildProcess\\' => + array ( + 0 => __DIR__ . '/..' . '/react/child-process/src', + ), + 'ECSPrefix202307\\React\\Cache\\' => + array ( + 0 => __DIR__ . '/..' . '/react/cache/src', + ), + 'ECSPrefix202307\\Psr\\SimpleCache\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/simple-cache/src', + ), + 'ECSPrefix202307\\Psr\\Log\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/log/src', + ), + 'ECSPrefix202307\\Psr\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/container/src', + ), + 'ECSPrefix202307\\Psr\\Cache\\' => + array ( + 0 => __DIR__ . '/..' . '/psr/cache/src', + ), + 'ECSPrefix202307\\Illuminate\\Contracts\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/contracts', + ), + 'ECSPrefix202307\\Illuminate\\Container\\' => + array ( + 0 => __DIR__ . '/..' . '/illuminate/container', + ), + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\' => + array ( + 0 => __DIR__ . '/..' . '/fidry/cpu-core-counter/src', + ), + 'ECSPrefix202307\\Evenement\\' => + array ( + 0 => __DIR__ . '/..' . '/evenement/evenement/src/Evenement', + ), + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/lexer/src', + ), + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\' => + array ( + 0 => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations', + ), + 'ECSPrefix202307\\Composer\\XdebugHandler\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/xdebug-handler/src', + ), + 'ECSPrefix202307\\Composer\\Semver\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/semver/src', + ), + 'ECSPrefix202307\\Composer\\Pcre\\' => + array ( + 0 => __DIR__ . '/..' . '/composer/pcre/src', + ), + 'ECSPrefix202307\\Clue\\React\\NDJson\\' => + array ( + 0 => __DIR__ . '/..' . '/clue/ndjson-react/src', + ), + ); + + public static $classMap = array ( + 'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php', + 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', + 'ECSPrefix202307\\Clue\\React\\NDJson\\Decoder' => __DIR__ . '/..' . '/clue/ndjson-react/src/Decoder.php', + 'ECSPrefix202307\\Clue\\React\\NDJson\\Encoder' => __DIR__ . '/..' . '/clue/ndjson-react/src/Encoder.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchAllResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllStrictGroupsResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchAllStrictGroupsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchAllWithOffsetsResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchAllWithOffsetsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchStrictGroupsResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchStrictGroupsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\MatchWithOffsetsResult' => __DIR__ . '/..' . '/composer/pcre/src/MatchWithOffsetsResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\PcreException' => __DIR__ . '/..' . '/composer/pcre/src/PcreException.php', + 'ECSPrefix202307\\Composer\\Pcre\\Preg' => __DIR__ . '/..' . '/composer/pcre/src/Preg.php', + 'ECSPrefix202307\\Composer\\Pcre\\Regex' => __DIR__ . '/..' . '/composer/pcre/src/Regex.php', + 'ECSPrefix202307\\Composer\\Pcre\\ReplaceResult' => __DIR__ . '/..' . '/composer/pcre/src/ReplaceResult.php', + 'ECSPrefix202307\\Composer\\Pcre\\UnexpectedNullMatchException' => __DIR__ . '/..' . '/composer/pcre/src/UnexpectedNullMatchException.php', + 'ECSPrefix202307\\Composer\\Semver\\Comparator' => __DIR__ . '/..' . '/composer/semver/src/Comparator.php', + 'ECSPrefix202307\\Composer\\Semver\\CompilingMatcher' => __DIR__ . '/..' . '/composer/semver/src/CompilingMatcher.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\Bound' => __DIR__ . '/..' . '/composer/semver/src/Constraint/Bound.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\Constraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/Constraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\ConstraintInterface' => __DIR__ . '/..' . '/composer/semver/src/Constraint/ConstraintInterface.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MatchAllConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MatchAllConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MatchNoneConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MatchNoneConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Constraint\\MultiConstraint' => __DIR__ . '/..' . '/composer/semver/src/Constraint/MultiConstraint.php', + 'ECSPrefix202307\\Composer\\Semver\\Interval' => __DIR__ . '/..' . '/composer/semver/src/Interval.php', + 'ECSPrefix202307\\Composer\\Semver\\Intervals' => __DIR__ . '/..' . '/composer/semver/src/Intervals.php', + 'ECSPrefix202307\\Composer\\Semver\\Semver' => __DIR__ . '/..' . '/composer/semver/src/Semver.php', + 'ECSPrefix202307\\Composer\\Semver\\VersionParser' => __DIR__ . '/..' . '/composer/semver/src/VersionParser.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\PhpConfig' => __DIR__ . '/..' . '/composer/xdebug-handler/src/PhpConfig.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\Process' => __DIR__ . '/..' . '/composer/xdebug-handler/src/Process.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\Status' => __DIR__ . '/..' . '/composer/xdebug-handler/src/Status.php', + 'ECSPrefix202307\\Composer\\XdebugHandler\\XdebugHandler' => __DIR__ . '/..' . '/composer/xdebug-handler/src/XdebugHandler.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationException' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\AnnotationRegistry' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Attribute' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Attributes' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attributes.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Enum' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\IgnoreAnnotation' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\NamedArgumentConstructor' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Required' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Required.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Annotation\\Target' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Target.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\DocLexer' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocLexer.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\DocParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\ImplicitlyIgnoredAnnotationNames' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\IndexedReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\PhpParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\PsrCachedReader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\Reader' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php', + 'ECSPrefix202307\\Doctrine\\Common\\Annotations\\TokenParser' => __DIR__ . '/..' . '/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php', + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\AbstractLexer' => __DIR__ . '/..' . '/doctrine/lexer/src/AbstractLexer.php', + 'ECSPrefix202307\\Doctrine\\Common\\Lexer\\Token' => __DIR__ . '/..' . '/doctrine/lexer/src/Token.php', + 'ECSPrefix202307\\Evenement\\EventEmitter' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitter.php', + 'ECSPrefix202307\\Evenement\\EventEmitterInterface' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitterInterface.php', + 'ECSPrefix202307\\Evenement\\EventEmitterTrait' => __DIR__ . '/..' . '/evenement/evenement/src/Evenement/EventEmitterTrait.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\CpuCoreCounter' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/CpuCoreCounter.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Diagnoser' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Diagnoser.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Executor\\ProcOpenExecutor' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Executor\\ProcessExecutor' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\CpuCoreFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\CpuInfoFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\DummyCpuCoreFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\FinderRegistry' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/FinderRegistry.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\HwLogicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\HwPhysicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\LscpuLogicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\LscpuPhysicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NProcFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/NProcFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NProcessorFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\NullCpuCoreFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\OnlyOnOSFamilyFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\ProcOpenBasedFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\SkipOnOSFamilyFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\WmicLogicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\WmicPhysicalFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\Finder\\_NProcessorFinder' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php', + 'ECSPrefix202307\\Fidry\\CpuCoreCounter\\NumberOfCpuCoreNotFound' => __DIR__ . '/..' . '/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php', + 'ECSPrefix202307\\Illuminate\\Container\\BoundMethod' => __DIR__ . '/..' . '/illuminate/container/BoundMethod.php', + 'ECSPrefix202307\\Illuminate\\Container\\Container' => __DIR__ . '/..' . '/illuminate/container/Container.php', + 'ECSPrefix202307\\Illuminate\\Container\\ContextualBindingBuilder' => __DIR__ . '/..' . '/illuminate/container/ContextualBindingBuilder.php', + 'ECSPrefix202307\\Illuminate\\Container\\EntryNotFoundException' => __DIR__ . '/..' . '/illuminate/container/EntryNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Container\\RewindableGenerator' => __DIR__ . '/..' . '/illuminate/container/RewindableGenerator.php', + 'ECSPrefix202307\\Illuminate\\Container\\Util' => __DIR__ . '/..' . '/illuminate/container/Util.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Access\\Authorizable' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Access/Authorizable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Access\\Gate' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Access/Gate.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Authenticatable' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Authenticatable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\CanResetPassword' => __DIR__ . '/..' . '/illuminate/contracts/Auth/CanResetPassword.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Guard' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Guard.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\Middleware\\AuthenticatesRequests' => __DIR__ . '/..' . '/illuminate/contracts/Auth/Middleware/AuthenticatesRequests.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\MustVerifyEmail' => __DIR__ . '/..' . '/illuminate/contracts/Auth/MustVerifyEmail.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\PasswordBroker' => __DIR__ . '/..' . '/illuminate/contracts/Auth/PasswordBroker.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\PasswordBrokerFactory' => __DIR__ . '/..' . '/illuminate/contracts/Auth/PasswordBrokerFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\StatefulGuard' => __DIR__ . '/..' . '/illuminate/contracts/Auth/StatefulGuard.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\SupportsBasicAuth' => __DIR__ . '/..' . '/illuminate/contracts/Auth/SupportsBasicAuth.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Auth\\UserProvider' => __DIR__ . '/..' . '/illuminate/contracts/Auth/UserProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\Broadcaster' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/Broadcaster.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\HasBroadcastChannel' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/HasBroadcastChannel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBeUnique' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/ShouldBeUnique.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBroadcast' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/ShouldBroadcast.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Broadcasting\\ShouldBroadcastNow' => __DIR__ . '/..' . '/illuminate/contracts/Broadcasting/ShouldBroadcastNow.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Bus\\Dispatcher' => __DIR__ . '/..' . '/illuminate/contracts/Bus/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Bus\\QueueingDispatcher' => __DIR__ . '/..' . '/illuminate/contracts/Bus/QueueingDispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Cache/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Lock' => __DIR__ . '/..' . '/illuminate/contracts/Cache/Lock.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\LockProvider' => __DIR__ . '/..' . '/illuminate/contracts/Cache/LockProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\LockTimeoutException' => __DIR__ . '/..' . '/illuminate/contracts/Cache/LockTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Repository' => __DIR__ . '/..' . '/illuminate/contracts/Cache/Repository.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cache\\Store' => __DIR__ . '/..' . '/illuminate/contracts/Cache/Store.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Config\\Repository' => __DIR__ . '/..' . '/illuminate/contracts/Config/Repository.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Application' => __DIR__ . '/..' . '/illuminate/contracts/Console/Application.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Isolatable' => __DIR__ . '/..' . '/illuminate/contracts/Console/Isolatable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\Kernel' => __DIR__ . '/..' . '/illuminate/contracts/Console/Kernel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Console\\PromptsForMissingInput' => __DIR__ . '/..' . '/illuminate/contracts/Console/PromptsForMissingInput.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\BindingResolutionException' => __DIR__ . '/..' . '/illuminate/contracts/Container/BindingResolutionException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\CircularDependencyException' => __DIR__ . '/..' . '/illuminate/contracts/Container/CircularDependencyException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\Container' => __DIR__ . '/..' . '/illuminate/contracts/Container/Container.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Container\\ContextualBindingBuilder' => __DIR__ . '/..' . '/illuminate/contracts/Container/ContextualBindingBuilder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cookie\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Cookie/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Cookie\\QueueingFactory' => __DIR__ . '/..' . '/illuminate/contracts/Cookie/QueueingFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\Builder' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/Builder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\Castable' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/Castable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\CastsAttributes' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/CastsAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\CastsInboundAttributes' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\DeviatesCastableAttributes' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/DeviatesCastableAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\SerializesCastableAttributes' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/SerializesCastableAttributes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Eloquent\\SupportsPartialRelations' => __DIR__ . '/..' . '/illuminate/contracts/Database/Eloquent/SupportsPartialRelations.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Events\\MigrationEvent' => __DIR__ . '/..' . '/illuminate/contracts/Database/Events/MigrationEvent.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\ModelIdentifier' => __DIR__ . '/..' . '/illuminate/contracts/Database/ModelIdentifier.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\Builder' => __DIR__ . '/..' . '/illuminate/contracts/Database/Query/Builder.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\ConditionExpression' => __DIR__ . '/..' . '/illuminate/contracts/Database/Query/ConditionExpression.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Database\\Query\\Expression' => __DIR__ . '/..' . '/illuminate/contracts/Database/Query/Expression.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Debug\\ExceptionHandler' => __DIR__ . '/..' . '/illuminate/contracts/Debug/ExceptionHandler.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\DecryptException' => __DIR__ . '/..' . '/illuminate/contracts/Encryption/DecryptException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\EncryptException' => __DIR__ . '/..' . '/illuminate/contracts/Encryption/EncryptException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\Encrypter' => __DIR__ . '/..' . '/illuminate/contracts/Encryption/Encrypter.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Encryption\\StringEncrypter' => __DIR__ . '/..' . '/illuminate/contracts/Encryption/StringEncrypter.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Events\\Dispatcher' => __DIR__ . '/..' . '/illuminate/contracts/Events/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Cloud' => __DIR__ . '/..' . '/illuminate/contracts/Filesystem/Cloud.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Filesystem/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\FileNotFoundException' => __DIR__ . '/..' . '/illuminate/contracts/Filesystem/FileNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\Filesystem' => __DIR__ . '/..' . '/illuminate/contracts/Filesystem/Filesystem.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Filesystem\\LockTimeoutException' => __DIR__ . '/..' . '/illuminate/contracts/Filesystem/LockTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\Application' => __DIR__ . '/..' . '/illuminate/contracts/Foundation/Application.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\CachesConfiguration' => __DIR__ . '/..' . '/illuminate/contracts/Foundation/CachesConfiguration.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\CachesRoutes' => __DIR__ . '/..' . '/illuminate/contracts/Foundation/CachesRoutes.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\ExceptionRenderer' => __DIR__ . '/..' . '/illuminate/contracts/Foundation/ExceptionRenderer.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Foundation\\MaintenanceMode' => __DIR__ . '/..' . '/illuminate/contracts/Foundation/MaintenanceMode.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Hashing\\Hasher' => __DIR__ . '/..' . '/illuminate/contracts/Hashing/Hasher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Http\\Kernel' => __DIR__ . '/..' . '/illuminate/contracts/Http/Kernel.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Attachable' => __DIR__ . '/..' . '/illuminate/contracts/Mail/Attachable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Mail/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\MailQueue' => __DIR__ . '/..' . '/illuminate/contracts/Mail/MailQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Mailable' => __DIR__ . '/..' . '/illuminate/contracts/Mail/Mailable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Mail\\Mailer' => __DIR__ . '/..' . '/illuminate/contracts/Mail/Mailer.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Notifications\\Dispatcher' => __DIR__ . '/..' . '/illuminate/contracts/Notifications/Dispatcher.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Notifications\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Notifications/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\CursorPaginator' => __DIR__ . '/..' . '/illuminate/contracts/Pagination/CursorPaginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\LengthAwarePaginator' => __DIR__ . '/..' . '/illuminate/contracts/Pagination/LengthAwarePaginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pagination\\Paginator' => __DIR__ . '/..' . '/illuminate/contracts/Pagination/Paginator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pipeline\\Hub' => __DIR__ . '/..' . '/illuminate/contracts/Pipeline/Hub.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Pipeline\\Pipeline' => __DIR__ . '/..' . '/illuminate/contracts/Pipeline/Pipeline.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Process\\InvokedProcess' => __DIR__ . '/..' . '/illuminate/contracts/Process/InvokedProcess.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Process\\ProcessResult' => __DIR__ . '/..' . '/illuminate/contracts/Process/ProcessResult.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ClearableQueue' => __DIR__ . '/..' . '/illuminate/contracts/Queue/ClearableQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\EntityNotFoundException' => __DIR__ . '/..' . '/illuminate/contracts/Queue/EntityNotFoundException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\EntityResolver' => __DIR__ . '/..' . '/illuminate/contracts/Queue/EntityResolver.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Queue/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Job' => __DIR__ . '/..' . '/illuminate/contracts/Queue/Job.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Monitor' => __DIR__ . '/..' . '/illuminate/contracts/Queue/Monitor.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\Queue' => __DIR__ . '/..' . '/illuminate/contracts/Queue/Queue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\QueueableCollection' => __DIR__ . '/..' . '/illuminate/contracts/Queue/QueueableCollection.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\QueueableEntity' => __DIR__ . '/..' . '/illuminate/contracts/Queue/QueueableEntity.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeEncrypted' => __DIR__ . '/..' . '/illuminate/contracts/Queue/ShouldBeEncrypted.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeUnique' => __DIR__ . '/..' . '/illuminate/contracts/Queue/ShouldBeUnique.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldBeUniqueUntilProcessing' => __DIR__ . '/..' . '/illuminate/contracts/Queue/ShouldBeUniqueUntilProcessing.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Queue\\ShouldQueue' => __DIR__ . '/..' . '/illuminate/contracts/Queue/ShouldQueue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Connection' => __DIR__ . '/..' . '/illuminate/contracts/Redis/Connection.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Connector' => __DIR__ . '/..' . '/illuminate/contracts/Redis/Connector.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Redis/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Redis\\LimiterTimeoutException' => __DIR__ . '/..' . '/illuminate/contracts/Redis/LimiterTimeoutException.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\BindingRegistrar' => __DIR__ . '/..' . '/illuminate/contracts/Routing/BindingRegistrar.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\Registrar' => __DIR__ . '/..' . '/illuminate/contracts/Routing/Registrar.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\ResponseFactory' => __DIR__ . '/..' . '/illuminate/contracts/Routing/ResponseFactory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\UrlGenerator' => __DIR__ . '/..' . '/illuminate/contracts/Routing/UrlGenerator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Routing\\UrlRoutable' => __DIR__ . '/..' . '/illuminate/contracts/Routing/UrlRoutable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Session\\Middleware\\AuthenticatesSessions' => __DIR__ . '/..' . '/illuminate/contracts/Session/Middleware/AuthenticatesSessions.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Session\\Session' => __DIR__ . '/..' . '/illuminate/contracts/Session/Session.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Arrayable' => __DIR__ . '/..' . '/illuminate/contracts/Support/Arrayable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\CanBeEscapedWhenCastToString' => __DIR__ . '/..' . '/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\DeferrableProvider' => __DIR__ . '/..' . '/illuminate/contracts/Support/DeferrableProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\DeferringDisplayableValue' => __DIR__ . '/..' . '/illuminate/contracts/Support/DeferringDisplayableValue.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Htmlable' => __DIR__ . '/..' . '/illuminate/contracts/Support/Htmlable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Jsonable' => __DIR__ . '/..' . '/illuminate/contracts/Support/Jsonable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\MessageBag' => __DIR__ . '/..' . '/illuminate/contracts/Support/MessageBag.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\MessageProvider' => __DIR__ . '/..' . '/illuminate/contracts/Support/MessageProvider.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Renderable' => __DIR__ . '/..' . '/illuminate/contracts/Support/Renderable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\Responsable' => __DIR__ . '/..' . '/illuminate/contracts/Support/Responsable.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Support\\ValidatedData' => __DIR__ . '/..' . '/illuminate/contracts/Support/ValidatedData.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\HasLocalePreference' => __DIR__ . '/..' . '/illuminate/contracts/Translation/HasLocalePreference.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\Loader' => __DIR__ . '/..' . '/illuminate/contracts/Translation/Loader.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Translation\\Translator' => __DIR__ . '/..' . '/illuminate/contracts/Translation/Translator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\DataAwareRule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/DataAwareRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/Validation/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ImplicitRule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/ImplicitRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\InvokableRule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/InvokableRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Rule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/Rule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\UncompromisedVerifier' => __DIR__ . '/..' . '/illuminate/contracts/Validation/UncompromisedVerifier.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidatesWhenResolved' => __DIR__ . '/..' . '/illuminate/contracts/Validation/ValidatesWhenResolved.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidationRule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/ValidationRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\Validator' => __DIR__ . '/..' . '/illuminate/contracts/Validation/Validator.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\Validation\\ValidatorAwareRule' => __DIR__ . '/..' . '/illuminate/contracts/Validation/ValidatorAwareRule.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\Engine' => __DIR__ . '/..' . '/illuminate/contracts/View/Engine.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\Factory' => __DIR__ . '/..' . '/illuminate/contracts/View/Factory.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\View' => __DIR__ . '/..' . '/illuminate/contracts/View/View.php', + 'ECSPrefix202307\\Illuminate\\Contracts\\View\\ViewCompilationException' => __DIR__ . '/..' . '/illuminate/contracts/View/ViewCompilationException.php', + 'ECSPrefix202307\\Nette\\ArgumentOutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\DeprecatedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\DirectoryNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\FileNotFoundException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\HtmlStringable' => __DIR__ . '/..' . '/nette/utils/src/HtmlStringable.php', + 'ECSPrefix202307\\Nette\\IOException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\InvalidArgumentException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\InvalidStateException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\Iterators\\CachingIterator' => __DIR__ . '/..' . '/nette/utils/src/Iterators/CachingIterator.php', + 'ECSPrefix202307\\Nette\\Iterators\\Mapper' => __DIR__ . '/..' . '/nette/utils/src/Iterators/Mapper.php', + 'ECSPrefix202307\\Nette\\Localization\\ITranslator' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'ECSPrefix202307\\Nette\\Localization\\Translator' => __DIR__ . '/..' . '/nette/utils/src/Translator.php', + 'ECSPrefix202307\\Nette\\MemberAccessException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\NotImplementedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\NotSupportedException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\OutOfRangeException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\SmartObject' => __DIR__ . '/..' . '/nette/utils/src/SmartObject.php', + 'ECSPrefix202307\\Nette\\StaticClass' => __DIR__ . '/..' . '/nette/utils/src/StaticClass.php', + 'ECSPrefix202307\\Nette\\UnexpectedValueException' => __DIR__ . '/..' . '/nette/utils/src/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\ArrayHash' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayHash.php', + 'ECSPrefix202307\\Nette\\Utils\\ArrayList' => __DIR__ . '/..' . '/nette/utils/src/Utils/ArrayList.php', + 'ECSPrefix202307\\Nette\\Utils\\Arrays' => __DIR__ . '/..' . '/nette/utils/src/Utils/Arrays.php', + 'ECSPrefix202307\\Nette\\Utils\\AssertionException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Callback' => __DIR__ . '/..' . '/nette/utils/src/Utils/Callback.php', + 'ECSPrefix202307\\Nette\\Utils\\DateTime' => __DIR__ . '/..' . '/nette/utils/src/Utils/DateTime.php', + 'ECSPrefix202307\\Nette\\Utils\\FileSystem' => __DIR__ . '/..' . '/nette/utils/src/Utils/FileSystem.php', + 'ECSPrefix202307\\Nette\\Utils\\Floats' => __DIR__ . '/..' . '/nette/utils/src/Utils/Floats.php', + 'ECSPrefix202307\\Nette\\Utils\\Helpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/Helpers.php', + 'ECSPrefix202307\\Nette\\Utils\\Html' => __DIR__ . '/..' . '/nette/utils/src/Utils/Html.php', + 'ECSPrefix202307\\Nette\\Utils\\IHtmlString' => __DIR__ . '/..' . '/nette/utils/src/compatibility.php', + 'ECSPrefix202307\\Nette\\Utils\\Image' => __DIR__ . '/..' . '/nette/utils/src/Utils/Image.php', + 'ECSPrefix202307\\Nette\\Utils\\ImageException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Json' => __DIR__ . '/..' . '/nette/utils/src/Utils/Json.php', + 'ECSPrefix202307\\Nette\\Utils\\JsonException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\ObjectHelpers' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectHelpers.php', + 'ECSPrefix202307\\Nette\\Utils\\ObjectMixin' => __DIR__ . '/..' . '/nette/utils/src/Utils/ObjectMixin.php', + 'ECSPrefix202307\\Nette\\Utils\\Paginator' => __DIR__ . '/..' . '/nette/utils/src/Utils/Paginator.php', + 'ECSPrefix202307\\Nette\\Utils\\Random' => __DIR__ . '/..' . '/nette/utils/src/Utils/Random.php', + 'ECSPrefix202307\\Nette\\Utils\\Reflection' => __DIR__ . '/..' . '/nette/utils/src/Utils/Reflection.php', + 'ECSPrefix202307\\Nette\\Utils\\RegexpException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Strings' => __DIR__ . '/..' . '/nette/utils/src/Utils/Strings.php', + 'ECSPrefix202307\\Nette\\Utils\\Type' => __DIR__ . '/..' . '/nette/utils/src/Utils/Type.php', + 'ECSPrefix202307\\Nette\\Utils\\UnknownImageFileException' => __DIR__ . '/..' . '/nette/utils/src/Utils/exceptions.php', + 'ECSPrefix202307\\Nette\\Utils\\Validators' => __DIR__ . '/..' . '/nette/utils/src/Utils/Validators.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheException' => __DIR__ . '/..' . '/psr/cache/src/CacheException.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheItemInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemInterface.php', + 'ECSPrefix202307\\Psr\\Cache\\CacheItemPoolInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemPoolInterface.php', + 'ECSPrefix202307\\Psr\\Cache\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/cache/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Psr\\Container\\ContainerExceptionInterface' => __DIR__ . '/..' . '/psr/container/src/ContainerExceptionInterface.php', + 'ECSPrefix202307\\Psr\\Container\\ContainerInterface' => __DIR__ . '/..' . '/psr/container/src/ContainerInterface.php', + 'ECSPrefix202307\\Psr\\Container\\NotFoundExceptionInterface' => __DIR__ . '/..' . '/psr/container/src/NotFoundExceptionInterface.php', + 'ECSPrefix202307\\Psr\\Log\\AbstractLogger' => __DIR__ . '/..' . '/psr/log/src/AbstractLogger.php', + 'ECSPrefix202307\\Psr\\Log\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/log/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Psr\\Log\\LogLevel' => __DIR__ . '/..' . '/psr/log/src/LogLevel.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerAwareInterface' => __DIR__ . '/..' . '/psr/log/src/LoggerAwareInterface.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerAwareTrait' => __DIR__ . '/..' . '/psr/log/src/LoggerAwareTrait.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerInterface' => __DIR__ . '/..' . '/psr/log/src/LoggerInterface.php', + 'ECSPrefix202307\\Psr\\Log\\LoggerTrait' => __DIR__ . '/..' . '/psr/log/src/LoggerTrait.php', + 'ECSPrefix202307\\Psr\\Log\\NullLogger' => __DIR__ . '/..' . '/psr/log/src/NullLogger.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\CacheException' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheException.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\CacheInterface' => __DIR__ . '/..' . '/psr/simple-cache/src/CacheInterface.php', + 'ECSPrefix202307\\Psr\\SimpleCache\\InvalidArgumentException' => __DIR__ . '/..' . '/psr/simple-cache/src/InvalidArgumentException.php', + 'ECSPrefix202307\\React\\Cache\\ArrayCache' => __DIR__ . '/..' . '/react/cache/src/ArrayCache.php', + 'ECSPrefix202307\\React\\Cache\\CacheInterface' => __DIR__ . '/..' . '/react/cache/src/CacheInterface.php', + 'ECSPrefix202307\\React\\ChildProcess\\Process' => __DIR__ . '/..' . '/react/child-process/src/Process.php', + 'ECSPrefix202307\\React\\Dns\\BadServerException' => __DIR__ . '/..' . '/react/dns/src/BadServerException.php', + 'ECSPrefix202307\\React\\Dns\\Config\\Config' => __DIR__ . '/..' . '/react/dns/src/Config/Config.php', + 'ECSPrefix202307\\React\\Dns\\Config\\HostsFile' => __DIR__ . '/..' . '/react/dns/src/Config/HostsFile.php', + 'ECSPrefix202307\\React\\Dns\\Model\\Message' => __DIR__ . '/..' . '/react/dns/src/Model/Message.php', + 'ECSPrefix202307\\React\\Dns\\Model\\Record' => __DIR__ . '/..' . '/react/dns/src/Model/Record.php', + 'ECSPrefix202307\\React\\Dns\\Protocol\\BinaryDumper' => __DIR__ . '/..' . '/react/dns/src/Protocol/BinaryDumper.php', + 'ECSPrefix202307\\React\\Dns\\Protocol\\Parser' => __DIR__ . '/..' . '/react/dns/src/Protocol/Parser.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CachingExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/CachingExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CancellationException' => __DIR__ . '/..' . '/react/dns/src/Query/CancellationException.php', + 'ECSPrefix202307\\React\\Dns\\Query\\CoopExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/CoopExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\ExecutorInterface' => __DIR__ . '/..' . '/react/dns/src/Query/ExecutorInterface.php', + 'ECSPrefix202307\\React\\Dns\\Query\\FallbackExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/FallbackExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\HostsFileExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/HostsFileExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\Query' => __DIR__ . '/..' . '/react/dns/src/Query/Query.php', + 'ECSPrefix202307\\React\\Dns\\Query\\RetryExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/RetryExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\SelectiveTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/SelectiveTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TcpTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/TcpTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TimeoutException' => __DIR__ . '/..' . '/react/dns/src/Query/TimeoutException.php', + 'ECSPrefix202307\\React\\Dns\\Query\\TimeoutExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/TimeoutExecutor.php', + 'ECSPrefix202307\\React\\Dns\\Query\\UdpTransportExecutor' => __DIR__ . '/..' . '/react/dns/src/Query/UdpTransportExecutor.php', + 'ECSPrefix202307\\React\\Dns\\RecordNotFoundException' => __DIR__ . '/..' . '/react/dns/src/RecordNotFoundException.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\Factory' => __DIR__ . '/..' . '/react/dns/src/Resolver/Factory.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\Resolver' => __DIR__ . '/..' . '/react/dns/src/Resolver/Resolver.php', + 'ECSPrefix202307\\React\\Dns\\Resolver\\ResolverInterface' => __DIR__ . '/..' . '/react/dns/src/Resolver/ResolverInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtEvLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtEvLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtEventLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtEventLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtLibevLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtLibevLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtLibeventLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtLibeventLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\ExtUvLoop' => __DIR__ . '/..' . '/react/event-loop/src/ExtUvLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\Factory' => __DIR__ . '/..' . '/react/event-loop/src/Factory.php', + 'ECSPrefix202307\\React\\EventLoop\\Loop' => __DIR__ . '/..' . '/react/event-loop/src/Loop.php', + 'ECSPrefix202307\\React\\EventLoop\\LoopInterface' => __DIR__ . '/..' . '/react/event-loop/src/LoopInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\SignalsHandler' => __DIR__ . '/..' . '/react/event-loop/src/SignalsHandler.php', + 'ECSPrefix202307\\React\\EventLoop\\StreamSelectLoop' => __DIR__ . '/..' . '/react/event-loop/src/StreamSelectLoop.php', + 'ECSPrefix202307\\React\\EventLoop\\Tick\\FutureTickQueue' => __DIR__ . '/..' . '/react/event-loop/src/Tick/FutureTickQueue.php', + 'ECSPrefix202307\\React\\EventLoop\\TimerInterface' => __DIR__ . '/..' . '/react/event-loop/src/TimerInterface.php', + 'ECSPrefix202307\\React\\EventLoop\\Timer\\Timer' => __DIR__ . '/..' . '/react/event-loop/src/Timer/Timer.php', + 'ECSPrefix202307\\React\\EventLoop\\Timer\\Timers' => __DIR__ . '/..' . '/react/event-loop/src/Timer/Timers.php', + 'ECSPrefix202307\\React\\Promise\\Deferred' => __DIR__ . '/..' . '/react/promise/src/Deferred.php', + 'ECSPrefix202307\\React\\Promise\\Exception\\CompositeException' => __DIR__ . '/..' . '/react/promise/src/Exception/CompositeException.php', + 'ECSPrefix202307\\React\\Promise\\Exception\\LengthException' => __DIR__ . '/..' . '/react/promise/src/Exception/LengthException.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\CancellationQueue' => __DIR__ . '/..' . '/react/promise/src/Internal/CancellationQueue.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\FulfilledPromise' => __DIR__ . '/..' . '/react/promise/src/Internal/FulfilledPromise.php', + 'ECSPrefix202307\\React\\Promise\\Internal\\RejectedPromise' => __DIR__ . '/..' . '/react/promise/src/Internal/RejectedPromise.php', + 'ECSPrefix202307\\React\\Promise\\Promise' => __DIR__ . '/..' . '/react/promise/src/Promise.php', + 'ECSPrefix202307\\React\\Promise\\PromiseInterface' => __DIR__ . '/..' . '/react/promise/src/PromiseInterface.php', + 'ECSPrefix202307\\React\\Socket\\Connection' => __DIR__ . '/..' . '/react/socket/src/Connection.php', + 'ECSPrefix202307\\React\\Socket\\ConnectionInterface' => __DIR__ . '/..' . '/react/socket/src/ConnectionInterface.php', + 'ECSPrefix202307\\React\\Socket\\Connector' => __DIR__ . '/..' . '/react/socket/src/Connector.php', + 'ECSPrefix202307\\React\\Socket\\ConnectorInterface' => __DIR__ . '/..' . '/react/socket/src/ConnectorInterface.php', + 'ECSPrefix202307\\React\\Socket\\DnsConnector' => __DIR__ . '/..' . '/react/socket/src/DnsConnector.php', + 'ECSPrefix202307\\React\\Socket\\FdServer' => __DIR__ . '/..' . '/react/socket/src/FdServer.php', + 'ECSPrefix202307\\React\\Socket\\FixedUriConnector' => __DIR__ . '/..' . '/react/socket/src/FixedUriConnector.php', + 'ECSPrefix202307\\React\\Socket\\HappyEyeBallsConnectionBuilder' => __DIR__ . '/..' . '/react/socket/src/HappyEyeBallsConnectionBuilder.php', + 'ECSPrefix202307\\React\\Socket\\HappyEyeBallsConnector' => __DIR__ . '/..' . '/react/socket/src/HappyEyeBallsConnector.php', + 'ECSPrefix202307\\React\\Socket\\LimitingServer' => __DIR__ . '/..' . '/react/socket/src/LimitingServer.php', + 'ECSPrefix202307\\React\\Socket\\SecureConnector' => __DIR__ . '/..' . '/react/socket/src/SecureConnector.php', + 'ECSPrefix202307\\React\\Socket\\SecureServer' => __DIR__ . '/..' . '/react/socket/src/SecureServer.php', + 'ECSPrefix202307\\React\\Socket\\Server' => __DIR__ . '/..' . '/react/socket/src/Server.php', + 'ECSPrefix202307\\React\\Socket\\ServerInterface' => __DIR__ . '/..' . '/react/socket/src/ServerInterface.php', + 'ECSPrefix202307\\React\\Socket\\SocketServer' => __DIR__ . '/..' . '/react/socket/src/SocketServer.php', + 'ECSPrefix202307\\React\\Socket\\StreamEncryption' => __DIR__ . '/..' . '/react/socket/src/StreamEncryption.php', + 'ECSPrefix202307\\React\\Socket\\TcpConnector' => __DIR__ . '/..' . '/react/socket/src/TcpConnector.php', + 'ECSPrefix202307\\React\\Socket\\TcpServer' => __DIR__ . '/..' . '/react/socket/src/TcpServer.php', + 'ECSPrefix202307\\React\\Socket\\TimeoutConnector' => __DIR__ . '/..' . '/react/socket/src/TimeoutConnector.php', + 'ECSPrefix202307\\React\\Socket\\UnixConnector' => __DIR__ . '/..' . '/react/socket/src/UnixConnector.php', + 'ECSPrefix202307\\React\\Socket\\UnixServer' => __DIR__ . '/..' . '/react/socket/src/UnixServer.php', + 'ECSPrefix202307\\React\\Stream\\CompositeStream' => __DIR__ . '/..' . '/react/stream/src/CompositeStream.php', + 'ECSPrefix202307\\React\\Stream\\DuplexResourceStream' => __DIR__ . '/..' . '/react/stream/src/DuplexResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\DuplexStreamInterface' => __DIR__ . '/..' . '/react/stream/src/DuplexStreamInterface.php', + 'ECSPrefix202307\\React\\Stream\\ReadableResourceStream' => __DIR__ . '/..' . '/react/stream/src/ReadableResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\ReadableStreamInterface' => __DIR__ . '/..' . '/react/stream/src/ReadableStreamInterface.php', + 'ECSPrefix202307\\React\\Stream\\ThroughStream' => __DIR__ . '/..' . '/react/stream/src/ThroughStream.php', + 'ECSPrefix202307\\React\\Stream\\Util' => __DIR__ . '/..' . '/react/stream/src/Util.php', + 'ECSPrefix202307\\React\\Stream\\WritableResourceStream' => __DIR__ . '/..' . '/react/stream/src/WritableResourceStream.php', + 'ECSPrefix202307\\React\\Stream\\WritableStreamInterface' => __DIR__ . '/..' . '/react/stream/src/WritableStreamInterface.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Chunk' => __DIR__ . '/..' . '/sebastian/diff/src/Chunk.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\ConfigurationException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/ConfigurationException.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Diff' => __DIR__ . '/..' . '/sebastian/diff/src/Diff.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Differ' => __DIR__ . '/..' . '/sebastian/diff/src/Differ.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Exception' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/Exception.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\InvalidArgumentException' => __DIR__ . '/..' . '/sebastian/diff/src/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Line' => __DIR__ . '/..' . '/sebastian/diff/src/Line.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\LongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/LongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\MemoryEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\AbstractChunkOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\DiffOnlyOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\DiffOutputBuilderInterface' => __DIR__ . '/..' . '/sebastian/diff/src/Output/DiffOutputBuilderInterface.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\StrictUnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Output\\UnifiedDiffOutputBuilder' => __DIR__ . '/..' . '/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\Parser' => __DIR__ . '/..' . '/sebastian/diff/src/Parser.php', + 'ECSPrefix202307\\SebastianBergmann\\Diff\\TimeEfficientLongestCommonSubsequenceCalculator' => __DIR__ . '/..' . '/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Application' => __DIR__ . '/..' . '/symfony/console/Application.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Attribute\\AsCommand' => __DIR__ . '/..' . '/symfony/console/Attribute/AsCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CI\\GithubActionReporter' => __DIR__ . '/..' . '/symfony/console/CI/GithubActionReporter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Color' => __DIR__ . '/..' . '/symfony/console/Color.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\CommandLoaderInterface' => __DIR__ . '/..' . '/symfony/console/CommandLoader/CommandLoaderInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\ContainerCommandLoader' => __DIR__ . '/..' . '/symfony/console/CommandLoader/ContainerCommandLoader.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\CommandLoader\\FactoryCommandLoader' => __DIR__ . '/..' . '/symfony/console/CommandLoader/FactoryCommandLoader.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\Command' => __DIR__ . '/..' . '/symfony/console/Command/Command.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\CompleteCommand' => __DIR__ . '/..' . '/symfony/console/Command/CompleteCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\DumpCompletionCommand' => __DIR__ . '/..' . '/symfony/console/Command/DumpCompletionCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\HelpCommand' => __DIR__ . '/..' . '/symfony/console/Command/HelpCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\LazyCommand' => __DIR__ . '/..' . '/symfony/console/Command/LazyCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\ListCommand' => __DIR__ . '/..' . '/symfony/console/Command/ListCommand.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\LockableTrait' => __DIR__ . '/..' . '/symfony/console/Command/LockableTrait.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Command\\SignalableCommandInterface' => __DIR__ . '/..' . '/symfony/console/Command/SignalableCommandInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\CompletionInput' => __DIR__ . '/..' . '/symfony/console/Completion/CompletionInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\CompletionSuggestions' => __DIR__ . '/..' . '/symfony/console/Completion/CompletionSuggestions.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\BashCompletionOutput' => __DIR__ . '/..' . '/symfony/console/Completion/Output/BashCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\CompletionOutputInterface' => __DIR__ . '/..' . '/symfony/console/Completion/Output/CompletionOutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\FishCompletionOutput' => __DIR__ . '/..' . '/symfony/console/Completion/Output/FishCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Output\\ZshCompletionOutput' => __DIR__ . '/..' . '/symfony/console/Completion/Output/ZshCompletionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Completion\\Suggestion' => __DIR__ . '/..' . '/symfony/console/Completion/Suggestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\ConsoleEvents' => __DIR__ . '/..' . '/symfony/console/ConsoleEvents.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Cursor' => __DIR__ . '/..' . '/symfony/console/Cursor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\DependencyInjection\\AddConsoleCommandPass' => __DIR__ . '/..' . '/symfony/console/DependencyInjection/AddConsoleCommandPass.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\ApplicationDescription' => __DIR__ . '/..' . '/symfony/console/Descriptor/ApplicationDescription.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\Descriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/Descriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\DescriptorInterface' => __DIR__ . '/..' . '/symfony/console/Descriptor/DescriptorInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\JsonDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/JsonDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\MarkdownDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/MarkdownDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\ReStructuredTextDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/ReStructuredTextDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\TextDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/TextDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Descriptor\\XmlDescriptor' => __DIR__ . '/..' . '/symfony/console/Descriptor/XmlDescriptor.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\EventListener\\ErrorListener' => __DIR__ . '/..' . '/symfony/console/EventListener/ErrorListener.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleCommandEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleCommandEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleErrorEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleErrorEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleSignalEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleSignalEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Event\\ConsoleTerminateEvent' => __DIR__ . '/..' . '/symfony/console/Event/ConsoleTerminateEvent.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\CommandNotFoundException' => __DIR__ . '/..' . '/symfony/console/Exception/CommandNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/console/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\InvalidOptionException' => __DIR__ . '/..' . '/symfony/console/Exception/InvalidOptionException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\LogicException' => __DIR__ . '/..' . '/symfony/console/Exception/LogicException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\MissingInputException' => __DIR__ . '/..' . '/symfony/console/Exception/MissingInputException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\NamespaceNotFoundException' => __DIR__ . '/..' . '/symfony/console/Exception/NamespaceNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/console/Exception/RuntimeException.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\NullOutputFormatter' => __DIR__ . '/..' . '/symfony/console/Formatter/NullOutputFormatter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\NullOutputFormatterStyle' => __DIR__ . '/..' . '/symfony/console/Formatter/NullOutputFormatterStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatter' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatter.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyle' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\OutputFormatterStyleStack' => __DIR__ . '/..' . '/symfony/console/Formatter/OutputFormatterStyleStack.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Formatter\\WrappableOutputFormatterInterface' => __DIR__ . '/..' . '/symfony/console/Formatter/WrappableOutputFormatterInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\DebugFormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DebugFormatterHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\DescriptorHelper' => __DIR__ . '/..' . '/symfony/console/Helper/DescriptorHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Dumper' => __DIR__ . '/..' . '/symfony/console/Helper/Dumper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\FormatterHelper' => __DIR__ . '/..' . '/symfony/console/Helper/FormatterHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Helper' => __DIR__ . '/..' . '/symfony/console/Helper/Helper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\HelperInterface' => __DIR__ . '/..' . '/symfony/console/Helper/HelperInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\HelperSet' => __DIR__ . '/..' . '/symfony/console/Helper/HelperSet.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\InputAwareHelper' => __DIR__ . '/..' . '/symfony/console/Helper/InputAwareHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\OutputWrapper' => __DIR__ . '/..' . '/symfony/console/Helper/OutputWrapper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProcessHelper' => __DIR__ . '/..' . '/symfony/console/Helper/ProcessHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProgressBar' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressBar.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\ProgressIndicator' => __DIR__ . '/..' . '/symfony/console/Helper/ProgressIndicator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\QuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/QuestionHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\SymfonyQuestionHelper' => __DIR__ . '/..' . '/symfony/console/Helper/SymfonyQuestionHelper.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\Table' => __DIR__ . '/..' . '/symfony/console/Helper/Table.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableCell' => __DIR__ . '/..' . '/symfony/console/Helper/TableCell.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableCellStyle' => __DIR__ . '/..' . '/symfony/console/Helper/TableCellStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableRows' => __DIR__ . '/..' . '/symfony/console/Helper/TableRows.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableSeparator' => __DIR__ . '/..' . '/symfony/console/Helper/TableSeparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Helper\\TableStyle' => __DIR__ . '/..' . '/symfony/console/Helper/TableStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\ArgvInput' => __DIR__ . '/..' . '/symfony/console/Input/ArgvInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\ArrayInput' => __DIR__ . '/..' . '/symfony/console/Input/ArrayInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\Input' => __DIR__ . '/..' . '/symfony/console/Input/Input.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputArgument' => __DIR__ . '/..' . '/symfony/console/Input/InputArgument.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputAwareInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputAwareInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputDefinition' => __DIR__ . '/..' . '/symfony/console/Input/InputDefinition.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputInterface' => __DIR__ . '/..' . '/symfony/console/Input/InputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\InputOption' => __DIR__ . '/..' . '/symfony/console/Input/InputOption.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\StreamableInputInterface' => __DIR__ . '/..' . '/symfony/console/Input/StreamableInputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Input\\StringInput' => __DIR__ . '/..' . '/symfony/console/Input/StringInput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Logger\\ConsoleLogger' => __DIR__ . '/..' . '/symfony/console/Logger/ConsoleLogger.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\AnsiColorMode' => __DIR__ . '/..' . '/symfony/console/Output/AnsiColorMode.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\BufferedOutput' => __DIR__ . '/..' . '/symfony/console/Output/BufferedOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleOutput' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleOutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleOutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\ConsoleSectionOutput' => __DIR__ . '/..' . '/symfony/console/Output/ConsoleSectionOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\NullOutput' => __DIR__ . '/..' . '/symfony/console/Output/NullOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\Output' => __DIR__ . '/..' . '/symfony/console/Output/Output.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\OutputInterface' => __DIR__ . '/..' . '/symfony/console/Output/OutputInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\StreamOutput' => __DIR__ . '/..' . '/symfony/console/Output/StreamOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Output\\TrimmedBufferOutput' => __DIR__ . '/..' . '/symfony/console/Output/TrimmedBufferOutput.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\ChoiceQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ChoiceQuestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\ConfirmationQuestion' => __DIR__ . '/..' . '/symfony/console/Question/ConfirmationQuestion.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Question\\Question' => __DIR__ . '/..' . '/symfony/console/Question/Question.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\SignalRegistry\\SignalRegistry' => __DIR__ . '/..' . '/symfony/console/SignalRegistry/SignalRegistry.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\SingleCommandApplication' => __DIR__ . '/..' . '/symfony/console/SingleCommandApplication.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\OutputStyle' => __DIR__ . '/..' . '/symfony/console/Style/OutputStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\StyleInterface' => __DIR__ . '/..' . '/symfony/console/Style/StyleInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Style\\SymfonyStyle' => __DIR__ . '/..' . '/symfony/console/Style/SymfonyStyle.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Terminal' => __DIR__ . '/..' . '/symfony/console/Terminal.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\ApplicationTester' => __DIR__ . '/..' . '/symfony/console/Tester/ApplicationTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\CommandCompletionTester' => __DIR__ . '/..' . '/symfony/console/Tester/CommandCompletionTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\CommandTester' => __DIR__ . '/..' . '/symfony/console/Tester/CommandTester.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\Constraint\\CommandIsSuccessful' => __DIR__ . '/..' . '/symfony/console/Tester/Constraint/CommandIsSuccessful.php', + 'ECSPrefix202307\\Symfony\\Component\\Console\\Tester\\TesterTrait' => __DIR__ . '/..' . '/symfony/console/Tester/TesterTrait.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\FileNotFoundException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/FileNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\IOException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\IOExceptionInterface' => __DIR__ . '/..' . '/symfony/filesystem/Exception/IOExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/filesystem/Exception/RuntimeException.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Filesystem' => __DIR__ . '/..' . '/symfony/filesystem/Filesystem.php', + 'ECSPrefix202307\\Symfony\\Component\\Filesystem\\Path' => __DIR__ . '/..' . '/symfony/filesystem/Path.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\Comparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/Comparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\DateComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/DateComparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Comparator\\NumberComparator' => __DIR__ . '/..' . '/symfony/finder/Comparator/NumberComparator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Exception\\AccessDeniedException' => __DIR__ . '/..' . '/symfony/finder/Exception/AccessDeniedException.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Exception\\DirectoryNotFoundException' => __DIR__ . '/..' . '/symfony/finder/Exception/DirectoryNotFoundException.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Finder' => __DIR__ . '/..' . '/symfony/finder/Finder.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Gitignore' => __DIR__ . '/..' . '/symfony/finder/Gitignore.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Glob' => __DIR__ . '/..' . '/symfony/finder/Glob.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\CustomFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/CustomFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\DateRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DateRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\DepthRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/DepthRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\ExcludeDirectoryFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/ExcludeDirectoryFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FileTypeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FileTypeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FilecontentFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilecontentFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\FilenameFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/FilenameFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\LazyIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/LazyIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\MultiplePcreFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/MultiplePcreFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\PathFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/PathFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\RecursiveDirectoryIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/RecursiveDirectoryIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\SizeRangeFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SizeRangeFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\SortableIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/SortableIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\Iterator\\VcsIgnoredFilterIterator' => __DIR__ . '/..' . '/symfony/finder/Iterator/VcsIgnoredFilterIterator.php', + 'ECSPrefix202307\\Symfony\\Component\\Finder\\SplFileInfo' => __DIR__ . '/..' . '/symfony/finder/SplFileInfo.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Debug\\OptionsResolverIntrospector' => __DIR__ . '/..' . '/symfony/options-resolver/Debug/OptionsResolverIntrospector.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\AccessException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/AccessException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/ExceptionInterface.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\InvalidArgumentException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidArgumentException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\InvalidOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/InvalidOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\MissingOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/MissingOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\NoConfigurationException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoConfigurationException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\NoSuchOptionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/NoSuchOptionException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\OptionDefinitionException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/OptionDefinitionException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Exception\\UndefinedOptionsException' => __DIR__ . '/..' . '/symfony/options-resolver/Exception/UndefinedOptionsException.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\OptionConfigurator' => __DIR__ . '/..' . '/symfony/options-resolver/OptionConfigurator.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\Options' => __DIR__ . '/..' . '/symfony/options-resolver/Options.php', + 'ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\OptionsResolver' => __DIR__ . '/..' . '/symfony/options-resolver/OptionsResolver.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\Attribute\\Required' => __DIR__ . '/..' . '/symfony/service-contracts/Attribute/Required.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\Attribute\\SubscribedService' => __DIR__ . '/..' . '/symfony/service-contracts/Attribute/SubscribedService.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ResetInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ResetInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceLocatorTrait' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceLocatorTrait.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceProviderInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceProviderInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceSubscriberInterface' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberInterface.php', + 'ECSPrefix202307\\Symfony\\Contracts\\Service\\ServiceSubscriberTrait' => __DIR__ . '/..' . '/symfony/service-contracts/ServiceSubscriberTrait.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\CommandLine\\WorkerCommandLineFactory' => __DIR__ . '/..' . '/symplify/easy-parallel/src/CommandLine/WorkerCommandLineFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Contract\\SerializableInterface' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Contract/SerializableInterface.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\CpuCoreCountProvider' => __DIR__ . '/..' . '/symplify/easy-parallel/src/CpuCoreCountProvider.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\Action' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Enum/Action.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\Content' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Enum/Content.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\ReactCommand' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Enum/ReactCommand.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Enum\\ReactEvent' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Enum/ReactEvent.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Exception\\ParallelShouldNotHappenException' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Exception/ParallelShouldNotHappenException.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\FileSystem\\FilePathNormalizer' => __DIR__ . '/..' . '/symplify/easy-parallel/src/FileSystem/FilePathNormalizer.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\Reflection\\CommandFromReflectionFactory' => __DIR__ . '/..' . '/symplify/easy-parallel/src/Reflection/CommandFromReflectionFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ScheduleFactory' => __DIR__ . '/..' . '/symplify/easy-parallel/src/ScheduleFactory.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\EasyParallelConfig' => __DIR__ . '/..' . '/symplify/easy-parallel/src/ValueObject/EasyParallelConfig.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\ParallelProcess' => __DIR__ . '/..' . '/symplify/easy-parallel/src/ValueObject/ParallelProcess.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\ProcessPool' => __DIR__ . '/..' . '/symplify/easy-parallel/src/ValueObject/ProcessPool.php', + 'ECSPrefix202307\\Symplify\\EasyParallel\\ValueObject\\Schedule' => __DIR__ . '/..' . '/symplify/easy-parallel/src/ValueObject/Schedule.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\Category\\CategoryInfererInterface' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Contract/Category/CategoryInfererInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\CodeSampleInterface' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Contract/CodeSampleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\ConfigurableRuleInterface' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Contract/ConfigurableRuleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\DocumentedRuleInterface' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Contract/DocumentedRuleInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Contract\\RuleCodeSamplePrinterInterface' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Contract/RuleCodeSamplePrinterInterface.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Exception\\PoorDocumentationException' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Exception/PoorDocumentationException.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\Exception\\ShouldNotHappenException' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/Exception/ShouldNotHappenException.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\AbstractCodeSample' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/AbstractCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\CodeSample' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/CodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ComposerJsonAwareCodeSample' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ComposerJsonAwareCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ConfiguredCodeSample' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ConfiguredCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\CodeSample\\ExtraFileCodeSample' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/CodeSample/ExtraFileCodeSample.php', + 'ECSPrefix202307\\Symplify\\RuleDocGenerator\\ValueObject\\RuleDefinition' => __DIR__ . '/..' . '/symplify/rule-doc-generator-contracts/src/ValueObject/RuleDefinition.php', + 'ECSPrefix202307\\Webmozart\\Assert\\Assert' => __DIR__ . '/..' . '/webmozart/assert/src/Assert.php', + 'ECSPrefix202307\\Webmozart\\Assert\\InvalidArgumentException' => __DIR__ . '/..' . '/webmozart/assert/src/InvalidArgumentException.php', + 'ECSPrefix202307\\Webmozart\\Assert\\Mixin' => __DIR__ . '/..' . '/webmozart/assert/src/Mixin.php', + 'PhpCsFixer\\AbstractDoctrineAnnotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php', + 'PhpCsFixer\\AbstractFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractFixer.php', + 'PhpCsFixer\\AbstractFopenFlagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php', + 'PhpCsFixer\\AbstractFunctionReferenceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php', + 'PhpCsFixer\\AbstractNoUselessElseFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php', + 'PhpCsFixer\\AbstractPhpdocToTypeDeclarationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php', + 'PhpCsFixer\\AbstractPhpdocTypesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php', + 'PhpCsFixer\\AbstractProxyFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php', + 'PhpCsFixer\\Cache\\Cache' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/Cache.php', + 'PhpCsFixer\\Cache\\CacheInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php', + 'PhpCsFixer\\Cache\\CacheManagerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php', + 'PhpCsFixer\\Cache\\Directory' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/Directory.php', + 'PhpCsFixer\\Cache\\DirectoryInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php', + 'PhpCsFixer\\Cache\\FileCacheManager' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php', + 'PhpCsFixer\\Cache\\FileHandler' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php', + 'PhpCsFixer\\Cache\\FileHandlerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php', + 'PhpCsFixer\\Cache\\NullCacheManager' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php', + 'PhpCsFixer\\Cache\\Signature' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/Signature.php', + 'PhpCsFixer\\Cache\\SignatureInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php', + 'PhpCsFixer\\Config' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Config.php', + 'PhpCsFixer\\ConfigInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ConfigInterface.php', + 'PhpCsFixer\\ConfigurationException\\InvalidConfigurationException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\InvalidFixerConfigurationException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\InvalidForEnvFixerConfigurationException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php', + 'PhpCsFixer\\ConfigurationException\\RequiredFixerConfigurationException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php', + 'PhpCsFixer\\Console\\Application' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Application.php', + 'PhpCsFixer\\Console\\Command\\DescribeCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php', + 'PhpCsFixer\\Console\\Command\\DescribeNameNotFoundException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php', + 'PhpCsFixer\\Console\\Command\\DocumentationCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php', + 'PhpCsFixer\\Console\\Command\\FixCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php', + 'PhpCsFixer\\Console\\Command\\FixCommandExitStatusCalculator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php', + 'PhpCsFixer\\Console\\Command\\HelpCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php', + 'PhpCsFixer\\Console\\Command\\ListFilesCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php', + 'PhpCsFixer\\Console\\Command\\ListSetsCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php', + 'PhpCsFixer\\Console\\Command\\SelfUpdateCommand' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php', + 'PhpCsFixer\\Console\\ConfigurationResolver' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php', + 'PhpCsFixer\\Console\\Output\\ErrorOutput' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php', + 'PhpCsFixer\\Console\\Output\\OutputContext' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php', + 'PhpCsFixer\\Console\\Output\\Progress\\DotsOutput' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php', + 'PhpCsFixer\\Console\\Output\\Progress\\NullOutput' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputFactory' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php', + 'PhpCsFixer\\Console\\Output\\Progress\\ProgressOutputType' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\CheckstyleReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\GitlabReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\JsonReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\JunitReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReportSummary' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReporterFactory' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\ReporterInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\TextReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php', + 'PhpCsFixer\\Console\\Report\\FixReport\\XmlReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\JsonReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReportSummary' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReporterFactory' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\ReporterInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php', + 'PhpCsFixer\\Console\\Report\\ListSetsReport\\TextReporter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php', + 'PhpCsFixer\\Console\\SelfUpdate\\GithubClient' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php', + 'PhpCsFixer\\Console\\SelfUpdate\\GithubClientInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php', + 'PhpCsFixer\\Console\\SelfUpdate\\NewVersionChecker' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php', + 'PhpCsFixer\\Console\\SelfUpdate\\NewVersionCheckerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php', + 'PhpCsFixer\\Console\\WarningsDetector' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php', + 'PhpCsFixer\\Differ\\DiffConsoleFormatter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php', + 'PhpCsFixer\\Differ\\DifferInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php', + 'PhpCsFixer\\Differ\\FullDiffer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php', + 'PhpCsFixer\\Differ\\NullDiffer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php', + 'PhpCsFixer\\Differ\\UnifiedDiffer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php', + 'PhpCsFixer\\DocBlock\\Annotation' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php', + 'PhpCsFixer\\DocBlock\\DocBlock' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php', + 'PhpCsFixer\\DocBlock\\Line' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/Line.php', + 'PhpCsFixer\\DocBlock\\ShortDescription' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php', + 'PhpCsFixer\\DocBlock\\Tag' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php', + 'PhpCsFixer\\DocBlock\\TagComparator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php', + 'PhpCsFixer\\DocBlock\\TypeExpression' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php', + 'PhpCsFixer\\Doctrine\\Annotation\\Token' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php', + 'PhpCsFixer\\Doctrine\\Annotation\\Tokens' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php', + 'PhpCsFixer\\Documentation\\DocumentationLocator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php', + 'PhpCsFixer\\Documentation\\FixerDocumentGenerator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php', + 'PhpCsFixer\\Documentation\\ListDocumentGenerator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Documentation/ListDocumentGenerator.php', + 'PhpCsFixer\\Documentation\\RstUtils' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php', + 'PhpCsFixer\\Documentation\\RuleSetDocumentationGenerator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Documentation/RuleSetDocumentationGenerator.php', + 'PhpCsFixer\\Error\\Error' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Error/Error.php', + 'PhpCsFixer\\Error\\ErrorsManager' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php', + 'PhpCsFixer\\FileReader' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FileReader.php', + 'PhpCsFixer\\FileRemoval' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FileRemoval.php', + 'PhpCsFixer\\Finder' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Finder.php', + 'PhpCsFixer\\FixerConfiguration\\AliasedFixerOption' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\AliasedFixerOptionBuilder' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php', + 'PhpCsFixer\\FixerConfiguration\\AllowedValueSubset' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php', + 'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOption' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\DeprecatedFixerOptionInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php', + 'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolver' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php', + 'PhpCsFixer\\FixerConfiguration\\FixerConfigurationResolverInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOption' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOptionBuilder' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php', + 'PhpCsFixer\\FixerConfiguration\\FixerOptionInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php', + 'PhpCsFixer\\FixerConfiguration\\InvalidOptionsForEnvException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php', + 'PhpCsFixer\\FixerDefinition\\CodeSample' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php', + 'PhpCsFixer\\FixerDefinition\\CodeSampleInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSample' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php', + 'PhpCsFixer\\FixerDefinition\\FileSpecificCodeSampleInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\FixerDefinition' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php', + 'PhpCsFixer\\FixerDefinition\\FixerDefinitionInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSample' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificCodeSampleInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecification' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php', + 'PhpCsFixer\\FixerDefinition\\VersionSpecificationInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php', + 'PhpCsFixer\\FixerFactory' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerFactory.php', + 'PhpCsFixer\\FixerFileProcessedEvent' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php', + 'PhpCsFixer\\FixerNameValidator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/FixerNameValidator.php', + 'PhpCsFixer\\Fixer\\AbstractIncrementOperatorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php', + 'PhpCsFixer\\Fixer\\AbstractPhpUnitFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\ArrayPushFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\BacktickToShellExecFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\EregToPregFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\MbStrFunctionsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\ModernizeStrposFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoAliasFunctionsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoAliasLanguageConstructCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\NoMixedEchoPrintFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\PowToExponentiationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\RandomApiMigrationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php', + 'PhpCsFixer\\Fixer\\Alias\\SetTypeToCastFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\ArraySyntaxFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoMultilineWhitespaceAroundDoubleArrowFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoTrailingCommaInSinglelineArrayFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NoWhitespaceBeforeCommaInArrayFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\NormalizeIndexBraceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\TrimArraySpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\WhitespaceAfterCommaInArrayFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php', + 'PhpCsFixer\\Fixer\\ArrayNotation\\YieldFromArrayToYieldsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\BracesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\CurlyBracesPositionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\EncodingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NoMultipleStatementsPerLineFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NoTrailingCommaInSinglelineFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\NonPrintableCharacterFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\OctalNotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\PsrAutoloadingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php', + 'PhpCsFixer\\Fixer\\Basic\\SingleLineEmptyBodyFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\ClassReferenceNameCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\ConstantCaseFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\IntegerLiteralCaseFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\LowercaseKeywordsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\LowercaseStaticReferenceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\MagicConstantCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\MagicMethodCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\NativeFunctionCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php', + 'PhpCsFixer\\Fixer\\Casing\\NativeFunctionTypeDeclarationCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\CastSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\LowercaseCastFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\ModernizeTypesCastingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\NoShortBoolCastFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\NoUnsetCastFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php', + 'PhpCsFixer\\Fixer\\CastNotation\\ShortScalarCastFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ClassAttributesSeparationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ClassDefinitionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalClassFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalInternalClassFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\FinalPublicMethodForAbstractClassFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoBlankLinesAfterClassOpeningFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoNullPropertyInitializationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoPhp4ConstructorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\NoUnneededFinalMethodFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedClassElementsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedInterfacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTraitsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\OrderedTypesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\ProtectedToPrivateFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SelfAccessorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SelfStaticAccessorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SingleClassElementPerStatementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\SingleTraitInsertPerStatementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\ClassNotation\\VisibilityRequiredFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php', + 'PhpCsFixer\\Fixer\\ClassUsage\\DateTimeImmutableFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\CommentToPhpdocFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\HeaderCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\MultilineCommentOpeningClosingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\NoEmptyCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\NoTrailingWhitespaceInCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentSpacingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php', + 'PhpCsFixer\\Fixer\\Comment\\SingleLineCommentStyleFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php', + 'PhpCsFixer\\Fixer\\ConfigurableFixerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php', + 'PhpCsFixer\\Fixer\\ConstantNotation\\NativeConstantInvocationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ControlStructureBracesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ControlStructureContinuationPositionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\ElseifFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\EmptyLoopBodyFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\EmptyLoopConditionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\IncludeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoAlternativeSyntaxFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoBreakCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoSuperfluousElseifFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoTrailingCommaInListCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededControlParenthesesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUnneededCurlyBracesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\NoUselessElseFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SimplifiedIfReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSemicolonToColonFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchCaseSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\SwitchContinueToBreakFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\TrailingCommaInMultilineFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php', + 'PhpCsFixer\\Fixer\\ControlStructure\\YodaStyleFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php', + 'PhpCsFixer\\Fixer\\DeprecatedFixerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationArrayAssignmentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationBracesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationIndentationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php', + 'PhpCsFixer\\Fixer\\DoctrineAnnotation\\DoctrineAnnotationSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php', + 'PhpCsFixer\\Fixer\\FixerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\CombineNestedDirnameFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\DateTimeCreateFromFormatCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagOrderFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FopenFlagsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionDeclarationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\FunctionTypehintSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\ImplodeCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\LambdaNotUsedImportFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\MethodArgumentSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NativeFunctionInvocationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoSpacesAfterFunctionNameFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoTrailingCommaInSinglelineFunctionCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoUnreachableDefaultArgumentValueFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NoUselessSprintfFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\NullableTypeDeclarationForDefaultNullValueFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToParamTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToPropertyTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\PhpdocToReturnTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\RegularCallableCallFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\ReturnTypeDeclarationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\SingleLineThrowFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\StaticLambdaFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\UseArrowFunctionsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php', + 'PhpCsFixer\\Fixer\\FunctionNotation\\VoidReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php', + 'PhpCsFixer\\Fixer\\Import\\FullyQualifiedStrictTypesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php', + 'PhpCsFixer\\Fixer\\Import\\GlobalNamespaceImportFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php', + 'PhpCsFixer\\Fixer\\Import\\GroupImportFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoLeadingImportSlashFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoUnneededImportAliasFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php', + 'PhpCsFixer\\Fixer\\Import\\NoUnusedImportsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php', + 'PhpCsFixer\\Fixer\\Import\\OrderedImportsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php', + 'PhpCsFixer\\Fixer\\Import\\SingleImportPerStatementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php', + 'PhpCsFixer\\Fixer\\Import\\SingleLineAfterImportsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php', + 'PhpCsFixer\\Fixer\\Indentation' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ClassKeywordRemoveFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveIssetsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\CombineConsecutiveUnsetsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareEqualNormalizeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DeclareParenthesesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\DirConstantFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ErrorSuppressionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\ExplicitIndirectVariableFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\FunctionToConstantFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\GetClassToClassKeywordFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\IsNullFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\NoUnsetOnPropertyFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\NullableTypeDeclarationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAfterConstructFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php', + 'PhpCsFixer\\Fixer\\LanguageConstruct\\SingleSpaceAroundConstructFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php', + 'PhpCsFixer\\Fixer\\ListNotation\\ListSyntaxFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLineAfterNamespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\BlankLinesBeforeNamespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\CleanNamespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\NoBlankLinesBeforeNamespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\NoLeadingNamespaceWhitespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\NamespaceNotation\\SingleBlankLineBeforeNamespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php', + 'PhpCsFixer\\Fixer\\Naming\\NoHomoglyphNamesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\AssignNullCoalescingToCoalesceEqualFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\BinaryOperatorSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\ConcatSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\IncrementStyleFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\LogicalOperatorsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NewWithBracesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoSpaceAroundDoubleColonFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoUselessConcatOperatorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NoUselessNullsafeOperatorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\NotOperatorWithSuccessorSpaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\ObjectOperatorWithoutWhitespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\OperatorLinebreakFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\StandardizeIncrementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\StandardizeNotEqualsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryOperatorSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryToElvisOperatorFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\TernaryToNullCoalescingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php', + 'PhpCsFixer\\Fixer\\Operator\\UnaryOperatorSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\BlankLineAfterOpeningTagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\EchoTagSyntaxFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\FullOpeningTagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\LinebreakAfterOpeningTagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpTag\\NoClosingTagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitConstructFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderNameFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderReturnTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDataProviderStaticFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitDedicateAssertInternalTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitExpectationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitFqcnAnnotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitInternalClassFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMethodCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitMockShortWillReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNamespacedFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitNoExpectationAnnotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSetUpTearDownVisibilityFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitSizeClassFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitStrictFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTargetVersion' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestAnnotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestCaseStaticMethodCallsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php', + 'PhpCsFixer\\Fixer\\PhpUnit\\PhpUnitTestClassRequiresCoversFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\AlignMultilineCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocAnnotationRemoveFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\GeneralPhpdocTagRenameFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoBlankLinesAfterPhpdocFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoEmptyPhpdocFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\NoSuperfluousPhpdocTagsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAddMissingParamAnnotationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAlignFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocAnnotationWithoutDotFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocIndentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocInlineTagNormalizerFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocLineSpanFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAccessFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoAliasTagFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoEmptyReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoPackageFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocNoUselessInheritdocFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderByValueFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocOrderFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocParamOrderFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocReturnSelfReferenceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocScalarFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSeparationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSingleLineVarSpacingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocSummaryFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagCasingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTagTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocToCommentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimConsecutiveBlankLineSeparationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTrimFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocTypesOrderFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarAnnotationCorrectOrderFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php', + 'PhpCsFixer\\Fixer\\Phpdoc\\PhpdocVarWithoutNameFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\NoUselessReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\ReturnAssignmentFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php', + 'PhpCsFixer\\Fixer\\ReturnNotation\\SimplifiedNullReturnFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\MultilineWhitespaceBeforeSemicolonsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\NoEmptyStatementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\NoSinglelineWhitespaceBeforeSemicolonsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\SemicolonAfterInstructionFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php', + 'PhpCsFixer\\Fixer\\Semicolon\\SpaceAfterSemicolonFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\DeclareStrictTypesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\StrictComparisonFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php', + 'PhpCsFixer\\Fixer\\Strict\\StrictParamFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\EscapeImplicitBackslashesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\ExplicitStringVariableFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\HeredocToNowdocFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\NoBinaryStringFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\NoTrailingWhitespaceInStringFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\SimpleToComplexStringVariableFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\SingleQuoteFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\StringLengthToEmptyFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php', + 'PhpCsFixer\\Fixer\\StringNotation\\StringLineEndingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\ArrayIndentationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBeforeStatementFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\BlankLineBetweenImportGroupsFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\CompactNullableTypehintFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\HeredocIndentationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\IndentationTypeFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\LineEndingFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\MethodChainingIndentationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoExtraBlankLinesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesAroundOffsetFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoSpacesInsideParenthesisFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoTrailingWhitespaceFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\NoWhitespaceInBlankLineFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\SingleBlankLineAtEofFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\StatementIndentationFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\TypeDeclarationSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php', + 'PhpCsFixer\\Fixer\\Whitespace\\TypesSpacesFixer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php', + 'PhpCsFixer\\Fixer\\WhitespacesAwareFixerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php', + 'PhpCsFixer\\Indicator\\PhpUnitTestCaseIndicator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php', + 'PhpCsFixer\\Linter\\CachingLinter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php', + 'PhpCsFixer\\Linter\\Linter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/Linter.php', + 'PhpCsFixer\\Linter\\LinterInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php', + 'PhpCsFixer\\Linter\\LintingException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/LintingException.php', + 'PhpCsFixer\\Linter\\LintingResultInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php', + 'PhpCsFixer\\Linter\\ProcessLinter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php', + 'PhpCsFixer\\Linter\\ProcessLinterProcessBuilder' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php', + 'PhpCsFixer\\Linter\\ProcessLintingResult' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php', + 'PhpCsFixer\\Linter\\TokenizerLinter' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php', + 'PhpCsFixer\\Linter\\TokenizerLintingResult' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php', + 'PhpCsFixer\\Linter\\UnavailableLinterException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php', + 'PhpCsFixer\\PharChecker' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/PharChecker.php', + 'PhpCsFixer\\PharCheckerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php', + 'PhpCsFixer\\Preg' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Preg.php', + 'PhpCsFixer\\PregException' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/PregException.php', + 'PhpCsFixer\\RuleSet\\AbstractMigrationSetDescription' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php', + 'PhpCsFixer\\RuleSet\\AbstractRuleSetDescription' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php', + 'PhpCsFixer\\RuleSet\\RuleSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php', + 'PhpCsFixer\\RuleSet\\RuleSetDescriptionInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php', + 'PhpCsFixer\\RuleSet\\RuleSetInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php', + 'PhpCsFixer\\RuleSet\\RuleSets' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php', + 'PhpCsFixer\\RuleSet\\Sets\\DoctrineAnnotationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERCS1x0RiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERCS1x0Set' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PERSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP54MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP56MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP70MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP71MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP73MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP74MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP80MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP81MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHP82MigrationSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit100MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit30MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit32MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit35MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit43MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit48MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit50MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit52MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit54MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit55MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit56MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit57MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit60MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit75MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PHPUnit84MigrationRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR12RiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR12Set' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR1Set' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PSR2Set' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php', + 'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\PhpCsFixerSet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php', + 'PhpCsFixer\\RuleSet\\Sets\\SymfonyRiskySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php', + 'PhpCsFixer\\RuleSet\\Sets\\SymfonySet' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php', + 'PhpCsFixer\\Runner\\FileCachingLintingIterator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php', + 'PhpCsFixer\\Runner\\FileFilterIterator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php', + 'PhpCsFixer\\Runner\\FileLintingIterator' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php', + 'PhpCsFixer\\Runner\\Runner' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Runner/Runner.php', + 'PhpCsFixer\\StdinFileInfo' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/StdinFileInfo.php', + 'PhpCsFixer\\Tokenizer\\AbstractTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php', + 'PhpCsFixer\\Tokenizer\\AbstractTypeTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\AlternativeSyntaxAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\AbstractControlCaseStructuresAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\ArgumentAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\CaseAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\DataProviderAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\DefaultAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\EnumAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\MatchAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\NamespaceUseAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\StartEndTokenAwareAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\SwitchAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\Analysis\\TypeAnalysis' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ArgumentsAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\AttributeAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\BlocksAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ClassyAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\CommentsAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ControlCaseStructuresAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\DataProviderAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\FunctionsAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\GotoLabelAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\NamespaceUsesAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\NamespacesAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\RangeAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\ReferenceAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\Analyzer\\WhitespacesAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\CT' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php', + 'PhpCsFixer\\Tokenizer\\CodeHasher' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php', + 'PhpCsFixer\\Tokenizer\\Token' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php', + 'PhpCsFixer\\Tokenizer\\Tokens' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php', + 'PhpCsFixer\\Tokenizer\\TokensAnalyzer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php', + 'PhpCsFixer\\Tokenizer\\TransformerInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ArrayTypehintTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\AttributeTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\BraceClassInstantiationTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ClassConstantTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ConstructorPromotionTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\CurlyBraceTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\DisjunctiveNormalFormTypeParenthesisTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\FirstClassCallableTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ImportTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NameQualifiedTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NamedArgumentTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NamespaceOperatorTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\NullableTypeTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\ReturnRefTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\SquareBraceTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeAlternationTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeColonTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\TypeIntersectionTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\UseTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformer\\WhitespacyCommentTransformer' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php', + 'PhpCsFixer\\Tokenizer\\Transformers' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Tokenizer/Transformers.php', + 'PhpCsFixer\\ToolInfo' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ToolInfo.php', + 'PhpCsFixer\\ToolInfoInterface' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php', + 'PhpCsFixer\\Utils' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/Utils.php', + 'PhpCsFixer\\WhitespacesFixerConfig' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php', + 'PhpCsFixer\\WordMatcher' => __DIR__ . '/..' . '/friendsofphp/php-cs-fixer/src/WordMatcher.php', + 'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php', + 'ReturnTypeWillChange' => __DIR__ . '/..' . '/symfony/polyfill-php81/Resources/stubs/ReturnTypeWillChange.php', + 'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php', + 'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php', + 'Symfony\\Polyfill\\Php80\\Php80' => __DIR__ . '/..' . '/symfony/polyfill-php80/Php80.php', + 'Symfony\\Polyfill\\Php80\\PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/PhpToken.php', + 'Symfony\\Polyfill\\Php81\\Php81' => __DIR__ . '/..' . '/symfony/polyfill-php81/Php81.php', + 'Symplify\\CodingStandard\\DocBlock\\UselessDocBlockCleaner' => __DIR__ . '/..' . '/symplify/coding-standard/src/DocBlock/UselessDocBlockCleaner.php', + 'Symplify\\CodingStandard\\Enum\\BlockBorderType' => __DIR__ . '/..' . '/symplify/coding-standard/src/Enum/BlockBorderType.php', + 'Symplify\\CodingStandard\\Fixer\\AbstractSymplifyFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/AbstractSymplifyFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Annotation\\RemovePHPStormAnnotationFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Annotation/RemovePHPStormAnnotationFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\ArrayListItemNewlineFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayListItemNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\ArrayOpenerAndCloserNewlineFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/ArrayNotation/ArrayOpenerAndCloserNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\ArrayNotation\\StandaloneLineInMultilineArrayFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/ArrayNotation/StandaloneLineInMultilineArrayFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Commenting\\ParamReturnAndVarTagMalformsFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Commenting/ParamReturnAndVarTagMalformsFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Commenting\\RemoveUselessDefaultCommentFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Commenting/RemoveUselessDefaultCommentFixer.php', + 'Symplify\\CodingStandard\\Fixer\\LineLength\\LineLengthFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/LineLength/LineLengthFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\MethodChainingNewlineFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Spacing/MethodChainingNewlineFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\SpaceAfterCommaHereNowDocFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Spacing/SpaceAfterCommaHereNowDocFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\StandaloneLineConstructorParamFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Spacing/StandaloneLineConstructorParamFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Spacing\\StandaloneLinePromotedPropertyFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Spacing/StandaloneLinePromotedPropertyFixer.php', + 'Symplify\\CodingStandard\\Fixer\\Strict\\BlankLineAfterStrictTypesFixer' => __DIR__ . '/..' . '/symplify/coding-standard/src/Fixer/Strict/BlankLineAfterStrictTypesFixer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\ChainMethodCallAnalyzer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/ChainMethodCallAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\DocblockRelatedParamNamesResolver' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/DocblockRelatedParamNamesResolver.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\FunctionCallNameMatcher' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/FunctionCallNameMatcher.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\HeredocAnalyzer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/HeredocAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\Naming\\MethodNameResolver' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/Naming/MethodNameResolver.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\NewlineAnalyzer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/NewlineAnalyzer.php', + 'Symplify\\CodingStandard\\TokenAnalyzer\\ParamNewliner' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenAnalyzer/ParamNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\ArrayAnalyzer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/ArrayAnalyzer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\BlockFinder' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/BlockFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\CallAnalyzer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/CallAnalyzer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\IndentDetector' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/IndentDetector.php', + 'Symplify\\CodingStandard\\TokenRunner\\Analyzer\\FixerAnalyzer\\TokenSkipper' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Analyzer/FixerAnalyzer/TokenSkipper.php', + 'Symplify\\CodingStandard\\TokenRunner\\Arrays\\ArrayItemNewliner' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Arrays/ArrayItemNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Contract\\DocBlock\\MalformWorkerInterface' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Contract/DocBlock/MalformWorkerInterface.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\InlineVarMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVarMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\InlineVariableDocBlockMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/InlineVariableDocBlockMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\MissingParamNameMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingParamNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\MissingVarNameMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/MissingVarNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\ParamNameReferenceMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameReferenceMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\ParamNameTypoMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/ParamNameTypoMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SuperfluousReturnNameMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousReturnNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SuperfluousVarNameMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SuperfluousVarNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\DocBlock\\MalformWorker\\SwitchedTypeAndNameMalformWorker' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/DocBlock/MalformWorker/SwitchedTypeAndNameMalformWorker.php', + 'Symplify\\CodingStandard\\TokenRunner\\Enum\\LineKind' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Enum/LineKind.php', + 'Symplify\\CodingStandard\\TokenRunner\\Exception\\MissingImplementationException' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Exception/MissingImplementationException.php', + 'Symplify\\CodingStandard\\TokenRunner\\Exception\\TokenNotFoundException' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Exception/TokenNotFoundException.php', + 'Symplify\\CodingStandard\\TokenRunner\\TokenFinder' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/TokenFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\FirstLineLengthResolver' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/FirstLineLengthResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthCloserTransformer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthCloserTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthOpenerTransformer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthOpenerTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthResolver' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\LineLengthTransformer' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/LineLengthTransformer.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\TokensInliner' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensInliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Transformer\\FixerTransformer\\TokensNewliner' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Transformer/FixerTransformer/TokensNewliner.php', + 'Symplify\\CodingStandard\\TokenRunner\\Traverser\\ArrayBlockInfoFinder' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Traverser/ArrayBlockInfoFinder.php', + 'Symplify\\CodingStandard\\TokenRunner\\Traverser\\TokenReverser' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Traverser/TokenReverser.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObjectFactory\\LineLengthAndPositionFactory' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/ValueObjectFactory/LineLengthAndPositionFactory.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\BlockInfo' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/ValueObject/BlockInfo.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\LineLengthAndPosition' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/ValueObject/LineLengthAndPosition.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\TokenKinds' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/ValueObject/TokenKinds.php', + 'Symplify\\CodingStandard\\TokenRunner\\ValueObject\\Wrapper\\FixerWrapper\\ArrayWrapper' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/ValueObject/Wrapper/FixerWrapper/ArrayWrapper.php', + 'Symplify\\CodingStandard\\TokenRunner\\Whitespace\\IndentResolver' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Whitespace/IndentResolver.php', + 'Symplify\\CodingStandard\\TokenRunner\\Wrapper\\FixerWrapper\\ArrayWrapperFactory' => __DIR__ . '/..' . '/symplify/coding-standard/src/TokenRunner/Wrapper/FixerWrapper/ArrayWrapperFactory.php', + 'Symplify\\CodingStandard\\ValueObject\\BlockInfoMetadata' => __DIR__ . '/..' . '/symplify/coding-standard/src/ValueObject/BlockInfoMetadata.php', + 'Symplify\\CodingStandard\\ValueObject\\CodingStandardConfig' => __DIR__ . '/..' . '/symplify/coding-standard/src/ValueObject/CodingStandardConfig.php', + 'Symplify\\EasyCodingStandard\\Application\\EasyCodingStandardApplication' => __DIR__ . '/../..' . '/src/Application/EasyCodingStandardApplication.php', + 'Symplify\\EasyCodingStandard\\Application\\FileProcessorCollector' => __DIR__ . '/../..' . '/src/Application/FileProcessorCollector.php', + 'Symplify\\EasyCodingStandard\\Application\\SingleFileProcessor' => __DIR__ . '/../..' . '/src/Application/SingleFileProcessor.php', + 'Symplify\\EasyCodingStandard\\Application\\Version\\StaticVersionResolver' => __DIR__ . '/../..' . '/src/Application/Version/StaticVersionResolver.php', + 'Symplify\\EasyCodingStandard\\Caching\\Cache' => __DIR__ . '/../..' . '/packages/Caching/Cache.php', + 'Symplify\\EasyCodingStandard\\Caching\\CacheFactory' => __DIR__ . '/../..' . '/packages/Caching/CacheFactory.php', + 'Symplify\\EasyCodingStandard\\Caching\\ChangedFilesDetector' => __DIR__ . '/../..' . '/packages/Caching/ChangedFilesDetector.php', + 'Symplify\\EasyCodingStandard\\Caching\\FileHashComputer' => __DIR__ . '/../..' . '/packages/Caching/FileHashComputer.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\CacheFilePaths' => __DIR__ . '/../..' . '/packages/Caching/ValueObject/CacheFilePaths.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\CacheItem' => __DIR__ . '/../..' . '/packages/Caching/ValueObject/CacheItem.php', + 'Symplify\\EasyCodingStandard\\Caching\\ValueObject\\Storage\\FileCacheStorage' => __DIR__ . '/../..' . '/packages/Caching/ValueObject/Storage/FileCacheStorage.php', + 'Symplify\\EasyCodingStandard\\Config\\ECSConfig' => __DIR__ . '/../..' . '/src/Config/ECSConfig.php', + 'Symplify\\EasyCodingStandard\\Configuration\\ConfigInitializer' => __DIR__ . '/../..' . '/src/Configuration/ConfigInitializer.php', + 'Symplify\\EasyCodingStandard\\Configuration\\ConfigurationFactory' => __DIR__ . '/../..' . '/src/Configuration/ConfigurationFactory.php', + 'Symplify\\EasyCodingStandard\\Configuration\\InitPathsResolver' => __DIR__ . '/../..' . '/src/Configuration/InitPathsResolver.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\AbstractCheckCommand' => __DIR__ . '/../..' . '/src/Console/Command/AbstractCheckCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\CheckCommand' => __DIR__ . '/../..' . '/src/Console/Command/CheckCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\ListCheckersCommand' => __DIR__ . '/../..' . '/src/Console/Command/ListCheckersCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\Command\\WorkerCommand' => __DIR__ . '/../..' . '/src/Console/Command/WorkerCommand.php', + 'Symplify\\EasyCodingStandard\\Console\\EasyCodingStandardConsoleApplication' => __DIR__ . '/../..' . '/src/Console/EasyCodingStandardConsoleApplication.php', + 'Symplify\\EasyCodingStandard\\Console\\ExitCode' => __DIR__ . '/../..' . '/src/Console/ExitCode.php', + 'Symplify\\EasyCodingStandard\\Console\\Formatter\\ColorConsoleDiffFormatter' => __DIR__ . '/../..' . '/src/Console/Formatter/ColorConsoleDiffFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\ConsoleOutputFormatter' => __DIR__ . '/../..' . '/src/Console/Output/ConsoleOutputFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\ExitCodeResolver' => __DIR__ . '/../..' . '/src/Console/Output/ExitCodeResolver.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\JsonOutputFormatter' => __DIR__ . '/../..' . '/src/Console/Output/JsonOutputFormatter.php', + 'Symplify\\EasyCodingStandard\\Console\\Output\\OutputFormatterCollector' => __DIR__ . '/../..' . '/src/Console/Output/OutputFormatterCollector.php', + 'Symplify\\EasyCodingStandard\\Console\\Reporter\\CheckerListReporter' => __DIR__ . '/../..' . '/src/Console/Reporter/CheckerListReporter.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\EasyCodingStandardStyle' => __DIR__ . '/../..' . '/src/Console/Style/EasyCodingStandardStyle.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\EasyCodingStandardStyleFactory' => __DIR__ . '/../..' . '/src/Console/Style/EasyCodingStandardStyleFactory.php', + 'Symplify\\EasyCodingStandard\\Console\\Style\\SymfonyStyleFactory' => __DIR__ . '/../..' . '/src/Console/Style/SymfonyStyleFactory.php', + 'Symplify\\EasyCodingStandard\\Contract\\Application\\FileProcessorInterface' => __DIR__ . '/../..' . '/src/Contract/Application/FileProcessorInterface.php', + 'Symplify\\EasyCodingStandard\\Contract\\Console\\Output\\OutputFormatterInterface' => __DIR__ . '/../..' . '/src/Contract/Console/Output/OutputFormatterInterface.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\CompilerPassHelper' => __DIR__ . '/../..' . '/src/DependencyInjection/CompilerPass/CompilerPassHelper.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\ConflictingCheckersCompilerPass' => __DIR__ . '/../..' . '/src/DependencyInjection/CompilerPass/ConflictingCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\RemoveExcludedCheckersCompilerPass' => __DIR__ . '/../..' . '/src/DependencyInjection/CompilerPass/RemoveExcludedCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\CompilerPass\\RemoveMutualCheckersCompilerPass' => __DIR__ . '/../..' . '/src/DependencyInjection/CompilerPass/RemoveMutualCheckersCompilerPass.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\EasyCodingStandardContainerFactory' => __DIR__ . '/../..' . '/src/DependencyInjection/EasyCodingStandardContainerFactory.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\NewContainerFactory' => __DIR__ . '/../..' . '/src/DependencyInjection/NewContainerFactory.php', + 'Symplify\\EasyCodingStandard\\DependencyInjection\\SimpleParameterProvider' => __DIR__ . '/../..' . '/src/DependencyInjection/SimpleParameterProvider.php', + 'Symplify\\EasyCodingStandard\\Error\\FileDiffFactory' => __DIR__ . '/../..' . '/src/Error/FileDiffFactory.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\ConflictingCheckersLoadedException' => __DIR__ . '/../..' . '/src/Exception/Configuration/ConflictingCheckersLoadedException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\FileNotFoundException' => __DIR__ . '/../..' . '/src/Exception/Configuration/FileNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\InitializationException' => __DIR__ . '/../..' . '/src/Exception/Configuration/InitializationException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\OutputFormatterNotFoundException' => __DIR__ . '/../..' . '/src/Exception/Configuration/OutputFormatterNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\SourceNotFoundException' => __DIR__ . '/../..' . '/src/Exception/Configuration/SourceNotFoundException.php', + 'Symplify\\EasyCodingStandard\\Exception\\Configuration\\WhitespaceConfigurationException' => __DIR__ . '/../..' . '/src/Exception/Configuration/WhitespaceConfigurationException.php', + 'Symplify\\EasyCodingStandard\\Exception\\ShouldNotHappenException' => __DIR__ . '/../..' . '/src/Exception/ShouldNotHappenException.php', + 'Symplify\\EasyCodingStandard\\Exception\\VersionException' => __DIR__ . '/../..' . '/src/Exception/VersionException.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\FileFilter' => __DIR__ . '/../..' . '/src/FileSystem/FileFilter.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\PathNormalizer' => __DIR__ . '/../..' . '/src/FileSystem/PathNormalizer.php', + 'Symplify\\EasyCodingStandard\\FileSystem\\StaticRelativeFilePathHelper' => __DIR__ . '/../..' . '/src/FileSystem/StaticRelativeFilePathHelper.php', + 'Symplify\\EasyCodingStandard\\Finder\\SourceFinder' => __DIR__ . '/../..' . '/src/Finder/SourceFinder.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\Application\\FixerFileProcessor' => __DIR__ . '/../..' . '/packages/FixerRunner/Application/FixerFileProcessor.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\Parser\\FileToTokensParser' => __DIR__ . '/../..' . '/packages/FixerRunner/Parser/FileToTokensParser.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\ValueObject\\Spacing' => __DIR__ . '/../..' . '/packages/FixerRunner/ValueObject/Spacing.php', + 'Symplify\\EasyCodingStandard\\FixerRunner\\WhitespacesFixerConfigFactory' => __DIR__ . '/../..' . '/packages/FixerRunner/WhitespacesFixerConfigFactory.php', + 'Symplify\\EasyCodingStandard\\MemoryLimitter' => __DIR__ . '/../..' . '/src/MemoryLimitter.php', + 'Symplify\\EasyCodingStandard\\Parallel\\Application\\ParallelFileProcessor' => __DIR__ . '/../..' . '/packages/Parallel/Application/ParallelFileProcessor.php', + 'Symplify\\EasyCodingStandard\\Parallel\\ValueObject\\Bridge' => __DIR__ . '/../..' . '/packages/Parallel/ValueObject/Bridge.php', + 'Symplify\\EasyCodingStandard\\Parallel\\ValueObject\\Name' => __DIR__ . '/../..' . '/packages/Parallel/ValueObject/Name.php', + 'Symplify\\EasyCodingStandard\\Parallel\\WorkerRunner' => __DIR__ . '/../..' . '/packages/Parallel/WorkerRunner.php', + 'Symplify\\EasyCodingStandard\\Reporter\\ProcessedFileReporter' => __DIR__ . '/../..' . '/src/Reporter/ProcessedFileReporter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Contract\\SkipVoterInterface' => __DIR__ . '/../..' . '/packages/Skipper/Contract/SkipVoterInterface.php', + 'Symplify\\EasyCodingStandard\\Skipper\\FileSystem\\FnMatchPathNormalizer' => __DIR__ . '/../..' . '/packages/Skipper/FileSystem/FnMatchPathNormalizer.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Fnmatcher' => __DIR__ . '/../..' . '/packages/Skipper/Fnmatcher.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Matcher\\FileInfoMatcher' => __DIR__ . '/../..' . '/packages/Skipper/Matcher/FileInfoMatcher.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedClassAndCodesResolver' => __DIR__ . '/../..' . '/packages/Skipper/SkipCriteriaResolver/SkippedClassAndCodesResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedClassResolver' => __DIR__ . '/../..' . '/packages/Skipper/SkipCriteriaResolver/SkippedClassResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedMessagesResolver' => __DIR__ . '/../..' . '/packages/Skipper/SkipCriteriaResolver/SkippedMessagesResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipCriteriaResolver\\SkippedPathsResolver' => __DIR__ . '/../..' . '/packages/Skipper/SkipCriteriaResolver/SkippedPathsResolver.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\ClassAndCodeSkipVoter' => __DIR__ . '/../..' . '/packages/Skipper/SkipVoter/ClassAndCodeSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\ClassSkipVoter' => __DIR__ . '/../..' . '/packages/Skipper/SkipVoter/ClassSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\MessageSkipVoter' => __DIR__ . '/../..' . '/packages/Skipper/SkipVoter/MessageSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\SkipVoter\\PathSkipVoter' => __DIR__ . '/../..' . '/packages/Skipper/SkipVoter/PathSkipVoter.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Skipper\\SkipSkipper' => __DIR__ . '/../..' . '/packages/Skipper/Skipper/SkipSkipper.php', + 'Symplify\\EasyCodingStandard\\Skipper\\Skipper\\Skipper' => __DIR__ . '/../..' . '/packages/Skipper/Skipper/Skipper.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\Application\\SniffFileProcessor' => __DIR__ . '/../..' . '/packages/SniffRunner/Application/SniffFileProcessor.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\DataCollector\\SniffMetadataCollector' => __DIR__ . '/../..' . '/packages/SniffRunner/DataCollector/SniffMetadataCollector.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\File\\FileFactory' => __DIR__ . '/../..' . '/packages/SniffRunner/File/FileFactory.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\ValueObject\\Error\\CodingStandardError' => __DIR__ . '/../..' . '/packages/SniffRunner/ValueObject/Error/CodingStandardError.php', + 'Symplify\\EasyCodingStandard\\SniffRunner\\ValueObject\\File' => __DIR__ . '/../..' . '/packages/SniffRunner/ValueObject/File.php', + 'Symplify\\EasyCodingStandard\\Testing\\Contract\\ConfigAwareInterface' => __DIR__ . '/../..' . '/src/Testing/Contract/ConfigAwareInterface.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\AbstractCheckerTestCase' => __DIR__ . '/../..' . '/src/Testing/PHPUnit/AbstractCheckerTestCase.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\AbstractTestCase' => __DIR__ . '/../..' . '/src/Testing/PHPUnit/AbstractTestCase.php', + 'Symplify\\EasyCodingStandard\\Testing\\PHPUnit\\FixtureFinder' => __DIR__ . '/../..' . '/src/Testing/PHPUnit/FixtureFinder.php', + 'Symplify\\EasyCodingStandard\\Utils\\ParametersMerger' => __DIR__ . '/../..' . '/src/Utils/ParametersMerger.php', + 'Symplify\\EasyCodingStandard\\Utils\\PrivatesAccessorHelper' => __DIR__ . '/../..' . '/src/Utils/PrivatesAccessorHelper.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Configuration' => __DIR__ . '/../..' . '/src/ValueObject/Configuration.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\ErrorAndDiffResult' => __DIR__ . '/../..' . '/src/ValueObject/Error/ErrorAndDiffResult.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\FileDiff' => __DIR__ . '/../..' . '/src/ValueObject/Error/FileDiff.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Error\\SystemError' => __DIR__ . '/../..' . '/src/ValueObject/Error/SystemError.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Option' => __DIR__ . '/../..' . '/src/ValueObject/Option.php', + 'Symplify\\EasyCodingStandard\\ValueObject\\Set\\SetList' => __DIR__ . '/../..' . '/src/ValueObject/Set/SetList.php', + 'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php', + 'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit24ab6383ac11570ff93fe409c40ede8c::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit24ab6383ac11570ff93fe409c40ede8c::$prefixDirsPsr4; + $loader->classMap = ComposerStaticInit24ab6383ac11570ff93fe409c40ede8c::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 00000000000..664340f1fd9 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,2732 @@ +{ + "packages": [ + { + "name": "clue\/ndjson-react", + "version": "v1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/clue\/reactphp-ndjson.git", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/clue\/reactphp-ndjson\/zipball\/392dc165fce93b5bb5c637b67e59619223c931b0", + "reference": "392dc165fce93b5bb5c637b67e59619223c931b0", + "shasum": "" + }, + "require": { + "php": ">=5.3", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react\/event-loop": "^1.2" + }, + "time": "2022-12-23T10:58:28+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Clue\\React\\NDJson\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering" + } + ], + "description": "Streaming newline-delimited JSON (NDJSON) parser and encoder for ReactPHP.", + "homepage": "https:\/\/github.com\/clue\/reactphp-ndjson", + "keywords": [ + "NDJSON", + "json", + "jsonlines", + "newline", + "reactphp", + "streaming" + ], + "support": { + "issues": "https:\/\/github.com\/clue\/reactphp-ndjson\/issues", + "source": "https:\/\/github.com\/clue\/reactphp-ndjson\/tree\/v1.3.0" + }, + "funding": [ + { + "url": "https:\/\/clue.engineering\/support", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/clue", + "type": "github" + } + ], + "install-path": "..\/clue\/ndjson-react" + }, + { + "name": "composer\/pcre", + "version": "3.1.0", + "version_normalized": "3.1.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/composer\/pcre.git", + "reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/composer\/pcre\/zipball\/4bff79ddd77851fe3cdd11616ed3f92841ba5bd2", + "reference": "4bff79ddd77851fe3cdd11616ed3f92841ba5bd2", + "shasum": "" + }, + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "phpstan\/phpstan": "^1.3", + "phpstan\/phpstan-strict-rules": "^1.1", + "symfony\/phpunit-bridge": "^5" + }, + "time": "2022-11-17T09:50:14+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\Pcre\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http:\/\/seld.be" + } + ], + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "keywords": [ + "PCRE", + "preg", + "regex", + "regular expression" + ], + "support": { + "issues": "https:\/\/github.com\/composer\/pcre\/issues", + "source": "https:\/\/github.com\/composer\/pcre\/tree\/3.1.0" + }, + "funding": [ + { + "url": "https:\/\/packagist.com", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/composer", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/composer\/composer", + "type": "tidelift" + } + ], + "install-path": ".\/pcre" + }, + { + "name": "composer\/semver", + "version": "3.3.2", + "version_normalized": "3.3.2.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/composer\/semver.git", + "reference": "3953f23262f2bff1919fc82183ad9acb13ff62c9" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/composer\/semver\/zipball\/3953f23262f2bff1919fc82183ad9acb13ff62c9", + "reference": "3953f23262f2bff1919fc82183ad9acb13ff62c9", + "shasum": "" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "phpstan\/phpstan": "^1.4", + "symfony\/phpunit-bridge": "^4.2 || ^5" + }, + "time": "2022-04-01T19:23:25+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\Semver\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http:\/\/www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http:\/\/seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http:\/\/robbast.nl" + } + ], + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "keywords": [ + "semantic", + "semver", + "validation", + "versioning" + ], + "support": { + "irc": "irc:\/\/irc.freenode.org\/composer", + "issues": "https:\/\/github.com\/composer\/semver\/issues", + "source": "https:\/\/github.com\/composer\/semver\/tree\/3.3.2" + }, + "funding": [ + { + "url": "https:\/\/packagist.com", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/composer", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/composer\/composer", + "type": "tidelift" + } + ], + "install-path": ".\/semver" + }, + { + "name": "composer\/xdebug-handler", + "version": "3.0.3", + "version_normalized": "3.0.3.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/composer\/xdebug-handler.git", + "reference": "ced299686f41dce890debac69273b47ffe98a40c" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/composer\/xdebug-handler\/zipball\/ced299686f41dce890debac69273b47ffe98a40c", + "reference": "ced299686f41dce890debac69273b47ffe98a40c", + "shasum": "" + }, + "require": { + "composer\/pcre": "^1 || ^2 || ^3", + "php": "^7.2.5 || ^8.0", + "psr\/log": "^1 || ^2 || ^3" + }, + "require-dev": { + "phpstan\/phpstan": "^1.0", + "phpstan\/phpstan-strict-rules": "^1.1", + "symfony\/phpunit-bridge": "^6.0" + }, + "time": "2022-02-25T21:32:43+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\XdebugHandler\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "description": "Restarts a process without Xdebug.", + "keywords": [ + "Xdebug", + "performance" + ], + "support": { + "irc": "irc:\/\/irc.freenode.org\/composer", + "issues": "https:\/\/github.com\/composer\/xdebug-handler\/issues", + "source": "https:\/\/github.com\/composer\/xdebug-handler\/tree\/3.0.3" + }, + "funding": [ + { + "url": "https:\/\/packagist.com", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/composer", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/composer\/composer", + "type": "tidelift" + } + ], + "install-path": ".\/xdebug-handler" + }, + { + "name": "doctrine\/annotations", + "version": "2.0.1", + "version_normalized": "2.0.1.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/doctrine\/annotations.git", + "reference": "e157ef3f3124bbf6fe7ce0ffd109e8a8ef284e7f" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/doctrine\/annotations\/zipball\/e157ef3f3124bbf6fe7ce0ffd109e8a8ef284e7f", + "reference": "e157ef3f3124bbf6fe7ce0ffd109e8a8ef284e7f", + "shasum": "" + }, + "require": { + "doctrine\/lexer": "^2 || ^3", + "ext-tokenizer": "*", + "php": "^7.2 || ^8.0", + "psr\/cache": "^1 || ^2 || ^3" + }, + "require-dev": { + "doctrine\/cache": "^2.0", + "doctrine\/coding-standard": "^10", + "phpstan\/phpstan": "^1.8.0", + "phpunit\/phpunit": "^7.5 || ^8.5 || ^9.5", + "symfony\/cache": "^5.4 || ^6", + "vimeo\/psalm": "^4.10" + }, + "suggest": { + "php": "PHP 8.0 or higher comes with attributes, a native replacement for annotations" + }, + "time": "2023-02-02T22:02:53+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Common\\Annotations\\": "lib\/Doctrine\/Common\/Annotations" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "Docblock Annotations Parser", + "homepage": "https:\/\/www.doctrine-project.org\/projects\/annotations.html", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "support": { + "issues": "https:\/\/github.com\/doctrine\/annotations\/issues", + "source": "https:\/\/github.com\/doctrine\/annotations\/tree\/2.0.1" + }, + "install-path": "..\/doctrine\/annotations" + }, + { + "name": "doctrine\/lexer", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/doctrine\/lexer.git", + "reference": "84a527db05647743d50373e0ec53a152f2cde568" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/doctrine\/lexer\/zipball\/84a527db05647743d50373e0ec53a152f2cde568", + "reference": "84a527db05647743d50373e0ec53a152f2cde568", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "doctrine\/coding-standard": "^10", + "phpstan\/phpstan": "^1.9", + "phpunit\/phpunit": "^9.5", + "psalm\/plugin-phpunit": "^0.18.3", + "vimeo\/psalm": "^5.0" + }, + "time": "2022-12-15T16:57:16+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Common\\Lexer\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "homepage": "https:\/\/www.doctrine-project.org\/projects\/lexer.html", + "keywords": [ + "annotations", + "docblock", + "lexer", + "parser", + "php" + ], + "support": { + "issues": "https:\/\/github.com\/doctrine\/lexer\/issues", + "source": "https:\/\/github.com\/doctrine\/lexer\/tree\/3.0.0" + }, + "funding": [ + { + "url": "https:\/\/www.doctrine-project.org\/sponsorship.html", + "type": "custom" + }, + { + "url": "https:\/\/www.patreon.com\/phpdoctrine", + "type": "patreon" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/doctrine%2Flexer", + "type": "tidelift" + } + ], + "install-path": "..\/doctrine\/lexer" + }, + { + "name": "evenement\/evenement", + "version": "v3.0.1", + "version_normalized": "3.0.1.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/igorw\/evenement.git", + "reference": "531bfb9d15f8aa57454f5f0285b18bec903b8fb7" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/igorw\/evenement\/zipball\/531bfb9d15f8aa57454f5f0285b18bec903b8fb7", + "reference": "531bfb9d15f8aa57454f5f0285b18bec903b8fb7", + "shasum": "" + }, + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit\/phpunit": "^6.0" + }, + "time": "2017-07-23T21:35:13+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Evenement\\": "src\/Evenement\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "description": "\u00c9v\u00e9nement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "support": { + "issues": "https:\/\/github.com\/igorw\/evenement\/issues", + "source": "https:\/\/github.com\/igorw\/evenement\/tree\/master" + }, + "install-path": "..\/evenement\/evenement" + }, + { + "name": "fidry\/cpu-core-counter", + "version": "0.5.1", + "version_normalized": "0.5.1.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/theofidry\/cpu-core-counter.git", + "reference": "b58e5a3933e541dc286cc91fc4f3898bbc6f1623" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/theofidry\/cpu-core-counter\/zipball\/b58e5a3933e541dc286cc91fc4f3898bbc6f1623", + "reference": "b58e5a3933e541dc286cc91fc4f3898bbc6f1623", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry\/makefile": "^0.2.0", + "phpstan\/extension-installer": "^1.2.0", + "phpstan\/phpstan": "^1.9.2", + "phpstan\/phpstan-deprecation-rules": "^1.0.0", + "phpstan\/phpstan-phpunit": "^1.2.2", + "phpstan\/phpstan-strict-rules": "^1.4.4", + "phpunit\/phpunit": "^9.5.26 || ^8.5.31", + "theofidry\/php-cs-fixer-config": "^1.0", + "webmozarts\/strict-phpunit": "^7.5" + }, + "time": "2022-12-24T12:35:10+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Fidry\\CpuCoreCounter\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Th\u00e9o FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "description": "Tiny utility to get the number of CPU cores.", + "keywords": [ + "CPU", + "core" + ], + "support": { + "issues": "https:\/\/github.com\/theofidry\/cpu-core-counter\/issues", + "source": "https:\/\/github.com\/theofidry\/cpu-core-counter\/tree\/0.5.1" + }, + "funding": [ + { + "url": "https:\/\/github.com\/theofidry", + "type": "github" + } + ], + "install-path": "..\/fidry\/cpu-core-counter" + }, + { + "name": "friendsofphp\/php-cs-fixer", + "version": "v3.22.0", + "version_normalized": "3.22.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/PHP-CS-Fixer\/PHP-CS-Fixer.git", + "reference": "92b019f6c8d79aa26349d0db7671d37440dc0ff3" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/PHP-CS-Fixer\/PHP-CS-Fixer\/zipball\/92b019f6c8d79aa26349d0db7671d37440dc0ff3", + "reference": "92b019f6c8d79aa26349d0db7671d37440dc0ff3", + "shasum": "" + }, + "require": { + "composer\/semver": "^3.3", + "composer\/xdebug-handler": "^3.0.3", + "doctrine\/annotations": "^2", + "doctrine\/lexer": "^2 || ^3", + "ext-json": "*", + "ext-tokenizer": "*", + "php": "^7.4 || ^8.0", + "sebastian\/diff": "^4.0 || ^5.0", + "symfony\/console": "^5.4 || ^6.0", + "symfony\/event-dispatcher": "^5.4 || ^6.0", + "symfony\/filesystem": "^5.4 || ^6.0", + "symfony\/finder": "^5.4 || ^6.0", + "symfony\/options-resolver": "^5.4 || ^6.0", + "symfony\/polyfill-mbstring": "^1.27", + "symfony\/polyfill-php80": "^1.27", + "symfony\/polyfill-php81": "^1.27", + "symfony\/process": "^5.4 || ^6.0", + "symfony\/stopwatch": "^5.4 || ^6.0" + }, + "require-dev": { + "facile-it\/paraunit": "^1.3 || ^2.0", + "justinrainbow\/json-schema": "^5.2", + "keradus\/cli-executor": "^2.0", + "mikey179\/vfsstream": "^1.6.11", + "php-coveralls\/php-coveralls": "^2.5.3", + "php-cs-fixer\/accessible-object": "^1.1", + "php-cs-fixer\/phpunit-constraint-isidenticalstring": "^1.2", + "php-cs-fixer\/phpunit-constraint-xmlmatchesxsd": "^1.2.1", + "phpspec\/prophecy": "^1.16", + "phpspec\/prophecy-phpunit": "^2.0", + "phpunit\/phpunit": "^9.5", + "phpunitgoodpractices\/polyfill": "^1.6", + "phpunitgoodpractices\/traits": "^1.9.2", + "symfony\/phpunit-bridge": "^6.2.3", + "symfony\/yaml": "^5.4 || ^6.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "time": "2023-07-16T23:08:06+00:00", + "bin": [ + "php-cs-fixer" + ], + "type": "application", + "installation-source": "dist", + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumi\u0144ski", + "email": "dariusz.ruminski@gmail.com" + } + ], + "description": "A tool to automatically fix PHP code style", + "keywords": [ + "Static code analysis", + "fixer", + "standards", + "static analysis" + ], + "support": { + "issues": "https:\/\/github.com\/PHP-CS-Fixer\/PHP-CS-Fixer\/issues", + "source": "https:\/\/github.com\/PHP-CS-Fixer\/PHP-CS-Fixer\/tree\/v3.22.0" + }, + "funding": [ + { + "url": "https:\/\/github.com\/keradus", + "type": "github" + } + ], + "install-path": "..\/friendsofphp\/php-cs-fixer" + }, + { + "name": "illuminate\/container", + "version": "v10.16.0", + "version_normalized": "10.16.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/illuminate\/container.git", + "reference": "ddc26273085fad3c471b2602ad820e0097ff7939" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/illuminate\/container\/zipball\/ddc26273085fad3c471b2602ad820e0097ff7939", + "reference": "ddc26273085fad3c471b2602ad820e0097ff7939", + "shasum": "" + }, + "require": { + "illuminate\/contracts": "^10.0", + "php": "^8.1", + "psr\/container": "^1.1.1|^2.0.1" + }, + "provide": { + "psr\/container-implementation": "1.1|2.0" + }, + "time": "2023-06-18T09:12:03+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "10.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Illuminate\\Container\\": "" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Container package.", + "homepage": "https:\/\/laravel.com", + "support": { + "issues": "https:\/\/github.com\/laravel\/framework\/issues", + "source": "https:\/\/github.com\/laravel\/framework" + }, + "install-path": "..\/illuminate\/container" + }, + { + "name": "illuminate\/contracts", + "version": "v10.16.0", + "version_normalized": "10.16.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/illuminate\/contracts.git", + "reference": "ec47d1aa1a1b1a679d8553836b417343881b8215" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/illuminate\/contracts\/zipball\/ec47d1aa1a1b1a679d8553836b417343881b8215", + "reference": "ec47d1aa1a1b1a679d8553836b417343881b8215", + "shasum": "" + }, + "require": { + "php": "^8.1", + "psr\/container": "^1.1.1|^2.0.1", + "psr\/simple-cache": "^1.0|^2.0|^3.0" + }, + "time": "2023-06-27T14:35:49+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "10.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Illuminate\\Contracts\\": "" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "description": "The Illuminate Contracts package.", + "homepage": "https:\/\/laravel.com", + "support": { + "issues": "https:\/\/github.com\/laravel\/framework\/issues", + "source": "https:\/\/github.com\/laravel\/framework" + }, + "install-path": "..\/illuminate\/contracts" + }, + { + "name": "nette\/utils", + "version": "v3.2.9", + "version_normalized": "3.2.9.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/nette\/utils.git", + "reference": "c91bac3470c34b2ecd5400f6e6fdf0b64a836a5c" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/nette\/utils\/zipball\/c91bac3470c34b2ecd5400f6e6fdf0b64a836a5c", + "reference": "c91bac3470c34b2ecd5400f6e6fdf0b64a836a5c", + "shasum": "" + }, + "require": { + "php": ">=7.2 <8.3" + }, + "conflict": { + "nette\/di": "<3.0.6" + }, + "require-dev": { + "jetbrains\/phpstorm-attributes": "dev-master", + "nette\/tester": "~2.0", + "phpstan\/phpstan": "^1.0", + "tracy\/tracy": "^2.3" + }, + "suggest": { + "ext-gd": "to use Image", + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()", + "ext-xml": "to use Strings::length() etc. when mbstring is not available" + }, + "time": "2023-01-18T03:26:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "BSD-3-Clause", + "GPL-2.0-only", + "GPL-3.0-only" + ], + "authors": [ + { + "name": "David Grudl", + "homepage": "https:\/\/davidgrudl.com" + }, + { + "name": "Nette Community", + "homepage": "https:\/\/nette.org\/contributors" + } + ], + "description": "\ud83d\udee0 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding\/decoding, validation, slug or strong password generating etc.", + "homepage": "https:\/\/nette.org", + "keywords": [ + "array", + "core", + "datetime", + "images", + "json", + "nette", + "paginator", + "password", + "slugify", + "string", + "unicode", + "utf-8", + "utility", + "validation" + ], + "support": { + "issues": "https:\/\/github.com\/nette\/utils\/issues", + "source": "https:\/\/github.com\/nette\/utils\/tree\/v3.2.9" + }, + "install-path": "..\/nette\/utils" + }, + { + "name": "psr\/cache", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/php-fig\/cache.git", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/php-fig\/cache\/zipball\/aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "reference": "aa5030cfa5405eccfdcb1083ce040c2cb8d253bf", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-02-03T23:26:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Cache\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "description": "Common interface for caching libraries", + "keywords": [ + "cache", + "psr", + "psr-6" + ], + "support": { + "source": "https:\/\/github.com\/php-fig\/cache\/tree\/3.0.0" + }, + "install-path": "..\/psr\/cache" + }, + { + "name": "psr\/container", + "version": "2.0.2", + "version_normalized": "2.0.2.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/php-fig\/container.git", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/php-fig\/container\/zipball\/c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "reference": "c71ecc56dfe541dbd90c5360474fbc405f8d5963", + "shasum": "" + }, + "require": { + "php": ">=7.4.0" + }, + "time": "2021-11-05T16:47:00+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Container\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "description": "Common Container Interface (PHP FIG PSR-11)", + "homepage": "https:\/\/github.com\/php-fig\/container", + "keywords": [ + "PSR-11", + "container", + "container-interface", + "container-interop", + "psr" + ], + "support": { + "issues": "https:\/\/github.com\/php-fig\/container\/issues", + "source": "https:\/\/github.com\/php-fig\/container\/tree\/2.0.2" + }, + "install-path": "..\/psr\/container" + }, + { + "name": "psr\/log", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/php-fig\/log.git", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/php-fig\/log\/zipball\/fe5ea303b0887d5caefd3d431c3e61ad47037001", + "reference": "fe5ea303b0887d5caefd3d431c3e61ad47037001", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-07-14T16:46:02+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Log\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https:\/\/github.com\/php-fig\/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https:\/\/github.com\/php-fig\/log\/tree\/3.0.0" + }, + "install-path": "..\/psr\/log" + }, + { + "name": "psr\/simple-cache", + "version": "3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/php-fig\/simple-cache.git", + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/php-fig\/simple-cache\/zipball\/764e0b3939f5ca87cb904f570ef9be2d78a07865", + "reference": "764e0b3939f5ca87cb904f570ef9be2d78a07865", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "time": "2021-10-29T13:26:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\SimpleCache\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "description": "Common interfaces for simple caching", + "keywords": [ + "cache", + "caching", + "psr", + "psr-16", + "simple-cache" + ], + "support": { + "source": "https:\/\/github.com\/php-fig\/simple-cache\/tree\/3.0.0" + }, + "install-path": "..\/psr\/simple-cache" + }, + { + "name": "react\/cache", + "version": "v1.2.0", + "version_normalized": "1.2.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/cache.git", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/cache\/zipball\/d47c472b64aa5608225f47965a484b75c7817d5b", + "reference": "d47c472b64aa5608225f47965a484b75c7817d5b", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react\/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "time": "2022-11-30T15:59:55+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Cache\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "reactphp" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/cache\/issues", + "source": "https:\/\/github.com\/reactphp\/cache\/tree\/v1.2.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/cache" + }, + { + "name": "react\/child-process", + "version": "v0.6.5", + "version_normalized": "0.6.5.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/child-process.git", + "reference": "e71eb1aa55f057c7a4a0d08d06b0b0a484bead43" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/child-process\/zipball\/e71eb1aa55f057c7a4a0d08d06b0b0a484bead43", + "reference": "e71eb1aa55f057c7a4a0d08d06b0b0a484bead43", + "shasum": "" + }, + "require": { + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react\/event-loop": "^1.2", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35", + "react\/socket": "^1.8", + "sebastian\/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "time": "2022-09-16T13:41:56+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\ChildProcess\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": [ + "event-driven", + "process", + "reactphp" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/child-process\/issues", + "source": "https:\/\/github.com\/reactphp\/child-process\/tree\/v0.6.5" + }, + "funding": [ + { + "url": "https:\/\/github.com\/WyriHaximus", + "type": "github" + }, + { + "url": "https:\/\/github.com\/clue", + "type": "github" + } + ], + "install-path": "..\/react\/child-process" + }, + { + "name": "react\/dns", + "version": "v1.11.0", + "version_normalized": "1.11.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/dns.git", + "reference": "3be0fc8f1eb37d6875cd6f0c6c7d0be81435de9f" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/dns\/zipball\/3be0fc8f1eb37d6875cd6f0c6c7d0be81435de9f", + "reference": "3be0fc8f1eb37d6875cd6f0c6c7d0be81435de9f", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "react\/cache": "^1.0 || ^0.6 || ^0.5", + "react\/event-loop": "^1.2", + "react\/promise": "^3.0 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^4.8.35", + "react\/async": "^4 || ^3 || ^2", + "react\/promise-timer": "^1.9" + }, + "time": "2023-06-02T12:45:26+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Dns\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "async", + "dns", + "dns-resolver", + "reactphp" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/dns\/issues", + "source": "https:\/\/github.com\/reactphp\/dns\/tree\/v1.11.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/dns" + }, + { + "name": "react\/event-loop", + "version": "v1.4.0", + "version_normalized": "1.4.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/event-loop.git", + "reference": "6e7e587714fff7a83dcc7025aee42ab3b265ae05" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/event-loop\/zipball\/6e7e587714fff7a83dcc7025aee42ab3b265ae05", + "reference": "6e7e587714fff7a83dcc7025aee42ab3b265ae05", + "shasum": "" + }, + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit\/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "time": "2023-05-05T10:11:24+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\EventLoop\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "ReactPHP's core reactor event loop that libraries can use for evented I\/O.", + "keywords": [ + "asynchronous", + "event-loop" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/event-loop\/issues", + "source": "https:\/\/github.com\/reactphp\/event-loop\/tree\/v1.4.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/event-loop" + }, + { + "name": "react\/promise", + "version": "v3.0.0", + "version_normalized": "3.0.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/promise.git", + "reference": "c86753c76fd3be465d93b308f18d189f01a22be4" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/promise\/zipball\/c86753c76fd3be465d93b308f18d189f01a22be4", + "reference": "c86753c76fd3be465d93b308f18d189f01a22be4", + "shasum": "" + }, + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan\/phpstan": "1.10.20 || 1.4.10", + "phpunit\/phpunit": "^9.5 || ^7.5" + }, + "time": "2023-07-11T16:12:49+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "files": [ + "src\/functions_include.php" + ], + "psr-4": { + "ECSPrefix202307\\React\\Promise\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "A lightweight implementation of CommonJS Promises\/A for PHP", + "keywords": [ + "promise", + "promises" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/promise\/issues", + "source": "https:\/\/github.com\/reactphp\/promise\/tree\/v3.0.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/promise" + }, + { + "name": "react\/socket", + "version": "v1.13.0", + "version_normalized": "1.13.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/socket.git", + "reference": "cff482bbad5848ecbe8b57da57e4e213b03619aa" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/socket\/zipball\/cff482bbad5848ecbe8b57da57e4e213b03619aa", + "reference": "cff482bbad5848ecbe8b57da57e4e213b03619aa", + "shasum": "" + }, + "require": { + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.0", + "react\/dns": "^1.11", + "react\/event-loop": "^1.2", + "react\/promise": "^3 || ^2.6 || ^1.2.1", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react\/async": "^4 || ^3 || ^2", + "react\/promise-stream": "^1.4", + "react\/promise-timer": "^1.9" + }, + "time": "2023-06-07T10:28:34+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Socket\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "Async, streaming plaintext TCP\/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "Connection", + "Socket", + "async", + "reactphp", + "stream" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/socket\/issues", + "source": "https:\/\/github.com\/reactphp\/socket\/tree\/v1.13.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/socket" + }, + { + "name": "react\/stream", + "version": "v1.3.0", + "version_normalized": "1.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/reactphp\/stream.git", + "reference": "6fbc9672905c7d5a885f2da2fc696f65840f4a66" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/reactphp\/stream\/zipball\/6fbc9672905c7d5a885f2da2fc696f65840f4a66", + "reference": "6fbc9672905c7d5a885f2da2fc696f65840f4a66", + "shasum": "" + }, + "require": { + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0", + "php": ">=5.3.8", + "react\/event-loop": "^1.2" + }, + "require-dev": { + "clue\/stream-filter": "~1.2", + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "time": "2023-06-16T10:52:11+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Stream\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Christian L\u00fcck", + "email": "christian@clue.engineering", + "homepage": "https:\/\/clue.engineering\/" + }, + { + "name": "Cees-Jan Kiewiet", + "email": "reactphp@ceesjankiewiet.nl", + "homepage": "https:\/\/wyrihaximus.net\/" + }, + { + "name": "Jan Sorgalla", + "email": "jsorgalla@gmail.com", + "homepage": "https:\/\/sorgalla.com\/" + }, + { + "name": "Chris Boden", + "email": "cboden@gmail.com", + "homepage": "https:\/\/cboden.dev\/" + } + ], + "description": "Event-driven readable and writable streams for non-blocking I\/O in ReactPHP", + "keywords": [ + "event-driven", + "io", + "non-blocking", + "pipe", + "reactphp", + "readable", + "stream", + "writable" + ], + "support": { + "issues": "https:\/\/github.com\/reactphp\/stream\/issues", + "source": "https:\/\/github.com\/reactphp\/stream\/tree\/v1.3.0" + }, + "funding": [ + { + "url": "https:\/\/opencollective.com\/reactphp", + "type": "open_collective" + } + ], + "install-path": "..\/react\/stream" + }, + { + "name": "sebastian\/diff", + "version": "5.0.3", + "version_normalized": "5.0.3.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/sebastianbergmann\/diff.git", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/sebastianbergmann\/diff\/zipball\/912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "reference": "912dc2fbe3e3c1e7873313cc801b100b6c68c87b", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit\/phpunit": "^10.0", + "symfony\/process": "^4.2 || ^5" + }, + "time": "2023-05-01T07:48:21+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "src\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "description": "Diff implementation", + "homepage": "https:\/\/github.com\/sebastianbergmann\/diff", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "support": { + "issues": "https:\/\/github.com\/sebastianbergmann\/diff\/issues", + "security": "https:\/\/github.com\/sebastianbergmann\/diff\/security\/policy", + "source": "https:\/\/github.com\/sebastianbergmann\/diff\/tree\/5.0.3" + }, + "funding": [ + { + "url": "https:\/\/github.com\/sebastianbergmann", + "type": "github" + } + ], + "install-path": "..\/sebastian\/diff" + }, + { + "name": "squizlabs\/php_codesniffer", + "version": "3.7.2", + "version_normalized": "3.7.2.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer.git", + "reference": "ed8e00df0a83aa96acf703f8c2979ff33341f879" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/squizlabs\/PHP_CodeSniffer\/zipball\/ed8e00df0a83aa96acf703f8c2979ff33341f879", + "reference": "ed8e00df0a83aa96acf703f8c2979ff33341f879", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit\/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "time": "2023-02-22T23:07:41+00:00", + "bin": [ + "bin\/phpcs", + "bin\/phpcbf" + ], + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "installation-source": "dist", + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer\/issues", + "source": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer", + "wiki": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer\/wiki" + }, + "install-path": "..\/squizlabs\/php_codesniffer" + }, + { + "name": "symfony\/console", + "version": "v6.3.0", + "version_normalized": "6.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/console.git", + "reference": "8788808b07cf0bdd6e4b7fdd23d8ddb1470c83b7" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/console\/zipball\/8788808b07cf0bdd6e4b7fdd23d8ddb1470c83b7", + "reference": "8788808b07cf0bdd6e4b7fdd23d8ddb1470c83b7", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony\/deprecation-contracts": "^2.5|^3", + "symfony\/polyfill-mbstring": "~1.0", + "symfony\/service-contracts": "^2.5|^3", + "symfony\/string": "^5.4|^6.0" + }, + "conflict": { + "symfony\/dependency-injection": "<5.4", + "symfony\/dotenv": "<5.4", + "symfony\/event-dispatcher": "<5.4", + "symfony\/lock": "<5.4", + "symfony\/process": "<5.4" + }, + "provide": { + "psr\/log-implementation": "1.0|2.0|3.0" + }, + "require-dev": { + "psr\/log": "^1|^2|^3", + "symfony\/config": "^5.4|^6.0", + "symfony\/dependency-injection": "^5.4|^6.0", + "symfony\/event-dispatcher": "^5.4|^6.0", + "symfony\/lock": "^5.4|^6.0", + "symfony\/process": "^5.4|^6.0", + "symfony\/var-dumper": "^5.4|^6.0" + }, + "time": "2023-05-29T12:49:39+00:00", + "type": "library", + "extra": { + "patches_applied": [ + "patches\/symfony-console-helper-helper-php.patch" + ] + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symfony\\Component\\Console\\": "" + }, + "exclude-from-classmap": [ + "\/Tests\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Eases the creation of beautiful and testable command line interfaces", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "cli", + "command-line", + "console", + "terminal" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/console\/tree\/v6.3.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/console" + }, + { + "name": "symfony\/deprecation-contracts", + "version": "v3.3.0", + "version_normalized": "3.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/deprecation-contracts.git", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/deprecation-contracts\/zipball\/7c3aff79d10325257a001fcf92d991f24fc967cf", + "reference": "7c3aff79d10325257a001fcf92d991f24fc967cf", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony\/contracts", + "url": "https:\/\/github.com\/symfony\/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https:\/\/symfony.com", + "support": { + "source": "https:\/\/github.com\/symfony\/deprecation-contracts\/tree\/v3.3.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/deprecation-contracts" + }, + { + "name": "symfony\/filesystem", + "version": "v6.3.1", + "version_normalized": "6.3.1.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/filesystem.git", + "reference": "edd36776956f2a6fcf577edb5b05eb0e3bdc52ae" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/filesystem\/zipball\/edd36776956f2a6fcf577edb5b05eb0e3bdc52ae", + "reference": "edd36776956f2a6fcf577edb5b05eb0e3bdc52ae", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony\/polyfill-ctype": "~1.8", + "symfony\/polyfill-mbstring": "~1.8" + }, + "time": "2023-06-01T08:30:39+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symfony\\Component\\Filesystem\\": "" + }, + "exclude-from-classmap": [ + "\/Tests\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Provides basic utilities for the filesystem", + "homepage": "https:\/\/symfony.com", + "support": { + "source": "https:\/\/github.com\/symfony\/filesystem\/tree\/v6.3.1" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/filesystem" + }, + { + "name": "symfony\/finder", + "version": "v6.3.0", + "version_normalized": "6.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/finder.git", + "reference": "d9b01ba073c44cef617c7907ce2419f8d00d75e2" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/finder\/zipball\/d9b01ba073c44cef617c7907ce2419f8d00d75e2", + "reference": "d9b01ba073c44cef617c7907ce2419f8d00d75e2", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "symfony\/filesystem": "^6.0" + }, + "time": "2023-04-02T01:25:41+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symfony\\Component\\Finder\\": "" + }, + "exclude-from-classmap": [ + "\/Tests\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Finds files and directories via an intuitive fluent interface", + "homepage": "https:\/\/symfony.com", + "support": { + "source": "https:\/\/github.com\/symfony\/finder\/tree\/v6.3.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/finder" + }, + { + "name": "symfony\/options-resolver", + "version": "v6.3.0", + "version_normalized": "6.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/options-resolver.git", + "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/options-resolver\/zipball\/a10f19f5198d589d5c33333cffe98dc9820332dd", + "reference": "a10f19f5198d589d5c33333cffe98dc9820332dd", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "symfony\/deprecation-contracts": "^2.5|^3" + }, + "time": "2023-05-12T14:21:09+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symfony\\Component\\OptionsResolver\\": "" + }, + "exclude-from-classmap": [ + "\/Tests\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Provides an improved replacement for the array_replace PHP function", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "config", + "configuration", + "options" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/options-resolver\/tree\/v6.3.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/options-resolver" + }, + { + "name": "symfony\/polyfill-mbstring", + "version": "v1.27.0", + "version_normalized": "1.27.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/polyfill-mbstring.git", + "reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/polyfill-mbstring\/zipball\/8ad114f6b39e2c98a8b0e3bd907732c207c2b534", + "reference": "8ad114f6b39e2c98a8b0e3bd907732c207c2b534", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "provide": { + "ext-mbstring": "*" + }, + "suggest": { + "ext-mbstring": "For best performance" + }, + "time": "2022-11-03T14:55:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.27-dev" + }, + "thanks": { + "name": "symfony\/polyfill", + "url": "https:\/\/github.com\/symfony\/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Mbstring\\": "" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Symfony polyfill for the Mbstring extension", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "compatibility", + "mbstring", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/polyfill-mbstring\/tree\/v1.27.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/polyfill-mbstring" + }, + { + "name": "symfony\/polyfill-php80", + "version": "v1.27.0", + "version_normalized": "1.27.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/polyfill-php80.git", + "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/polyfill-php80\/zipball\/7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", + "reference": "7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2022-11-03T14:55:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.27-dev" + }, + "thanks": { + "name": "symfony\/polyfill", + "url": "https:\/\/github.com\/symfony\/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources\/stubs" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/polyfill-php80\/tree\/v1.27.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/polyfill-php80" + }, + { + "name": "symfony\/polyfill-php81", + "version": "v1.27.0", + "version_normalized": "1.27.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/polyfill-php81.git", + "reference": "707403074c8ea6e2edaf8794b0157a0bfa52157a" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/polyfill-php81\/zipball\/707403074c8ea6e2edaf8794b0157a0bfa52157a", + "reference": "707403074c8ea6e2edaf8794b0157a0bfa52157a", + "shasum": "" + }, + "require": { + "php": ">=7.1" + }, + "time": "2022-11-03T14:55:06+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.27-dev" + }, + "thanks": { + "name": "symfony\/polyfill", + "url": "https:\/\/github.com\/symfony\/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php81\\": "" + }, + "classmap": [ + "Resources\/stubs" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.1+ features to lower PHP versions", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/polyfill-php81\/tree\/v1.27.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/polyfill-php81" + }, + { + "name": "symfony\/service-contracts", + "version": "v3.3.0", + "version_normalized": "3.3.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symfony\/service-contracts.git", + "reference": "40da9cc13ec349d9e4966ce18b5fbcd724ab10a4" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symfony\/service-contracts\/zipball\/40da9cc13ec349d9e4966ce18b5fbcd724ab10a4", + "reference": "40da9cc13ec349d9e4966ce18b5fbcd724ab10a4", + "shasum": "" + }, + "require": { + "php": ">=8.1", + "psr\/container": "^2.0" + }, + "conflict": { + "ext-psr": "<1.1|>=2" + }, + "time": "2023-05-23T14:45:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "3.4-dev" + }, + "thanks": { + "name": "symfony\/contracts", + "url": "https:\/\/github.com\/symfony\/contracts" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symfony\\Contracts\\Service\\": "" + }, + "exclude-from-classmap": [ + "\/Test\/" + ] + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https:\/\/symfony.com\/contributors" + } + ], + "description": "Generic abstractions related to writing services", + "homepage": "https:\/\/symfony.com", + "keywords": [ + "abstractions", + "contracts", + "decoupling", + "interfaces", + "interoperability", + "standards" + ], + "support": { + "source": "https:\/\/github.com\/symfony\/service-contracts\/tree\/v3.3.0" + }, + "funding": [ + { + "url": "https:\/\/symfony.com\/sponsor", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/fabpot", + "type": "github" + }, + { + "url": "https:\/\/tidelift.com\/funding\/github\/packagist\/symfony\/symfony", + "type": "tidelift" + } + ], + "install-path": "..\/symfony\/service-contracts" + }, + { + "name": "symplify\/coding-standard", + "version": "12.0.2", + "version_normalized": "12.0.2.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symplify\/coding-standard.git", + "reference": "e0009665738a004d5dac08d1ef99f6bffb52640d" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symplify\/coding-standard\/zipball\/e0009665738a004d5dac08d1ef99f6bffb52640d", + "reference": "e0009665738a004d5dac08d1ef99f6bffb52640d", + "shasum": "" + }, + "require": { + "friendsofphp\/php-cs-fixer": "^3.18", + "nette\/utils": "^3.2", + "php": ">=8.1", + "symplify\/rule-doc-generator-contracts": "^11.1" + }, + "require-dev": { + "php-parallel-lint\/php-parallel-lint": "^1.3", + "phpstan\/extension-installer": "^1.3", + "phpstan\/phpstan": "^1.10.26", + "phpunit\/phpunit": "^10.2", + "rector\/rector": "^0.17.7", + "squizlabs\/php_codesniffer": "^3.7.2", + "symplify\/easy-ci": "^11.3", + "symplify\/easy-coding-standard": "^12.0.1", + "symplify\/phpstan-extensions": "^11.2", + "symplify\/rule-doc-generator": "^11.2", + "tomasvotruba\/class-leak": "0.0.22.72", + "tomasvotruba\/type-coverage": "^0.2", + "tomasvotruba\/unused-public": "^0.1.14" + }, + "time": "2023-07-25T15:37:06+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symplify\\CodingStandard\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "description": "Set of Symplify rules for PHP_CodeSniffer and PHP CS Fixer.", + "support": { + "issues": "https:\/\/github.com\/symplify\/coding-standard\/issues", + "source": "https:\/\/github.com\/symplify\/coding-standard\/tree\/12.0.2" + }, + "funding": [ + { + "url": "https:\/\/www.paypal.me\/rectorphp", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/tomasvotruba", + "type": "github" + } + ], + "install-path": "..\/symplify\/coding-standard" + }, + { + "name": "symplify\/easy-parallel", + "version": "11.1.27", + "version_normalized": "11.1.27.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symplify\/easy-parallel.git", + "reference": "28911142f6a0f4127271f745e2403bb84fcd2b87" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symplify\/easy-parallel\/zipball\/28911142f6a0f4127271f745e2403bb84fcd2b87", + "reference": "28911142f6a0f4127271f745e2403bb84fcd2b87", + "shasum": "" + }, + "require": { + "clue\/ndjson-react": "^1.3", + "fidry\/cpu-core-counter": "^0.4.0 || ^0.5.1", + "php": ">=8.1", + "react\/child-process": "^0.6.5", + "react\/event-loop": "^1.3", + "react\/socket": "^1.12", + "symfony\/console": "^6.2" + }, + "require-dev": { + "php-parallel-lint\/php-parallel-lint": "^1.3", + "phpstan\/extension-installer": "^1.2", + "phpunit\/phpunit": "^9.5.26", + "rector\/rector": "^0.15.10", + "symplify\/easy-ci": "^11.1", + "symplify\/easy-coding-standard": "^11.1", + "symplify\/package-builder": "^11.2", + "symplify\/phpstan-extensions": "^11.1", + "symplify\/symplify-kernel": "^11.2", + "tomasvotruba\/unused-public": "^0.0.34" + }, + "time": "2023-02-04T15:19:23+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symplify\\EasyParallel\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "description": "Helper package for easier CLI project parallelization", + "support": { + "issues": "https:\/\/github.com\/symplify\/easy-parallel\/issues", + "source": "https:\/\/github.com\/symplify\/easy-parallel\/tree\/11.1.27" + }, + "funding": [ + { + "url": "https:\/\/www.paypal.me\/rectorphp", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/tomasvotruba", + "type": "github" + } + ], + "install-path": "..\/symplify\/easy-parallel" + }, + { + "name": "symplify\/rule-doc-generator-contracts", + "version": "11.1.26", + "version_normalized": "11.1.26.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/symplify\/rule-doc-generator-contracts.git", + "reference": "3e66b3fec678b74a076395ec629d535fb95293b5" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/symplify\/rule-doc-generator-contracts\/zipball\/3e66b3fec678b74a076395ec629d535fb95293b5", + "reference": "3e66b3fec678b74a076395ec629d535fb95293b5", + "shasum": "" + }, + "require": { + "nette\/utils": "^3.2", + "php": ">=8.1" + }, + "require-dev": { + "php-parallel-lint\/php-parallel-lint": "^1.3", + "phpstan\/extension-installer": "^1.2", + "rector\/rector": "^0.15.10", + "symplify\/easy-ci": "^11.1", + "symplify\/easy-coding-standard": "^11.1", + "symplify\/easy-testing": "^11.1", + "symplify\/phpstan-extensions": "^11.1", + "symplify\/phpstan-rules": "11.2.3.72", + "tomasvotruba\/unused-public": "^0.0.34" + }, + "time": "2023-02-07T07:16:13+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "11.2-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Symplify\\RuleDocGenerator\\": "src" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "description": "Contracts for production code of RuleDocGenerator", + "support": { + "source": "https:\/\/github.com\/symplify\/rule-doc-generator-contracts\/tree\/11.1.26" + }, + "funding": [ + { + "url": "https:\/\/www.paypal.me\/rectorphp", + "type": "custom" + }, + { + "url": "https:\/\/github.com\/tomasvotruba", + "type": "github" + } + ], + "install-path": "..\/symplify\/rule-doc-generator-contracts" + }, + { + "name": "webmozart\/assert", + "version": "1.11.0", + "version_normalized": "1.11.0.0", + "source": { + "type": "git", + "url": "https:\/\/github.com\/webmozarts\/assert.git", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991" + }, + "dist": { + "type": "zip", + "url": "https:\/\/api.github.com\/repos\/webmozarts\/assert\/zipball\/11cb2199493b2f8a3b53e7f19068fc6aac760991", + "reference": "11cb2199493b2f8a3b53e7f19068fc6aac760991", + "shasum": "" + }, + "require": { + "ext-ctype": "*", + "php": "^7.2 || ^8.0" + }, + "conflict": { + "phpstan\/phpstan": "<0.12.20", + "vimeo\/psalm": "<4.6.1 || 4.6.2" + }, + "require-dev": { + "phpunit\/phpunit": "^8.5.13" + }, + "time": "2022-06-03T18:03:27+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.10-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "ECSPrefix202307\\Webmozart\\Assert\\": "src\/" + } + }, + "notification-url": "https:\/\/packagist.org\/downloads\/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Bernhard Schussek", + "email": "bschussek@gmail.com" + } + ], + "description": "Assertions to validate method input\/output with nice error messages.", + "keywords": [ + "assert", + "check", + "validate" + ], + "support": { + "issues": "https:\/\/github.com\/webmozarts\/assert\/issues", + "source": "https:\/\/github.com\/webmozarts\/assert\/tree\/1.11.0" + }, + "install-path": "..\/webmozart\/assert" + } + ], + "dev": false, + "dev-package-names": [] +} \ No newline at end of file diff --git a/vendor/composer/installed.php b/vendor/composer/installed.php new file mode 100644 index 00000000000..ebc826a550d --- /dev/null +++ b/vendor/composer/installed.php @@ -0,0 +1,5 @@ + array('name' => 'symplify/easy-coding-standard', 'pretty_version' => '12.0.5', 'version' => '12.0.5.0', 'reference' => 'b350c93d4b8bbd297a835ad10938d9feb79a0725', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev' => \false), 'versions' => array('clue/ndjson-react' => array('pretty_version' => 'v1.3.0', 'version' => '1.3.0.0', 'reference' => '392dc165fce93b5bb5c637b67e59619223c931b0', 'type' => 'library', 'install_path' => __DIR__ . '/../clue/ndjson-react', 'aliases' => array(), 'dev_requirement' => \false), 'composer/pcre' => array('pretty_version' => '3.1.0', 'version' => '3.1.0.0', 'reference' => '4bff79ddd77851fe3cdd11616ed3f92841ba5bd2', 'type' => 'library', 'install_path' => __DIR__ . '/./pcre', 'aliases' => array(), 'dev_requirement' => \false), 'composer/semver' => array('pretty_version' => '3.3.2', 'version' => '3.3.2.0', 'reference' => '3953f23262f2bff1919fc82183ad9acb13ff62c9', 'type' => 'library', 'install_path' => __DIR__ . '/./semver', 'aliases' => array(), 'dev_requirement' => \false), 'composer/xdebug-handler' => array('pretty_version' => '3.0.3', 'version' => '3.0.3.0', 'reference' => 'ced299686f41dce890debac69273b47ffe98a40c', 'type' => 'library', 'install_path' => __DIR__ . '/./xdebug-handler', 'aliases' => array(), 'dev_requirement' => \false), 'doctrine/annotations' => array('pretty_version' => '2.0.1', 'version' => '2.0.1.0', 'reference' => 'e157ef3f3124bbf6fe7ce0ffd109e8a8ef284e7f', 'type' => 'library', 'install_path' => __DIR__ . '/../doctrine/annotations', 'aliases' => array(), 'dev_requirement' => \false), 'doctrine/lexer' => array('pretty_version' => '3.0.0', 'version' => '3.0.0.0', 'reference' => '84a527db05647743d50373e0ec53a152f2cde568', 'type' => 'library', 'install_path' => __DIR__ . '/../doctrine/lexer', 'aliases' => array(), 'dev_requirement' => \false), 'evenement/evenement' => array('pretty_version' => 'v3.0.1', 'version' => '3.0.1.0', 'reference' => '531bfb9d15f8aa57454f5f0285b18bec903b8fb7', 'type' => 'library', 'install_path' => __DIR__ . '/../evenement/evenement', 'aliases' => array(), 'dev_requirement' => \false), 'fidry/cpu-core-counter' => array('pretty_version' => '0.5.1', 'version' => '0.5.1.0', 'reference' => 'b58e5a3933e541dc286cc91fc4f3898bbc6f1623', 'type' => 'library', 'install_path' => __DIR__ . '/../fidry/cpu-core-counter', 'aliases' => array(), 'dev_requirement' => \false), 'friendsofphp/php-cs-fixer' => array('pretty_version' => 'v3.22.0', 'version' => '3.22.0.0', 'reference' => '92b019f6c8d79aa26349d0db7671d37440dc0ff3', 'type' => 'application', 'install_path' => __DIR__ . '/../friendsofphp/php-cs-fixer', 'aliases' => array(), 'dev_requirement' => \false), 'illuminate/container' => array('pretty_version' => 'v10.16.0', 'version' => '10.16.0.0', 'reference' => 'ddc26273085fad3c471b2602ad820e0097ff7939', 'type' => 'library', 'install_path' => __DIR__ . '/../illuminate/container', 'aliases' => array(), 'dev_requirement' => \false), 'illuminate/contracts' => array('pretty_version' => 'v10.16.0', 'version' => '10.16.0.0', 'reference' => 'ec47d1aa1a1b1a679d8553836b417343881b8215', 'type' => 'library', 'install_path' => __DIR__ . '/../illuminate/contracts', 'aliases' => array(), 'dev_requirement' => \false), 'nette/utils' => array('pretty_version' => 'v3.2.9', 'version' => '3.2.9.0', 'reference' => 'c91bac3470c34b2ecd5400f6e6fdf0b64a836a5c', 'type' => 'library', 'install_path' => __DIR__ . '/../nette/utils', 'aliases' => array(), 'dev_requirement' => \false), 'psr/cache' => array('pretty_version' => '3.0.0', 'version' => '3.0.0.0', 'reference' => 'aa5030cfa5405eccfdcb1083ce040c2cb8d253bf', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/cache', 'aliases' => array(), 'dev_requirement' => \false), 'psr/container' => array('pretty_version' => '2.0.2', 'version' => '2.0.2.0', 'reference' => 'c71ecc56dfe541dbd90c5360474fbc405f8d5963', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/container', 'aliases' => array(), 'dev_requirement' => \false), 'psr/container-implementation' => array('dev_requirement' => \false, 'provided' => array(0 => '1.1|2.0')), 'psr/log' => array('pretty_version' => '3.0.0', 'version' => '3.0.0.0', 'reference' => 'fe5ea303b0887d5caefd3d431c3e61ad47037001', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/log', 'aliases' => array(), 'dev_requirement' => \false), 'psr/log-implementation' => array('dev_requirement' => \false, 'provided' => array(0 => '1.0|2.0|3.0')), 'psr/simple-cache' => array('pretty_version' => '3.0.0', 'version' => '3.0.0.0', 'reference' => '764e0b3939f5ca87cb904f570ef9be2d78a07865', 'type' => 'library', 'install_path' => __DIR__ . '/../psr/simple-cache', 'aliases' => array(), 'dev_requirement' => \false), 'react/cache' => array('pretty_version' => 'v1.2.0', 'version' => '1.2.0.0', 'reference' => 'd47c472b64aa5608225f47965a484b75c7817d5b', 'type' => 'library', 'install_path' => __DIR__ . '/../react/cache', 'aliases' => array(), 'dev_requirement' => \false), 'react/child-process' => array('pretty_version' => 'v0.6.5', 'version' => '0.6.5.0', 'reference' => 'e71eb1aa55f057c7a4a0d08d06b0b0a484bead43', 'type' => 'library', 'install_path' => __DIR__ . '/../react/child-process', 'aliases' => array(), 'dev_requirement' => \false), 'react/dns' => array('pretty_version' => 'v1.11.0', 'version' => '1.11.0.0', 'reference' => '3be0fc8f1eb37d6875cd6f0c6c7d0be81435de9f', 'type' => 'library', 'install_path' => __DIR__ . '/../react/dns', 'aliases' => array(), 'dev_requirement' => \false), 'react/event-loop' => array('pretty_version' => 'v1.4.0', 'version' => '1.4.0.0', 'reference' => '6e7e587714fff7a83dcc7025aee42ab3b265ae05', 'type' => 'library', 'install_path' => __DIR__ . '/../react/event-loop', 'aliases' => array(), 'dev_requirement' => \false), 'react/promise' => array('pretty_version' => 'v3.0.0', 'version' => '3.0.0.0', 'reference' => 'c86753c76fd3be465d93b308f18d189f01a22be4', 'type' => 'library', 'install_path' => __DIR__ . '/../react/promise', 'aliases' => array(), 'dev_requirement' => \false), 'react/socket' => array('pretty_version' => 'v1.13.0', 'version' => '1.13.0.0', 'reference' => 'cff482bbad5848ecbe8b57da57e4e213b03619aa', 'type' => 'library', 'install_path' => __DIR__ . '/../react/socket', 'aliases' => array(), 'dev_requirement' => \false), 'react/stream' => array('pretty_version' => 'v1.3.0', 'version' => '1.3.0.0', 'reference' => '6fbc9672905c7d5a885f2da2fc696f65840f4a66', 'type' => 'library', 'install_path' => __DIR__ . '/../react/stream', 'aliases' => array(), 'dev_requirement' => \false), 'sebastian/diff' => array('pretty_version' => '5.0.3', 'version' => '5.0.3.0', 'reference' => '912dc2fbe3e3c1e7873313cc801b100b6c68c87b', 'type' => 'library', 'install_path' => __DIR__ . '/../sebastian/diff', 'aliases' => array(), 'dev_requirement' => \false), 'squizlabs/php_codesniffer' => array('pretty_version' => '3.7.2', 'version' => '3.7.2.0', 'reference' => 'ed8e00df0a83aa96acf703f8c2979ff33341f879', 'type' => 'library', 'install_path' => __DIR__ . '/../squizlabs/php_codesniffer', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/console' => array('pretty_version' => 'v6.3.0', 'version' => '6.3.0.0', 'reference' => '8788808b07cf0bdd6e4b7fdd23d8ddb1470c83b7', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/console', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/deprecation-contracts' => array('pretty_version' => 'v3.3.0', 'version' => '3.3.0.0', 'reference' => '7c3aff79d10325257a001fcf92d991f24fc967cf', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/deprecation-contracts', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/event-dispatcher' => array('dev_requirement' => \false, 'replaced' => array(0 => '6.*')), 'symfony/filesystem' => array('pretty_version' => 'v6.3.1', 'version' => '6.3.1.0', 'reference' => 'edd36776956f2a6fcf577edb5b05eb0e3bdc52ae', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/filesystem', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/finder' => array('pretty_version' => 'v6.3.0', 'version' => '6.3.0.0', 'reference' => 'd9b01ba073c44cef617c7907ce2419f8d00d75e2', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/finder', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/options-resolver' => array('pretty_version' => 'v6.3.0', 'version' => '6.3.0.0', 'reference' => 'a10f19f5198d589d5c33333cffe98dc9820332dd', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/options-resolver', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/polyfill-ctype' => array('dev_requirement' => \false, 'replaced' => array(0 => '*')), 'symfony/polyfill-intl-grapheme' => array('dev_requirement' => \false, 'replaced' => array(0 => '*')), 'symfony/polyfill-intl-normalizer' => array('dev_requirement' => \false, 'replaced' => array(0 => '*')), 'symfony/polyfill-mbstring' => array('pretty_version' => 'v1.27.0', 'version' => '1.27.0.0', 'reference' => '8ad114f6b39e2c98a8b0e3bd907732c207c2b534', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-mbstring', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/polyfill-php80' => array('pretty_version' => 'v1.27.0', 'version' => '1.27.0.0', 'reference' => '7a6ff3f1959bb01aefccb463a0f2cd3d3d2fd936', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-php80', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/polyfill-php81' => array('pretty_version' => 'v1.27.0', 'version' => '1.27.0.0', 'reference' => '707403074c8ea6e2edaf8794b0157a0bfa52157a', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/polyfill-php81', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/process' => array('dev_requirement' => \false, 'replaced' => array(0 => '6.*')), 'symfony/service-contracts' => array('pretty_version' => 'v3.3.0', 'version' => '3.3.0.0', 'reference' => '40da9cc13ec349d9e4966ce18b5fbcd724ab10a4', 'type' => 'library', 'install_path' => __DIR__ . '/../symfony/service-contracts', 'aliases' => array(), 'dev_requirement' => \false), 'symfony/stopwatch' => array('dev_requirement' => \false, 'replaced' => array(0 => '6.*')), 'symfony/string' => array('dev_requirement' => \false, 'replaced' => array(0 => '6.*')), 'symplify/coding-standard' => array('pretty_version' => '12.0.2', 'version' => '12.0.2.0', 'reference' => 'e0009665738a004d5dac08d1ef99f6bffb52640d', 'type' => 'library', 'install_path' => __DIR__ . '/../symplify/coding-standard', 'aliases' => array(), 'dev_requirement' => \false), 'symplify/easy-coding-standard' => array('pretty_version' => '12.0.5', 'version' => '12.0.5.0', 'reference' => 'b350c93d4b8bbd297a835ad10938d9feb79a0725', 'type' => 'library', 'install_path' => __DIR__ . '/../../', 'aliases' => array(), 'dev_requirement' => \false), 'symplify/easy-parallel' => array('pretty_version' => '11.1.27', 'version' => '11.1.27.0', 'reference' => '28911142f6a0f4127271f745e2403bb84fcd2b87', 'type' => 'library', 'install_path' => __DIR__ . '/../symplify/easy-parallel', 'aliases' => array(), 'dev_requirement' => \false), 'symplify/rule-doc-generator-contracts' => array('pretty_version' => '11.1.26', 'version' => '11.1.26.0', 'reference' => '3e66b3fec678b74a076395ec629d535fb95293b5', 'type' => 'library', 'install_path' => __DIR__ . '/../symplify/rule-doc-generator-contracts', 'aliases' => array(), 'dev_requirement' => \false), 'webmozart/assert' => array('pretty_version' => '1.11.0', 'version' => '1.11.0.0', 'reference' => '11cb2199493b2f8a3b53e7f19068fc6aac760991', 'type' => 'library', 'install_path' => __DIR__ . '/../webmozart/assert', 'aliases' => array(), 'dev_requirement' => \false))); diff --git a/vendor/composer/pcre/LICENSE b/vendor/composer/pcre/LICENSE new file mode 100644 index 00000000000..c5a282ff42a --- /dev/null +++ b/vendor/composer/pcre/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2021 Composer + +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. diff --git a/vendor/composer/pcre/README.md b/vendor/composer/pcre/README.md new file mode 100644 index 00000000000..973b17d8dad --- /dev/null +++ b/vendor/composer/pcre/README.md @@ -0,0 +1,181 @@ +composer/pcre +============= + +PCRE wrapping library that offers type-safe `preg_*` replacements. + +This library gives you a way to ensure `preg_*` functions do not fail silently, returning +unexpected `null`s that may not be handled. + +As of 3.0 this library enforces [`PREG_UNMATCHED_AS_NULL`](#preg_unmatched_as_null) usage +for all matching and replaceCallback functions, [read more below](#preg_unmatched_as_null) +to understand the implications. + +It thus makes it easier to work with static analysis tools like PHPStan or Psalm as it +simplifies and reduces the possible return values from all the `preg_*` functions which +are quite packed with edge cases. + +This library is a thin wrapper around `preg_*` functions with [some limitations](#restrictions--limitations). +If you are looking for a richer API to handle regular expressions have a look at +[rawr/t-regx](https://packagist.org/packages/rawr/t-regx) instead. + +[![Continuous Integration](https://github.com/composer/pcre/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/pcre/actions) + + +Installation +------------ + +Install the latest version with: + +```bash +$ composer require composer/pcre +``` + + +Requirements +------------ + +* PHP 7.4.0 is required for 3.x versions +* PHP 7.2.0 is required for 2.x versions +* PHP 5.3.2 is required for 1.x versions + + +Basic usage +----------- + +Instead of: + +```php +if (preg_match('{fo+}', $string, $matches)) { ... } +if (preg_match('{fo+}', $string, $matches, PREG_OFFSET_CAPTURE)) { ... } +if (preg_match_all('{fo+}', $string, $matches)) { ... } +$newString = preg_replace('{fo+}', 'bar', $string); +$newString = preg_replace_callback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = preg_replace_callback_array(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = preg_grep('{[a-z]}', $elements); +$array = preg_split('{[a-z]+}', $string); +``` + +You can now call these on the `Preg` class: + +```php +use Composer\Pcre\Preg; + +if (Preg::match('{fo+}', $string, $matches)) { ... } +if (Preg::matchWithOffsets('{fo+}', $string, $matches)) { ... } +if (Preg::matchAll('{fo+}', $string, $matches)) { ... } +$newString = Preg::replace('{fo+}', 'bar', $string); +$newString = Preg::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string); +$newString = Preg::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string); +$filtered = Preg::grep('{[a-z]}', $elements); +$array = Preg::split('{[a-z]+}', $string); +``` + +The main difference is if anything fails to match/replace/.., it will throw a `Composer\Pcre\PcreException` +instead of returning `null` (or false in some cases), so you can now use the return values safely relying on +the fact that they can only be strings (for replace), ints (for match) or arrays (for grep/split). + +Additionally the `Preg` class provides match methods that return `bool` rather than `int`, for stricter type safety +when the number of pattern matches is not useful: + +```php +use Composer\Pcre\Preg; + +if (Preg::isMatch('{fo+}', $string, $matches)) // bool +if (Preg::isMatchAll('{fo+}', $string, $matches)) // bool +``` + +Finally the `Preg` class provides a few `*StrictGroups` method variants that ensure match groups +are always present and thus non-nullable, making it easier to write type-safe code: + +```php +use Composer\Pcre\Preg; + +// $matches is guaranteed to be an array of strings, if a subpattern does not match and produces a null it will throw +if (Preg::matchStrictGroups('{fo+}', $string, $matches)) +if (Preg::matchAllStrictGroups('{fo+}', $string, $matches)) +``` + +**Note:** This is generally safe to use as long as you do not have optional subpatterns (i.e. `(something)?` +or `(something)*` or branches with a `|` that result in some groups not being matched at all). +A subpattern that can match an empty string like `(.*)` is **not** optional, it will be present as an +empty string in the matches. A non-matching subpattern, even if optional like `(?:foo)?` will anyway not be present in +matches so it is also not a problem to use these with `*StrictGroups` methods. + +If you would prefer a slightly more verbose usage, replacing by-ref arguments by result objects, you can use the `Regex` class: + +```php +use Composer\Pcre\Regex; + +// this is useful when you are just interested in knowing if something matched +// as it returns a bool instead of int(1/0) for match +$bool = Regex::isMatch('{fo+}', $string); + +$result = Regex::match('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchWithOffsets('{fo+}', $string); +if ($result->matched) { something($result->matches); } + +$result = Regex::matchAll('{fo+}', $string); +if ($result->matched && $result->count > 3) { something($result->matches); } + +$newString = Regex::replace('{fo+}', 'bar', $string)->result; +$newString = Regex::replaceCallback('{fo+}', function ($match) { return strtoupper($match[0]); }, $string)->result; +$newString = Regex::replaceCallbackArray(['{fo+}' => fn ($match) => strtoupper($match[0])], $string)->result; +``` + +Note that `preg_grep` and `preg_split` are only callable via the `Preg` class as they do not have +complex return types warranting a specific result object. + +See the [MatchResult](src/MatchResult.php), [MatchWithOffsetsResult](src/MatchWithOffsetsResult.php), [MatchAllResult](src/MatchAllResult.php), +[MatchAllWithOffsetsResult](src/MatchAllWithOffsetsResult.php), and [ReplaceResult](src/ReplaceResult.php) class sources for more details. + +Restrictions / Limitations +-------------------------- + +Due to type safety requirements a few restrictions are in place. + +- matching using `PREG_OFFSET_CAPTURE` is made available via `matchWithOffsets` and `matchAllWithOffsets`. + You cannot pass the flag to `match`/`matchAll`. +- `Preg::split` will also reject `PREG_SPLIT_OFFSET_CAPTURE` and you should use `splitWithOffsets` + instead. +- `matchAll` rejects `PREG_SET_ORDER` as it also changes the shape of the returned matches. There + is no alternative provided as you can fairly easily code around it. +- `preg_filter` is not supported as it has a rather crazy API, most likely you should rather + use `Preg::grep` in combination with some loop and `Preg::replace`. +- `replace`, `replaceCallback` and `replaceCallbackArray` do not support an array `$subject`, + only simple strings. +- As of 2.0, the library always uses `PREG_UNMATCHED_AS_NULL` for matching, which offers [much + saner/more predictable results](#preg_unmatched_as_null). As of 3.0 the flag is also set for + `replaceCallback` and `replaceCallbackArray`. + +#### PREG_UNMATCHED_AS_NULL + +As of 2.0, this library always uses PREG_UNMATCHED_AS_NULL for all `match*` and `isMatch*` +functions. As of 3.0 it is also done for `replaceCallback` and `replaceCallbackArray`. + +This means your matches will always contain all matching groups, either as null if unmatched +or as string if it matched. + +The advantages in clarity and predictability are clearer if you compare the two outputs of +running this with and without PREG_UNMATCHED_AS_NULL in $flags: + +```php +preg_match('/(a)(b)*(c)(d)*/', 'ac', $matches, $flags); +``` + +| no flag | PREG_UNMATCHED_AS_NULL | +| --- | --- | +| array (size=4) | array (size=5) | +| 0 => string 'ac' (length=2) | 0 => string 'ac' (length=2) | +| 1 => string 'a' (length=1) | 1 => string 'a' (length=1) | +| 2 => string '' (length=0) | 2 => null | +| 3 => string 'c' (length=1) | 3 => string 'c' (length=1) | +| | 4 => null | +| group 2 (any unmatched group preceding one that matched) is set to `''`. You cannot tell if it matched an empty string or did not match at all | group 2 is `null` when unmatched and a string if it matched, easy to check for | +| group 4 (any optional group without a matching one following) is missing altogether. So you have to check with `isset()`, but really you want `isset($m[4]) && $m[4] !== ''` for safety unless you are very careful to check that a non-optional group follows it | group 4 is always set, and null in this case as there was no match, easy to check for with `$m[4] !== null` | + +License +------- + +composer/pcre is licensed under the MIT License, see the LICENSE file for details. diff --git a/vendor/composer/pcre/composer.json b/vendor/composer/pcre/composer.json new file mode 100644 index 00000000000..fd8147a30d6 --- /dev/null +++ b/vendor/composer/pcre/composer.json @@ -0,0 +1,46 @@ +{ + "name": "composer\/pcre", + "description": "PCRE wrapping library that offers type-safe preg_* replacements.", + "type": "library", + "license": "MIT", + "keywords": [ + "pcre", + "regex", + "preg", + "regular expression" + ], + "authors": [ + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http:\/\/seld.be" + } + ], + "require": { + "php": "^7.4 || ^8.0" + }, + "require-dev": { + "symfony\/phpunit-bridge": "^5", + "phpstan\/phpstan": "^1.3", + "phpstan\/phpstan-strict-rules": "^1.1" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\Pcre\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Composer\\Pcre\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "vendor\/bin\/simple-phpunit", + "phpstan": "phpstan analyse" + } +} \ No newline at end of file diff --git a/vendor/composer/pcre/src/MatchAllResult.php b/vendor/composer/pcre/src/MatchAllResult.php new file mode 100644 index 00000000000..2a171ce9d89 --- /dev/null +++ b/vendor/composer/pcre/src/MatchAllResult.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchAllResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + /** + * @readonly + * @var 0|positive-int + */ + public $count; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php b/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php new file mode 100644 index 00000000000..8f355968d14 --- /dev/null +++ b/vendor/composer/pcre/src/MatchAllStrictGroupsResult.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchAllStrictGroupsResult +{ + /** + * An array of match group => list of matched strings + * + * @readonly + * @var array> + */ + public $matches; + /** + * @readonly + * @var 0|positive-int + */ + public $count; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php b/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php new file mode 100644 index 00000000000..e868e7c32f7 --- /dev/null +++ b/vendor/composer/pcre/src/MatchAllWithOffsetsResult.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchAllWithOffsetsResult +{ + /** + * An array of match group => list of matches, every match being a pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array> + * @phpstan-var array}>> + */ + public $matches; + /** + * @readonly + * @var 0|positive-int + */ + public $count; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array> $matches + * @phpstan-param array}>> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + $this->count = $count; + } +} diff --git a/vendor/composer/pcre/src/MatchResult.php b/vendor/composer/pcre/src/MatchResult.php new file mode 100644 index 00000000000..01dd007c575 --- /dev/null +++ b/vendor/composer/pcre/src/MatchResult.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/vendor/composer/pcre/src/MatchStrictGroupsResult.php b/vendor/composer/pcre/src/MatchStrictGroupsResult.php new file mode 100644 index 00000000000..181f9eb731c --- /dev/null +++ b/vendor/composer/pcre/src/MatchStrictGroupsResult.php @@ -0,0 +1,36 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchStrictGroupsResult +{ + /** + * An array of match group => string matched + * + * @readonly + * @var array + */ + public $matches; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/vendor/composer/pcre/src/MatchWithOffsetsResult.php b/vendor/composer/pcre/src/MatchWithOffsetsResult.php new file mode 100644 index 00000000000..af7627724f5 --- /dev/null +++ b/vendor/composer/pcre/src/MatchWithOffsetsResult.php @@ -0,0 +1,38 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class MatchWithOffsetsResult +{ + /** + * An array of match group => pair of string matched + offset in bytes (or -1 if no match) + * + * @readonly + * @var array + * @phpstan-var array}> + */ + public $matches; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + * @param array $matches + * @phpstan-param array}> $matches + */ + public function __construct(int $count, array $matches) + { + $this->matches = $matches; + $this->matched = (bool) $count; + } +} diff --git a/vendor/composer/pcre/src/PcreException.php b/vendor/composer/pcre/src/PcreException.php new file mode 100644 index 00000000000..5656aa0212e --- /dev/null +++ b/vendor/composer/pcre/src/PcreException.php @@ -0,0 +1,52 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +class PcreException extends \RuntimeException +{ + /** + * @param string $function + * @param string|string[] $pattern + * @return self + */ + public static function fromFunction($function, $pattern) + { + $code = \preg_last_error(); + if (\is_array($pattern)) { + $pattern = \implode(', ', $pattern); + } + return new PcreException($function . '(): failed executing "' . $pattern . '": ' . self::pcreLastErrorMessage($code), $code); + } + /** + * @param int $code + * @return string + */ + private static function pcreLastErrorMessage($code) + { + if (\function_exists('preg_last_error_msg')) { + return \preg_last_error_msg(); + } + // older php versions did not set the code properly in all cases + if (\PHP_VERSION_ID < 70201 && $code === 0) { + return 'UNDEFINED_ERROR'; + } + $constants = \get_defined_constants(\true); + if (!isset($constants['pcre'])) { + return 'UNDEFINED_ERROR'; + } + foreach ($constants['pcre'] as $const => $val) { + if ($val === $code && \substr($const, -6) === '_ERROR') { + return $const; + } + } + return 'UNDEFINED_ERROR'; + } +} diff --git a/vendor/composer/pcre/src/Preg.php b/vendor/composer/pcre/src/Preg.php new file mode 100644 index 00000000000..b58d67560ed --- /dev/null +++ b/vendor/composer/pcre/src/Preg.php @@ -0,0 +1,382 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +class Preg +{ + /** @internal */ + public const ARRAY_MSG = '$subject as an array is not supported. You can use \'foreach\' instead.'; + /** @internal */ + public const INVALID_TYPE_MSG = '$subject must be a string, %s given.'; + /** + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * + * @param-out array $matches + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : int + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + $result = \preg_match($pattern, $subject, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset); + if ($result === \false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + return $result; + } + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|1 + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function matchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : int + { + $result = self::match($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatches($pattern, $matchesInternal, 'match'); + return $result; + } + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_OFFSET_CAPTURE are always set, no other flags are supported + * @return 0|1 + * + * @param-out array}> $matches + */ + public static function matchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0) : int + { + $result = \preg_match($pattern, $subject, $matches, $flags | \PREG_UNMATCHED_AS_NULL | \PREG_OFFSET_CAPTURE, $offset); + if ($result === \false) { + throw PcreException::fromFunction('preg_match', $pattern); + } + return $result; + } + /** + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * + * @param-out array> $matches + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : int + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + $result = \preg_match_all($pattern, $subject, $matches, $flags | \PREG_UNMATCHED_AS_NULL, $offset); + if (!\is_int($result)) { + // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + return $result; + } + /** + * Variant of `match()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @return 0|positive-int + * @throws UnexpectedNullMatchException + * + * @param-out array> $matches + */ + public static function matchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : int + { + $result = self::matchAll($pattern, $subject, $matchesInternal, $flags, $offset); + $matches = self::enforceNonNullMatchAll($pattern, $matchesInternal, 'matchAll'); + return $result; + } + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + * @return 0|positive-int + * + * @phpstan-param array}>> $matches + */ + public static function matchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0) : int + { + self::checkSetOrder($flags); + $result = \preg_match_all($pattern, $subject, $matches, $flags | \PREG_UNMATCHED_AS_NULL | \PREG_OFFSET_CAPTURE, $offset); + if (!\is_int($result)) { + // PHP < 8 may return null, 8+ returns int|false + throw PcreException::fromFunction('preg_match_all', $pattern); + } + return $result; + } + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + * @param int $count Set by method + * + * @param-out int<0, max> $count + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1, int &$count = null) : string + { + if (!\is_scalar($subject)) { + if (\is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + throw new \TypeError(\sprintf(static::INVALID_TYPE_MSG, \gettype($subject))); + } + $result = \preg_replace($pattern, $replacement, $subject, $limit, $count); + if ($result === null) { + throw PcreException::fromFunction('preg_replace', $pattern); + } + return $result; + } + /** + * @param string|string[] $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0) : string + { + if (!\is_scalar($subject)) { + if (\is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + throw new \TypeError(\sprintf(static::INVALID_TYPE_MSG, \gettype($subject))); + } + $result = \preg_replace_callback($pattern, $replacement, $subject, $limit, $count, $flags | \PREG_UNMATCHED_AS_NULL); + if ($result === null) { + throw PcreException::fromFunction('preg_replace_callback', $pattern); + } + return $result; + } + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+ + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackStrictGroups(string $pattern, callable $replacement, $subject, int $limit = -1, int &$count = null, int $flags = 0) : string + { + return self::replaceCallback($pattern, function (array $matches) use($pattern, $replacement) { + return $replacement(self::enforceNonNullMatches($pattern, $matches, 'replaceCallback')); + }, $subject, $limit, $count, $flags); + } + /** + * @param array): string> $pattern + * @param string $subject + * @param int $count Set by method + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + * + * @param-out int<0, max> $count + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int &$count = null, int $flags = 0) : string + { + if (!\is_scalar($subject)) { + if (\is_array($subject)) { + throw new \InvalidArgumentException(static::ARRAY_MSG); + } + throw new \TypeError(\sprintf(static::INVALID_TYPE_MSG, \gettype($subject))); + } + $result = \preg_replace_callback_array($pattern, $subject, $limit, $count, $flags | \PREG_UNMATCHED_AS_NULL); + if ($result === null) { + $pattern = \array_keys($pattern); + throw PcreException::fromFunction('preg_replace_callback_array', $pattern); + } + return $result; + } + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE + * @return list + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0) : array + { + if (($flags & \PREG_SPLIT_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_SPLIT_OFFSET_CAPTURE is not supported as it changes the type of $matches, use splitWithOffsets() instead'); + } + $result = \preg_split($pattern, $subject, $limit, $flags); + if ($result === \false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + return $result; + } + /** + * @param int-mask $flags PREG_SPLIT_NO_EMPTY or PREG_SPLIT_DELIM_CAPTURE, PREG_SPLIT_OFFSET_CAPTURE is always set + * @return list + * @phpstan-return list}> + */ + public static function splitWithOffsets(string $pattern, string $subject, int $limit = -1, int $flags = 0) : array + { + $result = \preg_split($pattern, $subject, $limit, $flags | \PREG_SPLIT_OFFSET_CAPTURE); + if ($result === \false) { + throw PcreException::fromFunction('preg_split', $pattern); + } + return $result; + } + /** + * @template T of string|\Stringable + * @param string $pattern + * @param array $array + * @param int-mask $flags PREG_GREP_INVERT + * @return array + */ + public static function grep(string $pattern, array $array, int $flags = 0) : array + { + $result = \preg_grep($pattern, $array, $flags); + if ($result === \false) { + throw PcreException::fromFunction('preg_grep', $pattern); + } + return $result; + } + /** + * Variant of match() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array $matches + */ + public static function isMatch(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : bool + { + return (bool) static::match($pattern, $subject, $matches, $flags, $offset); + } + /** + * Variant of `isMatch()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + * + * @param-out array $matches + */ + public static function isMatchStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : bool + { + return (bool) self::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + /** + * Variant of matchAll() which returns a bool instead of int + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : bool + { + return (bool) static::matchAll($pattern, $subject, $matches, $flags, $offset); + } + /** + * Variant of `isMatchAll()` which outputs non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array> $matches + */ + public static function isMatchAllStrictGroups(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : bool + { + return (bool) self::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + } + /** + * Variant of matchWithOffsets() which returns a bool instead of int + * + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}> $matches + */ + public static function isMatchWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0) : bool + { + return (bool) static::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + /** + * Variant of matchAllWithOffsets() which returns a bool instead of int + * + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param array> $matches Set by method + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * + * @param-out array}>> $matches + */ + public static function isMatchAllWithOffsets(string $pattern, string $subject, ?array &$matches, int $flags = 0, int $offset = 0) : bool + { + return (bool) static::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + } + private static function checkOffsetCapture(int $flags, string $useFunctionName) : void + { + if (($flags & \PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the type of $matches, use ' . $useFunctionName . '() instead'); + } + } + private static function checkSetOrder(int $flags) : void + { + if (($flags & \PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the type of $matches'); + } + } + /** + * @param array $matches + * @return array + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatches(string $pattern, array $matches, string $variantMethod) + { + foreach ($matches as $group => $match) { + if (null === $match) { + throw new UnexpectedNullMatchException('Pattern "' . $pattern . '" had an unexpected unmatched group "' . $group . '", make sure the pattern always matches or use ' . $variantMethod . '() instead.'); + } + } + /** @var array */ + return $matches; + } + /** + * @param array> $matches + * @return array> + * @throws UnexpectedNullMatchException + */ + private static function enforceNonNullMatchAll(string $pattern, array $matches, string $variantMethod) + { + foreach ($matches as $group => $groupMatches) { + foreach ($groupMatches as $match) { + if (null === $match) { + throw new UnexpectedNullMatchException('Pattern "' . $pattern . '" had an unexpected unmatched group "' . $group . '", make sure the pattern always matches or use ' . $variantMethod . '() instead.'); + } + } + } + /** @var array> */ + return $matches; + } +} diff --git a/vendor/composer/pcre/src/Regex.php b/vendor/composer/pcre/src/Regex.php new file mode 100644 index 00000000000..937d3ecdf30 --- /dev/null +++ b/vendor/composer/pcre/src/Regex.php @@ -0,0 +1,148 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +class Regex +{ + /** + * @param non-empty-string $pattern + */ + public static function isMatch(string $pattern, string $subject, int $offset = 0) : bool + { + return (bool) Preg::match($pattern, $subject, $matches, 0, $offset); + } + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function match(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchResult + { + self::checkOffsetCapture($flags, 'matchWithOffsets'); + $count = Preg::match($pattern, $subject, $matches, $flags, $offset); + return new MatchResult($count, $matches); + } + /** + * Variant of `match()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchStrictGroupsResult + { + $count = Preg::matchStrictGroups($pattern, $subject, $matches, $flags, $offset); + return new MatchStrictGroupsResult($count, $matches); + } + /** + * Runs preg_match with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchWithOffsetsResult + { + $count = Preg::matchWithOffsets($pattern, $subject, $matches, $flags, $offset); + return new MatchWithOffsetsResult($count, $matches); + } + /** + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + */ + public static function matchAll(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchAllResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + $count = Preg::matchAll($pattern, $subject, $matches, $flags, $offset); + return new MatchAllResult($count, $matches); + } + /** + * Variant of `matchAll()` which returns non-null matches (or throws) + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL is always set, no other flags are supported + * @throws UnexpectedNullMatchException + */ + public static function matchAllStrictGroups(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchAllStrictGroupsResult + { + self::checkOffsetCapture($flags, 'matchAllWithOffsets'); + self::checkSetOrder($flags); + $count = Preg::matchAllStrictGroups($pattern, $subject, $matches, $flags, $offset); + return new MatchAllStrictGroupsResult($count, $matches); + } + /** + * Runs preg_match_all with PREG_OFFSET_CAPTURE + * + * @param non-empty-string $pattern + * @param int-mask $flags PREG_UNMATCHED_AS_NULL and PREG_MATCH_OFFSET are always set, no other flags are supported + */ + public static function matchAllWithOffsets(string $pattern, string $subject, int $flags = 0, int $offset = 0) : MatchAllWithOffsetsResult + { + self::checkSetOrder($flags); + $count = Preg::matchAllWithOffsets($pattern, $subject, $matches, $flags, $offset); + return new MatchAllWithOffsetsResult($count, $matches); + } + /** + * @param string|string[] $pattern + * @param string|string[] $replacement + * @param string $subject + */ + public static function replace($pattern, $replacement, $subject, int $limit = -1) : ReplaceResult + { + $result = Preg::replace($pattern, $replacement, $subject, $limit, $count); + return new ReplaceResult($count, $result); + } + /** + * @param string|string[] $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallback($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0) : ReplaceResult + { + $result = Preg::replaceCallback($pattern, $replacement, $subject, $limit, $count, $flags); + return new ReplaceResult($count, $result); + } + /** + * Variant of `replaceCallback()` which outputs non-null matches (or throws) + * + * @param string $pattern + * @param callable(array): string $replacement + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE or PREG_UNMATCHED_AS_NULL, only available on PHP 7.4+ + */ + public static function replaceCallbackStrictGroups($pattern, callable $replacement, $subject, int $limit = -1, int $flags = 0) : ReplaceResult + { + $result = Preg::replaceCallbackStrictGroups($pattern, $replacement, $subject, $limit, $count, $flags); + return new ReplaceResult($count, $result); + } + /** + * @param array): string> $pattern + * @param string $subject + * @param int-mask $flags PREG_OFFSET_CAPTURE is supported, PREG_UNMATCHED_AS_NULL is always set + */ + public static function replaceCallbackArray(array $pattern, $subject, int $limit = -1, int $flags = 0) : ReplaceResult + { + $result = Preg::replaceCallbackArray($pattern, $subject, $limit, $count, $flags); + return new ReplaceResult($count, $result); + } + private static function checkOffsetCapture(int $flags, string $useFunctionName) : void + { + if (($flags & \PREG_OFFSET_CAPTURE) !== 0) { + throw new \InvalidArgumentException('PREG_OFFSET_CAPTURE is not supported as it changes the return type, use ' . $useFunctionName . '() instead'); + } + } + private static function checkSetOrder(int $flags) : void + { + if (($flags & \PREG_SET_ORDER) !== 0) { + throw new \InvalidArgumentException('PREG_SET_ORDER is not supported as it changes the return type'); + } + } +} diff --git a/vendor/composer/pcre/src/ReplaceResult.php b/vendor/composer/pcre/src/ReplaceResult.php new file mode 100644 index 00000000000..746a306d2be --- /dev/null +++ b/vendor/composer/pcre/src/ReplaceResult.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +final class ReplaceResult +{ + /** + * @readonly + * @var string + */ + public $result; + /** + * @readonly + * @var 0|positive-int + */ + public $count; + /** + * @readonly + * @var bool + */ + public $matched; + /** + * @param 0|positive-int $count + */ + public function __construct(int $count, string $result) + { + $this->count = $count; + $this->matched = (bool) $count; + $this->result = $result; + } +} diff --git a/vendor/composer/pcre/src/UnexpectedNullMatchException.php b/vendor/composer/pcre/src/UnexpectedNullMatchException.php new file mode 100644 index 00000000000..86829a2a055 --- /dev/null +++ b/vendor/composer/pcre/src/UnexpectedNullMatchException.php @@ -0,0 +1,19 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Pcre; + +class UnexpectedNullMatchException extends PcreException +{ + public static function fromFunction($function, $pattern) + { + throw new \LogicException('fromFunction should not be called on ' . self::class . ', use ' . PcreException::class); + } +} diff --git a/vendor/composer/semver/CHANGELOG.md b/vendor/composer/semver/CHANGELOG.md new file mode 100644 index 00000000000..c9514773571 --- /dev/null +++ b/vendor/composer/semver/CHANGELOG.md @@ -0,0 +1,209 @@ +# Change Log + +All notable changes to this project will be documented in this file. +This project adheres to [Semantic Versioning](http://semver.org/). + +### [3.3.2] 2022-04-01 + + * Fixed handling of non-string values (#134) + +### [3.3.1] 2022-03-16 + + * Fixed possible cache key clash in the CompilingMatcher memoization (#132) + +### [3.3.0] 2022-03-15 + + * Improved performance of CompilingMatcher by memoizing more (#131) + * Added CompilingMatcher::clear to clear all memoization caches + +### [3.2.9] 2022-02-04 + + * Revert #129 (Fixed MultiConstraint with MatchAllConstraint) which caused regressions + +### [3.2.8] 2022-02-04 + + * Updates to latest phpstan / CI by @Seldaek in https://github.com/composer/semver/pull/130 + * Fixed MultiConstraint with MatchAllConstraint by @Toflar in https://github.com/composer/semver/pull/129 + +### [3.2.7] 2022-01-04 + + * Fixed: typo in type definition of Intervals class causing issues with Psalm scanning vendors + +### [3.2.6] 2021-10-25 + + * Fixed: type improvements to parseStability + +### [3.2.5] 2021-05-24 + + * Fixed: issue comparing disjunctive MultiConstraints to conjunctive ones (#127) + * Fixed: added complete type information using phpstan annotations + +### [3.2.4] 2020-11-13 + + * Fixed: code clean-up + +### [3.2.3] 2020-11-12 + + * Fixed: constraints in the form of `X || Y, >=Y.1` and other such complex constructs were in some cases being optimized into a more restrictive constraint + +### [3.2.2] 2020-10-14 + + * Fixed: internal code cleanups + +### [3.2.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [3.2.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [3.1.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 3.0.1 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [3.0.1] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + +### [3.0.0] 2020-05-26 + + * Break: Renamed `EmptyConstraint`, replace it with `MatchAllConstraint` + * Break: Unlikely to affect anyone but strictly speaking a breaking change, `*.*` and such variants will not match all `dev-*` versions anymore, only `*` does + * Break: ConstraintInterface is now considered internal/private and not meant to be implemented by third parties anymore + * Added `Intervals` class to check if a constraint is a subsets of another one, and allow compacting complex MultiConstraints into simpler ones + * Added `CompilingMatcher` class to speed up constraint matching against simple Constraint instances + * Added `MatchAllConstraint` and `MatchNoneConstraint` which match everything and nothing + * Added more advanced optimization of contiguous constraints inside MultiConstraint + * Added tentative support for PHP 8 + * Fixed ConstraintInterface::matches to be commutative in all cases + +### [2.0.0] 2020-04-21 + + * Break: `dev-master`, `dev-trunk` and `dev-default` now normalize to `dev-master`, `dev-trunk` and `dev-default` instead of `9999999-dev` in 1.x + * Break: Removed the deprecated `AbstractConstraint` + * Added `getUpperBound` and `getLowerBound` to ConstraintInterface. They return `Composer\Semver\Constraint\Bound` instances + * Added `MultiConstraint::create` to create the most-optimal form of ConstraintInterface from an array of constraint strings + +### [1.7.2] 2020-12-03 + + * Fixed: Allow installing on php 8 + +### [1.7.1] 2020-09-27 + + * Fixed: accidental validation of broken constraints combining ^/~ and wildcards, and -dev suffix allowing weird cases + * Fixed: normalization of beta0 and such which was dropping the 0 + +### [1.7.0] 2020-09-09 + + * Added: support for `x || @dev`, not very useful but seen in the wild and failed to validate with 1.5.2/1.6.0 + * Added: support for `foobar-dev` being equal to `dev-foobar`, dev-foobar is the official way to write it but we need to support the other for BC and convenience + +### [1.6.0] 2020-09-08 + + * Added: support for constraints like `^2.x-dev` and `~2.x-dev`, not very useful but seen in the wild and failed to validate with 1.5.2 + * Fixed: invalid aliases will no longer throw, unless explicitly validated by Composer in the root package + +### [1.5.2] 2020-09-08 + + * Fixed: handling of some invalid -dev versions which were seen as valid + * Fixed: some doctypes + +### [1.5.1] 2020-01-13 + + * Fixed: Parsing of aliased version was not validating the alias to be a valid version + +### [1.5.0] 2019-03-19 + + * Added: some support for date versions (e.g. 201903) in `~` operator + * Fixed: support for stabilities in `~` operator was inconsistent + +### [1.4.2] 2016-08-30 + + * Fixed: collapsing of complex constraints lead to buggy constraints + +### [1.4.1] 2016-06-02 + + * Changed: branch-like requirements no longer strip build metadata - [composer/semver#38](https://github.com/composer/semver/pull/38). + +### [1.4.0] 2016-03-30 + + * Added: getters on MultiConstraint - [composer/semver#35](https://github.com/composer/semver/pull/35). + +### [1.3.0] 2016-02-25 + + * Fixed: stability parsing - [composer/composer#1234](https://github.com/composer/composer/issues/4889). + * Changed: collapse contiguous constraints when possible. + +### [1.2.0] 2015-11-10 + + * Changed: allow multiple numerical identifiers in 'pre-release' version part. + * Changed: add more 'v' prefix support. + +### [1.1.0] 2015-11-03 + + * Changed: dropped redundant `test` namespace. + * Changed: minor adjustment in datetime parsing normalization. + * Changed: `ConstraintInterface` relaxed, setPrettyString is not required anymore. + * Changed: `AbstractConstraint` marked deprecated, will be removed in 2.0. + * Changed: `Constraint` is now extensible. + +### [1.0.0] 2015-09-21 + + * Break: `VersionConstraint` renamed to `Constraint`. + * Break: `SpecificConstraint` renamed to `AbstractConstraint`. + * Break: `LinkConstraintInterface` renamed to `ConstraintInterface`. + * Break: `VersionParser::parseNameVersionPairs` was removed. + * Changed: `VersionParser::parseConstraints` allows (but ignores) build metadata now. + * Changed: `VersionParser::parseConstraints` allows (but ignores) prefixing numeric versions with a 'v' now. + * Changed: Fixed namespace(s) of test files. + * Changed: `Comparator::compare` no longer throws `InvalidArgumentException`. + * Changed: `Constraint` now throws `InvalidArgumentException`. + +### [0.1.0] 2015-07-23 + + * Added: `Composer\Semver\Comparator`, various methods to compare versions. + * Added: various documents such as README.md, LICENSE, etc. + * Added: configuration files for Git, Travis, php-cs-fixer, phpunit. + * Break: the following namespaces were renamed: + - Namespace: `Composer\Package\Version` -> `Composer\Semver` + - Namespace: `Composer\Package\LinkConstraint` -> `Composer\Semver\Constraint` + - Namespace: `Composer\Test\Package\Version` -> `Composer\Test\Semver` + - Namespace: `Composer\Test\Package\LinkConstraint` -> `Composer\Test\Semver\Constraint` + * Changed: code style using php-cs-fixer. + +[3.3.2]: https://github.com/composer/semver/compare/3.3.1...3.3.2 +[3.3.1]: https://github.com/composer/semver/compare/3.3.0...3.3.1 +[3.3.0]: https://github.com/composer/semver/compare/3.2.9...3.3.0 +[3.2.9]: https://github.com/composer/semver/compare/3.2.8...3.2.9 +[3.2.8]: https://github.com/composer/semver/compare/3.2.7...3.2.8 +[3.2.7]: https://github.com/composer/semver/compare/3.2.6...3.2.7 +[3.2.6]: https://github.com/composer/semver/compare/3.2.5...3.2.6 +[3.2.5]: https://github.com/composer/semver/compare/3.2.4...3.2.5 +[3.2.4]: https://github.com/composer/semver/compare/3.2.3...3.2.4 +[3.2.3]: https://github.com/composer/semver/compare/3.2.2...3.2.3 +[3.2.2]: https://github.com/composer/semver/compare/3.2.1...3.2.2 +[3.2.1]: https://github.com/composer/semver/compare/3.2.0...3.2.1 +[3.2.0]: https://github.com/composer/semver/compare/3.1.0...3.2.0 +[3.1.0]: https://github.com/composer/semver/compare/3.0.1...3.1.0 +[3.0.1]: https://github.com/composer/semver/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/semver/compare/2.0.0...3.0.0 +[2.0.0]: https://github.com/composer/semver/compare/1.5.1...2.0.0 +[1.7.2]: https://github.com/composer/semver/compare/1.7.1...1.7.2 +[1.7.1]: https://github.com/composer/semver/compare/1.7.0...1.7.1 +[1.7.0]: https://github.com/composer/semver/compare/1.6.0...1.7.0 +[1.6.0]: https://github.com/composer/semver/compare/1.5.2...1.6.0 +[1.5.2]: https://github.com/composer/semver/compare/1.5.1...1.5.2 +[1.5.1]: https://github.com/composer/semver/compare/1.5.0...1.5.1 +[1.5.0]: https://github.com/composer/semver/compare/1.4.2...1.5.0 +[1.4.2]: https://github.com/composer/semver/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/semver/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/semver/compare/1.3.0...1.4.0 +[1.3.0]: https://github.com/composer/semver/compare/1.2.0...1.3.0 +[1.2.0]: https://github.com/composer/semver/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/semver/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/semver/compare/0.1.0...1.0.0 +[0.1.0]: https://github.com/composer/semver/compare/5e0b9a4da...0.1.0 diff --git a/vendor/composer/semver/LICENSE b/vendor/composer/semver/LICENSE new file mode 100644 index 00000000000..46697586262 --- /dev/null +++ b/vendor/composer/semver/LICENSE @@ -0,0 +1,19 @@ +Copyright (C) 2015 Composer + +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. diff --git a/vendor/composer/semver/README.md b/vendor/composer/semver/README.md new file mode 100644 index 00000000000..35db99a5c3c --- /dev/null +++ b/vendor/composer/semver/README.md @@ -0,0 +1,98 @@ +composer/semver +=============== + +Semver (Semantic Versioning) library that offers utilities, version constraint parsing and validation. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +[![Continuous Integration](https://github.com/composer/semver/workflows/Continuous%20Integration/badge.svg?branch=main)](https://github.com/composer/semver/actions) + + +Installation +------------ + +Install the latest version with: + +```bash +$ composer require composer/semver +``` + + +Requirements +------------ + +* PHP 5.3.2 is required but using the latest version of PHP is highly recommended. + + +Version Comparison +------------------ + +For details on how versions are compared, refer to the [Versions](https://getcomposer.org/doc/articles/versions.md) +article in the documentation section of the [getcomposer.org](https://getcomposer.org) website. + + +Basic usage +----------- + +### Comparator + +The [`Composer\Semver\Comparator`](https://github.com/composer/semver/blob/main/src/Comparator.php) class provides the following methods for comparing versions: + +* greaterThan($v1, $v2) +* greaterThanOrEqualTo($v1, $v2) +* lessThan($v1, $v2) +* lessThanOrEqualTo($v1, $v2) +* equalTo($v1, $v2) +* notEqualTo($v1, $v2) + +Each function takes two version strings as arguments and returns a boolean. For example: + +```php +use Composer\Semver\Comparator; + +Comparator::greaterThan('1.25.0', '1.24.0'); // 1.25.0 > 1.24.0 +``` + +### Semver + +The [`Composer\Semver\Semver`](https://github.com/composer/semver/blob/main/src/Semver.php) class provides the following methods: + +* satisfies($version, $constraints) +* satisfiedBy(array $versions, $constraint) +* sort($versions) +* rsort($versions) + +### Intervals + +The [`Composer\Semver\Intervals`](https://github.com/composer/semver/blob/main/src/Intervals.php) static class provides +a few utilities to work with complex constraints or read version intervals from a constraint: + +```php +use Composer\Semver\Intervals; + +// Checks whether $candidate is a subset of $constraint +Intervals::isSubsetOf(ConstraintInterface $candidate, ConstraintInterface $constraint); + +// Checks whether $a and $b have any intersection, equivalent to $a->matches($b) +Intervals::haveIntersections(ConstraintInterface $a, ConstraintInterface $b); + +// Optimizes a complex multi constraint by merging all intervals down to the smallest +// possible multi constraint. The drawbacks are this is not very fast, and the resulting +// multi constraint will have no human readable prettyConstraint configured on it +Intervals::compactConstraint(ConstraintInterface $constraint); + +// Creates an array of numeric intervals and branch constraints representing a given constraint +Intervals::get(ConstraintInterface $constraint); + +// Clears the memoization cache when you are done processing constraints +Intervals::clear() +``` + +See the class docblocks for more details. + + +License +------- + +composer/semver is licensed under the MIT License, see the LICENSE file for details. diff --git a/vendor/composer/semver/composer.json b/vendor/composer/semver/composer.json new file mode 100644 index 00000000000..bb7e6086cb9 --- /dev/null +++ b/vendor/composer/semver/composer.json @@ -0,0 +1,59 @@ +{ + "name": "composer\/semver", + "description": "Semver library that offers utilities, version constraint parsing and validation.", + "type": "library", + "license": "MIT", + "keywords": [ + "semver", + "semantic", + "versioning", + "validation" + ], + "authors": [ + { + "name": "Nils Adermann", + "email": "naderman@naderman.de", + "homepage": "http:\/\/www.naderman.de" + }, + { + "name": "Jordi Boggiano", + "email": "j.boggiano@seld.be", + "homepage": "http:\/\/seld.be" + }, + { + "name": "Rob Bast", + "email": "rob.bast@gmail.com", + "homepage": "http:\/\/robbast.nl" + } + ], + "support": { + "irc": "irc:\/\/irc.freenode.org\/composer", + "issues": "https:\/\/github.com\/composer\/semver\/issues" + }, + "require": { + "php": "^5.3.2 || ^7.0 || ^8.0" + }, + "require-dev": { + "symfony\/phpunit-bridge": "^4.2 || ^5", + "phpstan\/phpstan": "^1.4" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\Semver\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Composer\\Semver\\": "tests" + } + }, + "extra": { + "branch-alias": { + "dev-main": "3.x-dev" + } + }, + "scripts": { + "test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor\/bin\/simple-phpunit", + "phpstan": "@php vendor\/bin\/phpstan analyse" + } +} \ No newline at end of file diff --git a/vendor/composer/semver/src/Comparator.php b/vendor/composer/semver/src/Comparator.php new file mode 100644 index 00000000000..36722d6dfb1 --- /dev/null +++ b/vendor/composer/semver/src/Comparator.php @@ -0,0 +1,104 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +class Comparator +{ + /** + * Evaluates the expression: $version1 > $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThan($version1, $version2) + { + return self::compare($version1, '>', $version2); + } + /** + * Evaluates the expression: $version1 >= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function greaterThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '>=', $version2); + } + /** + * Evaluates the expression: $version1 < $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThan($version1, $version2) + { + return self::compare($version1, '<', $version2); + } + /** + * Evaluates the expression: $version1 <= $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function lessThanOrEqualTo($version1, $version2) + { + return self::compare($version1, '<=', $version2); + } + /** + * Evaluates the expression: $version1 == $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function equalTo($version1, $version2) + { + return self::compare($version1, '==', $version2); + } + /** + * Evaluates the expression: $version1 != $version2. + * + * @param string $version1 + * @param string $version2 + * + * @return bool + */ + public static function notEqualTo($version1, $version2) + { + return self::compare($version1, '!=', $version2); + } + /** + * Evaluates the expression: $version1 $operator $version2. + * + * @param string $version1 + * @param string $operator + * @param string $version2 + * + * @return bool + * + * @phpstan-param Constraint::STR_OP_* $operator + */ + public static function compare($version1, $operator, $version2) + { + $constraint = new Constraint($operator, $version2); + return $constraint->matchSpecific(new Constraint('==', $version1), \true); + } +} diff --git a/vendor/composer/semver/src/CompilingMatcher.php b/vendor/composer/semver/src/CompilingMatcher.php new file mode 100644 index 00000000000..264babf97c3 --- /dev/null +++ b/vendor/composer/semver/src/CompilingMatcher.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +use ECSPrefix202307\Composer\Semver\Constraint\ConstraintInterface; +/** + * Helper class to evaluate constraint by compiling and reusing the code to evaluate + */ +class CompilingMatcher +{ + /** + * @var array + * @phpstan-var array + */ + private static $compiledCheckerCache = array(); + /** + * @var array + * @phpstan-var array + */ + private static $resultCache = array(); + /** @var bool */ + private static $enabled; + /** + * @phpstan-var array + */ + private static $transOpInt = array(Constraint::OP_EQ => Constraint::STR_OP_EQ, Constraint::OP_LT => Constraint::STR_OP_LT, Constraint::OP_LE => Constraint::STR_OP_LE, Constraint::OP_GT => Constraint::STR_OP_GT, Constraint::OP_GE => Constraint::STR_OP_GE, Constraint::OP_NE => Constraint::STR_OP_NE); + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$resultCache = array(); + self::$compiledCheckerCache = array(); + } + /** + * Evaluates the expression: $constraint match $operator $version + * + * @param ConstraintInterface $constraint + * @param int $operator + * @phpstan-param Constraint::OP_* $operator + * @param string $version + * + * @return mixed + */ + public static function match(ConstraintInterface $constraint, $operator, $version) + { + $resultCacheKey = $operator . $constraint . ';' . $version; + if (isset(self::$resultCache[$resultCacheKey])) { + return self::$resultCache[$resultCacheKey]; + } + if (self::$enabled === null) { + self::$enabled = !\in_array('eval', \explode(',', (string) \ini_get('disable_functions')), \true); + } + if (!self::$enabled) { + return self::$resultCache[$resultCacheKey] = $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 self::$resultCache[$resultCacheKey] = $function($version, \strpos($version, 'dev-') === 0); + } +} diff --git a/vendor/composer/semver/src/Constraint/Bound.php b/vendor/composer/semver/src/Constraint/Bound.php new file mode 100644 index 00000000000..a051f244acf --- /dev/null +++ b/vendor/composer/semver/src/Constraint/Bound.php @@ -0,0 +1,103 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +class Bound +{ + /** + * @var string + */ + private $version; + /** + * @var bool + */ + private $isInclusive; + /** + * @param string $version + * @param bool $isInclusive + */ + public function __construct($version, $isInclusive) + { + $this->version = $version; + $this->isInclusive = $isInclusive; + } + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + /** + * @return bool + */ + public function isInclusive() + { + return $this->isInclusive; + } + /** + * @return bool + */ + public function isZero() + { + return $this->getVersion() === '0.0.0.0-dev' && $this->isInclusive(); + } + /** + * @return bool + */ + public function isPositiveInfinity() + { + return $this->getVersion() === \PHP_INT_MAX . '.0.0.0' && !$this->isInclusive(); + } + /** + * Compares a bound to another with a given operator. + * + * @param Bound $other + * @param string $operator + * + * @return bool + */ + 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 they are the same it doesn't matter + if ($this == $other) { + return \false; + } + $compareResult = \version_compare($this->getVersion(), $other->getVersion()); + // Not the same version means we don't need to check if the bounds are inclusive or not + if (0 !== $compareResult) { + return ('>' === $operator ? 1 : -1) === $compareResult; + } + // Question we're answering here is "am I higher than $other?" + return '>' === $operator ? $other->isInclusive() : !$other->isInclusive(); + } + public function __toString() + { + return \sprintf('%s [%s]', $this->getVersion(), $this->isInclusive() ? 'inclusive' : 'exclusive'); + } + /** + * @return self + */ + public static function zero() + { + return new Bound('0.0.0.0-dev', \true); + } + /** + * @return self + */ + public static function positiveInfinity() + { + return new Bound(\PHP_INT_MAX . '.0.0.0', \false); + } +} diff --git a/vendor/composer/semver/src/Constraint/Constraint.php b/vendor/composer/semver/src/Constraint/Constraint.php new file mode 100644 index 00000000000..8bc6502dcca --- /dev/null +++ b/vendor/composer/semver/src/Constraint/Constraint.php @@ -0,0 +1,354 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +/** + * Defines a constraint. + */ +class Constraint implements ConstraintInterface +{ + /* operator integer values */ + const OP_EQ = 0; + const OP_LT = 1; + const OP_LE = 2; + const OP_GT = 3; + const OP_GE = 4; + const OP_NE = 5; + /* operator string values */ + const STR_OP_EQ = '=='; + const STR_OP_EQ_ALT = '='; + const STR_OP_LT = '<'; + const STR_OP_LE = '<='; + const STR_OP_GT = '>'; + const STR_OP_GE = '>='; + const STR_OP_NE = '!='; + const STR_OP_NE_ALT = '<>'; + /** + * Operator to integer translation table. + * + * @var array + * @phpstan-var array + */ + 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); + /** + * Integer to operator translation table. + * + * @var array + * @phpstan-var array + */ + private static $transOpInt = array(self::OP_EQ => '==', self::OP_LT => '<', self::OP_LE => '<=', self::OP_GT => '>', self::OP_GE => '>=', self::OP_NE => '!='); + /** + * @var int + * @phpstan-var self::OP_* + */ + protected $operator; + /** @var string */ + protected $version; + /** @var string|null */ + protected $prettyString; + /** @var Bound */ + protected $lowerBound; + /** @var Bound */ + protected $upperBound; + /** + * Sets operator and version to compare with. + * + * @param string $operator + * @param string $version + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @phpstan-param self::STR_OP_* $operator + */ + 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; + } + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + /** + * @return string + * + * @phpstan-return self::STR_OP_* + */ + public function getOperator() + { + return self::$transOpInt[$this->operator]; + } + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if ($provider instanceof self) { + return $this->matchSpecific($provider); + } + // turn matching around to find a match + return $provider->matches($this); + } + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + return $this->__toString(); + } + /** + * Get all supported comparison operators. + * + * @return array + * + * @phpstan-return list + */ + public static function getSupportedOperators() + { + return \array_keys(self::$transOpStr); + } + /** + * @param string $operator + * @return int + * + * @phpstan-param self::STR_OP_* $operator + * @phpstan-return self::OP_* + */ + public static function getOperatorConstant($operator) + { + return self::$transOpStr[$operator]; + } + /** + * @param string $a + * @param string $b + * @param string $operator + * @param bool $compareBranches + * + * @throws \InvalidArgumentException if invalid operator is given. + * + * @return bool + * + * @phpstan-param self::STR_OP_* $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; + } + // when branches are not comparable, we make sure dev branches never match anything + if (!$compareBranches && ($aIsBranch || $bIsBranch)) { + return \false; + } + return \version_compare($a, $b, $operator); + } + /** + * {@inheritDoc} + */ + 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'; + } + } else { + // $this->operator must be self::OP_GT || self::OP_GE here + 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); + } + /** + * @param Constraint $provider + * @param bool $compareBranches + * + * @return bool + */ + 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; + // '!=' operator is match when other operator is not '==' operator or version is not match + // these kinds of comparisons always have a solution + 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); + } + // an example for the condition is <= 2.0 & < 1.0 + // these kinds of comparisons always have a solution + 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)) { + // special case, e.g. require >= 1.0 and provide < 1.0 + // 1.0 >= 1.0 but 1.0 is outside of the provided interval + return !(self::$transOpInt[$provider->operator] === $providerNoEqualOp && self::$transOpInt[$this->operator] !== $noEqualOp && \version_compare($provider->version, $this->version, '==')); + } + return \false; + } + /** + * @return string + */ + public function __toString() + { + return self::$transOpInt[$this->operator] . ' ' . $this->version; + } + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + return $this->lowerBound; + } + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + return $this->upperBound; + } + /** + * @return void + */ + private function extractBounds() + { + if (null !== $this->lowerBound) { + return; + } + // Branches + 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; + } + } +} diff --git a/vendor/composer/semver/src/Constraint/ConstraintInterface.php b/vendor/composer/semver/src/Constraint/ConstraintInterface.php new file mode 100644 index 00000000000..72149033834 --- /dev/null +++ b/vendor/composer/semver/src/Constraint/ConstraintInterface.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +/** + * DO NOT IMPLEMENT this interface. It is only meant for usage as a type hint + * in libraries relying on composer/semver but creating your own constraint class + * that implements this interface is not a supported use case and will cause the + * composer/semver components to return unexpected results. + */ +interface ConstraintInterface +{ + /** + * Checks whether the given constraint intersects in any way with this constraint + * + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider); + /** + * Provides a compiled version of the constraint for the given operator + * The compiled version must be a PHP expression. + * Executor of compile version must provide 2 variables: + * - $v = the string version to compare with + * - $b = whether or not the version is a non-comparable branch (starts with "dev-") + * + * @see Constraint::OP_* for the list of available operators. + * @example return '!$b && version_compare($v, '1.0', '>')'; + * + * @param int $otherOperator one Constraint::OP_* + * + * @return string + * + * @phpstan-param Constraint::OP_* $otherOperator + */ + public function compile($otherOperator); + /** + * @return Bound + */ + public function getUpperBound(); + /** + * @return Bound + */ + public function getLowerBound(); + /** + * @return string + */ + public function getPrettyString(); + /** + * @param string|null $prettyString + * + * @return void + */ + public function setPrettyString($prettyString); + /** + * @return string + */ + public function __toString(); +} diff --git a/vendor/composer/semver/src/Constraint/MatchAllConstraint.php b/vendor/composer/semver/src/Constraint/MatchAllConstraint.php new file mode 100644 index 00000000000..bf8bb9cb3ef --- /dev/null +++ b/vendor/composer/semver/src/Constraint/MatchAllConstraint.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +/** + * Defines the absence of a constraint. + * + * This constraint matches everything. + */ +class MatchAllConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return \true; + } + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'true'; + } + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + return (string) $this; + } + /** + * {@inheritDoc} + */ + public function __toString() + { + return '*'; + } + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return Bound::positiveInfinity(); + } + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return Bound::zero(); + } +} diff --git a/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php b/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php new file mode 100644 index 00000000000..7027956169e --- /dev/null +++ b/vendor/composer/semver/src/Constraint/MatchNoneConstraint.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +/** + * Blackhole of constraints, nothing escapes it + */ +class MatchNoneConstraint implements ConstraintInterface +{ + /** @var string|null */ + protected $prettyString; + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + return \false; + } + /** + * {@inheritDoc} + */ + public function compile($otherOperator) + { + return 'false'; + } + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + return (string) $this; + } + /** + * {@inheritDoc} + */ + public function __toString() + { + return '[]'; + } + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + return new Bound('0.0.0.0-dev', \false); + } + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + return new Bound('0.0.0.0-dev', \false); + } +} diff --git a/vendor/composer/semver/src/Constraint/MultiConstraint.php b/vendor/composer/semver/src/Constraint/MultiConstraint.php new file mode 100644 index 00000000000..aa9115730f4 --- /dev/null +++ b/vendor/composer/semver/src/Constraint/MultiConstraint.php @@ -0,0 +1,258 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver\Constraint; + +/** + * Defines a conjunctive or disjunctive set of constraints. + */ +class MultiConstraint implements ConstraintInterface +{ + /** + * @var ConstraintInterface[] + * @phpstan-var non-empty-array + */ + protected $constraints; + /** @var string|null */ + protected $prettyString; + /** @var string|null */ + protected $string; + /** @var bool */ + protected $conjunctive; + /** @var Bound|null */ + protected $lowerBound; + /** @var Bound|null */ + protected $upperBound; + /** + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @throws \InvalidArgumentException If less than 2 constraints are passed + */ + 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; + } + /** + * @return ConstraintInterface[] + */ + public function getConstraints() + { + return $this->constraints; + } + /** + * @return bool + */ + public function isConjunctive() + { + return $this->conjunctive; + } + /** + * @return bool + */ + public function isDisjunctive() + { + return !$this->conjunctive; + } + /** + * {@inheritDoc} + */ + 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); + } + /** + * @param ConstraintInterface $provider + * + * @return bool + */ + public function matches(ConstraintInterface $provider) + { + if (\false === $this->conjunctive) { + foreach ($this->constraints as $constraint) { + if ($provider->matches($constraint)) { + return \true; + } + } + return \false; + } + // when matching a conjunctive and a disjunctive multi constraint we have to iterate over the disjunctive one + // otherwise we'd return true if different parts of the disjunctive constraint match the conjunctive one + // which would lead to incorrect results, e.g. [>1 and <2] would match [<1 or >2] although they do not intersect + if ($provider instanceof MultiConstraint && $provider->isDisjunctive()) { + return $provider->matches($this); + } + foreach ($this->constraints as $constraint) { + if (!$provider->matches($constraint)) { + return \false; + } + } + return \true; + } + /** + * {@inheritDoc} + */ + public function setPrettyString($prettyString) + { + $this->prettyString = $prettyString; + } + /** + * {@inheritDoc} + */ + public function getPrettyString() + { + if ($this->prettyString) { + return $this->prettyString; + } + return (string) $this; + } + /** + * {@inheritDoc} + */ + 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) . ']'; + } + /** + * {@inheritDoc} + */ + public function getLowerBound() + { + $this->extractBounds(); + if (null === $this->lowerBound) { + throw new \LogicException('extractBounds should have populated the lowerBound property'); + } + return $this->lowerBound; + } + /** + * {@inheritDoc} + */ + public function getUpperBound() + { + $this->extractBounds(); + if (null === $this->upperBound) { + throw new \LogicException('extractBounds should have populated the upperBound property'); + } + return $this->upperBound; + } + /** + * Tries to optimize the constraints as much as possible, meaning + * reducing/collapsing congruent constraints etc. + * Does not necessarily return a MultiConstraint instance if + * things can be reduced to a simple constraint + * + * @param ConstraintInterface[] $constraints A set of constraints + * @param bool $conjunctive Whether the constraints should be treated as conjunctive or disjunctive + * + * @return ConstraintInterface + */ + 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); + } + /** + * @param ConstraintInterface[] $constraints + * @param bool $conjunctive + * @return ?array + * + * @phpstan-return array{0: list, 1: bool}|null + */ + private static function optimizeConstraints(array $constraints, $conjunctive) + { + // parse the two OR groups and if they are contiguous we collapse + // them into one constraint + // [>= 1 < 2] || [>= 2 < 3] || [>= 3 < 4] => [>= 1 < 4] + 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); + } + } + // TODO: Here's the place to put more optimizations + return null; + } + /** + * @return void + */ + 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(); + } + } + } +} diff --git a/vendor/composer/semver/src/Interval.php b/vendor/composer/semver/src/Interval.php new file mode 100644 index 00000000000..05478cea719 --- /dev/null +++ b/vendor/composer/semver/src/Interval.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +class Interval +{ + /** @var Constraint */ + private $start; + /** @var Constraint */ + private $end; + public function __construct(Constraint $start, Constraint $end) + { + $this->start = $start; + $this->end = $end; + } + /** + * @return Constraint + */ + public function getStart() + { + return $this->start; + } + /** + * @return Constraint + */ + public function getEnd() + { + return $this->end; + } + /** + * @return Constraint + */ + public static function fromZero() + { + static $zero; + if (null === $zero) { + $zero = new Constraint('>=', '0.0.0.0-dev'); + } + return $zero; + } + /** + * @return Constraint + */ + public static function untilPositiveInfinity() + { + static $positiveInfinity; + if (null === $positiveInfinity) { + $positiveInfinity = new Constraint('<', \PHP_INT_MAX . '.0.0.0'); + } + return $positiveInfinity; + } + /** + * @return self + */ + public static function any() + { + return new self(self::fromZero(), self::untilPositiveInfinity()); + } + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function anyDev() + { + // any == exclude nothing + return array('names' => array(), 'exclude' => \true); + } + /** + * @return array{'names': string[], 'exclude': bool} + */ + public static function noDev() + { + // nothing == no names included + return array('names' => array(), 'exclude' => \false); + } +} diff --git a/vendor/composer/semver/src/Intervals.php b/vendor/composer/semver/src/Intervals.php new file mode 100644 index 00000000000..d92166b1b11 --- /dev/null +++ b/vendor/composer/semver/src/Intervals.php @@ -0,0 +1,399 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +use ECSPrefix202307\Composer\Semver\Constraint\ConstraintInterface; +use ECSPrefix202307\Composer\Semver\Constraint\MatchAllConstraint; +use ECSPrefix202307\Composer\Semver\Constraint\MatchNoneConstraint; +use ECSPrefix202307\Composer\Semver\Constraint\MultiConstraint; +/** + * Helper class generating intervals from constraints + * + * This contains utilities for: + * + * - compacting an existing constraint which can be used to combine several into one + * by creating a MultiConstraint out of the many constraints you have. + * + * - checking whether one subset is a subset of another. + * + * Note: You should call clear to free memoization memory usage when you are done using this class + */ +class Intervals +{ + /** + * @phpstan-var array + */ + private static $intervalsCache = array(); + /** + * @phpstan-var array + */ + private static $opSortOrder = array('>=' => -3, '<' => -2, '>' => 2, '<=' => 3); + /** + * Clears the memoization cache once you are done + * + * @return void + */ + public static function clear() + { + self::$intervalsCache = array(); + } + /** + * Checks whether $candidate is a subset of $constraint + * + * @return bool + */ + 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; + } + /** + * Checks whether $a and $b have any intersection, equivalent to $a->matches($b) + * + * @return bool + */ + 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; + } + /** + * Attempts to optimize a MultiConstraint + * + * When merging MultiConstraints together they can get very large, this will + * compact it by looking at the real intervals covered by all the constraints + * and then creates a new constraint containing only the smallest amount of rules + * to match the same intervals. + * + * @return ConstraintInterface + */ + 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 current interval ends with < N and next interval begins with > N we can swap this out for != N + // but this needs to happen as a conjunctive expression together with the start of the current interval + // and end of next interval, so [>=M, N, [>=M, !=N, getEnd()->getOperator() === '<' && $i + 1 < $count) { + $nextInterval = $intervals['numeric'][$i + 1]; + if ($interval->getEnd()->getVersion() === $nextInterval->getStart()->getVersion() && $nextInterval->getStart()->getOperator() === '>') { + // only add a start if we didn't already do so, can be skipped if we're looking at second + // interval in [>=M, N, P, =M, !=N] already and we only want to add !=P right now + if (\count($unEqualConstraints) === 0 && (string) $interval->getStart() !== (string) Interval::fromZero()) { + $unEqualConstraints[] = $interval->getStart(); + } + $unEqualConstraints[] = new Constraint('!=', $interval->getEnd()->getVersion()); + continue; + } + } + if (\count($unEqualConstraints) > 0) { + // this is where the end of the following interval of a != constraint is added as explained above + if ((string) $interval->getEnd() !== (string) Interval::untilPositiveInfinity()) { + $unEqualConstraints[] = $interval->getEnd(); + } + // count is 1 if entire constraint is just one != expression + if (\count($unEqualConstraints) > 1) { + $constraints[] = new MultiConstraint($unEqualConstraints, \true); + } else { + $constraints[] = $unEqualConstraints[0]; + } + $unEqualConstraints = array(); + continue; + } + // convert back >= x - <= x intervals to == x + 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(); + } + // otherwise constraint should contain a != operator and already cover this + } + } else { + foreach ($intervals['branches']['names'] as $branchName) { + if ($intervals['branches']['exclude']) { + $devConstraints[] = new Constraint('!=', $branchName); + } else { + $devConstraints[] = new Constraint('==', $branchName); + } + } + // excluded branches, e.g. != dev-foo are conjunctive with the interval, so + // > 2.0 != dev-foo must return a conjunctive constraint + 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); + } + // otherwise devConstraints contains a list of == operators for branches which are disjunctive with the + // rest of the constraint + $constraints = \array_merge($constraints, $devConstraints); + } + if (\count($constraints) > 1) { + return new MultiConstraint($constraints, \false); + } + if (\count($constraints) === 1) { + return $constraints[0]; + } + return new MatchNoneConstraint(); + } + /** + * Creates an array of numeric intervals and branch constraints representing a given constraint + * + * if the returned numeric array is empty it means the constraint matches nothing in the numeric range (0 - +inf) + * if the returned branches array is empty it means no dev-* versions are matched + * if a constraint matches all possible dev-* versions, branches will contain Interval::anyDev() + * + * @return array + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + public static function get(ConstraintInterface $constraint) + { + $key = (string) $constraint; + if (!isset(self::$intervalsCache[$key])) { + self::$intervalsCache[$key] = self::generateIntervals($constraint); + } + return self::$intervalsCache[$key]; + } + /** + * @param bool $stopOnFirstValidInterval + * + * @phpstan-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + 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']) { + // disjunctive constraint, so only exclude what's excluded in all constraints + // !=a,!=b || !=b,!=c => !=b + $branches['names'] = \array_intersect($branches['names'], $b['names']); + } else { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // (==b || ==c) || !=a,!=b => !=a + $branches['exclude'] = \true; + $branches['names'] = \array_diff($b['names'], $branches['names']); + } + } else { + if ($branches['exclude']) { + // disjunctive constraint so exclude all names which are not explicitly included in the alternative + // !=a,!=b || (==b || ==c) => !=a + $branches['names'] = \array_diff($branches['names'], $b['names']); + } else { + // disjunctive constraint, so just add all the other branches + // (==a || ==b) || ==c => ==a || ==b || ==c + $branches['names'] = \array_merge($branches['names'], $b['names']); + } + } + } + } else { + $branches = Interval::anyDev(); + foreach ($constraintBranches as $b) { + if ($b['exclude']) { + if ($branches['exclude']) { + // conjunctive, so just add all branch names to be excluded + // !=a && !=b => !=a,!=b + $branches['names'] = \array_merge($branches['names'], $b['names']); + } else { + // conjunctive, so only keep included names which are not excluded + // (==a||==c) && !=a,!=b => ==c + $branches['names'] = \array_diff($branches['names'], $b['names']); + } + } else { + if ($branches['exclude']) { + // conjunctive, so only keep included names which are not excluded + // !=a,!=b && (==a||==c) => ==c + $branches['names'] = \array_diff($b['names'], $branches['names']); + $branches['exclude'] = \false; + } else { + // conjunctive, so only keep names that are included in both + // (==a||==b) && (==a||==c) => ==a + $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; + $start = null; + foreach ($borders as $border) { + if ($border['side'] === 'start') { + $activeIntervals++; + } else { + $activeIntervals--; + } + if (!$start && $activeIntervals >= $activationThreshold) { + $start = new Constraint($border['operator'], $border['version']); + } elseif ($start && $activeIntervals < $activationThreshold) { + // filter out invalid intervals like > x - <= x, or >= x - < x + 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-return array{'numeric': Interval[], 'branches': array{'names': string[], 'exclude': bool}} + */ + private static function generateSingleConstraintIntervals(Constraint $constraint) + { + $op = $constraint->getOperator(); + // handle branch constraints first + if (\strpos($constraint->getVersion(), 'dev-') === 0) { + $intervals = array(); + $branches = array('names' => array(), 'exclude' => \false); + // != dev-foo means any numeric version may match, we treat >/< like != they are not really defined for branches + 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 === '!=') { + // convert !=x to intervals of 0 - x - +inf + dev* + return array('numeric' => array(new Interval(Interval::fromZero(), new Constraint('<', $constraint->getVersion())), new Interval(new Constraint('>', $constraint->getVersion()), Interval::untilPositiveInfinity())), 'branches' => Interval::anyDev()); + } + // convert ==x to an interval of >=x - <=x + return array('numeric' => array(new Interval(new Constraint('>=', $constraint->getVersion()), new Constraint('<=', $constraint->getVersion()))), 'branches' => Interval::noDev()); + } +} diff --git a/vendor/composer/semver/src/Semver.php b/vendor/composer/semver/src/Semver.php new file mode 100644 index 00000000000..06391b54ed2 --- /dev/null +++ b/vendor/composer/semver/src/Semver.php @@ -0,0 +1,111 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +class Semver +{ + const SORT_ASC = 1; + const SORT_DESC = -1; + /** @var VersionParser */ + private static $versionParser; + /** + * Determine if given version satisfies given constraints. + * + * @param string $version + * @param string $constraints + * + * @return bool + */ + 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); + } + /** + * Return all versions that satisfy given constraints. + * + * @param string[] $versions + * @param string $constraints + * + * @return string[] + */ + public static function satisfiedBy(array $versions, $constraints) + { + $versions = \array_filter($versions, function ($version) use($constraints) { + return Semver::satisfies($version, $constraints); + }); + return \array_values($versions); + } + /** + * Sort given array of versions. + * + * @param string[] $versions + * + * @return string[] + */ + public static function sort(array $versions) + { + return self::usort($versions, self::SORT_ASC); + } + /** + * Sort given array of versions in reverse. + * + * @param string[] $versions + * + * @return string[] + */ + public static function rsort(array $versions) + { + return self::usort($versions, self::SORT_DESC); + } + /** + * @param string[] $versions + * @param int $direction + * + * @return string[] + */ + private static function usort(array $versions, $direction) + { + if (null === self::$versionParser) { + self::$versionParser = new VersionParser(); + } + $versionParser = self::$versionParser; + $normalized = array(); + // Normalize outside of usort() scope for minor performance increase. + // Creates an array of arrays: [[normalized, key], ...] + 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; + }); + // Recreate input array, using the original indexes which are now in sorted order. + $sorted = array(); + foreach ($normalized as $item) { + $sorted[] = $versions[$item[1]]; + } + return $sorted; + } +} diff --git a/vendor/composer/semver/src/VersionParser.php b/vendor/composer/semver/src/VersionParser.php new file mode 100644 index 00000000000..375d836025f --- /dev/null +++ b/vendor/composer/semver/src/VersionParser.php @@ -0,0 +1,488 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\Semver; + +use ECSPrefix202307\Composer\Semver\Constraint\ConstraintInterface; +use ECSPrefix202307\Composer\Semver\Constraint\MatchAllConstraint; +use ECSPrefix202307\Composer\Semver\Constraint\MultiConstraint; +use ECSPrefix202307\Composer\Semver\Constraint\Constraint; +/** + * Version parser. + * + * @author Jordi Boggiano + */ +class VersionParser +{ + /** + * Regex to match pre-release data (sort of). + * + * Due to backwards compatibility: + * - Instead of enforcing hyphen, an underscore, dot or nothing at all are also accepted. + * - Only stabilities as recognized by Composer are allowed to precede a numerical identifier. + * - Numerical-only pre-release identifiers are not supported, see tests. + * + * |--------------| + * [major].[minor].[patch] -[pre-release] +[build-metadata] + * + * @var string + */ + private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)((?:[.-]?\\d+)*+)?)?([.-]?dev)?'; + /** @var string */ + private static $stabilitiesRegex = 'stable|RC|beta|alpha|dev'; + /** + * Returns the stability of a version. + * + * @param string $version + * + * @return string + * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' + */ + public static function parseStability($version) + { + $version = (string) \preg_replace('{#.+$}', '', (string) $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'; + } + /** + * @param string $stability + * + * @return string + */ + public static function normalizeStability($stability) + { + $stability = \strtolower((string) $stability); + return $stability === 'rc' ? 'RC' : $stability; + } + /** + * Normalizes a version string to be able to perform comparisons on it. + * + * @param string $version + * @param ?string $fullVersion optional complete version string to give more context + * + * @throws \UnexpectedValueException + * + * @return string + */ + public function normalize($version, $fullVersion = null) + { + $version = \trim((string) $version); + $origVersion = $version; + if (null === $fullVersion) { + $fullVersion = $version; + } + // strip off aliasing + if (\preg_match('{^([^,\\s]++) ++as ++([^,\\s]++)$}', $version, $match)) { + $version = $match[1]; + } + // strip off stability flag + if (\preg_match('{@(?:' . self::$stabilitiesRegex . ')$}i', $version, $match)) { + $version = \substr($version, 0, \strlen($version) - \strlen($match[0])); + } + // normalize master/trunk/default branches to dev-name for BC with 1.x as these used to be valid constraints + if (\in_array($version, array('master', 'trunk', 'default'), \true)) { + $version = 'dev-' . $version; + } + // if requirement is branch-like, use full name + if (\stripos($version, 'dev-') === 0) { + return 'dev-' . \substr($version, 4); + } + // strip off build metadata + if (\preg_match('{^([^,\\s+]++)\\+[^\\s]++$}', $version, $match)) { + $version = $match[1]; + } + // match classical versioning + 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; + // match date(time) based versioning + } 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; + } + // add version modifiers if a version was matched + 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; + } + // match dev branches + if (\preg_match('{(.*?)[.-]?dev$}i', $version, $match)) { + try { + $normalized = $this->normalizeBranch($match[1]); + // a branch ending with -dev is only valid if it is numeric + // if it gets prefixed with dev- it means the branch name should + // have had a dev- prefix already when passed to normalize + 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); + } + /** + * Extract numeric prefix from alias, if it is in numeric format, suitable for version comparison. + * + * @param string $branch Branch name (e.g. 2.1.x-dev) + * + * @return string|false Numeric prefix if present (e.g. 2.1.) or false + */ + public function parseNumericAliasPrefix($branch) + { + if (\preg_match('{^(?P(\\d++\\.)*\\d++)(?:\\.x)?-dev$}i', (string) $branch, $matches)) { + return $matches['version'] . '.'; + } + return \false; + } + /** + * Normalizes a branch name to be able to perform comparisons on it. + * + * @param string $name + * + * @return string + */ + public function normalizeBranch($name) + { + $name = \trim((string) $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; + } + /** + * Normalizes a default branch name (i.e. master on git) to 9999999-dev. + * + * @param string $name + * + * @return string + * + * @deprecated No need to use this anymore in theory, Composer 2 does not normalize any branch names to 9999999-dev anymore + */ + public function normalizeDefaultBranch($name) + { + if ($name === 'dev-master' || $name === 'dev-default' || $name === 'dev-trunk') { + return '9999999-dev'; + } + return (string) $name; + } + /** + * Parses a constraint string into MultiConstraint and/or Constraint objects. + * + * @param string $constraints + * + * @return ConstraintInterface + */ + public function parseConstraints($constraints) + { + $prettyConstraint = (string) $constraints; + $orConstraints = \preg_split('{\\s*\\|\\|?\\s*}', \trim((string) $constraints)); + if (\false === $orConstraints) { + throw new \RuntimeException('Failed to preg_split string: ' . $constraints); + } + $orGroups = array(); + foreach ($orConstraints as $constraints) { + $andConstraints = \preg_split('{(?< ,]) *(? 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; + } + /** + * @param string $constraint + * + * @throws \UnexpectedValueException + * + * @return array + * + * @phpstan-return non-empty-array + */ + private function parseConstraint($constraint) + { + // strip off aliasing + if (\preg_match('{^([^,\\s]++) ++as ++([^,\\s]++)$}', $constraint, $match)) { + $constraint = $match[1]; + } + // strip @stability flags, and keep it for later use + if (\preg_match('{^([^,\\s]*?)@(' . self::$stabilitiesRegex . ')$}i', $constraint, $match)) { + $constraint = '' !== $match[1] ? $match[1] : '*'; + if ($match[2] !== 'stable') { + $stabilityModifier = $match[2]; + } + } + // get rid of #refs as those are used by composer only + 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]+)?'; + // Tilde Range + // + // Like wildcard constraints, unsuffixed tilde constraints say that they must be greater than the previous + // version, to ensure that unstable instances of the current version are allowed. However, if a stability + // suffix is added to the constraint, then a >= match on the current version is used instead. + 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'); + } + // Work out which position in the version we are operating at + 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; + } + // when matching 2.x-dev or 3.0.x-dev we have to shift the second or third number, despite no second/third number matching above + if (!empty($matches[8])) { + $position++; + } + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + $lowVersion = $this->normalize(\substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highPosition = \max(1, $position - 1); + $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + return array($lowerBound, $upperBound); + } + // Caret Range + // + // Allows changes that do not modify the left-most non-zero digit in the [major, minor, patch] tuple. + // In other words, this allows patch and minor updates for versions 1.0.0 and above, patch updates for + // versions 0.X >=0.1.0, and no updates for versions 0.0.X + if (\preg_match('{^\\^' . $versionRegex . '($)}i', $constraint, $matches)) { + // Work out which position in the version we are operating at + 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; + } + // Calculate the stability suffix + $stabilitySuffix = ''; + if (empty($matches[5]) && empty($matches[7]) && empty($matches[8])) { + $stabilitySuffix .= '-dev'; + } + $lowVersion = $this->normalize(\substr($constraint . $stabilitySuffix, 1)); + $lowerBound = new Constraint('>=', $lowVersion); + // For upper bound, we increment the position of one more significance, + // but highPosition = 0 would be illegal + $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + return array($lowerBound, $upperBound); + } + // X Range + // + // Any of X, x, or * may be used to "stand in" for one of the numeric values in the [major, minor, patch] tuple. + // A partial version range is treated as an X-Range, so the special character is in fact optional. + 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)); + } + // Hyphen Range + // + // Specifies an inclusive set. If a partial version is provided as the first version in the inclusive range, + // then the missing pieces are replaced with zeroes. If a partial version is provided as the second version in + // the inclusive range, then all versions that start with the supplied parts of the tuple are accepted, but + // nothing that would be greater than the provided tuple parts. + if (\preg_match('{^(?P' . $versionRegex . ') +- +(?P' . $versionRegex . ')($)}i', $constraint, $matches)) { + // Calculate the stability suffix + $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]); + // validate to version + $this->normalize($matches['to']); + $highVersion = $this->manipulateVersionString($highMatch, $empty($matches[12]) ? 1 : 2, 1) . '-dev'; + $upperBound = new Constraint('<', $highVersion); + } + return array($lowerBound, $upperBound); + } + // Basic Comparators + if (\preg_match('{^(<>|!=|>=?|<=?|==?)?\\s*(.*)}', $constraint, $matches)) { + try { + try { + $version = $this->normalize($matches[2]); + } catch (\UnexpectedValueException $e) { + // recover from an invalid constraint like foobar-dev which should be dev-foobar + // except if the constraint uses a known operator, in which case it must be a parse error + 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); + } + /** + * Increment, decrement, or simply pad a version number. + * + * Support function for {@link parseConstraint()} + * + * @param array $matches Array with version parts in array indexes 1,2,3,4 + * @param int $position 1,2,3,4 - which segment of the version to increment/decrement + * @param int $increment + * @param string $pad The string to pad version parts after $position + * + * @return string|null The new version + * + * @phpstan-param string[] $matches + */ + private function manipulateVersionString(array $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] was 0, carry the decrement + if ($matches[$i] < 0) { + $matches[$i] = $pad; + --$position; + // Return null on a carry overflow + if ($i === 1) { + return null; + } + } + } + } + return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4]; + } + /** + * Expand shorthand stability string to long version. + * + * @param string $stability + * + * @return string + */ + 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; + } + } +} diff --git a/vendor/composer/xdebug-handler/CHANGELOG.md b/vendor/composer/xdebug-handler/CHANGELOG.md new file mode 100644 index 00000000000..c5b5bcf4e1a --- /dev/null +++ b/vendor/composer/xdebug-handler/CHANGELOG.md @@ -0,0 +1,134 @@ +## [Unreleased] + +## [3.0.3] - 2022-02-25 + * Added: support for composer/pcre versions 2 and 3. + +## [3.0.2] - 2022-02-24 + * Fixed: regression in 3.0.1 affecting Xdebug 2 + +## [3.0.1] - 2022-01-04 + * Fixed: error when calling `isXdebugActive` before class instantiation. + +## [3.0.0] - 2021-12-23 + * Removed: support for legacy PHP versions (< PHP 7.2.5). + * Added: type declarations to arguments and return values. + * Added: strict typing to all classes. + +## [2.0.3] - 2021-12-08 + * Added: support, type annotations and refactoring for stricter PHPStan analysis. + +## [2.0.2] - 2021-07-31 + * Added: support for `xdebug_info('mode')` in Xdebug 3.1. + * Added: support for Psr\Log versions 2 and 3. + * Fixed: remove ini directives from non-cli HOST/PATH sections. + +## [2.0.1] - 2021-05-05 + * Fixed: don't restart if the cwd is a UNC path and cmd.exe will be invoked. + +## [2.0.0] - 2021-04-09 + * Break: this is a major release, see [UPGRADE.md](UPGRADE.md) for more information. + * Break: removed optional `$colorOption` constructor param and passthru fallback. + * Break: renamed `requiresRestart` param from `$isLoaded` to `$default`. + * Break: changed `restart` param `$command` from a string to an array. + * Added: support for Xdebug3 to only restart if Xdebug is not running with `xdebug.mode=off`. + * Added: `isXdebugActive()` method to determine if Xdebug is still running in the restart. + * Added: feature to bypass the shell in PHP-7.4+ by giving `proc_open` an array of arguments. + * Added: Process utility class to the API. + +## [1.4.6] - 2021-03-25 + * Fixed: fail restart if `proc_open` has been disabled in `disable_functions`. + * Fixed: enable Windows CTRL event handling in the restarted process. + +## [1.4.5] - 2020-11-13 + * Fixed: use `proc_open` when available for correct FD forwarding to the restarted process. + +## [1.4.4] - 2020-10-24 + * Fixed: exception if 'pcntl_signal' is disabled. + +## [1.4.3] - 2020-08-19 + * Fixed: restore SIGINT to default handler in restarted process if no other handler exists. + +## [1.4.2] - 2020-06-04 + * Fixed: ignore SIGINTs to let the restarted process handle them. + +## [1.4.1] - 2020-03-01 + * Fixed: restart fails if an ini file is empty. + +## [1.4.0] - 2019-11-06 + * Added: support for `NO_COLOR` environment variable: https://no-color.org + * Added: color support for Hyper terminal: https://github.com/zeit/hyper + * Fixed: correct capitalization of Xdebug (apparently). + * Fixed: improved handling for uopz extension. + +## [1.3.3] - 2019-05-27 + * Fixed: add environment changes to `$_ENV` if it is being used. + +## [1.3.2] - 2019-01-28 + * Fixed: exit call being blocked by uopz extension, resulting in application code running twice. + +## [1.3.1] - 2018-11-29 + * Fixed: fail restart if `passthru` has been disabled in `disable_functions`. + * Fixed: fail restart if an ini file cannot be opened, otherwise settings will be missing. + +## [1.3.0] - 2018-08-31 + * Added: `setPersistent` method to use environment variables for the restart. + * Fixed: improved debugging by writing output to stderr. + * Fixed: no restart when `php_ini_scanned_files` is not functional and is needed. + +## [1.2.1] - 2018-08-23 + * Fixed: fatal error with apc, when using `apc.mmap_file_mask`. + +## [1.2.0] - 2018-08-16 + * Added: debug information using `XDEBUG_HANDLER_DEBUG`. + * Added: fluent interface for setters. + * Added: `PhpConfig` helper class for calling PHP sub-processes. + * Added: `PHPRC` original value to restart stettings, for use in a restarted process. + * Changed: internal procedure to disable ini-scanning, using `-n` command-line option. + * Fixed: replaced `escapeshellarg` usage to avoid locale problems. + * Fixed: improved color-option handling to respect double-dash delimiter. + * Fixed: color-option handling regression from main script changes. + * Fixed: improved handling when checking main script. + * Fixed: handling for standard input, that never actually did anything. + * Fixed: fatal error when ctype extension is not available. + +## [1.1.0] - 2018-04-11 + * Added: `getRestartSettings` method for calling PHP processes in a restarted process. + * Added: API definition and @internal class annotations. + * Added: protected `requiresRestart` method for extending classes. + * Added: `setMainScript` method for applications that change the working directory. + * Changed: private `tmpIni` variable to protected for extending classes. + * Fixed: environment variables not available in $_SERVER when restored in the restart. + * Fixed: relative path problems caused by Phar::interceptFileFuncs. + * Fixed: incorrect handling when script file cannot be found. + +## [1.0.0] - 2018-03-08 + * Added: PSR3 logging for optional status output. + * Added: existing ini settings are merged to catch command-line overrides. + * Added: code, tests and other artefacts to decouple from Composer. + * Break: the following class was renamed: + - `Composer\XdebugHandler` -> `Composer\XdebugHandler\XdebugHandler` + +[Unreleased]: https://github.com/composer/xdebug-handler/compare/3.0.3...HEAD +[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.2...3.0.3 +[3.0.2]: https://github.com/composer/xdebug-handler/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/composer/xdebug-handler/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/composer/xdebug-handler/compare/2.0.3...3.0.0 +[2.0.3]: https://github.com/composer/xdebug-handler/compare/2.0.2...2.0.3 +[2.0.2]: https://github.com/composer/xdebug-handler/compare/2.0.1...2.0.2 +[2.0.1]: https://github.com/composer/xdebug-handler/compare/2.0.0...2.0.1 +[2.0.0]: https://github.com/composer/xdebug-handler/compare/1.4.6...2.0.0 +[1.4.6]: https://github.com/composer/xdebug-handler/compare/1.4.5...1.4.6 +[1.4.5]: https://github.com/composer/xdebug-handler/compare/1.4.4...1.4.5 +[1.4.4]: https://github.com/composer/xdebug-handler/compare/1.4.3...1.4.4 +[1.4.3]: https://github.com/composer/xdebug-handler/compare/1.4.2...1.4.3 +[1.4.2]: https://github.com/composer/xdebug-handler/compare/1.4.1...1.4.2 +[1.4.1]: https://github.com/composer/xdebug-handler/compare/1.4.0...1.4.1 +[1.4.0]: https://github.com/composer/xdebug-handler/compare/1.3.3...1.4.0 +[1.3.3]: https://github.com/composer/xdebug-handler/compare/1.3.2...1.3.3 +[1.3.2]: https://github.com/composer/xdebug-handler/compare/1.3.1...1.3.2 +[1.3.1]: https://github.com/composer/xdebug-handler/compare/1.3.0...1.3.1 +[1.3.0]: https://github.com/composer/xdebug-handler/compare/1.2.1...1.3.0 +[1.2.1]: https://github.com/composer/xdebug-handler/compare/1.2.0...1.2.1 +[1.2.0]: https://github.com/composer/xdebug-handler/compare/1.1.0...1.2.0 +[1.1.0]: https://github.com/composer/xdebug-handler/compare/1.0.0...1.1.0 +[1.0.0]: https://github.com/composer/xdebug-handler/compare/d66f0d15cb57...1.0.0 diff --git a/vendor/composer/xdebug-handler/LICENSE b/vendor/composer/xdebug-handler/LICENSE new file mode 100644 index 00000000000..963618a14e8 --- /dev/null +++ b/vendor/composer/xdebug-handler/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Composer + +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. diff --git a/vendor/composer/xdebug-handler/README.md b/vendor/composer/xdebug-handler/README.md new file mode 100644 index 00000000000..56618fc14a8 --- /dev/null +++ b/vendor/composer/xdebug-handler/README.md @@ -0,0 +1,298 @@ +# composer/xdebug-handler + +[![packagist](https://img.shields.io/packagist/v/composer/xdebug-handler)](https://packagist.org/packages/composer/xdebug-handler) +[![Continuous Integration](https://github.com/composer/xdebug-handler/actions/workflows/continuous-integration.yml/badge.svg?branch=main)](https://github.com/composer/xdebug-handler/actions?query=branch:main) +![license](https://img.shields.io/github/license/composer/xdebug-handler.svg) +![php](https://img.shields.io/packagist/php-v/composer/xdebug-handler?colorB=8892BF) + +Restart a CLI process without loading the Xdebug extension, unless `xdebug.mode=off`. + +Originally written as part of [composer/composer](https://github.com/composer/composer), +now extracted and made available as a stand-alone library. + +### Version 3 + +Removed support for legacy PHP versions and added type declarations. + +Long term support for version 2 (PHP 5.3.2 - 7.2.4) follows [Composer 2.2 LTS](https://blog.packagist.com/composer-2-2/) policy. + +## Installation + +Install the latest version with: + +```bash +$ composer require composer/xdebug-handler +``` + +## Requirements + +* PHP 7.2.5 minimum, although using the latest PHP version is highly recommended. + +## Basic Usage +```php +use Composer\XdebugHandler\XdebugHandler; + +$xdebug = new XdebugHandler('myapp'); +$xdebug->check(); +unset($xdebug); +``` + +The constructor takes a single parameter, `$envPrefix`, which is upper-cased and prepended to default base values to create two distinct environment variables. The above example enables the use of: + +- `MYAPP_ALLOW_XDEBUG=1` to override automatic restart and allow Xdebug +- `MYAPP_ORIGINAL_INIS` to obtain ini file locations in a restarted process + +## Advanced Usage + +* [How it works](#how-it-works) +* [Limitations](#limitations) +* [Helper methods](#helper-methods) +* [Setter methods](#setter-methods) +* [Process configuration](#process-configuration) +* [Troubleshooting](#troubleshooting) +* [Extending the library](#extending-the-library) + +### How it works + +A temporary ini file is created from the loaded (and scanned) ini files, with any references to the Xdebug extension commented out. Current ini settings are merged, so that most ini settings made on the command-line or by the application are included (see [Limitations](#limitations)) + +* `MYAPP_ALLOW_XDEBUG` is set with internal data to flag and use in the restart. +* The command-line and environment are [configured](#process-configuration) for the restart. +* The application is restarted in a new process. + * The restart settings are stored in the environment. + * `MYAPP_ALLOW_XDEBUG` is unset. + * The application runs and exits. +* The main process exits with the exit code from the restarted process. + +#### Signal handling +Asynchronous signal handling is automatically enabled if the pcntl extension is loaded. `SIGINT` is set to `SIG_IGN` in the parent +process and restored to `SIG_DFL` in the restarted process (if no other handler has been set). + +From PHP 7.4 on Windows, `CTRL+C` and `CTRL+BREAK` handling is automatically enabled in the restarted process and ignored in the parent process. + +### Limitations +There are a few things to be aware of when running inside a restarted process. + +* Extensions set on the command-line will not be loaded. +* Ini file locations will be reported as per the restart - see [getAllIniFiles()](#getallinifiles). +* Php sub-processes may be loaded with Xdebug enabled - see [Process configuration](#process-configuration). + +### Helper methods +These static methods provide information from the current process, regardless of whether it has been restarted or not. + +#### _getAllIniFiles(): array_ +Returns an array of the original ini file locations. Use this instead of calling `php_ini_loaded_file` and `php_ini_scanned_files`, which will report the wrong values in a restarted process. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$files = XdebugHandler::getAllIniFiles(); + +# $files[0] always exists, it could be an empty string +$loadedIni = array_shift($files); +$scannedInis = $files; +``` + +These locations are also available in the `MYAPP_ORIGINAL_INIS` environment variable. This is a path-separated string comprising the location returned from `php_ini_loaded_file`, which could be empty, followed by locations parsed from calling `php_ini_scanned_files`. + +#### _getRestartSettings(): ?array_ +Returns an array of settings that can be used with PHP [sub-processes](#sub-processes), or null if the process was not restarted. + +```php +use Composer\XdebugHandler\XdebugHandler; + +$settings = XdebugHandler::getRestartSettings(); +/** + * $settings: array (if the current process was restarted, + * or called with the settings from a previous restart), or null + * + * 'tmpIni' => the temporary ini file used in the restart (string) + * 'scannedInis' => if there were any scanned inis (bool) + * 'scanDir' => the original PHP_INI_SCAN_DIR value (false|string) + * 'phprc' => the original PHPRC value (false|string) + * 'inis' => the original inis from getAllIniFiles (array) + * 'skipped' => the skipped version from getSkippedVersion (string) + */ +``` + +#### _getSkippedVersion(): string_ +Returns the Xdebug version string that was skipped by the restart, or an empty string if there was no restart (or Xdebug is still loaded, perhaps by an extending class restarting for a reason other than removing Xdebug). + +```php +use Composer\XdebugHandler\XdebugHandler; + +$version = XdebugHandler::getSkippedVersion(); +# $version: '3.1.1' (for example), or an empty string +``` + +#### _isXdebugActive(): bool_ +Returns true if Xdebug is loaded and is running in an active mode (if it supports modes). Returns false if Xdebug is not loaded, or it is running with `xdebug.mode=off`. + +### Setter methods +These methods implement a fluent interface and must be called before the main `check()` method. + +#### _setLogger(LoggerInterface $logger): self_ +Enables the output of status messages to an external PSR3 logger. All messages are reported with either `DEBUG` or `WARNING` log levels. For example (showing the level and message): + +``` +// No restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=off +DEBUG No restart (APP_ALLOW_XDEBUG=0) Allowed by xdebug.mode + +// Restart overridden +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.1) xdebug.mode=coverage,debug,develop +DEBUG No restart (MYAPP_ALLOW_XDEBUG=1) + +// Failed restart +DEBUG Checking MYAPP_ALLOW_XDEBUG +DEBUG The Xdebug extension is loaded (3.1.0) +WARNING No restart (Unable to create temp ini file at: ...) +``` + +Status messages can also be output with `XDEBUG_HANDLER_DEBUG`. See [Troubleshooting](#troubleshooting). + +#### _setMainScript(string $script): self_ +Sets the location of the main script to run in the restart. This is only needed in more esoteric use-cases, or if the `argv[0]` location is inaccessible. The script name `--` is supported for standard input. + +#### _setPersistent(): self_ +Configures the restart using [persistent settings](#persistent-settings), so that Xdebug is not loaded in any sub-process. + +Use this method if your application invokes one or more PHP sub-process and the Xdebug extension is not needed. This avoids the overhead of implementing specific [sub-process](#sub-processes) strategies. + +Alternatively, this method can be used to set up a default _Xdebug-free_ environment which can be changed if a sub-process requires Xdebug, then restored afterwards: + +```php +function SubProcessWithXdebug() +{ + $phpConfig = new Composer\XdebugHandler\PhpConfig(); + + # Set the environment to the original configuration + $phpConfig->useOriginal(); + + # run the process with Xdebug loaded + ... + + # Restore Xdebug-free environment + $phpConfig->usePersistent(); +} +``` + +### Process configuration +The library offers two strategies to invoke a new PHP process without loading Xdebug, using either _standard_ or _persistent_ settings. Note that this is only important if the application calls a PHP sub-process. + +#### Standard settings +Uses command-line options to remove Xdebug from the new process only. + +* The -n option is added to the command-line. This tells PHP not to scan for additional inis. +* The temporary ini is added to the command-line with the -c option. + +>_If the new process calls a PHP sub-process, Xdebug will be loaded in that sub-process (unless it implements xdebug-handler, in which case there will be another restart)._ + +This is the default strategy used in the restart. + +#### Persistent settings +Uses environment variables to remove Xdebug from the new process and persist these settings to any sub-process. + +* `PHP_INI_SCAN_DIR` is set to an empty string. This tells PHP not to scan for additional inis. +* `PHPRC` is set to the temporary ini. + +>_If the new process calls a PHP sub-process, Xdebug will not be loaded in that sub-process._ + +This strategy can be used in the restart by calling [setPersistent()](#setpersistent). + +#### Sub-processes +The `PhpConfig` helper class makes it easy to invoke a PHP sub-process (with or without Xdebug loaded), regardless of whether there has been a restart. + +Each of its methods returns an array of PHP options (to add to the command-line) and sets up the environment for the required strategy. The [getRestartSettings()](#getrestartsettings) method is used internally. + +* `useOriginal()` - Xdebug will be loaded in the new process. +* `useStandard()` - Xdebug will **not** be loaded in the new process - see [standard settings](#standard-settings). +* `userPersistent()` - Xdebug will **not** be loaded in the new process - see [persistent settings](#persistent-settings) + +If there was no restart, an empty options array is returned and the environment is not changed. + +```php +use Composer\XdebugHandler\PhpConfig; + +$config = new PhpConfig; + +$options = $config->useOriginal(); +# $options: empty array +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->useStandard(); +# $options: [-n, -c, tmpIni] +# environment: PHPRC and PHP_INI_SCAN_DIR set to original values + +$options = $config->usePersistent(); +# $options: empty array +# environment: PHPRC=tmpIni, PHP_INI_SCAN_DIR='' +``` + +### Troubleshooting +The following environment settings can be used to troubleshoot unexpected behavior: + +* `XDEBUG_HANDLER_DEBUG=1` Outputs status messages to `STDERR`, if it is defined, irrespective of any PSR3 logger. Each message is prefixed `xdebug-handler[pid]`, where pid is the process identifier. + +* `XDEBUG_HANDLER_DEBUG=2` As above, but additionally saves the temporary ini file and reports its location in a status message. + +### Extending the library +The API is defined by classes and their accessible elements that are not annotated as @internal. The main class has two protected methods that can be overridden to provide additional functionality: + +#### _requiresRestart(bool $default): bool_ +By default the process will restart if Xdebug is loaded and not running with `xdebug.mode=off`. Extending this method allows an application to decide, by returning a boolean (or equivalent) value. +It is only called if `MYAPP_ALLOW_XDEBUG` is empty, so it will not be called in the restarted process (where this variable contains internal data), or if the restart has been overridden. + +Note that the [setMainScript()](#setmainscriptscript) and [setPersistent()](#setpersistent) setters can be used here, if required. + +#### _restart(array $command): void_ +An application can extend this to modify the temporary ini file, its location given in the `tmpIni` property. New settings can be safely appended to the end of the data, which is `PHP_EOL` terminated. + +The `$command` parameter is an array of unescaped command-line arguments that will be used for the new process. + +Remember to finish with `parent::restart($command)`. + +#### Example +This example demonstrates two ways to extend basic functionality: + +* To avoid the overhead of spinning up a new process, the restart is skipped if a simple help command is requested. + +* The application needs write-access to phar files, so it will force a restart if `phar.readonly` is set (regardless of whether Xdebug is loaded) and change this value in the temporary ini file. + +```php +use Composer\XdebugHandler\XdebugHandler; +use MyApp\Command; + +class MyRestarter extends XdebugHandler +{ + private $required; + + protected function requiresRestart(bool $default): bool + { + if (Command::isHelp()) { + # No need to disable Xdebug for this + return false; + } + + $this->required = (bool) ini_get('phar.readonly'); + return $this->required || $default; + } + + protected function restart(array $command): void + { + if ($this->required) { + # Add required ini setting to tmpIni + $content = file_get_contents($this->tmpIni); + $content .= 'phar.readonly=0'.PHP_EOL; + file_put_contents($this->tmpIni, $content); + } + + parent::restart($command); + } +} +``` + +## License +composer/xdebug-handler is licensed under the MIT License, see the LICENSE file for details. diff --git a/vendor/composer/xdebug-handler/composer.json b/vendor/composer/xdebug-handler/composer.json new file mode 100644 index 00000000000..9d97318a0d0 --- /dev/null +++ b/vendor/composer/xdebug-handler/composer.json @@ -0,0 +1,44 @@ +{ + "name": "composer\/xdebug-handler", + "description": "Restarts a process without Xdebug.", + "type": "library", + "license": "MIT", + "keywords": [ + "xdebug", + "performance" + ], + "authors": [ + { + "name": "John Stevenson", + "email": "john-stevenson@blueyonder.co.uk" + } + ], + "support": { + "irc": "irc:\/\/irc.freenode.org\/composer", + "issues": "https:\/\/github.com\/composer\/xdebug-handler\/issues" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr\/log": "^1 || ^2 || ^3", + "composer\/pcre": "^1 || ^2 || ^3" + }, + "require-dev": { + "symfony\/phpunit-bridge": "^6.0", + "phpstan\/phpstan": "^1.0", + "phpstan\/phpstan-strict-rules": "^1.1" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Composer\\XdebugHandler\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Composer\\XdebugHandler\\Tests\\": "tests" + } + }, + "scripts": { + "test": "@php vendor\/bin\/simple-phpunit", + "phpstan": "@php vendor\/bin\/phpstan analyse" + } +} \ No newline at end of file diff --git a/vendor/composer/xdebug-handler/src/PhpConfig.php b/vendor/composer/xdebug-handler/src/PhpConfig.php new file mode 100644 index 00000000000..d31d5c15f2f --- /dev/null +++ b/vendor/composer/xdebug-handler/src/PhpConfig.php @@ -0,0 +1,82 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +namespace ECSPrefix202307\Composer\XdebugHandler; + +/** + * @author John Stevenson + * + * @phpstan-type restartData array{tmpIni: string, scannedInis: bool, scanDir: false|string, phprc: false|string, inis: string[], skipped: string} + */ +class PhpConfig +{ + /** + * Use the original PHP configuration + * + * @return string[] Empty array of PHP cli options + */ + public function useOriginal() : array + { + $this->getDataAndReset(); + return []; + } + /** + * Use standard restart settings + * + * @return string[] PHP cli options + */ + public function useStandard() : array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + return ['-n', '-c', $data['tmpIni']]; + } + return []; + } + /** + * Use environment variables to persist settings + * + * @return string[] Empty array of PHP cli options + */ + public function usePersistent() : array + { + $data = $this->getDataAndReset(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['tmpIni']); + $this->updateEnv('PHP_INI_SCAN_DIR', ''); + } + return []; + } + /** + * Returns restart data if available and resets the environment + * + * @phpstan-return restartData|null + */ + private function getDataAndReset() : ?array + { + $data = XdebugHandler::getRestartSettings(); + if ($data !== null) { + $this->updateEnv('PHPRC', $data['phprc']); + $this->updateEnv('PHP_INI_SCAN_DIR', $data['scanDir']); + } + return $data; + } + /** + * Updates a restart settings value in the environment + * + * @param string $name + * @param string|false $value + */ + private function updateEnv(string $name, $value) : void + { + Process::setEnv($name, \false !== $value ? $value : null); + } +} diff --git a/vendor/composer/xdebug-handler/src/Process.php b/vendor/composer/xdebug-handler/src/Process.php new file mode 100644 index 00000000000..3347faa60b2 --- /dev/null +++ b/vendor/composer/xdebug-handler/src/Process.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Composer\XdebugHandler; + +use ECSPrefix202307\Composer\Pcre\Preg; +/** + * Process utility functions + * + * @author John Stevenson + */ +class Process +{ + /** + * Escapes a string to be used as a shell argument. + * + * From https://github.com/johnstevenson/winbox-args + * MIT Licensed (c) John Stevenson + * + * @param string $arg The argument to be escaped + * @param bool $meta Additionally escape cmd.exe meta characters + * @param bool $module The argument is the module to invoke + */ + public static function escape(string $arg, bool $meta = \true, bool $module = \false) : string + { + 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::isMatch('/%[^%]+%/', $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; + } + /** + * Escapes an array of arguments that make up a shell command + * + * @param string[] $args Argument list, with the module name first + */ + public static function escapeShellCommand(array $args) : string + { + $command = ''; + $module = \array_shift($args); + if ($module !== null) { + $command = self::escape($module, \true, \true); + foreach ($args as $arg) { + $command .= ' ' . self::escape($arg); + } + } + return $command; + } + /** + * Makes putenv environment changes available in $_SERVER and $_ENV + * + * @param string $name + * @param ?string $value A null value unsets the variable + */ + public static function setEnv(string $name, ?string $value = null) : bool + { + $unset = null === $value; + if (!\putenv($unset ? $name : $name . '=' . $value)) { + return \false; + } + if ($unset) { + unset($_SERVER[$name]); + } else { + $_SERVER[$name] = $value; + } + // Update $_ENV if it is being used + if (\false !== \stripos((string) \ini_get('variables_order'), 'E')) { + if ($unset) { + unset($_ENV[$name]); + } else { + $_ENV[$name] = $value; + } + } + return \true; + } +} diff --git a/vendor/composer/xdebug-handler/src/Status.php b/vendor/composer/xdebug-handler/src/Status.php new file mode 100644 index 00000000000..7124911c267 --- /dev/null +++ b/vendor/composer/xdebug-handler/src/Status.php @@ -0,0 +1,175 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Composer\XdebugHandler; + +use ECSPrefix202307\Psr\Log\LoggerInterface; +use ECSPrefix202307\Psr\Log\LogLevel; +/** + * @author John Stevenson + * @internal + */ +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'; + /** @var bool */ + private $debug; + /** @var string */ + private $envAllowXdebug; + /** @var string|null */ + private $loaded; + /** @var LoggerInterface|null */ + private $logger; + /** @var bool */ + private $modeOff; + /** @var float */ + private $time; + /** + * @param string $envAllowXdebug Prefixed _ALLOW_XDEBUG name + * @param bool $debug Whether debug output is required + */ + public function __construct(string $envAllowXdebug, bool $debug) + { + $start = \getenv(self::ENV_RESTART); + Process::setEnv(self::ENV_RESTART); + $this->time = \is_numeric($start) ? \round((\microtime(\true) - $start) * 1000) : 0; + $this->envAllowXdebug = $envAllowXdebug; + $this->debug = $debug && \defined('STDERR'); + $this->modeOff = \false; + } + /** + * Activates status message output to a PSR3 logger + * + * @return void + */ + public function setLogger(LoggerInterface $logger) : void + { + $this->logger = $logger; + } + /** + * Calls a handler method to report a message + * + * @throws \InvalidArgumentException If $op is not known + */ + public function report(string $op, ?string $data) : void + { + if ($this->logger !== null || $this->debug) { + $callable = [$this, 'report' . $op]; + if (!\is_callable($callable)) { + throw new \InvalidArgumentException('Unknown op handler: ' . $op); + } + $params = $data !== null ? [$data] : []; + \call_user_func_array($callable, $params); + } + } + /** + * Outputs a status message + */ + private function output(string $text, ?string $level = null) : void + { + if ($this->logger !== null) { + $this->logger->log($level !== null ? $level : LogLevel::DEBUG, $text); + } + if ($this->debug) { + \fwrite(\STDERR, \sprintf('xdebug-handler[%d] %s', \getmypid(), $text . \PHP_EOL)); + } + } + /** + * Checking status message + */ + private function reportCheck(string $loaded) : void + { + list($version, $mode) = \explode('|', $loaded); + if ($version !== '') { + $this->loaded = '(' . $version . ')' . ($mode !== '' ? ' xdebug.mode=' . $mode : ''); + } + $this->modeOff = $mode === 'off'; + $this->output('Checking ' . $this->envAllowXdebug); + } + /** + * Error status message + */ + private function reportError(string $error) : void + { + $this->output(\sprintf('No restart (%s)', $error), LogLevel::WARNING); + } + /** + * Info status message + */ + private function reportInfo(string $info) : void + { + $this->output($info); + } + /** + * No restart status message + */ + private function reportNoRestart() : void + { + $this->output($this->getLoadedMessage()); + if ($this->loaded !== null) { + $text = \sprintf('No restart (%s)', $this->getEnvAllow()); + if (!(bool) \getenv($this->envAllowXdebug)) { + $text .= ' Allowed by ' . ($this->modeOff ? 'xdebug.mode' : 'application'); + } + $this->output($text); + } + } + /** + * Restart status message + */ + private function reportRestart() : void + { + $this->output($this->getLoadedMessage()); + Process::setEnv(self::ENV_RESTART, (string) \microtime(\true)); + } + /** + * Restarted status message + */ + private function reportRestarted() : void + { + $loaded = $this->getLoadedMessage(); + $text = \sprintf('Restarted (%d ms). %s', $this->time, $loaded); + $level = $this->loaded !== null ? LogLevel::WARNING : null; + $this->output($text, $level); + } + /** + * Restarting status message + */ + private function reportRestarting(string $command) : void + { + $text = \sprintf('Process restarting (%s)', $this->getEnvAllow()); + $this->output($text); + $text = 'Running ' . $command; + $this->output($text); + } + /** + * Returns the _ALLOW_XDEBUG environment variable as name=value + */ + private function getEnvAllow() : string + { + return $this->envAllowXdebug . '=' . \getenv($this->envAllowXdebug); + } + /** + * Returns the Xdebug status and version + */ + private function getLoadedMessage() : string + { + $loaded = $this->loaded !== null ? \sprintf('loaded %s', $this->loaded) : 'not loaded'; + return 'The Xdebug extension is ' . $loaded; + } +} diff --git a/vendor/composer/xdebug-handler/src/XdebugHandler.php b/vendor/composer/xdebug-handler/src/XdebugHandler.php new file mode 100644 index 00000000000..4c14ca54bd6 --- /dev/null +++ b/vendor/composer/xdebug-handler/src/XdebugHandler.php @@ -0,0 +1,540 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Composer\XdebugHandler; + +use ECSPrefix202307\Composer\Pcre\Preg; +use ECSPrefix202307\Psr\Log\LoggerInterface; +/** + * @author John Stevenson + * + * @phpstan-import-type restartData from PhpConfig + */ +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'; + /** @var string|null */ + protected $tmpIni; + /** @var bool */ + private static $inRestart; + /** @var string */ + private static $name; + /** @var string|null */ + private static $skipped; + /** @var bool */ + private static $xdebugActive; + /** @var string|null */ + private static $xdebugMode; + /** @var string|null */ + private static $xdebugVersion; + /** @var bool */ + private $cli; + /** @var string|null */ + private $debug; + /** @var string */ + private $envAllowXdebug; + /** @var string */ + private $envOriginalInis; + /** @var bool */ + private $persistent; + /** @var string|null */ + private $script; + /** @var Status */ + private $statusWriter; + /** + * Constructor + * + * The $envPrefix is used to create distinct environment variables. It is + * uppercased and prepended to the default base values. For example 'myapp' + * would result in MYAPP_ALLOW_XDEBUG and MYAPP_ORIGINAL_INIS. + * + * @param string $envPrefix Value used in environment variables + * @throws \RuntimeException If the parameter is invalid + */ + public function __construct(string $envPrefix) + { + if ($envPrefix === '') { + throw new \RuntimeException('Invalid constructor parameter'); + } + self::$name = \strtoupper($envPrefix); + $this->envAllowXdebug = self::$name . self::SUFFIX_ALLOW; + $this->envOriginalInis = self::$name . self::SUFFIX_INIS; + self::setXdebugDetails(); + self::$inRestart = \false; + if ($this->cli = \PHP_SAPI === 'cli') { + $this->debug = (string) \getenv(self::DEBUG); + } + $this->statusWriter = new Status($this->envAllowXdebug, (bool) $this->debug); + } + /** + * Activates status message output to a PSR3 logger + */ + public function setLogger(LoggerInterface $logger) : self + { + $this->statusWriter->setLogger($logger); + return $this; + } + /** + * Sets the main script location if it cannot be called from argv + */ + public function setMainScript(string $script) : self + { + $this->script = $script; + return $this; + } + /** + * Persist the settings to keep Xdebug out of sub-processes + */ + public function setPersistent() : self + { + $this->persistent = \true; + return $this; + } + /** + * Checks if Xdebug is loaded and the process needs to be restarted + * + * This behaviour can be disabled by setting the MYAPP_ALLOW_XDEBUG + * environment variable to 1. This variable is used internally so that + * the restarted process is created only once. + */ + public function check() : void + { + $this->notify(Status::CHECK, self::$xdebugVersion . '|' . self::$xdebugMode); + $envArgs = \explode('|', (string) \getenv($this->envAllowXdebug)); + if (!(bool) $envArgs[0] && $this->requiresRestart(self::$xdebugActive)) { + // Restart required + $this->notify(Status::RESTART); + if ($this->prepareRestart()) { + $command = $this->getCommand(); + $this->restart($command); + } + return; + } + if (self::RESTART_ID === $envArgs[0] && \count($envArgs) === 5) { + // Restarted, so unset environment variable and use saved values + $this->notify(Status::RESTARTED); + Process::setEnv($this->envAllowXdebug); + self::$inRestart = \true; + if (self::$xdebugVersion === null) { + // Skipped version is only set if Xdebug is not loaded + self::$skipped = $envArgs[1]; + } + $this->tryEnableSignals(); + // Put restart settings in the environment + $this->setEnvRestartSettings($envArgs); + return; + } + $this->notify(Status::NORESTART); + $settings = self::getRestartSettings(); + if ($settings !== null) { + // Called with existing settings, so sync our settings + $this->syncSettings($settings); + } + } + /** + * Returns an array of php.ini locations with at least one entry + * + * The equivalent of calling php_ini_loaded_file then php_ini_scanned_files. + * The loaded ini location is the first entry and may be empty. + * + * @return string[] + */ + public static function getAllIniFiles() : array + { + if (self::$name !== null) { + $env = \getenv(self::$name . self::SUFFIX_INIS); + if (\false !== $env) { + return \explode(\PATH_SEPARATOR, $env); + } + } + $paths = [(string) \php_ini_loaded_file()]; + $scanned = \php_ini_scanned_files(); + if ($scanned !== \false) { + $paths = \array_merge($paths, \array_map('trim', \explode(',', $scanned))); + } + return $paths; + } + /** + * Returns an array of restart settings or null + * + * Settings will be available if the current process was restarted, or + * called with the settings from an existing restart. + * + * @phpstan-return restartData|null + */ + public static function getRestartSettings() : ?array + { + $envArgs = \explode('|', (string) \getenv(self::RESTART_SETTINGS)); + if (\count($envArgs) !== 6 || !self::$inRestart && \php_ini_loaded_file() !== $envArgs[0]) { + return null; + } + return ['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]]; + } + /** + * Returns the Xdebug version that triggered a successful restart + */ + public static function getSkippedVersion() : string + { + return (string) self::$skipped; + } + /** + * Returns whether Xdebug is loaded and active + * + * true: if Xdebug is loaded and is running in an active mode. + * false: if Xdebug is not loaded, or it is running with xdebug.mode=off. + */ + public static function isXdebugActive() : bool + { + self::setXdebugDetails(); + return self::$xdebugActive; + } + /** + * Allows an extending class to decide if there should be a restart + * + * The default is to restart if Xdebug is loaded and its mode is not "off". + */ + protected function requiresRestart(bool $default) : bool + { + return $default; + } + /** + * Allows an extending class to access the tmpIni + * + * @param string[] $command * + */ + protected function restart(array $command) : void + { + $this->doRestart($command); + } + /** + * Executes the restarted command then deletes the tmp ini + * + * @param string[] $command + * @phpstan-return never + */ + private function doRestart(array $command) : void + { + $this->tryEnableSignals(); + $this->notify(Status::RESTARTING, \implode(' ', $command)); + if (\PHP_VERSION_ID >= 70400) { + $cmd = $command; + } else { + $cmd = Process::escapeShellCommand($command); + if (\defined('PHP_WINDOWS_VERSION_BUILD')) { + // Outer quotes required on cmd string below PHP 8 + $cmd = '"' . $cmd . '"'; + } + } + $process = \proc_open(\is_array($cmd) ? \implode(' ', $cmd) : $cmd, [], $pipes); + if (\is_resource($process)) { + $exitCode = \proc_close($process); + } + if (!isset($exitCode)) { + // Unlikely that php or the default shell cannot be invoked + $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((string) $this->tmpIni); + } + exit($exitCode); + } + /** + * Returns true if everything was written for the restart + * + * If any of the following fails (however unlikely) we must return false to + * stop potential recursion: + * - tmp ini file creation + * - environment variable creation + */ + private function prepareRestart() : bool + { + $error = null; + $iniFiles = self::getAllIniFiles(); + $scannedInis = \count($iniFiles) > 1; + $tmpDir = \sys_get_temp_dir(); + if (!$this->cli) { + $error = 'Unsupported SAPI: ' . \PHP_SAPI; + } elseif (!$this->checkConfiguration($info)) { + $error = $info; + } elseif (!$this->checkMainScript()) { + $error = 'Unable to access main script: ' . $this->script; + } elseif (!$this->writeTmpIni($iniFiles, $tmpDir, $error)) { + $error = $error !== null ? $error : 'Unable to create temp ini file at: ' . $tmpDir; + } elseif (!$this->setEnvironment($scannedInis, $iniFiles)) { + $error = 'Unable to set environment variables'; + } + if ($error !== null) { + $this->notify(Status::ERROR, $error); + } + return $error === null; + } + /** + * Returns true if the tmp ini file was written + * + * @param string[] $iniFiles All ini files used in the current process + */ + private function writeTmpIni(array $iniFiles, string $tmpDir, ?string &$error) : bool + { + if (($tmpfile = @\tempnam($tmpDir, '')) === \false) { + return \false; + } + $this->tmpIni = $tmpfile; + // $iniFiles has at least one item and it may be empty + if ($iniFiles[0] === '') { + \array_shift($iniFiles); + } + $content = ''; + $sectionRegex = '/^\\s*\\[(?:PATH|HOST)\\s*=/mi'; + $xdebugRegex = '/^\\s*(zend_extension\\s*=.*xdebug.*)$/mi'; + foreach ($iniFiles as $file) { + // Check for inaccessible ini files + if (($data = @\file_get_contents($file)) === \false) { + $error = 'Unable to read ini: ' . $file; + return \false; + } + // Check and remove directives after HOST and PATH sections + if (Preg::isMatchWithOffsets($sectionRegex, $data, $matches, \PREG_OFFSET_CAPTURE)) { + $data = \substr($data, 0, $matches[0][1]); + } + $content .= Preg::replace($xdebugRegex, ';$1', $data) . \PHP_EOL; + } + // Merge loaded settings into our ini content, if it is valid + $config = \parse_ini_string($content); + $loaded = \ini_get_all(null, \false); + if (\false === $config || \false === $loaded) { + $error = 'Unable to parse ini data'; + return \false; + } + $content .= $this->mergeLoadedConfig($loaded, $config); + // Work-around for https://bugs.php.net/bug.php?id=75932 + $content .= 'opcache.enable_cli=0' . \PHP_EOL; + return (bool) @\file_put_contents($this->tmpIni, $content); + } + /** + * Returns the command line arguments for the restart + * + * @return string[] + */ + private function getCommand() : array + { + $php = [\PHP_BINARY]; + $args = \array_slice($_SERVER['argv'], 1); + if (!$this->persistent) { + // Use command-line options + \array_push($php, '-n', '-c', $this->tmpIni); + } + return \array_merge($php, [$this->script], $args); + } + /** + * Returns true if the restart environment variables were set + * + * No need to update $_SERVER since this is set in the restarted process. + * + * @param string[] $iniFiles All ini files used in the current process + */ + private function setEnvironment(bool $scannedInis, array $iniFiles) : bool + { + $scanDir = \getenv('PHP_INI_SCAN_DIR'); + $phprc = \getenv('PHPRC'); + // Make original inis available to restarted process + if (!\putenv($this->envOriginalInis . '=' . \implode(\PATH_SEPARATOR, $iniFiles))) { + return \false; + } + if ($this->persistent) { + // Use the environment to persist the settings + if (!\putenv('PHP_INI_SCAN_DIR=') || !\putenv('PHPRC=' . $this->tmpIni)) { + return \false; + } + } + // Flag restarted process and save values for it to use + $envArgs = [self::RESTART_ID, self::$xdebugVersion, (int) $scannedInis, \false === $scanDir ? '*' : $scanDir, \false === $phprc ? '*' : $phprc]; + return \putenv($this->envAllowXdebug . '=' . \implode('|', $envArgs)); + } + /** + * Logs status messages + */ + private function notify(string $op, ?string $data = null) : void + { + $this->statusWriter->report($op, $data); + } + /** + * Returns default, changed and command-line ini settings + * + * @param mixed[] $loadedConfig All current ini settings + * @param mixed[] $iniConfig Settings from user ini files + * + */ + private function mergeLoadedConfig(array $loadedConfig, array $iniConfig) : string + { + $content = ''; + foreach ($loadedConfig as $name => $value) { + // Value will either be null, string or array (HHVM only) + if (!\is_string($value) || \strpos($name, 'xdebug') === 0 || $name === 'apc.mmap_file_mask') { + continue; + } + if (!isset($iniConfig[$name]) || $iniConfig[$name] !== $value) { + // Double-quote escape each value + $content .= $name . '="' . \addcslashes($value, '\\"') . '"' . \PHP_EOL; + } + } + return $content; + } + /** + * Returns true if the script name can be used + */ + private function checkMainScript() : bool + { + if ($this->script !== null) { + // Allow an application to set -- for standard input + return \file_exists($this->script) || '--' === $this->script; + } + if (\file_exists($this->script = $_SERVER['argv'][0])) { + return \true; + } + // Use a backtrace to resolve Phar and chdir issues. + $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + $main = \end($trace); + if ($main !== \false && isset($main['file'])) { + return \file_exists($this->script = $main['file']); + } + return \false; + } + /** + * Adds restart settings to the environment + * + * @param string[] $envArgs + */ + private function setEnvRestartSettings(array $envArgs) : void + { + $settings = [\php_ini_loaded_file(), $envArgs[2], $envArgs[3], $envArgs[4], \getenv($this->envOriginalInis), self::$skipped]; + Process::setEnv(self::RESTART_SETTINGS, \implode('|', $settings)); + } + /** + * Syncs settings and the environment if called with existing settings + * + * @phpstan-param restartData $settings + */ + private function syncSettings(array $settings) : void + { + if (\false === \getenv($this->envOriginalInis)) { + // Called by another app, so make original inis available + Process::setEnv($this->envOriginalInis, \implode(\PATH_SEPARATOR, $settings['inis'])); + } + self::$skipped = $settings['skipped']; + $this->notify(Status::INFO, 'Process called with existing restart settings'); + } + /** + * Returns true if there are no known configuration issues + */ + private function checkConfiguration(?string &$info) : bool + { + if (!\function_exists('proc_open')) { + $info = 'proc_open function is disabled'; + return \false; + } + if (\extension_loaded('uopz') && !(bool) \ini_get('uopz.disable')) { + // uopz works at opcode level and disables exit calls + if (\function_exists('uopz_allow_exit')) { + @\uopz_allow_exit(\true); + } else { + $info = 'uopz extension is not compatible'; + return \false; + } + } + // Check UNC paths when using cmd.exe + if (\defined('PHP_WINDOWS_VERSION_BUILD') && \PHP_VERSION_ID < 70400) { + $workingDir = \getcwd(); + if ($workingDir === \false) { + $info = 'unable to determine working directory'; + return \false; + } + if (0 === \strpos($workingDir, '\\\\')) { + $info = 'cmd.exe does not support UNC paths: ' . $workingDir; + return \false; + } + } + return \true; + } + /** + * Enables async signals and control interrupts in the restarted process + * + * Available on Unix PHP 7.1+ with the pcntl extension and Windows PHP 7.4+. + */ + private function tryEnableSignals() : void + { + if (\function_exists('pcntl_async_signals') && \function_exists('pcntl_signal')) { + \pcntl_async_signals(\true); + $message = 'Async signals enabled'; + if (!self::$inRestart) { + // Restarting, so ignore SIGINT in parent + \pcntl_signal(\SIGINT, \SIG_IGN); + } elseif (\is_int(\pcntl_signal_get_handler(\SIGINT))) { + // Restarted, no handler set so force default action + \pcntl_signal(\SIGINT, \SIG_DFL); + } + } + if (!self::$inRestart && \function_exists('sapi_windows_set_ctrl_handler')) { + // Restarting, so set a handler to ignore CTRL events in the parent. + // This ensures that CTRL+C events will be available in the child + // process without having to enable them there, which is unreliable. + \sapi_windows_set_ctrl_handler(function ($evt) { + }); + } + } + /** + * Sets static properties $xdebugActive, $xdebugVersion and $xdebugMode + */ + private static function setXdebugDetails() : void + { + if (self::$xdebugActive !== null) { + return; + } + self::$xdebugActive = \false; + if (!\extension_loaded('xdebug')) { + return; + } + $version = \phpversion('xdebug'); + self::$xdebugVersion = $version !== \false ? $version : 'unknown'; + if (\version_compare(self::$xdebugVersion, '3.1', '>=')) { + $modes = \xdebug_info('mode'); + self::$xdebugMode = \count($modes) === 0 ? 'off' : \implode(',', $modes); + self::$xdebugActive = self::$xdebugMode !== 'off'; + return; + } + // See if xdebug.mode is supported in this version + $iniMode = \ini_get('xdebug.mode'); + if ($iniMode === \false) { + self::$xdebugActive = \true; + return; + } + // Environment value wins but cannot be empty + $envMode = (string) \getenv('XDEBUG_MODE'); + if ($envMode !== '') { + self::$xdebugMode = $envMode; + } else { + self::$xdebugMode = $iniMode !== '' ? $iniMode : 'off'; + } + // An empty comma-separated list is treated as mode 'off' + if (Preg::isMatch('/^,+$/', \str_replace(' ', '', self::$xdebugMode))) { + self::$xdebugMode = 'off'; + } + self::$xdebugActive = self::$xdebugMode !== 'off'; + } +} diff --git a/vendor/doctrine/annotations/LICENSE b/vendor/doctrine/annotations/LICENSE new file mode 100644 index 00000000000..5e781fce4bb --- /dev/null +++ b/vendor/doctrine/annotations/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006-2013 Doctrine Project + +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. diff --git a/vendor/doctrine/annotations/README.md b/vendor/doctrine/annotations/README.md new file mode 100644 index 00000000000..6b8c0359be1 --- /dev/null +++ b/vendor/doctrine/annotations/README.md @@ -0,0 +1,24 @@ +⚠️ PHP 8 introduced +[attributes](https://www.php.net/manual/en/language.attributes.overview.php), +which are a native replacement for annotations. As such, this library is +considered feature complete, and should receive exclusively bugfixes and +security fixes. + +# Doctrine Annotations + +[![Build Status](https://github.com/doctrine/annotations/workflows/Continuous%20Integration/badge.svg?label=build)](https://github.com/doctrine/persistence/actions) +[![Dependency Status](https://www.versioneye.com/package/php--doctrine--annotations/badge.png)](https://www.versioneye.com/package/php--doctrine--annotations) +[![Reference Status](https://www.versioneye.com/php/doctrine:annotations/reference_badge.svg)](https://www.versioneye.com/php/doctrine:annotations/references) +[![Total Downloads](https://poser.pugx.org/doctrine/annotations/downloads.png)](https://packagist.org/packages/doctrine/annotations) +[![Latest Stable Version](https://img.shields.io/packagist/v/doctrine/annotations.svg?label=stable)](https://packagist.org/packages/doctrine/annotations) + +Docblock Annotations Parser library (extracted from [Doctrine Common](https://github.com/doctrine/common)). + +## Documentation + +See the [doctrine-project website](https://www.doctrine-project.org/projects/doctrine-annotations/en/latest/index.html). + +## Contributing + +When making a pull request, make sure your changes follow the +[Coding Standard Guidelines](https://www.doctrine-project.org/projects/doctrine-coding-standard/en/current/reference/index.html#introduction). diff --git a/vendor/doctrine/annotations/UPGRADE.md b/vendor/doctrine/annotations/UPGRADE.md new file mode 100644 index 00000000000..4172708f0c7 --- /dev/null +++ b/vendor/doctrine/annotations/UPGRADE.md @@ -0,0 +1,18 @@ +# Upgrade from 1.0.x to 2.0.x + +- The `NamedArgumentConstructorAnnotation` has been removed. Use the `@NamedArgumentConstructor` + annotation instead. +- `SimpleAnnotationReader` has been removed. +- `DocLexer::peek()` and `DocLexer::glimpse` now return +`Doctrine\Common\Lexer\Token` objects. When using `doctrine/lexer` 2, these +implement `ArrayAccess` as a way for you to still be able to treat them as +arrays in some ways. +- `CachedReader` and `FileCacheReader` have been removed. +- `AnnotationRegistry` methods related to registering annotations instead of + using autoloading have been removed. +- Parameter type declarations have been added to all methods of all classes. If +you have classes inheriting from classes inside this package, you should add +parameter and return type declarations. +- Support for PHP < 7.2 has been removed +- `PhpParser::parseClass()` has been removed. Use + `PhpParser::parseUseStatements()` instead. diff --git a/vendor/doctrine/annotations/composer.json b/vendor/doctrine/annotations/composer.json new file mode 100644 index 00000000000..c858a79c155 --- /dev/null +++ b/vendor/doctrine/annotations/composer.json @@ -0,0 +1,72 @@ +{ + "name": "doctrine\/annotations", + "description": "Docblock Annotations Parser", + "license": "MIT", + "type": "library", + "keywords": [ + "annotations", + "docblock", + "parser" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Benjamin Eberlei", + "email": "kontakt@beberlei.de" + }, + { + "name": "Jonathan Wage", + "email": "jonwage@gmail.com" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "homepage": "https:\/\/www.doctrine-project.org\/projects\/annotations.html", + "require": { + "php": "^7.2 || ^8.0", + "ext-tokenizer": "*", + "doctrine\/lexer": "^2 || ^3", + "psr\/cache": "^1 || ^2 || ^3" + }, + "require-dev": { + "doctrine\/cache": "^2.0", + "doctrine\/coding-standard": "^10", + "phpstan\/phpstan": "^1.8.0", + "phpunit\/phpunit": "^7.5 || ^8.5 || ^9.5", + "symfony\/cache": "^5.4 || ^6", + "vimeo\/psalm": "^4.10" + }, + "suggest": { + "php": "PHP 8.0 or higher comes with attributes, a native replacement for annotations" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Common\\Annotations\\": "lib\/Doctrine\/Common\/Annotations" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Performance\\Common\\Annotations\\": "tests\/Doctrine\/Performance\/Common\/Annotations", + "ECSPrefix202307\\Doctrine\\Tests\\Common\\Annotations\\": "tests\/Doctrine\/Tests\/Common\/Annotations" + }, + "files": [ + "tests\/Doctrine\/Tests\/Common\/Annotations\/Fixtures\/functions.php", + "tests\/Doctrine\/Tests\/Common\/Annotations\/Fixtures\/SingleClassLOC1000.php" + ] + }, + "config": { + "allow-plugins": { + "dealerdirect\/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} \ No newline at end of file diff --git a/vendor/doctrine/annotations/docs/en/annotations.rst b/vendor/doctrine/annotations/docs/en/annotations.rst new file mode 100644 index 00000000000..d32b15d12d1 --- /dev/null +++ b/vendor/doctrine/annotations/docs/en/annotations.rst @@ -0,0 +1,189 @@ +Handling Annotations +==================== + +There are several different approaches to handling annotations in PHP. +Doctrine Annotations maps docblock annotations to PHP classes. Because +not all docblock annotations are used for metadata purposes a filter is +applied to ignore or skip classes that are not Doctrine annotations. + +Take a look at the following code snippet: + +.. code-block:: php + + namespace MyProject\Entities; + + use Doctrine\ORM\Mapping AS ORM; + use Symfony\Component\Validator\Constraints AS Assert; + + /** + * @author Benjamin Eberlei + * @ORM\Entity + * @MyProject\Annotations\Foobarable + */ + class User + { + /** + * @ORM\Id @ORM\Column @ORM\GeneratedValue + * @dummy + * @var int + */ + private $id; + + /** + * @ORM\Column(type="string") + * @Assert\NotEmpty + * @Assert\Email + * @var string + */ + private $email; + } + +In this snippet you can see a variety of different docblock annotations: + +- Documentation annotations such as ``@var`` and ``@author``. These + annotations are ignored and never considered for throwing an + exception due to wrongly used annotations. +- Annotations imported through use statements. The statement ``use + Doctrine\ORM\Mapping AS ORM`` makes all classes under that namespace + available as ``@ORM\ClassName``. Same goes for the import of + ``@Assert``. +- The ``@dummy`` annotation. It is not a documentation annotation and + not ignored. For Doctrine Annotations it is not entirely clear how + to handle this annotation. Depending on the configuration an exception + (unknown annotation) will be thrown when parsing this annotation. +- The fully qualified annotation ``@MyProject\Annotations\Foobarable``. + This is transformed directly into the given class name. + +How are these annotations loaded? From looking at the code you could +guess that the ORM Mapping, Assert Validation and the fully qualified +annotation can just be loaded using +the defined PHP autoloaders. This is not the case however: For error +handling reasons every check for class existence inside the +``AnnotationReader`` sets the second parameter $autoload +of ``class_exists($name, $autoload)`` to false. To work flawlessly the +``AnnotationReader`` requires silent autoloaders which many autoloaders are +not. Silent autoloading is NOT part of the `PSR-0 specification +`_ +for autoloading. + +This is why Doctrine Annotations uses its own autoloading mechanism +through a global registry. If you are wondering about the annotation +registry being global, there is no other way to solve the architectural +problems of autoloading annotation classes in a straightforward fashion. +Additionally if you think about PHP autoloading then you recognize it is +a global as well. + +To anticipate the configuration section, making the above PHP class work +with Doctrine Annotations requires this setup: + +.. code-block:: php + + use Doctrine\Common\Annotations\AnnotationReader; + + $reader = new AnnotationReader(); + AnnotationReader::addGlobalIgnoredName('dummy'); + +We create the actual ``AnnotationReader`` instance. +Note that we also add ``dummy`` to the global list of ignored +annotations for which we do not throw exceptions. Setting this is +necessary in our example case, otherwise ``@dummy`` would trigger an +exception to be thrown during the parsing of the docblock of +``MyProject\Entities\User#id``. + +Setup and Configuration +----------------------- + +To use the annotations library is simple, you just need to create a new +``AnnotationReader`` instance: + +.. code-block:: php + + $reader = new \Doctrine\Common\Annotations\AnnotationReader(); + +This creates a simple annotation reader with no caching other than in +memory (in php arrays). Since parsing docblocks can be expensive you +should cache this process by using a caching reader. + +To cache annotations, you can create a ``Doctrine\Common\Annotations\PsrCachedReader``. +This reader decorates the original reader and stores all annotations in a PSR-6 +cache: + +.. code-block:: php + + use Doctrine\Common\Annotations\AnnotationReader; + use Doctrine\Common\Annotations\PsrCachedReader; + + $cache = ... // instantiate a PSR-6 Cache pool + + $reader = new PsrCachedReader( + new AnnotationReader(), + $cache, + $debug = true + ); + +The ``debug`` flag is used here as well to invalidate the cache files +when the PHP class with annotations changed and should be used during +development. + +.. warning :: + + The ``AnnotationReader`` works and caches under the + assumption that all annotations of a doc-block are processed at + once. That means that annotation classes that do not exist and + aren't loaded and cannot be autoloaded (using the + AnnotationRegistry) would never be visible and not accessible if a + cache is used unless the cache is cleared and the annotations + requested again, this time with all annotations defined. + +By default the annotation reader returns a list of annotations with +numeric indexes. If you want your annotations to be indexed by their +class name you can wrap the reader in an ``IndexedReader``: + +.. code-block:: php + + use Doctrine\Common\Annotations\AnnotationReader; + use Doctrine\Common\Annotations\IndexedReader; + + $reader = new IndexedReader(new AnnotationReader()); + +.. warning:: + + You should never wrap the indexed reader inside a cached reader, + only the other way around. This way you can re-use the cache with + indexed or numeric keys, otherwise your code may experience failures + due to caching in a numerical or indexed format. + +Ignoring missing exceptions +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +By default an exception is thrown from the ``AnnotationReader`` if an +annotation was found that: + +- is not part of the list of ignored "documentation annotations"; +- was not imported through a use statement; +- is not a fully qualified class that exists. + +You can disable this behavior for specific names if your docblocks do +not follow strict requirements: + +.. code-block:: php + + $reader = new \Doctrine\Common\Annotations\AnnotationReader(); + AnnotationReader::addGlobalIgnoredName('foo'); + +PHP Imports +~~~~~~~~~~~ + +By default the annotation reader parses the use-statement of a php file +to gain access to the import rules and register them for the annotation +processing. Only if you are using PHP Imports can you validate the +correct usage of annotations and throw exceptions if you misspelled an +annotation. This mechanism is enabled by default. + +To ease the upgrade path, we still allow you to disable this mechanism. +Note however that we will remove this in future versions: + +.. code-block:: php + + $reader = new \Doctrine\Common\Annotations\AnnotationReader(); + $reader->setEnabledPhpImports(false); diff --git a/vendor/doctrine/annotations/docs/en/custom.rst b/vendor/doctrine/annotations/docs/en/custom.rst new file mode 100644 index 00000000000..300516625cc --- /dev/null +++ b/vendor/doctrine/annotations/docs/en/custom.rst @@ -0,0 +1,443 @@ +Custom Annotation Classes +========================= + +If you want to define your own annotations, you just have to group them +in a namespace. +Annotation classes have to contain a class-level docblock with the text +``@Annotation``: + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** @Annotation */ + class Bar + { + // some code + } + +Inject annotation values +------------------------ + +The annotation parser checks if the annotation constructor has arguments, +if so then it will pass the value array, otherwise it will try to inject +values into public properties directly: + + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** + * @Annotation + * + * Some Annotation using a constructor + */ + class Bar + { + private $foo; + + public function __construct(array $values) + { + $this->foo = $values['foo']; + } + } + + /** + * @Annotation + * + * Some Annotation without a constructor + */ + class Foo + { + public $bar; + } + +Optional: Constructors with Named Parameters +-------------------------------------------- + +Starting with Annotations v1.11 a new annotation instantiation strategy +is available that aims at compatibility of Annotation classes with the PHP 8 +attribute feature. You need to declare a constructor with regular parameter +names that match the named arguments in the annotation syntax. + +To enable this feature, you can tag your annotation class with +``@NamedArgumentConstructor`` (available from v1.12) or implement the +``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation`` interface +(available from v1.11 and deprecated as of v1.12). +When using the ``@NamedArgumentConstructor`` tag, the first argument of the +constructor is considered as the default one. + + +Usage with the ``@NamedArgumentConstructor`` tag + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** + * @Annotation + * @NamedArgumentConstructor + */ + class Bar implements NamedArgumentConstructorAnnotation + { + private $foo; + + public function __construct(string $foo) + { + $this->foo = $foo; + } + } + + /** Usable with @Bar(foo="baz") */ + /** Usable with @Bar("baz") */ + +In combination with PHP 8's constructor property promotion feature +you can simplify this to: + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** + * @Annotation + * @NamedArgumentConstructor + */ + class Bar implements NamedArgumentConstructorAnnotation + { + public function __construct(private string $foo) {} + } + + +Usage with the +``Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation`` +interface (v1.11, deprecated as of v1.12): +.. code-block:: php + + namespace MyCompany\Annotations; + + use Doctrine\Common\Annotations\NamedArgumentConstructorAnnotation; + + /** @Annotation */ + class Bar implements NamedArgumentConstructorAnnotation + { + private $foo; + + public function __construct(private string $foo) {} + } + + /** Usable with @Bar(foo="baz") */ + +Annotation Target +----------------- + +``@Target`` indicates the kinds of class elements to which an annotation +type is applicable. Then you could define one or more targets: + +- ``CLASS`` Allowed in class docblocks +- ``PROPERTY`` Allowed in property docblocks +- ``METHOD`` Allowed in the method docblocks +- ``FUNCTION`` Allowed in function dockblocks +- ``ALL`` Allowed in class, property, method and function docblocks +- ``ANNOTATION`` Allowed inside other annotations + +If the annotations is not allowed in the current context, an +``AnnotationException`` is thrown. + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** + * @Annotation + * @Target({"METHOD","PROPERTY"}) + */ + class Bar + { + // some code + } + + /** + * @Annotation + * @Target("CLASS") + */ + class Foo + { + // some code + } + +Attribute types +--------------- + +The annotation parser checks the given parameters using the phpdoc +annotation ``@var``, The data type could be validated using the ``@var`` +annotation on the annotation properties or using the ``@Attributes`` and +``@Attribute`` annotations. + +If the data type does not match you get an ``AnnotationException`` + +.. code-block:: php + + namespace MyCompany\Annotations; + + /** + * @Annotation + * @Target({"METHOD","PROPERTY"}) + */ + class Bar + { + /** @var mixed */ + public $mixed; + + /** @var boolean */ + public $boolean; + + /** @var bool */ + public $bool; + + /** @var float */ + public $float; + + /** @var string */ + public $string; + + /** @var integer */ + public $integer; + + /** @var array */ + public $array; + + /** @var SomeAnnotationClass */ + public $annotation; + + /** @var array */ + public $arrayOfIntegers; + + /** @var array */ + public $arrayOfAnnotations; + } + + /** + * @Annotation + * @Target({"METHOD","PROPERTY"}) + * @Attributes({ + * @Attribute("stringProperty", type = "string"), + * @Attribute("annotProperty", type = "SomeAnnotationClass"), + * }) + */ + class Foo + { + public function __construct(array $values) + { + $this->stringProperty = $values['stringProperty']; + $this->annotProperty = $values['annotProperty']; + } + + // some code + } + +Annotation Required +------------------- + +``@Required`` indicates that the field must be specified when the +annotation is used. If it is not used you get an ``AnnotationException`` +stating that this value can not be null. + +Declaring a required field: + +.. code-block:: php + + /** + * @Annotation + * @Target("ALL") + */ + class Foo + { + /** @Required */ + public $requiredField; + } + +Usage: + +.. code-block:: php + + /** @Foo(requiredField="value") */ + public $direction; // Valid + + /** @Foo */ + public $direction; // Required field missing, throws an AnnotationException + + +Enumerated values +----------------- + +- An annotation property marked with ``@Enum`` is a field that accepts a + fixed set of scalar values. +- You should use ``@Enum`` fields any time you need to represent fixed + values. +- The annotation parser checks the given value and throws an + ``AnnotationException`` if the value does not match. + + +Declaring an enumerated property: + +.. code-block:: php + + /** + * @Annotation + * @Target("ALL") + */ + class Direction + { + /** + * @Enum({"NORTH", "SOUTH", "EAST", "WEST"}) + */ + public $value; + } + +Annotation usage: + +.. code-block:: php + + /** @Direction("NORTH") */ + public $direction; // Valid value + + /** @Direction("NORTHEAST") */ + public $direction; // Invalid value, throws an AnnotationException + + +Constants +--------- + +The use of constants and class constants is available on the annotations +parser. + +The following usages are allowed: + +.. code-block:: php + + namespace MyCompany\Entity; + + use MyCompany\Annotations\Foo; + use MyCompany\Annotations\Bar; + use MyCompany\Entity\SomeClass; + + /** + * @Foo(PHP_EOL) + * @Bar(Bar::FOO) + * @Foo({SomeClass::FOO, SomeClass::BAR}) + * @Bar({SomeClass::FOO_KEY = SomeClass::BAR_VALUE}) + */ + class User + { + } + + +Be careful with constants and the cache ! + +.. note:: + + The cached reader will not re-evaluate each time an annotation is + loaded from cache. When a constant is changed the cache must be + cleaned. + + +Usage +----- + +Using the library API is simple. Using the annotations described in the +previous section, you can now annotate other classes with your +annotations: + +.. code-block:: php + + namespace MyCompany\Entity; + + use MyCompany\Annotations\Foo; + use MyCompany\Annotations\Bar; + + /** + * @Foo(bar="foo") + * @Bar(foo="bar") + */ + class User + { + } + +Now we can write a script to get the annotations above: + +.. code-block:: php + + $reflClass = new ReflectionClass('MyCompany\Entity\User'); + $classAnnotations = $reader->getClassAnnotations($reflClass); + + foreach ($classAnnotations AS $annot) { + if ($annot instanceof \MyCompany\Annotations\Foo) { + echo $annot->bar; // prints "foo"; + } else if ($annot instanceof \MyCompany\Annotations\Bar) { + echo $annot->foo; // prints "bar"; + } + } + +You have a complete API for retrieving annotation class instances from a +class, property or method docblock: + + +Reader API +~~~~~~~~~~ + +Access all annotations of a class +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getClassAnnotations(\ReflectionClass $class); + +Access one annotation of a class +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getClassAnnotation(\ReflectionClass $class, $annotationName); + +Access all annotations of a method +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getMethodAnnotations(\ReflectionMethod $method); + +Access one annotation of a method +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getMethodAnnotation(\ReflectionMethod $method, $annotationName); + +Access all annotations of a property +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getPropertyAnnotations(\ReflectionProperty $property); + +Access one annotation of a property +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getPropertyAnnotation(\ReflectionProperty $property, $annotationName); + +Access all annotations of a function +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getFunctionAnnotations(\ReflectionFunction $property); + +Access one annotation of a function +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. code-block:: php + + public function getFunctionAnnotation(\ReflectionFunction $property, $annotationName); diff --git a/vendor/doctrine/annotations/docs/en/index.rst b/vendor/doctrine/annotations/docs/en/index.rst new file mode 100644 index 00000000000..a6e33833352 --- /dev/null +++ b/vendor/doctrine/annotations/docs/en/index.rst @@ -0,0 +1,102 @@ +Deprecation notice +================== + +PHP 8 introduced `attributes +`_, +which are a native replacement for annotations. As such, this library is +considered feature complete, and should receive exclusively bugfixes and +security fixes. + +Introduction +============ + +Doctrine Annotations allows to implement custom annotation +functionality for PHP classes and functions. + +.. code-block:: php + + class Foo + { + /** + * @MyAnnotation(myProperty="value") + */ + private $bar; + } + +Annotations aren't implemented in PHP itself which is why this component +offers a way to use the PHP doc-blocks as a place for the well known +annotation syntax using the ``@`` char. + +Annotations in Doctrine are used for the ORM configuration to build the +class mapping, but it can be used in other projects for other purposes +too. + +Installation +============ + +You can install the Annotation component with composer: + +.. code-block:: + +   $ composer require doctrine/annotations + +Create an annotation class +========================== + +An annotation class is a representation of the later used annotation +configuration in classes. The annotation class of the previous example +looks like this: + +.. code-block:: php + + /** + * @Annotation + */ + final class MyAnnotation + { + public $myProperty; + } + +The annotation class is declared as an annotation by ``@Annotation``. + +:ref:`Read more about custom annotations. ` + +Reading annotations +=================== + +The access to the annotations happens by reflection of the class or function +containing them. There are multiple reader-classes implementing the +``Doctrine\Common\Annotations\Reader`` interface, that can access the +annotations of a class. A common one is +``Doctrine\Common\Annotations\AnnotationReader``: + +.. code-block:: php + + use Doctrine\Common\Annotations\AnnotationReader; + + $reflectionClass = new ReflectionClass(Foo::class); + $property = $reflectionClass->getProperty('bar'); + + $reader = new AnnotationReader(); + $myAnnotation = $reader->getPropertyAnnotation( + $property, + MyAnnotation::class + ); + + echo $myAnnotation->myProperty; // result: "value" + +A reader has multiple methods to access the annotations of a class or +function. + +:ref:`Read more about handling annotations. ` + +IDE Support +----------- + +Some IDEs already provide support for annotations: + +- Eclipse via the `Symfony2 Plugin `_ +- PhpStorm via the `PHP Annotations Plugin `_ or the `Symfony Plugin `_ + +.. _Read more about handling annotations.: annotations +.. _Read more about custom annotations.: custom diff --git a/vendor/doctrine/annotations/docs/en/sidebar.rst b/vendor/doctrine/annotations/docs/en/sidebar.rst new file mode 100644 index 00000000000..6f5d13c46ab --- /dev/null +++ b/vendor/doctrine/annotations/docs/en/sidebar.rst @@ -0,0 +1,6 @@ +.. toctree:: + :depth: 3 + + index + annotations + custom diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php new file mode 100644 index 00000000000..ee341756fad --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation.php @@ -0,0 +1,45 @@ + $data Key-value for properties to be defined in this class. */ + public final function __construct(array $data) + { + foreach ($data as $key => $value) { + $this->{$key} = $value; + } + } + /** + * Error handler for unknown property accessor in Annotation class. + * + * @throws BadMethodCallException + */ + public function __get(string $name) + { + throw new BadMethodCallException(sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)); + } + /** + * Error handler for unknown property mutator in Annotation class. + * + * @param mixed $value Property value. + * + * @throws BadMethodCallException + */ + public function __set(string $name, $value) + { + throw new BadMethodCallException(sprintf("Unknown property '%s' on annotation '%s'.", $name, static::class)); + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php new file mode 100644 index 00000000000..021c22cea08 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Attribute.php @@ -0,0 +1,19 @@ + */ + public $value; +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php new file mode 100644 index 00000000000..bf84e61208f --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/Enum.php @@ -0,0 +1,55 @@ + */ + public $value; + /** + * Literal target declaration. + * + * @var mixed[] + */ + public $literal; + /** + * @phpstan-param array{literal?: mixed[], value: list} $values + * + * @throws InvalidArgumentException + */ + public function __construct(array $values) + { + if (!isset($values['literal'])) { + $values['literal'] = []; + } + 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']; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php new file mode 100644 index 00000000000..8e42b092476 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/IgnoreAnnotation.php @@ -0,0 +1,35 @@ + */ + public $names; + /** + * @phpstan-param array{value: string|list} $values + * + * @throws RuntimeException + */ + public function __construct(array $values) + { + if (is_string($values['value'])) { + $values['value'] = [$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']; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php new file mode 100644 index 00000000000..2ed2528d047 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Annotation/NamedArgumentConstructor.php @@ -0,0 +1,13 @@ + */ + private static $map = ['ALL' => self::TARGET_ALL, 'CLASS' => self::TARGET_CLASS, 'METHOD' => self::TARGET_METHOD, 'PROPERTY' => self::TARGET_PROPERTY, 'FUNCTION' => self::TARGET_FUNCTION, 'ANNOTATION' => self::TARGET_ANNOTATION]; + /** @phpstan-var list */ + public $value; + /** + * Targets as bitmask. + * + * @var int + */ + public $targets; + /** + * Literal target declaration. + * + * @var string + */ + public $literal; + /** + * @phpstan-param array{value?: string|list} $values + * + * @throws InvalidArgumentException + */ + public function __construct(array $values) + { + if (!isset($values['value'])) { + $values['value'] = null; + } + if (is_string($values['value'])) { + $values['value'] = [$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); + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php new file mode 100644 index 00000000000..fe91206ed7a --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationException.php @@ -0,0 +1,105 @@ + $available + * + * @return AnnotationException + */ + public static function enumeratorError(string $attributeName, string $annotationName, string $context, array $available, $given) + { + return new self(sprintf('[Enum Error] Attribute "%s" of @%s declared on %s accepts only [%s], but got %s.', $attributeName, $annotationName, $context, implode(', ', $available), is_object($given) ? get_class($given) : $given)); + } + /** @return AnnotationException */ + public static function optimizerPlusSaveComments() + { + return new self('You have to enable opcache.save_comments=1 or zend_optimizerplus.save_comments=1.'); + } + /** @return AnnotationException */ + public static function optimizerPlusLoadComments() + { + return new self('You have to enable opcache.load_comments=1 or zend_optimizerplus.load_comments=1.'); + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php new file mode 100644 index 00000000000..c3d03625cb5 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationReader.php @@ -0,0 +1,305 @@ + + */ + private static $globalImports = ['ignoreannotation' => Annotation\IgnoreAnnotation::class]; + /** + * A list with annotations that are not causing exceptions when not resolved to an annotation class. + * + * The names are case sensitive. + * + * @var array + */ + private static $globalIgnoredNames = ImplicitlyIgnoredAnnotationNames::LIST; + /** + * A list with annotations that are not causing exceptions when not resolved to an annotation class. + * + * The names are case sensitive. + * + * @var array + */ + private static $globalIgnoredNamespaces = []; + /** + * Add a new annotation to the globally ignored annotation names with regard to exception handling. + */ + public static function addGlobalIgnoredName(string $name) + { + self::$globalIgnoredNames[$name] = \true; + } + /** + * Add a new annotation to the globally ignored annotation namespaces with regard to exception handling. + */ + public static function addGlobalIgnoredNamespace(string $namespace) + { + self::$globalIgnoredNamespaces[$namespace] = \true; + } + /** + * Annotations parser. + * + * @var DocParser + */ + private $parser; + /** + * Annotations parser used to collect parsing metadata. + * + * @var DocParser + */ + private $preParser; + /** + * PHP parser used to collect imports. + * + * @var PhpParser + */ + private $phpParser; + /** + * In-memory cache mechanism to store imported annotations per class. + * + * @psalm-var array<'class'|'function', array>> + */ + private $imports = []; + /** + * In-memory cache mechanism to store ignored annotations per class. + * + * @psalm-var array<'class'|'function', array>> + */ + private $ignoredAnnotationNames = []; + /** + * Initializes a new AnnotationReader. + * + * @throws AnnotationException + */ + 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(); + } + // Make sure that the IgnoreAnnotation annotation is loaded + class_exists(IgnoreAnnotation::class); + $this->parser = $parser ?: new DocParser(); + $this->preParser = new DocParser(); + $this->preParser->setImports(self::$globalImports); + $this->preParser->setIgnoreNotImportedAnnotations(\true); + $this->preParser->setIgnoredAnnotationNames(self::$globalIgnoredNames); + $this->phpParser = new PhpParser(); + } + /** + * {@inheritDoc} + */ + public function getClassAnnotations(ReflectionClass $class) + { + $this->parser->setTarget(Target::TARGET_CLASS); + $this->parser->setImports($this->getImports($class)); + $this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($class)); + $this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces); + return $this->parser->parse($class->getDocComment(), 'class ' . $class->getName()); + } + /** + * {@inheritDoc} + */ + public function getClassAnnotation(ReflectionClass $class, $annotationName) + { + $annotations = $this->getClassAnnotations($class); + foreach ($annotations as $annotation) { + if ($annotation instanceof $annotationName) { + return $annotation; + } + } + return null; + } + /** + * {@inheritDoc} + */ + 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); + } + /** + * {@inheritDoc} + */ + public function getPropertyAnnotation(ReflectionProperty $property, $annotationName) + { + $annotations = $this->getPropertyAnnotations($property); + foreach ($annotations as $annotation) { + if ($annotation instanceof $annotationName) { + return $annotation; + } + } + return null; + } + /** + * {@inheritDoc} + */ + 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); + } + /** + * {@inheritDoc} + */ + public function getMethodAnnotation(ReflectionMethod $method, $annotationName) + { + $annotations = $this->getMethodAnnotations($method); + foreach ($annotations as $annotation) { + if ($annotation instanceof $annotationName) { + return $annotation; + } + } + return null; + } + /** + * Gets the annotations applied to a function. + * + * @phpstan-return list An array of Annotations. + */ + public function getFunctionAnnotations(ReflectionFunction $function) : array + { + $context = 'function ' . $function->getName(); + $this->parser->setTarget(Target::TARGET_FUNCTION); + $this->parser->setImports($this->getImports($function)); + $this->parser->setIgnoredAnnotationNames($this->getIgnoredAnnotationNames($function)); + $this->parser->setIgnoredAnnotationNamespaces(self::$globalIgnoredNamespaces); + return $this->parser->parse($function->getDocComment(), $context); + } + /** + * Gets a function annotation. + * + * @return object|null The Annotation or NULL, if the requested annotation does not exist. + */ + public function getFunctionAnnotation(ReflectionFunction $function, string $annotationName) + { + $annotations = $this->getFunctionAnnotations($function); + foreach ($annotations as $annotation) { + if ($annotation instanceof $annotationName) { + return $annotation; + } + } + return null; + } + /** + * Returns the ignored annotations for the given class or function. + * + * @param ReflectionClass|ReflectionFunction $reflection + * + * @return array + */ + private function getIgnoredAnnotationNames($reflection) : array + { + $type = $reflection instanceof ReflectionClass ? 'class' : 'function'; + $name = $reflection->getName(); + if (isset($this->ignoredAnnotationNames[$type][$name])) { + return $this->ignoredAnnotationNames[$type][$name]; + } + $this->collectParsingMetadata($reflection); + return $this->ignoredAnnotationNames[$type][$name]; + } + /** + * Retrieves imports for a class or a function. + * + * @param ReflectionClass|ReflectionFunction $reflection + * + * @return array + */ + private function getImports($reflection) : array + { + $type = $reflection instanceof ReflectionClass ? 'class' : 'function'; + $name = $reflection->getName(); + if (isset($this->imports[$type][$name])) { + return $this->imports[$type][$name]; + } + $this->collectParsingMetadata($reflection); + return $this->imports[$type][$name]; + } + /** + * Retrieves imports for methods. + * + * @return array + */ + private function getMethodImports(ReflectionMethod $method) + { + $class = $method->getDeclaringClass(); + $classImports = $this->getImports($class); + $traitImports = []; + foreach ($class->getTraits() as $trait) { + if (!$trait->hasMethod($method->getName()) || $trait->getFileName() !== $method->getFileName()) { + continue; + } + $traitImports = array_merge($traitImports, $this->phpParser->parseUseStatements($trait)); + } + return array_merge($classImports, $traitImports); + } + /** + * Retrieves imports for properties. + * + * @return array + */ + private function getPropertyImports(ReflectionProperty $property) + { + $class = $property->getDeclaringClass(); + $classImports = $this->getImports($class); + $traitImports = []; + foreach ($class->getTraits() as $trait) { + if (!$trait->hasProperty($property->getName())) { + continue; + } + $traitImports = array_merge($traitImports, $this->phpParser->parseUseStatements($trait)); + } + return array_merge($classImports, $traitImports); + } + /** + * Collects parsing metadata for a given class or function. + * + * @param ReflectionClass|ReflectionFunction $reflection + */ + private function collectParsingMetadata($reflection) : void + { + $type = $reflection instanceof ReflectionClass ? 'class' : 'function'; + $name = $reflection->getName(); + $ignoredAnnotationNames = self::$globalIgnoredNames; + $annotations = $this->preParser->parse($reflection->getDocComment(), $type . ' ' . $name); + foreach ($annotations as $annotation) { + if (!$annotation instanceof IgnoreAnnotation) { + continue; + } + foreach ($annotation->names as $annot) { + $ignoredAnnotationNames[$annot] = \true; + } + } + $this->imports[$type][$name] = array_merge(self::$globalImports, $this->phpParser->parseUseStatements($reflection), ['__NAMESPACE__' => $reflection->getNamespaceName(), 'self' => $name]); + $this->ignoredAnnotationNames[$type][$name] = $ignoredAnnotationNames; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php new file mode 100644 index 00000000000..930d09726ca --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/AnnotationRegistry.php @@ -0,0 +1,36 @@ + + */ +final class DocLexer extends AbstractLexer +{ + public const T_NONE = 1; + public const T_INTEGER = 2; + public const T_STRING = 3; + public const T_FLOAT = 4; + // All tokens that are also identifiers should be >= 100 + public const T_IDENTIFIER = 100; + public const T_AT = 101; + public const T_CLOSE_CURLY_BRACES = 102; + public const T_CLOSE_PARENTHESIS = 103; + public const T_COMMA = 104; + public const T_EQUALS = 105; + public const T_FALSE = 106; + public const T_NAMESPACE_SEPARATOR = 107; + public const T_OPEN_CURLY_BRACES = 108; + public const T_OPEN_PARENTHESIS = 109; + public const T_TRUE = 110; + public const T_NULL = 111; + public const T_COLON = 112; + public const T_MINUS = 113; + /** @var array */ + protected $noCase = ['@' => 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_MINUS, '\\' => self::T_NAMESPACE_SEPARATOR]; + /** @var array */ + protected $withCase = ['true' => self::T_TRUE, 'false' => self::T_FALSE, 'null' => self::T_NULL]; + /** + * Whether the next token starts immediately, or if there were + * non-captured symbols before that + */ + public function nextTokenIsAdjacent() : bool + { + return $this->token === null || $this->lookahead !== null && $this->lookahead->position - $this->token->position === strlen($this->token->value); + } + /** + * {@inheritdoc} + */ + protected function getCatchablePatterns() + { + return ['[a-z_\\\\][a-z0-9_\\:\\\\]*[a-z_][a-z0-9_]*', '(?:[+-]?[0-9]+(?:[\\.][0-9]+)*)(?:[eE][+-]?[0-9]+)?', '"(?:""|[^"])*+"']; + } + /** + * {@inheritdoc} + */ + protected function getNonCatchablePatterns() + { + return ['\\s+', '\\*+', '(.)']; + } + /** + * {@inheritdoc} + */ + 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]; + } + // Checking numeric value + if (is_numeric($value)) { + return strpos($value, '.') !== \false || stripos($value, 'e') !== \false ? self::T_FLOAT : self::T_INTEGER; + } + return $type; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php new file mode 100644 index 00000000000..02d56d05761 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/DocParser.php @@ -0,0 +1,1040 @@ + + */ + private static $classIdentifiers = [DocLexer::T_IDENTIFIER, DocLexer::T_TRUE, DocLexer::T_FALSE, DocLexer::T_NULL]; + /** + * The lexer. + * + * @var DocLexer + */ + private $lexer; + /** + * Current target context. + * + * @var int + */ + private $target; + /** + * Doc parser used to collect annotation target. + * + * @var DocParser + */ + private static $metadataParser; + /** + * Flag to control if the current annotation is nested or not. + * + * @var bool + */ + private $isNestedAnnotation = \false; + /** + * Hashmap containing all use-statements that are to be used when parsing + * the given doc block. + * + * @var array + */ + private $imports = []; + /** + * This hashmap is used internally to cache results of class_exists() + * look-ups. + * + * @var array + */ + private $classExists = []; + /** + * Whether annotations that have not been imported should be ignored. + * + * @var bool + */ + private $ignoreNotImportedAnnotations = \false; + /** + * An array of default namespaces if operating in simple mode. + * + * @var string[] + */ + private $namespaces = []; + /** + * A list with annotations that are not causing exceptions when not resolved to an annotation class. + * + * The names must be the raw names as used in the class, not the fully qualified + * + * @var bool[] indexed by annotation name + */ + private $ignoredAnnotationNames = []; + /** + * A list with annotations in namespaced format + * that are not causing exceptions when not resolved to an annotation class. + * + * @var bool[] indexed by namespace name + */ + private $ignoredAnnotationNamespaces = []; + /** @var string */ + private $context = ''; + /** + * Hash-map for caching annotation metadata. + * + * @var array + */ + private static $annotationMetadata = [Annotation\Target::class => ['is_annotation' => \true, 'has_constructor' => \true, 'has_named_argument_constructor' => \false, 'properties' => [], 'targets_literal' => 'ANNOTATION_CLASS', 'targets' => Target::TARGET_CLASS, 'default_property' => 'value', 'attribute_types' => ['value' => ['required' => \false, 'type' => 'array', 'array_type' => 'string', 'value' => 'array']]], Annotation\Attribute::class => ['is_annotation' => \true, 'has_constructor' => \false, 'has_named_argument_constructor' => \false, 'targets_literal' => 'ANNOTATION_ANNOTATION', 'targets' => Target::TARGET_ANNOTATION, 'default_property' => 'name', 'properties' => ['name' => 'name', 'type' => 'type', 'required' => 'required'], 'attribute_types' => ['value' => ['required' => \true, 'type' => 'string', 'value' => 'string'], 'type' => ['required' => \true, 'type' => 'string', 'value' => 'string'], 'required' => ['required' => \false, 'type' => 'boolean', 'value' => 'boolean']]], Annotation\Attributes::class => ['is_annotation' => \true, 'has_constructor' => \false, 'has_named_argument_constructor' => \false, 'targets_literal' => 'ANNOTATION_CLASS', 'targets' => Target::TARGET_CLASS, 'default_property' => 'value', 'properties' => ['value' => 'value'], 'attribute_types' => ['value' => ['type' => 'array', 'required' => \true, 'array_type' => Annotation\Attribute::class, 'value' => 'array<' . Annotation\Attribute::class . '>']]], Annotation\Enum::class => ['is_annotation' => \true, 'has_constructor' => \true, 'has_named_argument_constructor' => \false, 'targets_literal' => 'ANNOTATION_PROPERTY', 'targets' => Target::TARGET_PROPERTY, 'default_property' => 'value', 'properties' => ['value' => 'value'], 'attribute_types' => ['value' => ['type' => 'array', 'required' => \true], 'literal' => ['type' => 'array', 'required' => \false]]], Annotation\NamedArgumentConstructor::class => ['is_annotation' => \true, 'has_constructor' => \false, 'has_named_argument_constructor' => \false, 'targets_literal' => 'ANNOTATION_CLASS', 'targets' => Target::TARGET_CLASS, 'default_property' => null, 'properties' => [], 'attribute_types' => []]]; + /** + * Hash-map for handle types declaration. + * + * @var array + */ + private static $typeMap = [ + 'float' => 'double', + 'bool' => 'boolean', + // allow uppercase Boolean in honor of George Boole + 'Boolean' => 'boolean', + 'int' => 'integer', + ]; + /** + * Constructs a new DocParser. + */ + public function __construct() + { + $this->lexer = new DocLexer(); + } + /** + * Sets the annotation names that are ignored during the parsing process. + * + * The names are supposed to be the raw names as used in the class, not the + * fully qualified class names. + * + * @param bool[] $names indexed by annotation name + * + * @return void + */ + public function setIgnoredAnnotationNames(array $names) + { + $this->ignoredAnnotationNames = $names; + } + /** + * Sets the annotation namespaces that are ignored during the parsing process. + * + * @param bool[] $ignoredAnnotationNamespaces indexed by annotation namespace name + * + * @return void + */ + public function setIgnoredAnnotationNamespaces(array $ignoredAnnotationNamespaces) + { + $this->ignoredAnnotationNamespaces = $ignoredAnnotationNamespaces; + } + /** + * Sets ignore on not-imported annotations. + * + * @return void + */ + public function setIgnoreNotImportedAnnotations(bool $bool) + { + $this->ignoreNotImportedAnnotations = $bool; + } + /** + * Sets the default namespaces. + * + * @return void + * + * @throws RuntimeException + */ + public function addNamespace(string $namespace) + { + if ($this->imports) { + throw new RuntimeException('You must either use addNamespace(), or setImports(), but not both.'); + } + $this->namespaces[] = $namespace; + } + /** + * Sets the imports. + * + * @param array $imports + * + * @return void + * + * @throws RuntimeException + */ + public function setImports(array $imports) + { + if ($this->namespaces) { + throw new RuntimeException('You must either use addNamespace(), or setImports(), but not both.'); + } + $this->imports = $imports; + } + /** + * Sets current target context as bitmask. + * + * @return void + */ + public function setTarget(int $target) + { + $this->target = $target; + } + /** + * Parses the given docblock string for annotations. + * + * @phpstan-return list Array of annotations. If no annotations are found, an empty array is returned. + * + * @throws AnnotationException + * @throws ReflectionException + */ + public function parse(string $input, string $context = '') + { + $pos = $this->findInitialTokenPosition($input); + if ($pos === null) { + return []; + } + $this->context = $context; + $this->lexer->setInput(trim(substr($input, $pos), '* /')); + $this->lexer->moveNext(); + return $this->Annotations(); + } + /** + * Finds the first valid annotation + */ + private function findInitialTokenPosition(string $input) : ?int + { + $pos = 0; + // search for first valid annotation + while (($pos = strpos($input, '@', $pos)) !== \false) { + $preceding = substr($input, $pos - 1, 1); + // if the @ is preceded by a space, a tab or * it is valid + if ($pos === 0 || $preceding === ' ' || $preceding === '*' || $preceding === "\t") { + return $pos; + } + $pos++; + } + return null; + } + /** + * Attempts to match the given token with the current lookahead token. + * If they match, updates the lookahead token; otherwise raises a syntax error. + * + * @param int $token Type of token. + * + * @return bool True if tokens match; false otherwise. + * + * @throws AnnotationException + */ + private function match(int $token) : bool + { + if (!$this->lexer->isNextToken($token)) { + throw $this->syntaxError($this->lexer->getLiteral($token)); + } + return $this->lexer->moveNext(); + } + /** + * Attempts to match the current lookahead token with any of the given tokens. + * + * If any of them matches, this method updates the lookahead token; otherwise + * a syntax error is raised. + * + * @phpstan-param list $tokens + * + * @throws AnnotationException + */ + private function matchAny(array $tokens) : bool + { + if (!$this->lexer->isNextTokenAny($tokens)) { + throw $this->syntaxError(implode(' or ', array_map([$this->lexer, 'getLiteral'], $tokens))); + } + return $this->lexer->moveNext(); + } + /** + * Generates a new syntax error. + * + * @param string $expected Expected string. + * @param mixed[]|null $token Optional token. + */ + private function syntaxError(string $expected, ?array $token = null) : AnnotationException + { + 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 .= '.'; + return AnnotationException::syntaxError($message); + } + /** + * Attempts to check if a class exists or not. This never goes through the PHP autoloading mechanism + * but uses the {@link AnnotationRegistry} to load classes. + * + * @param class-string $fqcn + */ + private function classExists(string $fqcn) : bool + { + if (isset($this->classExists[$fqcn])) { + return $this->classExists[$fqcn]; + } + // first check if the class already exists, maybe loaded through another AnnotationReader + if (class_exists($fqcn, \false)) { + return $this->classExists[$fqcn] = \true; + } + // final check, does this class exist? + return $this->classExists[$fqcn] = AnnotationRegistry::loadAnnotationClass($fqcn); + } + /** + * Collects parsing metadata for a given annotation class + * + * @param class-string $name The annotation name + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function collectAnnotationMetadata(string $name) : void + { + if (self::$metadataParser === null) { + self::$metadataParser = new self(); + self::$metadataParser->setIgnoreNotImportedAnnotations(\true); + self::$metadataParser->setIgnoredAnnotationNames($this->ignoredAnnotationNames); + self::$metadataParser->setImports(['enum' => Enum::class, 'target' => Target::class, 'attribute' => Attribute::class, 'attributes' => Attributes::class, 'namedargumentconstructor' => NamedArgumentConstructor::class]); + // Make sure that annotations from metadata are loaded + class_exists(Enum::class); + class_exists(Target::class); + class_exists(Attribute::class); + class_exists(Attributes::class); + class_exists(NamedArgumentConstructor::class); + } + $class = new ReflectionClass($name); + $docComment = $class->getDocComment(); + // Sets default values for annotation metadata + $constructor = $class->getConstructor(); + $metadata = ['default_property' => null, 'has_constructor' => $constructor !== null && $constructor->getNumberOfParameters() > 0, 'constructor_args' => [], 'properties' => [], 'property_types' => [], 'attribute_types' => [], 'targets_literal' => null, 'targets' => Target::TARGET_ALL, 'is_annotation' => strpos($docComment, '@Annotation') !== \false]; + $metadata['has_named_argument_constructor'] = \false; + // verify that the class is really meant to be an 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 NamedArgumentConstructor) { + $metadata['has_named_argument_constructor'] = $metadata['has_constructor']; + if ($metadata['has_named_argument_constructor']) { + // choose the first argument as the default property + $metadata['default_property'] = $constructor->getParameters()[0]->getName(); + } + } + if (!$annotation instanceof Attributes) { + continue; + } + foreach ($annotation->value as $attribute) { + $this->collectAttributeTypeMetadata($metadata, $attribute); + } + } + // if not has a constructor will inject values into public properties + if ($metadata['has_constructor'] === \false) { + // collect all public properties + foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + $metadata['properties'][$property->name] = $property->name; + $propertyComment = $property->getDocComment(); + if ($propertyComment === \false) { + continue; + } + $attribute = new Attribute(); + $attribute->required = strpos($propertyComment, '@Required') !== \false; + $attribute->name = $property->name; + $attribute->type = strpos($propertyComment, '@var') !== \false && preg_match('/@var\\s+([^\\s]+)/', $propertyComment, $matches) ? $matches[1] : 'mixed'; + $this->collectAttributeTypeMetadata($metadata, $attribute); + // checks if the property has @Enum + if (strpos($propertyComment, '@Enum') === \false) { + continue; + } + $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; + } + } + // choose the first property as default property + $metadata['default_property'] = reset($metadata['properties']); + } elseif ($metadata['has_named_argument_constructor']) { + foreach ($constructor->getParameters() as $parameter) { + if ($parameter->isVariadic()) { + break; + } + $metadata['constructor_args'][$parameter->getName()] = ['position' => $parameter->getPosition(), 'default' => $parameter->isOptional() ? $parameter->getDefaultValue() : null]; + } + } + } + self::$annotationMetadata[$name] = $metadata; + } + /** + * Collects parsing metadata for a given attribute. + * + * @param mixed[] $metadata + */ + private function collectAttributeTypeMetadata(array &$metadata, Attribute $attribute) : void + { + // handle internal type declaration + $type = self::$typeMap[$attribute->type] ?? $attribute->type; + // handle the case if the property type is mixed + if ($type === 'mixed') { + return; + } + // Evaluate type + $pos = strpos($type, '<'); + if ($pos !== \false) { + // Checks if the property has array + $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; + } else { + // Checks if the property has type[] + $pos = strrpos($type, '['); + if ($pos !== \false) { + $arrayType = substr($type, 0, $pos); + $type = 'array'; + if (isset(self::$typeMap[$arrayType])) { + $arrayType = self::$typeMap[$arrayType]; + } + $metadata['attribute_types'][$attribute->name]['array_type'] = $arrayType; + } + } + $metadata['attribute_types'][$attribute->name]['type'] = $type; + $metadata['attribute_types'][$attribute->name]['value'] = $attribute->type; + $metadata['attribute_types'][$attribute->name]['required'] = $attribute->required; + } + /** + * Annotations ::= Annotation {[ "*" ]* [Annotation]}* + * + * @phpstan-return list + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function Annotations() : array + { + $annotations = []; + while ($this->lexer->lookahead !== null) { + if ($this->lexer->lookahead->type !== DocLexer::T_AT) { + $this->lexer->moveNext(); + continue; + } + // make sure the @ is preceded by non-catchable pattern + if ($this->lexer->token !== null && $this->lexer->lookahead->position === $this->lexer->token->position + strlen($this->lexer->token->value)) { + $this->lexer->moveNext(); + continue; + } + // make sure the @ is followed by either a namespace separator, or + // an identifier token + $peek = $this->lexer->glimpse(); + if ($peek === null || $peek->type !== DocLexer::T_NAMESPACE_SEPARATOR && !in_array($peek->type, self::$classIdentifiers, \true) || $peek->position !== $this->lexer->lookahead->position + 1) { + $this->lexer->moveNext(); + continue; + } + $this->isNestedAnnotation = \false; + $annot = $this->Annotation(); + if ($annot === \false) { + continue; + } + $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 object|false False if it is not a valid annotation. + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function Annotation() + { + $this->match(DocLexer::T_AT); + // check if we have an annotation + $name = $this->Identifier(); + if ($this->lexer->isNextToken(DocLexer::T_MINUS) && $this->lexer->nextTokenIsAdjacent()) { + // Annotations with dashes, such as "@foo-" or "@foo-bar", are to be discarded + return \false; + } + // only process names which are not fully qualified, yet + // fully qualified names must start with a \ + $originalName = $name; + if ($name[0] !== '\\') { + $pos = strpos($name, '\\'); + $alias = $pos === \false ? $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])) { + $namespace = ltrim($this->imports[$loweredAlias], '\\'); + $name = $pos !== \false ? $namespace . substr($name, $pos) : $namespace; + $found = $this->classExists($name); + } 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(<<<'EXCEPTION' +The annotation "@%s" in %s was never imported. Did you maybe forget to add a "use" statement for this annotation? +EXCEPTION +, $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)); + } + // at this point, $name contains the fully qualified class name of the + // annotation, and it is also guaranteed that this class exists, and + // that it is loaded + // collects the metadata annotation only if there is not yet + if (!isset(self::$annotationMetadata[$name])) { + $this->collectAnnotationMetadata($name); + } + // verify that the class is really meant to be an annotation and not just any ordinary class + if (self::$annotationMetadata[$name]['is_annotation'] === \false) { + if ($this->isIgnoredAnnotation($originalName) || $this->isIgnoredAnnotation($name)) { + return \false; + } + throw AnnotationException::semanticalError(sprintf(<<<'EXCEPTION' +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. +EXCEPTION +, $name, $name, $originalName, $this->context)); + } + //if target is nested annotation + $target = $this->isNestedAnnotation ? Target::TARGET_ANNOTATION : $this->target; + // Next will be nested + $this->isNestedAnnotation = \true; + //if annotation does not support current target + if ((self::$annotationMetadata[$name]['targets'] & $target) === 0 && $target) { + throw AnnotationException::semanticalError(sprintf(<<<'EXCEPTION' +Annotation @%s is not allowed to be declared on %s. You may only use this annotation on these code elements: %s. +EXCEPTION +, $originalName, $this->context, self::$annotationMetadata[$name]['targets_literal'])); + } + $arguments = $this->MethodCall(); + $values = $this->resolvePositionalValues($arguments, $name); + if (isset(self::$annotationMetadata[$name]['enum'])) { + // checks all declared attributes + foreach (self::$annotationMetadata[$name]['enum'] as $property => $enum) { + // checks if the attribute is a valid enumerator + if (isset($values[$property]) && !in_array($values[$property], $enum['value'])) { + throw AnnotationException::enumeratorError($property, $name, $this->context, $enum['literal'], $values[$property]); + } + } + } + // checks all declared attributes + foreach (self::$annotationMetadata[$name]['attribute_types'] as $property => $type) { + if ($property === self::$annotationMetadata[$name]['default_property'] && !isset($values[$property]) && isset($values['value'])) { + $property = 'value'; + } + // handle a not given attribute or null value + if (!isset($values[$property])) { + if ($type['required']) { + throw AnnotationException::requiredError($property, $originalName, $this->context, 'a(n) ' . $type['value']); + } + continue; + } + if ($type['type'] === 'array') { + // handle the case of a single value + if (!is_array($values[$property])) { + $values[$property] = [$values[$property]]; + } + // checks if the attribute has array type declaration, such as "array" + 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_named_argument_constructor']) { + if (PHP_VERSION_ID >= 80000) { + foreach ($values as $property => $value) { + if (!isset(self::$annotationMetadata[$name]['constructor_args'][$property])) { + throw AnnotationException::creationError(sprintf(<<<'EXCEPTION' +The annotation @%s declared on %s does not have a property named "%s" +that can be set through its named arguments constructor. +Available named arguments: %s +EXCEPTION +, $originalName, $this->context, $property, implode(', ', array_keys(self::$annotationMetadata[$name]['constructor_args'])))); + } + } + return $this->instantiateAnnotiation($originalName, $this->context, $name, $values); + } + $positionalValues = []; + foreach (self::$annotationMetadata[$name]['constructor_args'] as $property => $parameter) { + $positionalValues[$parameter['position']] = $parameter['default']; + } + foreach ($values as $property => $value) { + if (!isset(self::$annotationMetadata[$name]['constructor_args'][$property])) { + throw AnnotationException::creationError(sprintf(<<<'EXCEPTION' +The annotation @%s declared on %s does not have a property named "%s" +that can be set through its named arguments constructor. +Available named arguments: %s +EXCEPTION +, $originalName, $this->context, $property, implode(', ', array_keys(self::$annotationMetadata[$name]['constructor_args'])))); + } + $positionalValues[self::$annotationMetadata[$name]['constructor_args'][$property]['position']] = $value; + } + return $this->instantiateAnnotiation($originalName, $this->context, $name, $positionalValues); + } + // check if the annotation expects values via the constructor, + // or directly injected into public properties + if (self::$annotationMetadata[$name]['has_constructor'] === \true) { + return $this->instantiateAnnotiation($originalName, $this->context, $name, [$values]); + } + $instance = $this->instantiateAnnotiation($originalName, $this->context, $name, []); + foreach ($values as $property => $value) { + if (!isset(self::$annotationMetadata[$name]['properties'][$property])) { + if ($property !== 'value') { + throw AnnotationException::creationError(sprintf(<<<'EXCEPTION' +The annotation @%s declared on %s does not have a property named "%s". +Available properties: %s +EXCEPTION +, $originalName, $this->context, $property, implode(', ', self::$annotationMetadata[$name]['properties']))); + } + // handle the case if the property has no annotations + $property = self::$annotationMetadata[$name]['default_property']; + if (!$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; + } + /** + * MethodCall ::= ["(" [Values] ")"] + * + * @return mixed[] + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function MethodCall() : array + { + $values = []; + 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; + } + /** + * Values ::= Array | Value {"," Value}* [","] + * + * @return mixed[] + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function Values() : array + { + $values = [$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(); + $values[] = $value; + } + $namedArguments = []; + $positionalArguments = []; + foreach ($values as $k => $value) { + if (is_object($value) && $value instanceof stdClass) { + $namedArguments[$value->name] = $value->value; + } else { + $positionalArguments[$k] = $value; + } + } + return ['named_arguments' => $namedArguments, 'positional_arguments' => $positionalArguments]; + } + /** + * Constant ::= integer | string | float | boolean + * + * @return mixed + * + * @throws AnnotationException + */ + private function Constant() + { + $identifier = $this->Identifier(); + if (!defined($identifier) && strpos($identifier, '::') !== \false && $identifier[0] !== '\\') { + [$className, $const] = explode('::', $identifier); + $pos = strpos($className, '\\'); + $alias = $pos === \false ? $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 = $pos !== \false ? $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; + } + } + /** + * Checks if identifier ends with ::class and remove the leading backslash if it exists. + */ + if ($this->identifierEndsWithClassConstant($identifier) && !$this->identifierStartsWithBackslash($identifier)) { + return substr($identifier, 0, $this->getClassConstantPositionInIdentifier($identifier)); + } + if ($this->identifierEndsWithClassConstant($identifier) && $this->identifierStartsWithBackslash($identifier)) { + return substr($identifier, 1, $this->getClassConstantPositionInIdentifier($identifier) - 1); + } + if (!defined($identifier)) { + throw AnnotationException::semanticalErrorConstants($identifier, $this->context); + } + return constant($identifier); + } + private function identifierStartsWithBackslash(string $identifier) : bool + { + return $identifier[0] === '\\'; + } + private function identifierEndsWithClassConstant(string $identifier) : bool + { + return $this->getClassConstantPositionInIdentifier($identifier) === strlen($identifier) - strlen('::class'); + } + /** @return int|false */ + private function getClassConstantPositionInIdentifier(string $identifier) + { + return stripos($identifier, '::class'); + } + /** + * Identifier ::= string + * + * @throws AnnotationException + */ + private function Identifier() : string + { + // check if we have an annotation + if (!$this->lexer->isNextTokenAny(self::$classIdentifiers)) { + throw $this->syntaxError('namespace separator or identifier'); + } + $this->lexer->moveNext(); + $className = $this->lexer->token->value; + while ($this->lexer->lookahead !== null && $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; + } + /** + * Value ::= PlainValue | FieldAssignment + * + * @return mixed + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function Value() + { + $peek = $this->lexer->glimpse(); + if ($peek->type === DocLexer::T_EQUALS) { + return $this->FieldAssignment(); + } + return $this->PlainValue(); + } + /** + * PlainValue ::= integer | string | float | boolean | Array | Annotation + * + * @return mixed + * + * @throws AnnotationException + * @throws ReflectionException + */ + 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: + throw $this->syntaxError('PlainValue'); + } + } + /** + * FieldAssignment ::= FieldName "=" PlainValue + * FieldName ::= identifier + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function FieldAssignment() : stdClass + { + $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; + } + /** + * Array ::= "{" ArrayEntry {"," ArrayEntry}* [","] "}" + * + * @return mixed[] + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function Arrayx() : array + { + $array = $values = []; + $this->match(DocLexer::T_OPEN_CURLY_BRACES); + // If the array is empty, stop parsing and return. + 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); + // optional trailing 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) { + [$key, $val] = $value; + if ($key !== null) { + $array[$key] = $val; + } else { + $array[] = $val; + } + } + return $array; + } + /** + * ArrayEntry ::= Value | KeyValuePair + * KeyValuePair ::= Key ("=" | ":") PlainValue | Constant + * Key ::= string | integer | Constant + * + * @phpstan-return array{mixed, mixed} + * + * @throws AnnotationException + * @throws ReflectionException + */ + private function ArrayEntry() : array + { + $peek = $this->lexer->glimpse(); + if ($peek->type === DocLexer::T_EQUALS || $peek->type === DocLexer::T_COLON) { + if ($this->lexer->isNextToken(DocLexer::T_IDENTIFIER)) { + $key = $this->Constant(); + } else { + $this->matchAny([DocLexer::T_INTEGER, DocLexer::T_STRING]); + $key = $this->lexer->token->value; + } + $this->matchAny([DocLexer::T_EQUALS, DocLexer::T_COLON]); + return [$key, $this->PlainValue()]; + } + return [null, $this->Value()]; + } + /** + * Checks whether the given $name matches any ignored annotation name or namespace + */ + private function isIgnoredAnnotation(string $name) : bool + { + if ($this->ignoreNotImportedAnnotations || isset($this->ignoredAnnotationNames[$name])) { + return \true; + } + foreach (array_keys($this->ignoredAnnotationNamespaces) as $ignoredAnnotationNamespace) { + $ignoredAnnotationNamespace = rtrim($ignoredAnnotationNamespace, '\\') . '\\'; + if (stripos(rtrim($name, '\\') . '\\', $ignoredAnnotationNamespace) === 0) { + return \true; + } + } + return \false; + } + /** + * Resolve positional arguments (without name) to named ones + * + * @param array $arguments + * + * @return array + */ + private function resolvePositionalValues(array $arguments, string $name) : array + { + $positionalArguments = $arguments['positional_arguments'] ?? []; + $values = $arguments['named_arguments'] ?? []; + if (self::$annotationMetadata[$name]['has_named_argument_constructor'] && self::$annotationMetadata[$name]['default_property'] !== null) { + // We must ensure that we don't have positional arguments after named ones + $positions = array_keys($positionalArguments); + $lastPosition = null; + foreach ($positions as $position) { + if ($lastPosition === null && $position !== 0 || $lastPosition !== null && $position !== $lastPosition + 1) { + throw $this->syntaxError('Positional arguments after named arguments is not allowed'); + } + $lastPosition = $position; + } + foreach (self::$annotationMetadata[$name]['constructor_args'] as $property => $parameter) { + $position = $parameter['position']; + if (isset($values[$property]) || !isset($positionalArguments[$position])) { + continue; + } + $values[$property] = $positionalArguments[$position]; + } + } else { + if (count($positionalArguments) > 0 && !isset($values['value'])) { + if (count($positionalArguments) === 1) { + $value = array_pop($positionalArguments); + } else { + $value = array_values($positionalArguments); + } + $values['value'] = $value; + } + } + return $values; + } + /** + * Try to instantiate the annotation and catch and process any exceptions related to failure + * + * @param class-string $name + * @param array $arguments + * + * @return object + * + * @throws AnnotationException + */ + private function instantiateAnnotiation(string $originalName, string $context, string $name, array $arguments) + { + try { + return new $name(...$arguments); + } catch (Throwable $exception) { + throw AnnotationException::creationError(sprintf('An error occurred while instantiating the annotation @%s declared on %s: "%s".', $originalName, $context, $exception->getMessage()), $exception); + } + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php new file mode 100644 index 00000000000..909cd5ab292 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/ImplicitlyIgnoredAnnotationNames.php @@ -0,0 +1,82 @@ + \true, + 'Attribute' => \true, + 'Attributes' => \true, + /* Can we enable this? 'Enum' => true, */ + 'Required' => \true, + 'Target' => \true, + 'NamedArgumentConstructor' => \true, + ]; + private const WidelyUsedNonStandard = ['fix' => \true, 'fixme' => \true, 'override' => \true]; + private const PhpDocumentor1 = ['abstract' => \true, 'access' => \true, 'code' => \true, 'deprec' => \true, 'endcode' => \true, 'exception' => \true, 'final' => \true, 'ingroup' => \true, 'inheritdoc' => \true, 'inheritDoc' => \true, 'magic' => \true, 'name' => \true, 'private' => \true, 'static' => \true, 'staticvar' => \true, 'staticVar' => \true, 'toc' => \true, 'tutorial' => \true, 'throw' => \true]; + private const PhpDocumentor2 = [ + 'api' => \true, + 'author' => \true, + 'category' => \true, + 'copyright' => \true, + 'deprecated' => \true, + 'example' => \true, + 'filesource' => \true, + 'global' => \true, + 'ignore' => \true, + /* Can we enable this? 'index' => 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, + ]; + private const PHPUnit = ['author' => \true, 'after' => \true, 'afterClass' => \true, 'backupGlobals' => \true, 'backupStaticAttributes' => \true, 'before' => \true, 'beforeClass' => \true, 'codeCoverageIgnore' => \true, 'codeCoverageIgnoreStart' => \true, 'codeCoverageIgnoreEnd' => \true, 'covers' => \true, 'coversDefaultClass' => \true, 'coversNothing' => \true, 'dataProvider' => \true, 'depends' => \true, 'doesNotPerformAssertions' => \true, 'expectedException' => \true, 'expectedExceptionCode' => \true, 'expectedExceptionMessage' => \true, 'expectedExceptionMessageRegExp' => \true, 'group' => \true, 'large' => \true, 'medium' => \true, 'preserveGlobalState' => \true, 'requires' => \true, 'runTestsInSeparateProcesses' => \true, 'runInSeparateProcess' => \true, 'small' => \true, 'test' => \true, 'testdox' => \true, 'testWith' => \true, 'ticket' => \true, 'uses' => \true]; + private const PhpCheckStyle = ['SuppressWarnings' => \true]; + private const PhpStorm = ['noinspection' => \true]; + private const PEAR = ['package_version' => \true]; + private const PlainUML = ['startuml' => \true, 'enduml' => \true]; + private const Symfony = ['experimental' => \true]; + private const PhpCodeSniffer = ['codingStandardsIgnoreStart' => \true, 'codingStandardsIgnoreEnd' => \true]; + private const SlevomatCodingStandard = ['phpcsSuppress' => \true]; + private const Phan = ['suppress' => \true]; + private const Rector = ['noRector' => \true]; + private const StaticAnalysis = [ + // PHPStan, Psalm + 'extends' => \true, + 'implements' => \true, + 'readonly' => \true, + 'template' => \true, + 'use' => \true, + // Psalm + 'pure' => \true, + 'immutable' => \true, + ]; + public const LIST = self::Reserved + self::WidelyUsedNonStandard + self::PhpDocumentor1 + self::PhpDocumentor2 + self::PHPUnit + self::PhpCheckStyle + self::PhpStorm + self::PEAR + self::PlainUML + self::Symfony + self::SlevomatCodingStandard + self::PhpCodeSniffer + self::Phan + self::Rector + self::StaticAnalysis; + private function __construct() + { + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php new file mode 100644 index 00000000000..b9d7a9e57e8 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/IndexedReader.php @@ -0,0 +1,86 @@ +delegate = $reader; + } + /** + * {@inheritDoc} + */ + public function getClassAnnotations(ReflectionClass $class) + { + $annotations = []; + foreach ($this->delegate->getClassAnnotations($class) as $annot) { + $annotations[get_class($annot)] = $annot; + } + return $annotations; + } + /** + * {@inheritDoc} + */ + public function getClassAnnotation(ReflectionClass $class, $annotationName) + { + return $this->delegate->getClassAnnotation($class, $annotationName); + } + /** + * {@inheritDoc} + */ + public function getMethodAnnotations(ReflectionMethod $method) + { + $annotations = []; + foreach ($this->delegate->getMethodAnnotations($method) as $annot) { + $annotations[get_class($annot)] = $annot; + } + return $annotations; + } + /** + * {@inheritDoc} + */ + public function getMethodAnnotation(ReflectionMethod $method, $annotationName) + { + return $this->delegate->getMethodAnnotation($method, $annotationName); + } + /** + * {@inheritDoc} + */ + public function getPropertyAnnotations(ReflectionProperty $property) + { + $annotations = []; + foreach ($this->delegate->getPropertyAnnotations($property) as $annot) { + $annotations[get_class($annot)] = $annot; + } + return $annotations; + } + /** + * {@inheritDoc} + */ + public function getPropertyAnnotation(ReflectionProperty $property, $annotationName) + { + return $this->delegate->getPropertyAnnotation($property, $annotationName); + } + /** + * Proxies all methods to the delegate. + * + * @param mixed[] $args + * + * @return mixed + */ + public function __call(string $method, array $args) + { + return call_user_func_array([$this->delegate, $method], $args); + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php new file mode 100644 index 00000000000..22d59ca02fc --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PhpParser.php @@ -0,0 +1,66 @@ + a list with use statements in the form (Alias => FQN). + */ + public function parseUseStatements($reflection) : array + { + if (method_exists($reflection, 'getUseStatements')) { + return $reflection->getUseStatements(); + } + $filename = $reflection->getFileName(); + if ($filename === \false) { + return []; + } + $content = $this->getFileContent($filename, $reflection->getStartLine()); + if ($content === null) { + return []; + } + $namespace = preg_quote($reflection->getNamespaceName()); + $content = preg_replace('/^.*?(\\bnamespace\\s+' . $namespace . '\\s*[;{].*)$/s', '\\1', $content); + $tokenizer = new TokenParser('parseUseStatements($reflection->getNamespaceName()); + } + /** + * Gets the content of the file right up to the given line number. + * + * @param string $filename The name of the file to load. + * @param int $lineNumber The number of lines to read from file. + * + * @return string|null The content of the file or null if the file does not exist. + */ + private function getFileContent(string $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; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php new file mode 100644 index 00000000000..d58123d755a --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/PsrCachedReader.php @@ -0,0 +1,176 @@ +> */ + private $loadedAnnotations = []; + /** @var int[] */ + private $loadedFilemtimes = []; + public function __construct(Reader $reader, CacheItemPoolInterface $cache, bool $debug = \false) + { + $this->delegate = $reader; + $this->cache = $cache; + $this->debug = (bool) $debug; + } + /** + * {@inheritDoc} + */ + public function getClassAnnotations(ReflectionClass $class) + { + $cacheKey = $class->getName(); + if (isset($this->loadedAnnotations[$cacheKey])) { + return $this->loadedAnnotations[$cacheKey]; + } + $annots = $this->fetchFromCache($cacheKey, $class, 'getClassAnnotations', $class); + return $this->loadedAnnotations[$cacheKey] = $annots; + } + /** + * {@inheritDoc} + */ + public function getClassAnnotation(ReflectionClass $class, $annotationName) + { + foreach ($this->getClassAnnotations($class) as $annot) { + if ($annot instanceof $annotationName) { + return $annot; + } + } + return null; + } + /** + * {@inheritDoc} + */ + public function getPropertyAnnotations(ReflectionProperty $property) + { + $class = $property->getDeclaringClass(); + $cacheKey = $class->getName() . '$' . $property->getName(); + if (isset($this->loadedAnnotations[$cacheKey])) { + return $this->loadedAnnotations[$cacheKey]; + } + $annots = $this->fetchFromCache($cacheKey, $class, 'getPropertyAnnotations', $property); + return $this->loadedAnnotations[$cacheKey] = $annots; + } + /** + * {@inheritDoc} + */ + public function getPropertyAnnotation(ReflectionProperty $property, $annotationName) + { + foreach ($this->getPropertyAnnotations($property) as $annot) { + if ($annot instanceof $annotationName) { + return $annot; + } + } + return null; + } + /** + * {@inheritDoc} + */ + public function getMethodAnnotations(ReflectionMethod $method) + { + $class = $method->getDeclaringClass(); + $cacheKey = $class->getName() . '#' . $method->getName(); + if (isset($this->loadedAnnotations[$cacheKey])) { + return $this->loadedAnnotations[$cacheKey]; + } + $annots = $this->fetchFromCache($cacheKey, $class, 'getMethodAnnotations', $method); + return $this->loadedAnnotations[$cacheKey] = $annots; + } + /** + * {@inheritDoc} + */ + public function getMethodAnnotation(ReflectionMethod $method, $annotationName) + { + foreach ($this->getMethodAnnotations($method) as $annot) { + if ($annot instanceof $annotationName) { + return $annot; + } + } + return null; + } + public function clearLoadedAnnotations() : void + { + $this->loadedAnnotations = []; + $this->loadedFilemtimes = []; + } + /** @return mixed[] */ + private function fetchFromCache(string $cacheKey, ReflectionClass $class, string $method, Reflector $reflector) : array + { + $cacheKey = rawurlencode($cacheKey); + $item = $this->cache->getItem($cacheKey); + if ($this->debug && !$this->refresh($cacheKey, $class) || !$item->isHit()) { + $this->cache->save($item->set($this->delegate->{$method}($reflector))); + } + return $item->get(); + } + /** + * Used in debug mode to check if the cache is fresh. + * + * @return bool Returns true if the cache was fresh, or false if the class + * being read was modified since writing to the cache. + */ + private function refresh(string $cacheKey, ReflectionClass $class) : bool + { + $lastModification = $this->getLastModification($class); + if ($lastModification === 0) { + return \true; + } + $item = $this->cache->getItem('[C]' . $cacheKey); + if ($item->isHit() && $item->get() >= $lastModification) { + return \true; + } + $this->cache->save($item->set(time())); + return \false; + } + /** + * Returns the time the class was last modified, testing traits and parents + */ + private function getLastModification(ReflectionClass $class) : int + { + $filename = $class->getFileName(); + if (isset($this->loadedFilemtimes[$filename])) { + return $this->loadedFilemtimes[$filename]; + } + $parent = $class->getParentClass(); + $lastModification = max(array_merge([$filename ? filemtime($filename) : 0], array_map(function (ReflectionClass $reflectionTrait) : int { + return $this->getTraitLastModificationTime($reflectionTrait); + }, $class->getTraits()), array_map(function (ReflectionClass $class) : int { + return $this->getLastModification($class); + }, $class->getInterfaces()), $parent ? [$this->getLastModification($parent)] : [])); + assert($lastModification !== \false); + return $this->loadedFilemtimes[$filename] = $lastModification; + } + private function getTraitLastModificationTime(ReflectionClass $reflectionTrait) : int + { + $fileName = $reflectionTrait->getFileName(); + if (isset($this->loadedFilemtimes[$fileName])) { + return $this->loadedFilemtimes[$fileName]; + } + $lastModificationTime = max(array_merge([$fileName ? filemtime($fileName) : 0], array_map(function (ReflectionClass $reflectionTrait) : int { + return $this->getTraitLastModificationTime($reflectionTrait); + }, $reflectionTrait->getTraits()))); + assert($lastModificationTime !== \false); + return $this->loadedFilemtimes[$fileName] = $lastModificationTime; + } +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php new file mode 100644 index 00000000000..33608a72646 --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/Reader.php @@ -0,0 +1,74 @@ + An array of Annotations. + */ + public function getClassAnnotations(ReflectionClass $class); + /** + * Gets a class annotation. + * + * @param ReflectionClass $class The ReflectionClass of the class from which + * the class annotations should be read. + * @param class-string $annotationName The name of the annotation. + * + * @return T|null The Annotation or NULL, if the requested annotation does not exist. + * + * @template T + */ + public function getClassAnnotation(ReflectionClass $class, $annotationName); + /** + * Gets the annotations applied to a method. + * + * @param ReflectionMethod $method The ReflectionMethod of the method from which + * the annotations should be read. + * + * @return array An array of Annotations. + */ + public function getMethodAnnotations(ReflectionMethod $method); + /** + * Gets a method annotation. + * + * @param ReflectionMethod $method The ReflectionMethod to read the annotations from. + * @param class-string $annotationName The name of the annotation. + * + * @return T|null The Annotation or NULL, if the requested annotation does not exist. + * + * @template T + */ + public function getMethodAnnotation(ReflectionMethod $method, $annotationName); + /** + * Gets the annotations applied to a property. + * + * @param ReflectionProperty $property The ReflectionProperty of the property + * from which the annotations should be read. + * + * @return array An array of Annotations. + */ + public function getPropertyAnnotations(ReflectionProperty $property); + /** + * Gets a property annotation. + * + * @param ReflectionProperty $property The ReflectionProperty to read the annotations from. + * @param class-string $annotationName The name of the annotation. + * + * @return T|null The Annotation or NULL, if the requested annotation does not exist. + * + * @template T + */ + public function getPropertyAnnotation(ReflectionProperty $property, $annotationName); +} diff --git a/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php new file mode 100644 index 00000000000..b5cd521d5aa --- /dev/null +++ b/vendor/doctrine/annotations/lib/Doctrine/Common/Annotations/TokenParser.php @@ -0,0 +1,173 @@ + + */ + private $tokens; + /** + * The number of tokens. + * + * @var int + */ + private $numTokens; + /** + * The current array pointer. + * + * @var int + */ + private $pointer = 0; + public function __construct(string $contents) + { + $this->tokens = token_get_all($contents); + // The PHP parser sets internal compiler globals for certain things. Annoyingly, the last docblock comment it + // saw gets stored in doc_comment. When it comes to compile the next thing to be include()d this stored + // doc_comment becomes owned by the first thing the compiler sees in the file that it considers might have a + // docblock. If the first thing in the file is a class without a doc block this would cause calls to + // getDocBlock() on said class to return our long lost doc_comment. Argh. + // To workaround, cause the parser to parse an empty docblock. Sure getDocBlock() will return this, but at least + // it's harmless to us. + token_get_all("numTokens = count($this->tokens); + } + /** + * Gets the next non whitespace and non comment token. + * + * @param bool $docCommentIsComment If TRUE then a doc comment is considered a comment and skipped. + * If FALSE then only whitespace and normal comments are skipped. + * + * @return mixed[]|string|null The token if exists, null otherwise. + */ + public function next(bool $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; + } + /** + * Parses a single use statement. + * + * @return array A list with all found class names for a use statement. + */ + public function parseUseStatement() + { + $groupRoot = ''; + $class = ''; + $alias = ''; + $statements = []; + $explicitAlias = \false; + while ($token = $this->next()) { + if (!$explicitAlias && $token[0] === T_STRING) { + $class .= $token[1]; + $alias = $token[1]; + } elseif ($explicitAlias && $token[0] === T_STRING) { + $alias = $token[1]; + } elseif (PHP_VERSION_ID >= 80000 && ($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED)) { + $class .= $token[1]; + $classSplit = explode('\\', $token[1]); + $alias = $classSplit[count($classSplit) - 1]; + } elseif ($token[0] === T_NS_SEPARATOR) { + $class .= '\\'; + $alias = ''; + } elseif ($token[0] === T_AS) { + $explicitAlias = \true; + $alias = ''; + } elseif ($token === ',') { + $statements[strtolower($alias)] = $groupRoot . $class; + $class = ''; + $alias = ''; + $explicitAlias = \false; + } elseif ($token === ';') { + $statements[strtolower($alias)] = $groupRoot . $class; + break; + } elseif ($token === '{') { + $groupRoot = $class; + $class = ''; + } elseif ($token === '}') { + continue; + } else { + break; + } + } + return $statements; + } + /** + * Gets all use statements. + * + * @param string $namespaceName The namespace name of the reflected class. + * + * @return array A list with all found use statements. + */ + public function parseUseStatements(string $namespaceName) + { + $statements = []; + 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; + } + // Get fresh array for new namespace. This is to prevent the parser to collect the use statements + // for a previous namespace with the same name. This is the case if a namespace is defined twice + // or if a namespace with the same name is commented out. + $statements = []; + } + return $statements; + } + /** + * Gets the namespace. + * + * @return string The found namespace. + */ + public function parseNamespace() + { + $name = ''; + while (($token = $this->next()) && ($token[0] === T_STRING || $token[0] === T_NS_SEPARATOR || PHP_VERSION_ID >= 80000 && ($token[0] === T_NAME_QUALIFIED || $token[0] === T_NAME_FULLY_QUALIFIED))) { + $name .= $token[1]; + } + return $name; + } + /** + * Gets the class name. + * + * @return string The found class name. + */ + public function parseClass() + { + // Namespaces and class names are tokenized the same: T_STRINGs + // separated by T_NS_SEPARATOR so we can use one function to provide + // both. + return $this->parseNamespace(); + } +} diff --git a/vendor/doctrine/annotations/psalm.xml b/vendor/doctrine/annotations/psalm.xml new file mode 100644 index 00000000000..e6af3892387 --- /dev/null +++ b/vendor/doctrine/annotations/psalm.xml @@ -0,0 +1,15 @@ + + + + + + + + + diff --git a/vendor/doctrine/lexer/LICENSE b/vendor/doctrine/lexer/LICENSE new file mode 100644 index 00000000000..e8fdec4afb7 --- /dev/null +++ b/vendor/doctrine/lexer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2006-2018 Doctrine Project + +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. diff --git a/vendor/doctrine/lexer/README.md b/vendor/doctrine/lexer/README.md new file mode 100644 index 00000000000..784f2a27128 --- /dev/null +++ b/vendor/doctrine/lexer/README.md @@ -0,0 +1,9 @@ +# Doctrine Lexer + +[![Build Status](https://github.com/doctrine/lexer/workflows/Continuous%20Integration/badge.svg)](https://github.com/doctrine/lexer/actions) + +Base library for a lexer that can be used in Top-Down, Recursive Descent Parsers. + +This lexer is used in Doctrine Annotations and in Doctrine ORM (DQL). + +https://www.doctrine-project.org/projects/lexer.html diff --git a/vendor/doctrine/lexer/UPGRADE.md b/vendor/doctrine/lexer/UPGRADE.md new file mode 100644 index 00000000000..1933fcb2ec9 --- /dev/null +++ b/vendor/doctrine/lexer/UPGRADE.md @@ -0,0 +1,22 @@ +Note about upgrading: Doctrine uses static and runtime mechanisms to raise +awareness about deprecated code. + +- Use of `@deprecated` docblock that is detected by IDEs (like PHPStorm) or + Static Analysis tools (like Psalm, phpstan) +- Use of our low-overhead runtime deprecation API, details: + https://github.com/doctrine/deprecations/ + +# Upgrade to 3.0.0 + +`Doctrine\Common\Lexer\Token` no longer implements `ArrayAccess`. +Parameter type declarations have been added to +`Doctrine\Common\Lexer\AbstractLexer` and `Doctrine\Common\Lexer\Token`. +You should add both parameter type declarations and return type declarations to +your lexers, based on the `@return` phpdoc. + +# Upgrade to 2.0.0 + +`AbstractLexer::glimpse()` and `AbstractLexer::peek()` now return +instances of `Doctrine\Common\Lexer\Token`, which is an array-like class +Using it as an array is deprecated in favor of using properties of that class. +Using `count()` on it is deprecated with no replacement. diff --git a/vendor/doctrine/lexer/composer.json b/vendor/doctrine/lexer/composer.json new file mode 100644 index 00000000000..9c14d50fd12 --- /dev/null +++ b/vendor/doctrine/lexer/composer.json @@ -0,0 +1,55 @@ +{ + "name": "doctrine\/lexer", + "description": "PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.", + "license": "MIT", + "type": "library", + "keywords": [ + "php", + "parser", + "lexer", + "annotations", + "docblock" + ], + "authors": [ + { + "name": "Guilherme Blanco", + "email": "guilhermeblanco@gmail.com" + }, + { + "name": "Roman Borschel", + "email": "roman@code-factory.org" + }, + { + "name": "Johannes Schmitt", + "email": "schmittjoh@gmail.com" + } + ], + "homepage": "https:\/\/www.doctrine-project.org\/projects\/lexer.html", + "require": { + "php": "^8.1" + }, + "require-dev": { + "doctrine\/coding-standard": "^10", + "phpstan\/phpstan": "^1.9", + "phpunit\/phpunit": "^9.5", + "psalm\/plugin-phpunit": "^0.18.3", + "vimeo\/psalm": "^5.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Common\\Lexer\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Doctrine\\Tests\\Common\\Lexer\\": "tests" + } + }, + "config": { + "allow-plugins": { + "composer\/package-versions-deprecated": true, + "dealerdirect\/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} \ No newline at end of file diff --git a/vendor/doctrine/lexer/src/AbstractLexer.php b/vendor/doctrine/lexer/src/AbstractLexer.php new file mode 100644 index 00000000000..0465757bb40 --- /dev/null +++ b/vendor/doctrine/lexer/src/AbstractLexer.php @@ -0,0 +1,285 @@ +> + */ + private $tokens = []; + /** + * Current lexer position in input string. + * @var int + */ + private $position = 0; + /** + * Current peek of current lexer position. + * @var int + */ + private $peek = 0; + /** + * The next token in the input. + * + * @var mixed[]|null + * @psalm-var Token|null + */ + public $lookahead; + /** + * The last matched/seen token. + * + * @var mixed[]|null + * @psalm-var Token|null + */ + public $token; + /** + * Composed regex for input parsing. + * @var string|null + */ + private $regex = null; + /** + * Sets the input data to be tokenized. + * + * The Lexer is immediately reset and the new input tokenized. + * Any unprocessed tokens from any previous input are lost. + * + * @param string $input The input to be tokenized. + * + * @return void + */ + public function setInput(string $input) + { + $this->input = $input; + $this->tokens = []; + $this->reset(); + $this->scan($input); + } + /** + * Resets the lexer. + * + * @return void + */ + public function reset() + { + $this->lookahead = null; + $this->token = null; + $this->peek = 0; + $this->position = 0; + } + /** + * Resets the peek pointer to 0. + * + * @return void + */ + public function resetPeek() + { + $this->peek = 0; + } + /** + * Resets the lexer position on the input to the given position. + * + * @param int $position Position to place the lexical scanner. + * + * @return void + */ + public function resetPosition(int $position = 0) + { + $this->position = $position; + } + /** + * Retrieve the original lexer's input until a given position. + * + * @return string + */ + public function getInputUntilPosition(int $position) + { + return substr($this->input, 0, $position); + } + /** + * Checks whether a given token matches the current lookahead. + * + * @param int|string|\UnitEnum $type + * + * @return bool + * + * @psalm-assert-if-true !=null $this->lookahead + */ + public function isNextToken($type) + { + return $this->lookahead !== null && $this->lookahead->isA($type); + } + /** + * Checks whether any of the given tokens matches the current lookahead. + * + * @param list $types + * + * @return bool + * + * @psalm-assert-if-true !=null $this->lookahead + */ + public function isNextTokenAny(array $types) + { + return $this->lookahead !== null && $this->lookahead->isA(...$types); + } + /** + * Moves to the next token in the input string. + * + * @return bool + * + * @psalm-assert-if-true !null $this->lookahead + */ + 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; + } + /** + * Tells the lexer to skip input tokens until it sees a token with the given value. + * + * @param int|string|\UnitEnum $type The token type to skip until. + * + * @return void + */ + public function skipUntil($type) + { + while ($this->lookahead !== null && !$this->lookahead->isA($type)) { + $this->moveNext(); + } + } + /** + * Checks if given value is identical to the given token. + * + * @return bool + * @param int|string|\UnitEnum $token + */ + public function isA(string $value, $token) + { + return $this->getType($value) === $token; + } + /** + * Moves the lookahead token forward. + * + * @return mixed[]|null The next token or NULL if there are no more tokens ahead. + * @psalm-return Token|null + */ + public function peek() + { + if (isset($this->tokens[$this->position + $this->peek])) { + return $this->tokens[$this->position + $this->peek++]; + } + return null; + } + /** + * Peeks at the next token, returns it and immediately resets the peek. + * + * @return mixed[]|null The next token or NULL if there are no more tokens ahead. + * @psalm-return Token|null + */ + public function glimpse() + { + $peek = $this->peek(); + $this->peek = 0; + return $peek; + } + /** + * Scans the input string for tokens. + * + * @param string $input A query string. + * + * @return void + */ + protected function scan(string $input) + { + if (!isset($this->regex)) { + $this->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($this->regex, $input, -1, $flags); + if ($matches === \false) { + // Work around https://bugs.php.net/78122 + $matches = [[$input, 0]]; + } + foreach ($matches as $match) { + // Must remain before 'value' assignment since it can change content + $firstMatch = $match[0]; + $type = $this->getType($firstMatch); + $this->tokens[] = new Token($firstMatch, $type, $match[1]); + } + } + /** + * Gets the literal for a given token. + * + * @param int|string|\UnitEnum $token + * + * @return int|string + */ + public function getLiteral($token) + { + if ($token instanceof UnitEnum) { + return \get_class($token) . '::' . $token->name; + } + $className = static::class; + $reflClass = new ReflectionClass($className); + $constants = $reflClass->getConstants(); + foreach ($constants as $name => $value) { + if ($value === $token) { + return $className . '::' . $name; + } + } + return $token; + } + /** + * Regex modifiers + * + * @return string + */ + protected function getModifiers() + { + return 'iu'; + } + /** + * Lexical catchable patterns. + * + * @return string[] + */ + protected abstract function getCatchablePatterns(); + /** + * Lexical non-catchable patterns. + * + * @return string[] + */ + protected abstract function getNonCatchablePatterns(); + /** + * Retrieve token type. Also processes the token value if necessary. + * + * @return T|null + * + * @param-out V $value + */ + protected abstract function getType(string &$value); +} diff --git a/vendor/doctrine/lexer/src/Token.php b/vendor/doctrine/lexer/src/Token.php new file mode 100644 index 00000000000..4d40be162b0 --- /dev/null +++ b/vendor/doctrine/lexer/src/Token.php @@ -0,0 +1,50 @@ +value = $value; + $this->type = $type; + $this->position = $position; + } + /** @param T ...$types */ + public function isA(...$types) : bool + { + return in_array($this->type, $types, \true); + } +} diff --git a/vendor/evenement/evenement/CHANGELOG.md b/vendor/evenement/evenement/CHANGELOG.md new file mode 100644 index 00000000000..568f2295a5a --- /dev/null +++ b/vendor/evenement/evenement/CHANGELOG.md @@ -0,0 +1,35 @@ +CHANGELOG +========= + + +* v3.0.1 (2017-07-23) + + * Resolved regression introduced in once listeners in v3.0.0 [#49](https://github.com/igorw/evenement/pull/49) + +* v3.0.0 (2017-07-23) + + * Passing null as event name throw exception [#46](https://github.com/igorw/evenement/pull/46), and [#47](https://github.com/igorw/evenement/pull/47) + * Performance improvements [#39](https://github.com/igorw/evenement/pull/39), and [#45](https://github.com/igorw/evenement/pull/45) + * Remove once listeners [#44](https://github.com/igorw/evenement/pull/44), [#45](https://github.com/igorw/evenement/pull/45) + +* v2.1.0 (2017-07-17) + + * Chaining for "on" method [#30](https://github.com/igorw/evenement/pull/30) + * Unit tests (on Travis) improvements [#33](https://github.com/igorw/evenement/pull/33), [#36](https://github.com/igorw/evenement/pull/36), and [#37](https://github.com/igorw/evenement/pull/37) + * Benchmarks added [#35](https://github.com/igorw/evenement/pull/35), and [#40](https://github.com/igorw/evenement/pull/40) + * Minor performance improvements [#42](https://github.com/igorw/evenement/pull/42), and [#38](https://github.com/igorw/evenement/pull/38) + +* v2.0.0 (2012-11-02) + + * Require PHP >=5.4.0 + * Added EventEmitterTrait + * Removed EventEmitter2 + +* v1.1.0 (2017-07-17) + + * Chaining for "on" method [#29](https://github.com/igorw/evenement/pull/29) + * Minor performance improvements [#43](https://github.com/igorw/evenement/pull/43) + +* v1.0.0 (2012-05-30) + + * Inital stable release diff --git a/vendor/evenement/evenement/LICENSE b/vendor/evenement/evenement/LICENSE new file mode 100644 index 00000000000..d9a37d0a042 --- /dev/null +++ b/vendor/evenement/evenement/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Igor Wiedler + +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. diff --git a/vendor/evenement/evenement/README.md b/vendor/evenement/evenement/README.md new file mode 100644 index 00000000000..94430119b1e --- /dev/null +++ b/vendor/evenement/evenement/README.md @@ -0,0 +1,83 @@ +# Événement + +Événement is a very simple event dispatching library for PHP. + +It has the same design goals as [Silex](http://silex-project.org) and +[Pimple](http://pimple-project.org), to empower the user while staying concise +and simple. + +It is very strongly inspired by the EventEmitter API found in +[node.js](http://nodejs.org). + +[![Build Status](https://secure.travis-ci.org/igorw/evenement.png?branch=master)](http://travis-ci.org/igorw/evenement) + +## Fetch + +The recommended way to install Événement is [through composer](http://getcomposer.org). + +Just create a composer.json file for your project: + +```JSON +{ + "require": { + "evenement/evenement": "^3.0 || ^2.0" + } +} +``` + +**Note:** The `3.x` version of Événement requires PHP 7 and the `2.x` version requires PHP 5.4. If you are +using PHP 5.3, please use the `1.x` version: + +```JSON +{ + "require": { + "evenement/evenement": "^1.0" + } +} +``` + +And run these two commands to install it: + + $ curl -s http://getcomposer.org/installer | php + $ php composer.phar install + +Now you can add the autoloader, and you will have access to the library: + +```php +on('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +### Emitting Events + +```php +emit('user.created', [$user]); +``` + +Tests +----- + + $ ./vendor/bin/phpunit + +License +------- +MIT, see LICENSE. diff --git a/vendor/evenement/evenement/composer.json b/vendor/evenement/evenement/composer.json new file mode 100644 index 00000000000..2c94212a217 --- /dev/null +++ b/vendor/evenement/evenement/composer.json @@ -0,0 +1,34 @@ +{ + "name": "evenement\/evenement", + "description": "\u00c9v\u00e9nement is a very simple event dispatching library for PHP", + "keywords": [ + "event-dispatcher", + "event-emitter" + ], + "license": "MIT", + "authors": [ + { + "name": "Igor Wiedler", + "email": "igor@wiedler.ch" + } + ], + "require": { + "php": ">=7.0" + }, + "require-dev": { + "phpunit\/phpunit": "^6.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Evenement\\": "src\/Evenement\/" + } + }, + "autoload-dev": { + "files": [ + "tests\/Evenement\/Tests\/functions.php" + ], + "psr-4": { + "ECSPrefix202307\\Evenement\\": "tests\/Evenement\/" + } + } +} \ No newline at end of file diff --git a/vendor/evenement/evenement/doc/00-intro.md b/vendor/evenement/evenement/doc/00-intro.md new file mode 100644 index 00000000000..6c28a2ab2c7 --- /dev/null +++ b/vendor/evenement/evenement/doc/00-intro.md @@ -0,0 +1,28 @@ +# Introduction + +Événement is is French and means "event". The événement library aims to +provide a simple way of subscribing to events and notifying those subscribers +whenever an event occurs. + +The API that it exposes is almost a direct port of the EventEmitter API found +in node.js. It also includes an "EventEmitter". There are some minor +differences however. + +The EventEmitter is an implementation of the publish-subscribe pattern, which +is a generalized version of the observer pattern. The observer pattern +specifies an observable subject, which observers can register themselves to. +Once something interesting happens, the subject notifies its observers. + +Pub/sub takes the same idea but encapsulates the observation logic inside a +separate object which manages all of its subscribers or listeners. Subscribers +are bound to an event name, and will only receive notifications of the events +they subscribed to. + +**TLDR: What does evenement do, in short? It provides a mapping from event +names to a list of listener functions and triggers each listener for a given +event when it is emitted.** + +Why do we do this, you ask? To achieve decoupling. + +It allows you to design a system where the core will emit events, and modules +are able to subscribe to these events. And respond to them. diff --git a/vendor/evenement/evenement/doc/01-api.md b/vendor/evenement/evenement/doc/01-api.md new file mode 100644 index 00000000000..17ba333ecc3 --- /dev/null +++ b/vendor/evenement/evenement/doc/01-api.md @@ -0,0 +1,91 @@ +# API + +The API that événement exposes is defined by the +`Evenement\EventEmitterInterface`. The interface is useful if you want to +define an interface that extends the emitter and implicitly defines certain +events to be emitted, or if you want to type hint an `EventEmitter` to be +passed to a method without coupling to the specific implementation. + +## on($event, callable $listener) + +Allows you to subscribe to an event. + +Example: + +```php +$emitter->on('user.created', function (User $user) use ($logger) { + $logger->log(sprintf("User '%s' was created.", $user->getLogin())); +}); +``` + +Since the listener can be any callable, you could also use an instance method +instead of the anonymous function: + +```php +$loggerSubscriber = new LoggerSubscriber($logger); +$emitter->on('user.created', array($loggerSubscriber, 'onUserCreated')); +``` + +This has the benefit that listener does not even need to know that the emitter +exists. + +You can also accept more than one parameter for the listener: + +```php +$emitter->on('numbers_added', function ($result, $a, $b) {}); +``` + +## once($event, callable $listener) + +Convenience method that adds a listener which is guaranteed to only be called +once. + +Example: + +```php +$conn->once('connected', function () use ($conn, $data) { + $conn->send($data); +}); +``` + +## emit($event, array $arguments = []) + +Emit an event, which will call all listeners. + +Example: + +```php +$conn->emit('data', [$data]); +``` + +The second argument to emit is an array of listener arguments. This is how you +specify more args: + +```php +$result = $a + $b; +$emitter->emit('numbers_added', [$result, $a, $b]); +``` + +## listeners($event) + +Allows you to inspect the listeners attached to an event. Particularly useful +to check if there are any listeners at all. + +Example: + +```php +$e = new \RuntimeException('Everything is broken!'); +if (0 === count($emitter->listeners('error'))) { + throw $e; +} +``` + +## removeListener($event, callable $listener) + +Remove a specific listener for a specific event. + +## removeAllListeners($event = null) + +Remove all listeners for a specific event or all listeners all together. This +is useful for long-running processes, where you want to remove listeners in +order to allow them to get garbage collected. diff --git a/vendor/evenement/evenement/doc/02-plugin-system.md b/vendor/evenement/evenement/doc/02-plugin-system.md new file mode 100644 index 00000000000..6a083719318 --- /dev/null +++ b/vendor/evenement/evenement/doc/02-plugin-system.md @@ -0,0 +1,155 @@ +# Example: Plugin system + +In this example I will show you how to create a generic plugin system with +événement where plugins can alter the behaviour of the app. The app is a blog. +Boring, I know. By using the EventEmitter it will be easy to extend this blog +with additional functionality without modifying the core system. + +The blog is quite basic. Users are able to create blog posts when they log in. +The users are stored in a static config file, so there is no sign up process. +Once logged in they get a "new post" link which gives them a form where they +can create a new blog post with plain HTML. That will store the post in a +document database. The index lists all blog post titles by date descending. +Clicking on the post title will take you to the full post. + +## Plugin structure + +The goal of the plugin system is to allow features to be added to the blog +without modifying any core files of the blog. + +The plugins are managed through a config file, `plugins.json`. This JSON file +contains a JSON-encoded list of class-names for plugin classes. This allows +you to enable and disable plugins in a central location. The initial +`plugins.json` is just an empty array: +```json +[] +``` + +A plugin class must implement the `PluginInterface`: +```php +interface PluginInterface +{ + function attachEvents(EventEmitterInterface $emitter); +} +``` + +The `attachEvents` method allows the plugin to attach any events to the +emitter. For example: +```php +class FooPlugin implements PluginInterface +{ + public function attachEvents(EventEmitterInterface $emitter) + { + $emitter->on('foo', function () { + echo 'bar!'; + }); + } +} +``` + +The blog system creates an emitter instance and loads the plugins: +```php +$emitter = new EventEmitter(); + +$pluginClasses = json_decode(file_get_contents('plugins.json'), true); +foreach ($pluginClasses as $pluginClass) { + $plugin = new $pluginClass(); + $pluginClass->attachEvents($emitter); +} +``` + +This is the base system. There are no plugins yet, and there are no events yet +either. That's because I don't know which extension points will be needed. I +will add them on demand. + +## Feature: Markdown + +Writing blog posts in HTML sucks! Wouldn't it be great if I could write them +in a nice format such as markdown, and have that be converted to HTML for me? + +This feature will need two extension points. I need to be able to mark posts +as markdown, and I need to be able to hook into the rendering of the post body +and convert it from markdown to HTML. So the blog needs two new events: +`post.create` and `post.render`. + +In the code that creates the post, I'll insert the `post.create` event: +```php +class PostEvent +{ + public $post; + + public function __construct(array $post) + { + $this->post = $post; + } +} + +$post = createPostFromRequest($_POST); + +$event = new PostEvent($post); +$emitter->emit('post.create', [$event]); +$post = $event->post; + +$db->save('post', $post); +``` + +This shows that you can wrap a value in an event object to make it mutable, +allowing listeners to change it. + +The same thing for the `post.render` event: +```php +public function renderPostBody(array $post) +{ + $emitter = $this->emitter; + + $event = new PostEvent($post); + $emitter->emit('post.render', [$event]); + $post = $event->post; + + return $post['body']; +} + +

+

+``` + +Ok, the events are in place. It's time to create the first plugin, woohoo! I +will call this the `MarkdownPlugin`, so here's `plugins.json`: +```json +[ + "MarkdownPlugin" +] +``` + +The `MarkdownPlugin` class will be autoloaded, so I don't have to worry about +including any files. I just have to worry about implementing the plugin class. +The `markdown` function represents a markdown to HTML converter. +```php +class MarkdownPlugin implements PluginInterface +{ + public function attachEvents(EventEmitterInterface $emitter) + { + $emitter->on('post.create', function (PostEvent $event) { + $event->post['format'] = 'markdown'; + }); + + $emitter->on('post.render', function (PostEvent $event) { + if (isset($event->post['format']) && 'markdown' === $event->post['format']) { + $event->post['body'] = markdown($event->post['body']); + } + }); + } +} +``` + +There you go, the blog now renders posts as markdown. But all of the previous +posts before the addition of the markdown plugin are still rendered correctly +as raw HTML. + +## Feature: Comments + +TODO + +## Feature: Comment spam control + +TODO diff --git a/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php b/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php new file mode 100644 index 00000000000..9673331df48 --- /dev/null +++ b/vendor/evenement/evenement/examples/benchmark-emit-no-arguments.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +const ITERATIONS = 10000000; +use ECSPrefix202307\Evenement\EventEmitter; +require __DIR__ . '/../vendor/autoload.php'; +$emitter = new EventEmitter(); +$emitter->on('event', function () { +}); +$start = \microtime(\true); +for ($i = 0; $i < \ECSPrefix202307\ITERATIONS; $i++) { + $emitter->emit('event'); +} +$time = \microtime(\true) - $start; +echo 'Emitting ', \number_format(\ECSPrefix202307\ITERATIONS), ' events took: ', \number_format($time, 2), 's', \PHP_EOL; diff --git a/vendor/evenement/evenement/examples/benchmark-emit-once.php b/vendor/evenement/evenement/examples/benchmark-emit-once.php new file mode 100644 index 00000000000..35dec935335 --- /dev/null +++ b/vendor/evenement/evenement/examples/benchmark-emit-once.php @@ -0,0 +1,26 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +\ini_set('memory_limit', '512M'); +const ITERATIONS = 100000; +use ECSPrefix202307\Evenement\EventEmitter; +require __DIR__ . '/../vendor/autoload.php'; +$emitter = new EventEmitter(); +for ($i = 0; $i < \ECSPrefix202307\ITERATIONS; $i++) { + $emitter->once('event', function ($a, $b, $c) { + }); +} +$start = \microtime(\true); +$emitter->emit('event', [1, 2, 3]); +$time = \microtime(\true) - $start; +echo 'Emitting one event to ', \number_format(\ECSPrefix202307\ITERATIONS), ' once listeners took: ', \number_format($time, 2), 's', \PHP_EOL; diff --git a/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php b/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php new file mode 100644 index 00000000000..8aa6f8fc811 --- /dev/null +++ b/vendor/evenement/evenement/examples/benchmark-emit-one-argument.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +const ITERATIONS = 10000000; +use ECSPrefix202307\Evenement\EventEmitter; +require __DIR__ . '/../vendor/autoload.php'; +$emitter = new EventEmitter(); +$emitter->on('event', function ($a) { +}); +$start = \microtime(\true); +for ($i = 0; $i < \ECSPrefix202307\ITERATIONS; $i++) { + $emitter->emit('event', [1]); +} +$time = \microtime(\true) - $start; +echo 'Emitting ', \number_format(\ECSPrefix202307\ITERATIONS), ' events took: ', \number_format($time, 2), 's', \PHP_EOL; diff --git a/vendor/evenement/evenement/examples/benchmark-emit.php b/vendor/evenement/evenement/examples/benchmark-emit.php new file mode 100644 index 00000000000..ab60afff9d5 --- /dev/null +++ b/vendor/evenement/evenement/examples/benchmark-emit.php @@ -0,0 +1,25 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +const ITERATIONS = 10000000; +use ECSPrefix202307\Evenement\EventEmitter; +require __DIR__ . '/../vendor/autoload.php'; +$emitter = new EventEmitter(); +$emitter->on('event', function ($a, $b, $c) { +}); +$start = \microtime(\true); +for ($i = 0; $i < \ECSPrefix202307\ITERATIONS; $i++) { + $emitter->emit('event', [1, 2, 3]); +} +$time = \microtime(\true) - $start; +echo 'Emitting ', \number_format(\ECSPrefix202307\ITERATIONS), ' events took: ', \number_format($time, 2), 's', \PHP_EOL; diff --git a/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php b/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php new file mode 100644 index 00000000000..b039696ac84 --- /dev/null +++ b/vendor/evenement/evenement/examples/benchmark-remove-listener-once.php @@ -0,0 +1,35 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +\ini_set('memory_limit', '512M'); +const ITERATIONS = 100000; +use ECSPrefix202307\Evenement\EventEmitter; +require __DIR__ . '/../vendor/autoload.php'; +$emitter = new EventEmitter(); +$listeners = []; +for ($i = 0; $i < \ECSPrefix202307\ITERATIONS; $i++) { + $listeners[] = function ($a, $b, $c) { + }; +} +$start = \microtime(\true); +foreach ($listeners as $listener) { + $emitter->once('event', $listener); +} +$time = \microtime(\true) - $start; +echo 'Adding ', \number_format(\ECSPrefix202307\ITERATIONS), ' once listeners took: ', \number_format($time, 2), 's', \PHP_EOL; +$start = \microtime(\true); +foreach ($listeners as $listener) { + $emitter->removeListener('event', $listener); +} +$time = \microtime(\true) - $start; +echo 'Removing ', \number_format(\ECSPrefix202307\ITERATIONS), ' once listeners took: ', \number_format($time, 2), 's', \PHP_EOL; diff --git a/vendor/evenement/evenement/phpunit.xml.dist b/vendor/evenement/evenement/phpunit.xml.dist new file mode 100644 index 00000000000..70bc693a560 --- /dev/null +++ b/vendor/evenement/evenement/phpunit.xml.dist @@ -0,0 +1,24 @@ + + + + + + ./tests/Evenement/ + + + + + + ./src/ + + + diff --git a/vendor/evenement/evenement/src/Evenement/EventEmitter.php b/vendor/evenement/evenement/src/Evenement/EventEmitter.php new file mode 100644 index 00000000000..20a3d62436a --- /dev/null +++ b/vendor/evenement/evenement/src/Evenement/EventEmitter.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement; + +class EventEmitter implements EventEmitterInterface +{ + use EventEmitterTrait; +} diff --git a/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php b/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php new file mode 100644 index 00000000000..c7f02827ac0 --- /dev/null +++ b/vendor/evenement/evenement/src/Evenement/EventEmitterInterface.php @@ -0,0 +1,22 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement; + +interface EventEmitterInterface +{ + public function on($event, callable $listener); + public function once($event, callable $listener); + public function removeListener($event, callable $listener); + public function removeAllListeners($event = null); + public function listeners($event = null); + public function emit($event, array $arguments = []); +} diff --git a/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php b/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php new file mode 100644 index 00000000000..c64ee83f450 --- /dev/null +++ b/vendor/evenement/evenement/src/Evenement/EventEmitterTrait.php @@ -0,0 +1,108 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement; + +use InvalidArgumentException; +trait EventEmitterTrait +{ + protected $listeners = []; + protected $onceListeners = []; + public function on($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + if (!isset($this->listeners[$event])) { + $this->listeners[$event] = []; + } + $this->listeners[$event][] = $listener; + return $this; + } + public function once($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + if (!isset($this->onceListeners[$event])) { + $this->onceListeners[$event] = []; + } + $this->onceListeners[$event][] = $listener; + return $this; + } + public function removeListener($event, callable $listener) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + if (isset($this->listeners[$event])) { + $index = \array_search($listener, $this->listeners[$event], \true); + if (\false !== $index) { + unset($this->listeners[$event][$index]); + if (\count($this->listeners[$event]) === 0) { + unset($this->listeners[$event]); + } + } + } + if (isset($this->onceListeners[$event])) { + $index = \array_search($listener, $this->onceListeners[$event], \true); + if (\false !== $index) { + unset($this->onceListeners[$event][$index]); + if (\count($this->onceListeners[$event]) === 0) { + unset($this->onceListeners[$event]); + } + } + } + } + public function removeAllListeners($event = null) + { + if ($event !== null) { + unset($this->listeners[$event]); + } else { + $this->listeners = []; + } + if ($event !== null) { + unset($this->onceListeners[$event]); + } else { + $this->onceListeners = []; + } + } + public function listeners($event = null) : array + { + if ($event === null) { + $events = []; + $eventNames = \array_unique(\array_merge(\array_keys($this->listeners), \array_keys($this->onceListeners))); + foreach ($eventNames as $eventName) { + $events[$eventName] = \array_merge(isset($this->listeners[$eventName]) ? $this->listeners[$eventName] : [], isset($this->onceListeners[$eventName]) ? $this->onceListeners[$eventName] : []); + } + return $events; + } + return \array_merge(isset($this->listeners[$event]) ? $this->listeners[$event] : [], isset($this->onceListeners[$event]) ? $this->onceListeners[$event] : []); + } + public function emit($event, array $arguments = []) + { + if ($event === null) { + throw new InvalidArgumentException('event name must not be null'); + } + if (isset($this->listeners[$event])) { + foreach ($this->listeners[$event] as $listener) { + $listener(...$arguments); + } + } + if (isset($this->onceListeners[$event])) { + $listeners = $this->onceListeners[$event]; + unset($this->onceListeners[$event]); + foreach ($listeners as $listener) { + $listener(...$arguments); + } + } + } +} diff --git a/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php b/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php new file mode 100644 index 00000000000..c2bc7607700 --- /dev/null +++ b/vendor/evenement/evenement/tests/Evenement/Tests/EventEmitterTest.php @@ -0,0 +1,345 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement\Tests; + +use ECSPrefix202307\Evenement\EventEmitter; +use InvalidArgumentException; +use ECSPrefix202307\PHPUnit\Framework\TestCase; +class EventEmitterTest extends TestCase +{ + private $emitter; + public function setUp() + { + $this->emitter = new EventEmitter(); + } + public function testAddListenerWithLambda() + { + $this->emitter->on('foo', function () { + }); + } + public function testAddListenerWithMethod() + { + $listener = new Listener(); + $this->emitter->on('foo', [$listener, 'onFoo']); + } + public function testAddListenerWithStaticMethod() + { + $this->emitter->on('bar', ['ECSPrefix202307\\Evenement\\Tests\\Listener', 'onBar']); + } + public function testAddListenerWithInvalidListener() + { + try { + $this->emitter->on('foo', 'not a callable'); + $this->fail(); + } catch (\Exception $e) { + } catch (\TypeError $e) { + } + } + public function testOnce() + { + $listenerCalled = 0; + $this->emitter->once('foo', function () use(&$listenerCalled) { + $listenerCalled++; + }); + $this->assertSame(0, $listenerCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenerCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenerCalled); + } + public function testOnceWithArguments() + { + $capturedArgs = []; + $this->emitter->once('foo', function ($a, $b) use(&$capturedArgs) { + $capturedArgs = array($a, $b); + }); + $this->emitter->emit('foo', array('a', 'b')); + $this->assertSame(array('a', 'b'), $capturedArgs); + } + public function testEmitWithoutArguments() + { + $listenerCalled = \false; + $this->emitter->on('foo', function () use(&$listenerCalled) { + $listenerCalled = \true; + }); + $this->assertSame(\false, $listenerCalled); + $this->emitter->emit('foo'); + $this->assertSame(\true, $listenerCalled); + } + public function testEmitWithOneArgument() + { + $test = $this; + $listenerCalled = \false; + $this->emitter->on('foo', function ($value) use(&$listenerCalled, $test) { + $listenerCalled = \true; + $test->assertSame('bar', $value); + }); + $this->assertSame(\false, $listenerCalled); + $this->emitter->emit('foo', ['bar']); + $this->assertSame(\true, $listenerCalled); + } + public function testEmitWithTwoArguments() + { + $test = $this; + $listenerCalled = \false; + $this->emitter->on('foo', function ($arg1, $arg2) use(&$listenerCalled, $test) { + $listenerCalled = \true; + $test->assertSame('bar', $arg1); + $test->assertSame('baz', $arg2); + }); + $this->assertSame(\false, $listenerCalled); + $this->emitter->emit('foo', ['bar', 'baz']); + $this->assertSame(\true, $listenerCalled); + } + public function testEmitWithNoListeners() + { + $this->emitter->emit('foo'); + $this->emitter->emit('foo', ['bar']); + $this->emitter->emit('foo', ['bar', 'baz']); + } + public function testEmitWithTwoListeners() + { + $listenersCalled = 0; + $this->emitter->on('foo', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->emitter->on('foo', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(2, $listenersCalled); + } + public function testRemoveListenerMatching() + { + $listenersCalled = 0; + $listener = function () use(&$listenersCalled) { + $listenersCalled++; + }; + $this->emitter->on('foo', $listener); + $this->emitter->removeListener('foo', $listener); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(0, $listenersCalled); + } + public function testRemoveListenerNotMatching() + { + $listenersCalled = 0; + $listener = function () use(&$listenersCalled) { + $listenersCalled++; + }; + $this->emitter->on('foo', $listener); + $this->emitter->removeListener('bar', $listener); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenersCalled); + } + public function testRemoveAllListenersMatching() + { + $listenersCalled = 0; + $this->emitter->on('foo', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->emitter->removeAllListeners('foo'); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(0, $listenersCalled); + } + public function testRemoveAllListenersNotMatching() + { + $listenersCalled = 0; + $this->emitter->on('foo', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->emitter->removeAllListeners('bar'); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->assertSame(1, $listenersCalled); + } + public function testRemoveAllListenersWithoutArguments() + { + $listenersCalled = 0; + $this->emitter->on('foo', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->emitter->on('bar', function () use(&$listenersCalled) { + $listenersCalled++; + }); + $this->emitter->removeAllListeners(); + $this->assertSame(0, $listenersCalled); + $this->emitter->emit('foo'); + $this->emitter->emit('bar'); + $this->assertSame(0, $listenersCalled); + } + public function testCallablesClosure() + { + $calledWith = null; + $this->emitter->on('foo', function ($data) use(&$calledWith) { + $calledWith = $data; + }); + $this->emitter->emit('foo', ['bar']); + self::assertSame('bar', $calledWith); + } + public function testCallablesClass() + { + $listener = new Listener(); + $this->emitter->on('foo', [$listener, 'onFoo']); + $this->emitter->emit('foo', ['bar']); + self::assertSame(['bar'], $listener->getData()); + } + public function testCallablesClassInvoke() + { + $listener = new Listener(); + $this->emitter->on('foo', $listener); + $this->emitter->emit('foo', ['bar']); + self::assertSame(['bar'], $listener->getMagicData()); + } + public function testCallablesStaticClass() + { + $this->emitter->on('foo', '\\Evenement\\Tests\\Listener::onBar'); + $this->emitter->emit('foo', ['bar']); + self::assertSame(['bar'], Listener::getStaticData()); + } + public function testCallablesFunction() + { + $this->emitter->on('foo', 'ECSPrefix202307\\Evenement\\Tests\\setGlobalTestData'); + $this->emitter->emit('foo', ['bar']); + self::assertSame('bar', $GLOBALS['evenement-evenement-test-data']); + unset($GLOBALS['evenement-evenement-test-data']); + } + public function testListeners() + { + $onA = function () { + }; + $onB = function () { + }; + $onC = function () { + }; + $onceA = function () { + }; + $onceB = function () { + }; + $onceC = function () { + }; + self::assertCount(0, $this->emitter->listeners('event')); + $this->emitter->on('event', $onA); + self::assertCount(1, $this->emitter->listeners('event')); + self::assertSame([$onA], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceA); + self::assertCount(2, $this->emitter->listeners('event')); + self::assertSame([$onA, $onceA], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceB); + self::assertCount(3, $this->emitter->listeners('event')); + self::assertSame([$onA, $onceA, $onceB], $this->emitter->listeners('event')); + $this->emitter->on('event', $onB); + self::assertCount(4, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceA, $onceB], $this->emitter->listeners('event')); + $this->emitter->removeListener('event', $onceA); + self::assertCount(3, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceB], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceC); + self::assertCount(4, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onceB, $onceC], $this->emitter->listeners('event')); + $this->emitter->on('event', $onC); + self::assertCount(5, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onC, $onceB, $onceC], $this->emitter->listeners('event')); + $this->emitter->once('event', $onceA); + self::assertCount(6, $this->emitter->listeners('event')); + self::assertSame([$onA, $onB, $onC, $onceB, $onceC, $onceA], $this->emitter->listeners('event')); + $this->emitter->removeListener('event', $onB); + self::assertCount(5, $this->emitter->listeners('event')); + self::assertSame([$onA, $onC, $onceB, $onceC, $onceA], $this->emitter->listeners('event')); + $this->emitter->emit('event'); + self::assertCount(2, $this->emitter->listeners('event')); + self::assertSame([$onA, $onC], $this->emitter->listeners('event')); + } + public function testOnceCallIsNotRemovedWhenWorkingOverOnceListeners() + { + $aCalled = \false; + $aCallable = function () use(&$aCalled) { + $aCalled = \true; + }; + $bCalled = \false; + $bCallable = function () use(&$bCalled, $aCallable) { + $bCalled = \true; + $this->emitter->once('event', $aCallable); + }; + $this->emitter->once('event', $bCallable); + self::assertFalse($aCalled); + self::assertFalse($bCalled); + $this->emitter->emit('event'); + self::assertFalse($aCalled); + self::assertTrue($bCalled); + $this->emitter->emit('event'); + self::assertTrue($aCalled); + self::assertTrue($bCalled); + } + public function testEventNameMustBeStringOn() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + $this->emitter->on(null, function () { + }); + } + public function testEventNameMustBeStringOnce() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + $this->emitter->once(null, function () { + }); + } + public function testEventNameMustBeStringRemoveListener() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + $this->emitter->removeListener(null, function () { + }); + } + public function testEventNameMustBeStringEmit() + { + self::expectException(InvalidArgumentException::class); + self::expectExceptionMessage('event name must not be null'); + $this->emitter->emit(null); + } + public function testListenersGetAll() + { + $a = function () { + }; + $b = function () { + }; + $c = function () { + }; + $d = function () { + }; + $this->emitter->once('event2', $c); + $this->emitter->on('event', $a); + $this->emitter->once('event', $b); + $this->emitter->on('event', $c); + $this->emitter->once('event', $d); + self::assertSame(['event' => [$a, $c, $b, $d], 'event2' => [$c]], $this->emitter->listeners()); + } + public function testOnceNestedCallRegression() + { + $first = 0; + $second = 0; + $this->emitter->once('event', function () use(&$first, &$second) { + $first++; + $this->emitter->once('event', function () use(&$second) { + $second++; + }); + $this->emitter->emit('event'); + }); + $this->emitter->emit('event'); + self::assertSame(1, $first); + self::assertSame(1, $second); + } +} diff --git a/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php b/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php new file mode 100644 index 00000000000..62f77328a15 --- /dev/null +++ b/vendor/evenement/evenement/tests/Evenement/Tests/Listener.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement\Tests; + +class Listener +{ + private $data = []; + private $magicData = []; + private static $staticData = []; + public function onFoo($data) + { + $this->data[] = $data; + } + public function __invoke($data) + { + $this->magicData[] = $data; + } + public static function onBar($data) + { + self::$staticData[] = $data; + } + public function getData() + { + return $this->data; + } + public function getMagicData() + { + return $this->magicData; + } + public static function getStaticData() + { + return self::$staticData; + } +} diff --git a/vendor/evenement/evenement/tests/Evenement/Tests/functions.php b/vendor/evenement/evenement/tests/Evenement/Tests/functions.php new file mode 100644 index 00000000000..ef26b4e73d0 --- /dev/null +++ b/vendor/evenement/evenement/tests/Evenement/Tests/functions.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\Evenement\Tests; + +function setGlobalTestData($data) +{ + $GLOBALS['evenement-evenement-test-data'] = $data; +} diff --git a/vendor/fidry/cpu-core-counter/LICENSE.md b/vendor/fidry/cpu-core-counter/LICENSE.md new file mode 100644 index 00000000000..02442130a89 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/LICENSE.md @@ -0,0 +1,16 @@ +# The MIT License (MIT) + +Copyright (c) 2022 Théo FIDRY + +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. diff --git a/vendor/fidry/cpu-core-counter/README.md b/vendor/fidry/cpu-core-counter/README.md new file mode 100644 index 00000000000..8c86a187506 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/README.md @@ -0,0 +1,114 @@ +# CPU Core Counter + +This package is a tiny utility to get the number of CPU cores. + +```sh +composer require fidry/cpu-core-counter +``` + + +## Usage + +```php +use Fidry\CpuCoreCounter\CpuCoreCounter; +use Fidry\CpuCoreCounter\NumberOfCpuCoreNotFound; +use Fidry\CpuCoreCounter\Finder\DummyCpuCoreFinder; + +$counter = new CpuCoreCounter(); + +try { + $counter->getCount(); // e.g. 8 +} catch (NumberOfCpuCoreNotFound) { + return 1; // Fallback value +} + +// An alternative form where we not want to catch the exception: + +$counter = new CpuCoreCounter([ + ...CpuCoreCounter::getDefaultFinders(), + new DummyCpuCoreFinder(1), // Fallback value +]); + +$counter->getCount(); // e.g. 8 + +``` + + +## Advanced usage + +### Changing the finders + +When creating `CpuCoreCounter`, you may want to change the order of the finders +used or disable a specific finder. You can easily do so by passing the finders +you want + +```php +// Remove WindowsWmicFinder +$finders = array_filter( + CpuCoreCounter::getDefaultFinders(), + static fn (CpuCoreFinder $finder) => !($finder instanceof WindowsWmicFinder) +); + +$cores = (new CpuCoreCounter($finders))->getCount(); +``` + +```php +// Use CPUInfo first & don't use Nproc +$finders = [ + new CpuInfoFinder(), + new WindowsWmicFinder(), + new HwLogicalFinder(), +]; + +$cores = (new CpuCoreCounter($finders))->getCount(); +``` + +### Choosing only logical or physical finders + +`FinderRegistry` provides two helpful entries: + +- `::getDefaultLogicalFinders()`: gives an ordered list of finders that will + look for the _logical_ CPU cores count +- `::getDefaultPhysicalFinders()`: gives an ordered list of finders that will + look for the _physical_ CPU cores count + +By default when using `CpuCoreCounter`, it will use the logical finders since +it is more likely what you are looking for and is what is used by PHP source to +build the PHP binary. + + +### Checks what finders find what on your system + +You have two commands available that provides insight about what the finders +can find: + +``` +$ make diagnosis # From this repository +$ ./vendor/fidry/cpu-core-counter/bin/diagnose.php # From the library +``` + +And: +``` +$ make execute # From this repository +$ ./vendor/fidry/cpu-core-counter/bin/execute.php # From the library +``` + + +## Backward Compatibility Promise (BCP) + +The policy is for the major part following the same as [Symfony's one][symfony-bc-policy]. +Note that the code marked as `@private` or `@internal` are excluded from the BCP. + +The following elements are also excluded: + +- The `diagnose` and `execute` commands: those are for debugging/inspection purposes only +- `FinderRegistry::get*Finders()`: new finders may be added or the order of finders changed at any time + + +## License + +This package is licensed using the MIT License. + +Please have a look at [`LICENSE.md`](LICENSE.md). + +[symfony-bc-policy]: https://symfony.com/doc/current/contributing/code/bc.html diff --git a/vendor/fidry/cpu-core-counter/bin/diagnose.php b/vendor/fidry/cpu-core-counter/bin/diagnose.php new file mode 100644 index 00000000000..5489fa753bd --- /dev/null +++ b/vendor/fidry/cpu-core-counter/bin/diagnose.php @@ -0,0 +1,18 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Diagnoser; +use ECSPrefix202307\Fidry\CpuCoreCounter\Finder\FinderRegistry; +require_once __DIR__ . '/../vendor/autoload.php'; +echo 'Running diagnosis...' . \PHP_EOL . \PHP_EOL; +echo Diagnoser::diagnose(FinderRegistry::getAllVariants()) . \PHP_EOL; diff --git a/vendor/fidry/cpu-core-counter/bin/execute.php b/vendor/fidry/cpu-core-counter/bin/execute.php new file mode 100644 index 00000000000..40c39ec454d --- /dev/null +++ b/vendor/fidry/cpu-core-counter/bin/execute.php @@ -0,0 +1,18 @@ +#!/usr/bin/env php + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Diagnoser; +use ECSPrefix202307\Fidry\CpuCoreCounter\Finder\FinderRegistry; +require_once __DIR__ . '/../vendor/autoload.php'; +echo 'Executing finders...' . \PHP_EOL . \PHP_EOL; +echo Diagnoser::execute(FinderRegistry::getAllVariants()) . \PHP_EOL; diff --git a/vendor/fidry/cpu-core-counter/composer.json b/vendor/fidry/cpu-core-counter/composer.json new file mode 100644 index 00000000000..30f3ecd0105 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/composer.json @@ -0,0 +1,48 @@ +{ + "name": "fidry\/cpu-core-counter", + "description": "Tiny utility to get the number of CPU cores.", + "license": "MIT", + "type": "library", + "keywords": [ + "cpu", + "core" + ], + "authors": [ + { + "name": "Th\u00e9o FIDRY", + "email": "theo.fidry@gmail.com" + } + ], + "require": { + "php": "^7.2 || ^8.0" + }, + "require-dev": { + "fidry\/makefile": "^0.2.0", + "phpstan\/extension-installer": "^1.2.0", + "phpstan\/phpstan": "^1.9.2", + "phpstan\/phpstan-deprecation-rules": "^1.0.0", + "phpstan\/phpstan-phpunit": "^1.2.2", + "phpstan\/phpstan-strict-rules": "^1.4.4", + "phpunit\/phpunit": "^9.5.26 || ^8.5.31", + "theofidry\/php-cs-fixer-config": "^1.0", + "webmozarts\/strict-phpunit": "^7.5" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Fidry\\CpuCoreCounter\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\Fidry\\CpuCoreCounter\\Test\\": "tests\/" + } + }, + "config": { + "allow-plugins": { + "ergebnis\/composer-normalize": true, + "infection\/extension-installer": true, + "phpstan\/extension-installer": true + }, + "sort-packages": true + } +} \ No newline at end of file diff --git a/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php b/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php new file mode 100644 index 00000000000..388bdf7b397 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/CpuCoreCounter.php @@ -0,0 +1,76 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Finder\CpuCoreFinder; +use ECSPrefix202307\Fidry\CpuCoreCounter\Finder\FinderRegistry; +final class CpuCoreCounter +{ + /** + * @var list + */ + private $finders; + /** + * @var positive-int|null + */ + private $count; + /** + * @param list|null $finders + */ + public function __construct(?array $finders = null) + { + $this->finders = $finders ?? FinderRegistry::getDefaultLogicalFinders(); + } + /** + * @throws NumberOfCpuCoreNotFound + * + * @return positive-int + */ + public function getCount() : int + { + // Memoize result + if (null === $this->count) { + $this->count = $this->findCount(); + } + return $this->count; + } + /** + * @throws NumberOfCpuCoreNotFound + * + * @return positive-int + */ + private function findCount() : int + { + foreach ($this->finders as $finder) { + $cores = $finder->find(); + if (null !== $cores) { + return $cores; + } + } + throw NumberOfCpuCoreNotFound::create(); + } + /** + * @throws NumberOfCpuCoreNotFound + * + * @return array{CpuCoreFinder, positive-int} + */ + public function getFinderAndCores() : array + { + foreach ($this->finders as $finder) { + $cores = $finder->find(); + if (null !== $cores) { + return [$finder, $cores]; + } + } + throw NumberOfCpuCoreNotFound::create(); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Diagnoser.php b/vendor/fidry/cpu-core-counter/src/Diagnoser.php new file mode 100644 index 00000000000..2a470a7c000 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Diagnoser.php @@ -0,0 +1,63 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Finder\CpuCoreFinder; +use function array_map; +use function explode; +use function implode; +use function max; +use function str_repeat; +use const PHP_EOL; +/** + * Utility to debug. + * + * @private + */ +final class Diagnoser +{ + /** + * Provides an aggregated diagnosis based on each finders diagnosis. + * + * @param list $finders + */ + public static function diagnose(array $finders) : string + { + $diagnoses = array_map(static function (CpuCoreFinder $finder) : string { + return self::diagnoseFinder($finder); + }, $finders); + return implode(PHP_EOL, $diagnoses); + } + /** + * Executes each finders. + * + * @param list $finders + */ + public static function execute(array $finders) : string + { + $diagnoses = array_map(static function (CpuCoreFinder $finder) : string { + $coresCount = $finder->find(); + return implode('', [$finder->toString(), ': ', null === $coresCount ? 'NULL' : $coresCount]); + }, $finders); + return implode(PHP_EOL, $diagnoses); + } + private static function diagnoseFinder(CpuCoreFinder $finder) : string + { + $diagnosis = $finder->diagnose(); + $maxLineLength = max(array_map('strlen', explode(PHP_EOL, $diagnosis))); + $separator = str_repeat('-', $maxLineLength); + return implode('', [$finder->toString() . ':' . PHP_EOL, $separator . PHP_EOL, $diagnosis . PHP_EOL, $separator . PHP_EOL]); + } + private function __construct() + { + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php b/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php new file mode 100644 index 00000000000..9ef6a9b61e8 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Executor/ProcOpenExecutor.php @@ -0,0 +1,43 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Executor; + +use function fclose; +use function function_exists; +use function is_resource; +use function proc_close; +use function proc_open; +use function stream_get_contents; +final class ProcOpenExecutor implements ProcessExecutor +{ + public function execute(string $command) : ?array + { + if (!function_exists('proc_open')) { + return null; + } + $pipes = []; + $process = @proc_open($command, [ + ['pipe', 'rb'], + ['pipe', 'wb'], + // stdout + ['pipe', 'wb'], + ], $pipes); + if (!is_resource($process)) { + return null; + } + fclose($pipes[0]); + $stdout = (string) stream_get_contents($pipes[1]); + $stderr = (string) stream_get_contents($pipes[2]); + proc_close($process); + return [$stdout, $stderr]; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php b/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php new file mode 100644 index 00000000000..d99fdf86082 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Executor/ProcessExecutor.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Executor; + +interface ProcessExecutor +{ + /** + * @return array{string, string}|null STDOUT & STDERR tuple + */ + public function execute(string $command) : ?array; +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php new file mode 100644 index 00000000000..91fbccdc38d --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/CpuCoreFinder.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +interface CpuCoreFinder +{ + /** + * Provides an explanation which may offer some insight as to what the finder + * will be able to find. + * + * This is practical to have an idea of what each finder will find collect + * information for the unit tests, since integration tests are quite complicated + * as dependent on complex infrastructures. + */ + public function diagnose() : string; + /** + * Find the number of CPU cores. If it could not find it, returns null. The + * means used to find the cores are at the implementation discretion. + * + * @return positive-int|null + */ + public function find() : ?int; + public function toString() : string; +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php new file mode 100644 index 00000000000..e712eb364f4 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/CpuInfoFinder.php @@ -0,0 +1,70 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function file_get_contents; +use function is_file; +use function sprintf; +use function substr_count; +use const PHP_EOL; +/** + * Find the number of CPU cores looking up at the cpuinfo file which is available + * on Linux systems and Windows systems with a Linux sub-system. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://unix.stackexchange.com/questions/146051/number-of-processors-in-proc-cpuinfo + */ +final class CpuInfoFinder implements CpuCoreFinder +{ + private const CPU_INFO_PATH = '/proc/cpuinfo'; + public function diagnose() : string + { + if (!is_file(self::CPU_INFO_PATH)) { + return sprintf('The file "%s" could not be found.', self::CPU_INFO_PATH); + } + $cpuInfo = file_get_contents(self::CPU_INFO_PATH); + if (\false === $cpuInfo) { + return sprintf('Could not get the content of the file "%s".', self::CPU_INFO_PATH); + } + return sprintf('Found the file "%s" with the content:%s%s', self::CPU_INFO_PATH, PHP_EOL, $cpuInfo); + } + /** + * @return positive-int|null + */ + public function find() : ?int + { + $cpuInfo = self::getCpuInfo(); + return null === $cpuInfo ? null : self::countCpuCores($cpuInfo); + } + public function toString() : string + { + return 'CpuInfoFinder'; + } + private static function getCpuInfo() : ?string + { + if (!@is_file(self::CPU_INFO_PATH)) { + return null; + } + $cpuInfo = @file_get_contents(self::CPU_INFO_PATH); + return \false === $cpuInfo ? null : $cpuInfo; + } + /** + * @internal + * + * @return positive-int|null + */ + public static function countCpuCores(string $cpuInfo) : ?int + { + $processorCount = substr_count($cpuInfo, 'processor'); + return $processorCount > 0 ? $processorCount : null; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php new file mode 100644 index 00000000000..8c607f6dce6 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/DummyCpuCoreFinder.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function sprintf; +/** + * This finder returns whatever value you gave to it. This is useful for testing + * or as a fallback to avoid to catch the NumberOfCpuCoreNotFound exception. + */ +final class DummyCpuCoreFinder implements CpuCoreFinder +{ + /** + * @var positive-int + */ + private $count; + public function diagnose() : string + { + return sprintf('Will return "%d".', $this->count); + } + /** + * @param positive-int $count + */ + public function __construct(int $count) + { + $this->count = $count; + } + public function find() : ?int + { + return $this->count; + } + public function toString() : string + { + return sprintf('DummyCpuCoreFinder(value=%d)', $this->count); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php b/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php new file mode 100644 index 00000000000..8162095911e --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/FinderRegistry.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +final class FinderRegistry +{ + /** + * @return list List of all the known finders with all their variants. + */ + public static function getAllVariants() : array + { + return [new CpuInfoFinder(), new DummyCpuCoreFinder(1), new HwLogicalFinder(), new HwPhysicalFinder(), new LscpuLogicalFinder(), new LscpuPhysicalFinder(), new _NProcessorFinder(), new NProcessorFinder(), new NProcFinder(\true), new NProcFinder(\false), new NullCpuCoreFinder(), SkipOnOSFamilyFinder::forWindows(new DummyCpuCoreFinder(1)), OnlyOnOSFamilyFinder::forWindows(new DummyCpuCoreFinder(1)), new WmicPhysicalFinder(), new WmicLogicalFinder()]; + } + /** + * @return list + */ + public static function getDefaultLogicalFinders() : array + { + return [OnlyOnOSFamilyFinder::forWindows(new WmicLogicalFinder()), new NProcFinder(), new HwLogicalFinder(), new _NProcessorFinder(), new NProcessorFinder(), new LscpuLogicalFinder(), new CpuInfoFinder()]; + } + /** + * @return list + */ + public static function getDefaultPhysicalFinders() : array + { + return [OnlyOnOSFamilyFinder::forWindows(new WmicPhysicalFinder()), new HwPhysicalFinder(), new LscpuPhysicalFinder()]; + } + private function __construct() + { + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php new file mode 100644 index 00000000000..f0818c97946 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/HwLogicalFinder.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for Linux, BSD and OSX. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://opensource.apple.com/source/xnu/xnu-792.2.4/libkern/libkern/sysctl.h.auto.html + */ +final class HwLogicalFinder extends ProcOpenBasedFinder +{ + protected function getCommand() : string + { + return 'sysctl -n hw.logicalcpu'; + } + public function toString() : string + { + return 'HwLogicalFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php new file mode 100644 index 00000000000..c6dd9396a6f --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/HwPhysicalFinder.php @@ -0,0 +1,30 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of physical CPU cores for Linux, BSD and OSX. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L903-L909 + * @see https://opensource.apple.com/source/xnu/xnu-792.2.4/libkern/libkern/sysctl.h.auto.html + */ +final class HwPhysicalFinder extends ProcOpenBasedFinder +{ + protected function getCommand() : string + { + return 'sysctl -n hw.physicalcpu'; + } + public function toString() : string + { + return 'HwPhysicalFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php new file mode 100644 index 00000000000..411c7a035cd --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/LscpuLogicalFinder.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function count; +use function explode; +use function is_array; +use function preg_grep; +use const PHP_EOL; +/** + * The number of logical cores. + * + * @see https://stackoverflow.com/a/23378780/5846754 + */ +final class LscpuLogicalFinder extends ProcOpenBasedFinder +{ + public function getCommand() : string + { + return 'lscpu -p'; + } + protected function countCpuCores(string $process) : ?int + { + $lines = explode(PHP_EOL, $process); + $actualLines = preg_grep('/^\\d+,/', $lines); + if (!is_array($actualLines)) { + return null; + } + $count = count($actualLines); + return 0 === $count ? null : $count; + } + public function toString() : string + { + return 'LscpuLogicalFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php new file mode 100644 index 00000000000..61e84877b30 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/LscpuPhysicalFinder.php @@ -0,0 +1,55 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function count; +use function explode; +use function is_array; +use function preg_grep; +use function strtok; +use const PHP_EOL; +/** + * The number of physical processors. + * + * @see https://stackoverflow.com/a/23378780/5846754 + */ +final class LscpuPhysicalFinder extends ProcOpenBasedFinder +{ + public function toString() : string + { + return 'LscpuPhysicalFinder'; + } + public function getCommand() : string + { + return 'lscpu -p'; + } + protected function countCpuCores(string $process) : ?int + { + $lines = explode(PHP_EOL, $process); + $actualLines = preg_grep('/^\\d+/', $lines); + if (!is_array($actualLines)) { + return null; + } + $cores = []; + foreach ($actualLines as $line) { + strtok($line, ','); + $core = strtok(','); + if (\false === $core) { + continue; + } + $cores[$core] = \true; + } + unset($cores['-']); + $count = count($cores); + return 0 === $count ? null : $count; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php new file mode 100644 index 00000000000..9f28ecb343e --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/NProcFinder.php @@ -0,0 +1,44 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Executor\ProcessExecutor; +use function sprintf; +/** + * The number of (logical) cores. + * + * @see https://github.com/infection/infection/blob/fbd8c44/src/Resource/Processor/CpuCoresCountProvider.php#L69-L82 + * @see https://unix.stackexchange.com/questions/146051/number-of-processors-in-proc-cpuinfo + */ +final class NProcFinder extends ProcOpenBasedFinder +{ + /** + * @var bool + */ + private $all; + /** + * @param bool $all If disabled will give the number of cores available for the current process only. + */ + public function __construct(bool $all = \true, ?ProcessExecutor $executor = null) + { + parent::__construct($executor); + $this->all = $all; + } + public function toString() : string + { + return sprintf('NProcFinder(all=%s)', $this->all ? 'true' : 'false'); + } + protected function getCommand() : string + { + return 'nproc' . ($this->all ? ' --all' : ''); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php new file mode 100644 index 00000000000..591c17edf10 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/NProcessorFinder.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for FreeSBD, Solaris and the likes. + * + * @see https://twitter.com/freebsdfrau/status/1052016199452700678?s=20&t=M2pHkRqmmna-UF68lfL2hw + */ +final class NProcessorFinder extends ProcOpenBasedFinder +{ + protected function getCommand() : string + { + return 'getconf NPROCESSORS_ONLN'; + } + public function toString() : string + { + return 'NProcessorFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php new file mode 100644 index 00000000000..ac82ac02b65 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/NullCpuCoreFinder.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +/** + * This finder returns whatever value you gave to it. This is useful for testing. + */ +final class NullCpuCoreFinder implements CpuCoreFinder +{ + public function diagnose() : string + { + return 'Will return "null".'; + } + public function find() : ?int + { + return null; + } + public function toString() : string + { + return 'NullCpuCoreFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php new file mode 100644 index 00000000000..7aab9fc2c54 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/OnlyOnOSFamilyFinder.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function implode; +use function sprintf; +use const PHP_OS_FAMILY; +final class OnlyOnOSFamilyFinder implements CpuCoreFinder +{ + /** + * @var list + */ + private $skippedOSFamilies; + /** + * @var CpuCoreFinder + */ + private $decoratedFinder; + /** + * @param string|list $skippedOSFamilyOrFamilies + */ + public function __construct($skippedOSFamilyOrFamilies, CpuCoreFinder $decoratedFinder) + { + $this->skippedOSFamilies = (array) $skippedOSFamilyOrFamilies; + $this->decoratedFinder = $decoratedFinder; + } + public static function forWindows(CpuCoreFinder $decoratedFinder) : self + { + return new self('Windows', $decoratedFinder); + } + public static function forBSD(CpuCoreFinder $decoratedFinder) : self + { + return new self('BSD', $decoratedFinder); + } + public static function forDarwin(CpuCoreFinder $decoratedFinder) : self + { + return new self('Darwin', $decoratedFinder); + } + public static function forSolaris(CpuCoreFinder $decoratedFinder) : self + { + return new self('Solaris', $decoratedFinder); + } + public static function forLinux(CpuCoreFinder $decoratedFinder) : self + { + return new self('Linux', $decoratedFinder); + } + public function diagnose() : string + { + return $this->skip() ? sprintf('Skipped platform detected ("%s").', PHP_OS_FAMILY) : $this->decoratedFinder->diagnose(); + } + public function find() : ?int + { + return $this->skip() ? null : $this->decoratedFinder->find(); + } + public function toString() : string + { + return sprintf('OnlyOnOSFamilyFinder(only=(%s),%s)', implode(',', $this->skippedOSFamilies), $this->decoratedFinder->toString()); + } + private function skip() : bool + { + return !\in_array(PHP_OS_FAMILY, $this->skippedOSFamilies, \true); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php new file mode 100644 index 00000000000..f3cb1c7804c --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/ProcOpenBasedFinder.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use ECSPrefix202307\Fidry\CpuCoreCounter\Executor\ProcessExecutor; +use ECSPrefix202307\Fidry\CpuCoreCounter\Executor\ProcOpenExecutor; +use function filter_var; +use function function_exists; +use function is_int; +use function sprintf; +use function trim; +use const FILTER_VALIDATE_INT; +use const PHP_EOL; +abstract class ProcOpenBasedFinder implements CpuCoreFinder +{ + /** + * @var ProcessExecutor + */ + private $executor; + public function __construct(?ProcessExecutor $executor = null) + { + $this->executor = $executor ?? new ProcOpenExecutor(); + } + public function diagnose() : string + { + if (!function_exists('proc_open')) { + return 'The function "proc_open" is not available.'; + } + $command = $this->getCommand(); + $output = $this->executor->execute($command); + if (null === $output) { + return sprintf('Failed to execute the command "%s".', $command); + } + [$stdout, $stderr] = $output; + $failed = '' !== trim($stderr); + return $failed ? sprintf('Executed the command "%s" which wrote the following output to the STDERR:%s%s', $command, PHP_EOL, $stderr) : sprintf('Executed the command "%s" and got the following (STDOUT) output:%s%s', $command, PHP_EOL, $stdout); + } + /** + * @return positive-int|null + */ + public function find() : ?int + { + $output = $this->executor->execute($this->getCommand()); + if (null === $output) { + return null; + } + [$stdout, $stderr] = $output; + $failed = '' !== trim($stderr); + return $failed ? null : $this->countCpuCores($stdout); + } + /** + * @internal + * + * @return positive-int|null + */ + protected function countCpuCores(string $process) : ?int + { + $cpuCount = filter_var($process, FILTER_VALIDATE_INT); + return is_int($cpuCount) && $cpuCount > 0 ? $cpuCount : null; + } + protected abstract function getCommand() : string; +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php new file mode 100644 index 00000000000..616731c7df6 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/SkipOnOSFamilyFinder.php @@ -0,0 +1,71 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function implode; +use function in_array; +use function sprintf; +final class SkipOnOSFamilyFinder implements CpuCoreFinder +{ + /** + * @var list + */ + private $skippedOSFamilies; + /** + * @var CpuCoreFinder + */ + private $decoratedFinder; + /** + * @param string|list $skippedOSFamilyOrFamilies + */ + public function __construct($skippedOSFamilyOrFamilies, CpuCoreFinder $decoratedFinder) + { + $this->skippedOSFamilies = (array) $skippedOSFamilyOrFamilies; + $this->decoratedFinder = $decoratedFinder; + } + public static function forWindows(CpuCoreFinder $decoratedFinder) : self + { + return new self('Windows', $decoratedFinder); + } + public static function forBSD(CpuCoreFinder $decoratedFinder) : self + { + return new self('BSD', $decoratedFinder); + } + public static function forDarwin(CpuCoreFinder $decoratedFinder) : self + { + return new self('Darwin', $decoratedFinder); + } + public static function forSolaris(CpuCoreFinder $decoratedFinder) : self + { + return new self('Solaris', $decoratedFinder); + } + public static function forLinux(CpuCoreFinder $decoratedFinder) : self + { + return new self('Linux', $decoratedFinder); + } + public function diagnose() : string + { + return $this->skip() ? sprintf('Skipped platform detected ("%s").', \PHP_OS_FAMILY) : $this->decoratedFinder->diagnose(); + } + public function find() : ?int + { + return $this->skip() ? null : $this->decoratedFinder->find(); + } + public function toString() : string + { + return sprintf('SkipOnOSFamilyFinder(skip=(%s),%s)', implode(',', $this->skippedOSFamilies), $this->decoratedFinder->toString()); + } + private function skip() : bool + { + return in_array(\PHP_OS_FAMILY, $this->skippedOSFamilies, \true); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php new file mode 100644 index 00000000000..48d6f22d4d1 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/WmicLogicalFinder.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function preg_match; +/** + * Find the number of logical CPU cores for Windows. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L912-L916 + */ +final class WmicLogicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfLogicalProcessors[\\s\\n]+(?\\d+)/'; + protected function getCommand() : string + { + return 'wmic cpu get NumberOfLogicalProcessors'; + } + public function toString() : string + { + return 'WmicLogicalFinder'; + } + protected function countCpuCores(string $process) : ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + $count = $matches['count']; + return parent::countCpuCores($count); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php new file mode 100644 index 00000000000..f13d6d43ee0 --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/WmicPhysicalFinder.php @@ -0,0 +1,39 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +use function preg_match; +/** + * Find the number of physical CPU cores for Windows. + * + * @see https://github.com/paratestphp/paratest/blob/c163539818fd96308ca8dc60f46088461e366ed4/src/Runners/PHPUnit/Options.php#L912-L916 + */ +final class WmicPhysicalFinder extends ProcOpenBasedFinder +{ + private const CPU_CORE_COUNT_REGEX = '/NumberOfCores[\\s\\n]+(?\\d+)/'; + protected function getCommand() : string + { + return 'wmic cpu get NumberOfCores'; + } + public function toString() : string + { + return 'WmicPhysicalFinder'; + } + protected function countCpuCores(string $process) : ?int + { + if (0 === preg_match(self::CPU_CORE_COUNT_REGEX, $process, $matches)) { + return parent::countCpuCores($process); + } + $count = $matches['count']; + return parent::countCpuCores($count); + } +} diff --git a/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php b/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php new file mode 100644 index 00000000000..d6985d260ec --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/Finder/_NProcessorFinder.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter\Finder; + +/** + * Find the number of logical CPU cores for Linux and the likes. + * + * @see https://twitter.com/freebsdfrau/status/1052016199452700678?s=20&t=M2pHkRqmmna-UF68lfL2hw + */ +final class _NProcessorFinder extends ProcOpenBasedFinder +{ + protected function getCommand() : string + { + return 'getconf _NPROCESSORS_ONLN'; + } + public function toString() : string + { + return '_NProcessorFinder'; + } +} diff --git a/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php b/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php new file mode 100644 index 00000000000..859e3d5473c --- /dev/null +++ b/vendor/fidry/cpu-core-counter/src/NumberOfCpuCoreNotFound.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +declare (strict_types=1); +namespace ECSPrefix202307\Fidry\CpuCoreCounter; + +use RuntimeException; +final class NumberOfCpuCoreNotFound extends RuntimeException +{ + public static function create() : self + { + return new self('Could not find the number of CPU cores available.'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md b/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md new file mode 100644 index 00000000000..2993a52f0dd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/CHANGELOG.md @@ -0,0 +1,4794 @@ +CHANGELOG for PHP CS Fixer +========================== + +This file contains changelogs for stable releases only. + +Changelog for v3.22.0 +--------------------- + +* DX: add proper test for `SelfAccessorFixer` must run before `SelfAccessorFixer` (#7153) +* DX: FixerFactoryTest - apply CS (#7154) +* feature: Introduce `PhpUnitDataProviderReturnTypeFixer` (#7156) +* feature: Introduce `YieldFromArrayToYieldsFixer` (#7114) + +Changelog for v3.21.3 +--------------------- + +* Revert "DX: encourage to provide wider description" (#7155) + +Changelog for v3.21.2 +--------------------- + +* docs: check format of FixerDefinition::getDescription() (#7127) +* DX: add phpstan/phpstan-strict-rules (#7143) +* DX: allow for progressive cache (#7132) +* DX: Copy-pasteable `class::getPriority` for phpDoc diffs (#7148) +* DX: do not allow linebreak at the beginning of code sample (#7126) +* DX: encourage to provide wider description (#7128) +* DX: fix function calls (#7136) +* DX: fix PHPDoc types issues (#7135) +* DX: improve `Tokens` checking for found tokens (#7139) +* DX: Make `AbstractFixerTestCase::getTestFile()` final (#7116) +* DX: make `array_search` call strict (#7145) +* DX: remove `empty` calls (#7138) +* DX: store cache to file only if content will get modified (#7151) +* DX: unify Preg:match in logical conditions (#7146) +* DX: use booleans in conditions (#7149) +* DX: Use ParaUnit to speed up tests (#6883) +* DX: Use relative fixture path as integration test case's name (#7147) +* DX: use strict assertions (#7144) +* DX: `AbstractIntegrationTestCase::provideIntegrationCases` - yield over array, better typehinting (#7150) + +Changelog for v3.21.1 +--------------------- + +experimental release + +* Require PHP ^8.0.1 + +Changelog for v3.21.0 +--------------------- + +* bug: Fix and enhance Gitlab reporter (#7089) +* bug: Import with different case must not be removed by non-risky fixer (#7095) +* bug: ordered imports fixer top group only (#7023) +* bug: `FinalPublicMethodForAbstractClassFixer` - fix for readonly classes (#7123) +* DX: do not nest ".editorconfig" files (#7112) +* DX: exclude Dockerfile from dist (#7113) +* DX: fix checkbashisms installation (#7102) +* DX: fix Smoke tests for various git default branch name (#7119) +* DX: Fix `FileRemovalTest` (do not fail when running it standalone) (#7104) +* DX: Progress output refactor (#6848) +* DX: Rename abstract test classes to `*TestCase` convention (#7100) +* DX: test all PHPUnit migration sets (#7107) +* DX: [Docker] Distinguish Alpine version between PHP versions (#7105) +* feature: Create cache path if it does not exist (#7109) +* feature: Introduce `NullableTypeDeclarationFixer` (#7002) +* feature: Introduce `TypeDeclarationSpacesFixer` (#7001) +* feature: `BlankLineBetweenImportGroupsFixer` - keep indent (#7122) +* minor: Parse callable using full phpdoc grammar (#7094) +* minor: PHP8.3 const type tokenizing (#7055) + +Changelog for v3.20.0 +--------------------- + +* DX: fix priority of `FinalClassFixer` (#7091) +* DX: use FAST_LINT_TEST_CASES=1 for CI run on macOS (#7092) +* feature: SingleLineEmptyBodyFixer - support interfaces, traits and enums (#7096) +* feature: `NullableTypeDeclarationForDefaultNullValue` - support for nullability in union types (#5819) + +Changelog for v3.19.2 +--------------------- + +* bug: NoMultipleStatementsPerLineFixer must run before CurlyBracesPositionFixer (#7087) +* bug: PhpdocAddMissingParamAnnotationFixer - fix for promoted properties (#7090) +* DX: fix priority of SingleBlankLineBeforeNamespaceFixer (#7088) +* minor: Parse all phpdoc types using full grammar (#7010) + +Changelog for v3.19.1 +--------------------- + +* bug: CurlyBracesPositionFixer must run before StatementIndentationFixer (#7085) + +Changelog for v3.19.0 +--------------------- + +* bug: SelfAccessorFixer - fix for union types (#7080) +* DX: add `php_unit_data_provider_name` to `@PhpCsFixer:risky` set (#7069) +* DX: make data providers return type "iterable" (#7072) +* DX: rename tests and data providers (#7070) +* feature: Introduce `PhpUnitDataProviderNameFixer` (#7057) + +Changelog for v3.18.0 +--------------------- + +* bug: Fix tokenizing of type hints (#7054) +* bug: CompactNullableTypehintFixer - fix for whitespace between `?` and `static` (#6993) +* bug: consider function modifiers for `statement_indentation` (#6978) +* bug: Exclude `$this` from `TernaryToNullCoalescingFixer` (#7052) +* bug: False positive on used imports when docblock includes it with mismatching case (#6909) +* bug: Fix chained calls semicolon indent in switch case (#7045) +* bug: Fix multiline_whitespace_before_semicolons for echo tags (#7019) +* bug: Fix phpDoc align when there is inconsistent spacing after comment star (#7012) +* bug: Fix phpDoc parsing without PCRE JIT (#7031) +* bug: Fix PhpdocVarWithoutNameFixer with Closure with $this (#6979) +* bug: Fix `return_assignment` not formatting when variables are used in `catch` and `finally` (#6960) +* bug: Fix `TypeExpression::allowsNull()` with nullable (#7000) +* bug: Improve definition of conflicting fixers (#7066) +* bug: LambdaNotUsedImportFixer - fix for anonymous class with a string argument (#6972) +* bug: ListFilesCommand - fix computing of relative path (#7028) +* bug: make `php_unit_namespaced` less greedy (#6952) +* bug: PhpdocToCommentFixer - fix for PHPDoc before fn (#6973) +* bug: Restructure PER-CS rule sets (#6707) +* bug: SelfStaticAccessor - fix static access inside enums (#7024) +* bug: SingleSpaceAroundConstructFixer - fix more cases involving `static` (#6995) +* bug: `FullyQualifiedStrictTypesFixer` - fix shortening when namespace is not empty and import exists (#7027) +* bug: `NoUnneededControlParenthesesFixer` PHP8.0 null-safe operator (#7056) +* bug: `PhpdocToCommentFixer` support for enum cases (#7040) +* DX: add more tests to CommentsAnalyzer (#7041) +* DX: Cleanup duplicate files in finder (#7042) +* DX: ControlCaseStructuresAnalyzerTest - cleanup (#6874) +* DX: Fix warning when running test on PHP<8 (#7008) +* DX: handle `@` in PR title (#6982) +* DX: officially deprecate internal Utils anti-pattern class (#7039) +* DX: Remove Fabbot.io conditional configuration (#7038) +* DX: rename data providers (#7058) +* DX: Use `actions/stale` to handle stale issues and pull requests (#5085) +* DX: Use `Utils::naturalLanguageJoin()` in implode calls (#7032) +* feature: Add support for custom method placement in `ordered_class_elements` (#6360) +* feature: Allow case sensitive order for OrderedClassElementsFixer (#7020) +* feature: PHP8.3 - Add CT and block type for `Dynamic class constant fetch` (#7004) +* feature: Support attributes in `FinalClassFixer` (#6893) +* minor: "Callback" must not be fixed to "callback" by default (#7011) +* minor: Add `Util::naturalLanguageJoin()` (#7022) +* minor: ClassDefinitionFixer - handle attributes and `readonly` in anonymous class definitions (#7014) +* minor: FixerFactory::getFixersConflicts - better type hinting (#7044) +* minor: PHP8.3 - Fix TokensAnalyzer::isAnonymousClass support for `readonly` (#7013) +* minor: PHP8.3 - Typed class constants - handle nullable by transformer (#7009) +* minor: Reduce phpDoc type parser complexity from O(n^2) to O(nlog(n)) (#6988) +* minor: ReturnAssignmentFixer - Better handling of anonymous classes (#7015) +* minor: Transfer `HelpCommand::toString()` to `Utils` (#7034) +* minor: Unify "blank lines before namespace" fixers (#7053) +* minor: `SelfStaticAccessorFixer` improvements for enums (#7026) +* minor: `SingleSpaceAroundConstructFixer` - support space before `as` (#7029) +* minor: `UseArrowFunctionsFixer` - run before `FunctionDeclarationFixer` (#7065) + +Changelog for v3.17.0 +--------------------- + +* bug: Allow string quote to be escaped within phpdoc constant (#6798) +* bug: ConfigurationResolver - fix running without cache (#6915) +* bug: Fix array/object shape phpdoc type parse (#6962) +* bug: Fix FullyQualifiedStrictTypesFixer common prefix bug (#6898) +* bug: Fix non-parenthesized callable return type parse (#6961) +* bug: Fix parsing of edge cases phpdoc types (#6977) +* bug: FullyQualifiedStrictTypesFixer - fix for FQCN type with class with the same name being imported (#6923) +* bug: GroupImportFixer - support for aliased imports (#6951) +* bug: MultilineWhitespaceBeforeSemicolonsFixer - fix chained calls (#6926) +* bug: MultilineWhitespaceBeforeSemicolonsFixer - fix for discovering multi line calls (#6938) +* bug: NoBreakCommentFixer - fix for nested match (#6899) +* bug: NoExtraBlankLinesFixer - fix for attribute in abstract function (#6920) +* bug: PhpdocTypesFixer - handle types with no space between type and variable (#6922) +* bug: PhpUnitMockShortWillReturnFixer - fix for trailing commas (#6900) +* bug: StatementIndentationFixer - fix comments at the end of if/elseif/else blocks (#6918) +* bug: StatementIndentationFixer - fix for multiline arguments starting with "new" keyword (#6913) +* bug: StatementIndentationFixer - fix for multiline arguments starting with "new" keyword preceded by class instantiation (#6914) +* bug: VoidReturnFixer - fix for intervening attributes (#6863) +* docs: improve code samples for MultilineWhitespaceBeforeSemicolonsFixer (#6919) +* docs: improve cookbook (#6880) +* DX: add cache related tests (#6916) +* DX: Apply `self_static_accessor` fixer to the project (again) (#6927) +* DX: cancel running builds on subsequent pushes in CI (#6940) +* DX: convert more `static` to `self` assert calls (#6931) +* DX: fix GitHub Actions errors and warnings (#6917) +* DX: fix Unsafe call to private method errors reported by PHPStan (#6879) +* DX: Improve performance of FunctionsAnalyzer (#6939) +* DX: improve test method names to avoid confusion (#6974) +* DX: Include self_static_accessor fixer in PhpCsFixer set (#6882) +* DX: make data providers static with straight-forward changes (#6907) +* DX: Mark Tokens::getNamespaceDeclarations as @internal (#6949) +* DX: PHPStan improvements (#6868) +* DX: refactor PhpdocAlignFixerTest (#6925) +* DX: Remove @inheritdoc PHPDoc (#6955) +* DX: Run AutoReview tests only once (#6889) +* DX: simplify EncodingFixer (#6956) +* DX: update Symfony rule set (#6958) +* DX: Use $tokens->getNamespaceDeclarations() to improve performance (#6942) +* DX: use force option for php_unit_data_provider_static in PHPUnit 10.0 migration set (#6908) +* DX: use only PHP modules that are required (#6954) +* DX: use PHPUnit's "requires" instead of "if" condition (#6975) +* feature: Add align_multiline_comment rule to @Symfony (#6875) +* feature: Add no_null_property_initialization rule to @Symfony (#6876) +* feature: Add operator_linebreak rule to @Symfony (#6877) +* feature: add SingleLineEmptyBodyFixer (#6933) +* feature: DescribeCommand - allow describing custom fixers (#6957) +* feature: Introduce `OrderedTypesFixer` (#6571) +* feature: Order of PHPDoc @param annotations (#3909) +* feature: Parse parenthesized & conditional phpdoc type (#6796) +* feature: PhpUnitInternalClassFixer - add empty line before PHPDoc (#6924) +* feature: [PhpdocAlignFixer] Add support for every tag (#6564) +* minor: align NoSuperfluousPhpdocTagsFixer with actual Symfony configuration (#6953) +* minor: do not add empty line in PHPDoc when adding annotation in PHPUnit class (#6928) +* minor: PhpdocAlignFixer - support cases with type and variable separated with no space (#6921) +* minor: PhpdocSeparationFixer - add integration tests (#6929) +* minor: update PHPStan (to fix CI on master branch) (#6901) +* minor: Use single Dockerfile with multiple build targets (#6840) + +Changelog for v3.16.0 +--------------------- + +* bug: ControlStructureBracesFixer - handle closing tag (#6873) +* bug: CurlyBracesPositionFixer - fix for callable return type (#6855) +* bug: CurlyBracesPositionFixer - fix for DNF types (#6859) +* bug: Fix MultilineWhitespaceBeforeSemicolonsFixer (#5126) +* docs: Fix rule description (#6844) +* DX: fix checkbashisms installation (#6843) +* DX: make data providers static for fixer's tests (#6860) +* DX: refactor PHPUnit fixers adding class-level annotation to use shared code (#6756) +* DX: unify option's descriptions (#6856) +* feature: AbstractPhpUnitFixer - support attribute detection in docblock insertion (#6858) +* feature: add "force" option to PhpUnitDataProviderStaticFixer (#6757) +* feature: introduce single_space_around_construct, deprecate single_space_after_construct (#6857) +* feature: PhpUnitTestClassRequiresCoversFixer - support single-line PHPDocs (#6847) +* minor: Deprecate BracesFixer (#4885) +* minor: Fix autocompletion for `Tokens::offsetGet()` (#6838) +* minor: PHP8.2 Docker runtime (#6833) +* minor: Use Composer binary-only images instead of installer script (#6834) + +Changelog for v3.15.1 +--------------------- + +* bug: BinaryOperatorSpacesFixer - fix for static in type (#6835) +* bug: BinaryOperatorSpacesFixer - fix parameters with union types passed by reference (#6826) +* bug: NoUnusedImportsFixer - fix for splat operator (#6836) +* DX: fix CI (#6837) +* feature: Support for type casing in arrow functions (#6831) +* minor: fix CI on PHP 8.3 (#6827) + +Changelog for v3.15.0 +--------------------- + +* bug: VisibilityRequiredFixer - handle DNF types (#6806) +* DX: officially enable 8.2 support (#6825) + +Changelog for v3.14.5 +--------------------- + +* bug: EmptyLoopBodyFixer must keep comments inside (#6800) +* bug: FunctionsAnalyzer - fix detecting global function (#6792) +* bug: NativeFunctionTypeDeclarationCasingFixer - do not require T_STRING present in code (#6812) +* bug: PhpdocTypesFixer - do not change case of array keys (#6810) +* bug: PhpUnitTestAnnotationFixer - do not break single line @depends (#6824) +* docs: Add supported PHP versions section to the README (#6768) +* docs: drop Atom from readme, due to it's sunsetting (#6778) +* DX: Add composer keywords (#6781) +* DX: update PHPStan to 1.10.3 (#6805) +* feature: [PHP8.2] Support for readonly classes (#6745) +* minor: add custom tokens for Disjunctive Normal Form types parentheses (#6823) +* minor: PHP8.2 - handle union and intersection types for DNF types (#6804) +* minor: PHP8.2 - support property in const expressions (#6803) + +Changelog for v3.14.4 +--------------------- + +* bug: CurlyBracesPositionFixer - fix for open brace not preceded by space and followed by a comment (#6776) +* docs: drop license end year (#6767) +* DX: use numeric_literal_separator (#6766) +* feature: Allow installation of `sebastian/diff:^5.0.0` (#6771) + +Changelog for v3.14.3 +--------------------- + +* DX: Drop doctrine/annotations 1, allow doctrine/lexer 3 (#6730) + +Changelog for v3.14.2 +--------------------- + +* DX: Drop support for doctrine/lexer 1 (#6729) + +Changelog for v3.14.1 +--------------------- + +* DX: Allow doctrine/annotations 2 (#6721) + +Changelog for v3.14.0 +--------------------- + +* bug: Fix indentation for comment at end of function followed by a comma (#6542) +* bug: Fix PHPDoc alignment fixer containing callbacks using `\Closure` (#6746) +* bug: Fix type error when using paths intersection mode (#6734) +* bug: PhpdocSeparationFixer - Make groups handling more flexible (#6668) +* docs: make bug_report.md template more explicit (#6736) +* docs: PhpUnitTestCaseIndicator - fix docs (#6727) +* DX: apply CS (#6759) +* DX: bump doctrine/annotations to prevent installing version with unintentional BC break (#6739) +* DX: update deps (#6760) +* DX: upgrade dev-tools/composer.json (#6737) +* DX: upgrade PHPStan to 1.9.7 (#6741) +* feature: Add php 7.4 types to Cookbook docs (#6763) +* feature: add PhpUnitDataProviderStaticFixer (#6702) +* feature: binary_operator_spaces - Revert change about => alignment and use option instead (#6724) +* feature: make OrderedInterfacesFixer non-risky (#6722) +* feature: OctalNotationFixer - support _ notation (#6762) +* fix: enum case "PARENT" must not be renamed (#6732) +* minor: Follow PSR12 ordered imports in Symfony ruleset (#6712) +* minor: improve rule sets order (#6738) + +Changelog for v3.13.2 +--------------------- + +* bug: Fix type error when using paths intersection mode (#6734) + +Changelog for v3.13.1 +--------------------- + +* bug: Align all the arrows inside the same array (#6590) +* bug: Fix priority between `modernize_types_casting` and `no_unneeded_control_parentheses` (#6687) +* bug: TrailingCommaInMultilineFixer - do not add trailing comma when there is no break line after last element (#6677) +* docs: Fix docs for disabled rules in rulesets (#6679) +* docs: fix the cookbook_fixers.rst (#6672) +* docs: Update installation recommended commands for `mkdir` argument (`-p` insteadof `--parents`). (#6689) +* Make static data providers that are not using dynamic calls (#6696) +* minor: displaying number of checked files (#6674) + +Changelog for v3.13.0 +--------------------- + +* bug: BracesFixer - Fix unexpected extra blank line (#6667) +* bug: fix CI on master branch (#6663) +* bug: IsNullFixer - handle casting (#6661) +* docs: feature or bug (#6652) +* docs: Use case insensitive sorting for options (#6666) +* docs: [DateTimeCreateFromFormatCallFixer] Fix typos in the code sample (#6671) +* DX: update cli-executor (#6664) +* DX: update dev-tools (#6665) +* feature: Add global_namespace_import to @Symfony ruleset (#6662) +* feature: Add separate option for closure_fn_spacing (#6658) +* feature: general_phpdoc_annotation_remove - allow add case_sensitive option (#6660) +* minor: AllowedValueSubset - possible values are sorted (#6651) +* minor: Use md5 for file hashing to reduce possible collisions (#6597) + +Changelog for v3.12.0 +--------------------- + +* bug: SingleLineThrowFixer - Handle throw expression inside block (#6653) +* DX: create TODO to change default ruleset for v4 (#6601) +* DX: Fix SCA findings (#6626) +* DX: HelpCommand - fix docblock (#6584) +* DX: Narrow some docblock types (#6581) +* DX: Remove redundant check for PHP <5.2.7 (#6620) +* DX: Restore PHPDoc to type rules workflow step (#6615) +* DX: SCA - scope down types (#6630) +* DX: Specify value type in iterables in tests (#6594) +* DX: Test on PHP 8.2 (#6558) +* DX: Update GitHub Actions (#6606) +* DX: Update PHPStan (#6616) +* feature: Add `@PHP82Migration` ruleset (#6621) +* feature: ArrayPushFixer now fix short arrays (#6639) +* feature: NoSuperfluousPhpdocTagsFixer - support untyped and empty annotations in phpdoc (#5792) +* feature: NoUselessConcatOperatorFixer - Introduction (#6447) +* feature: Support for constants in traits (#6607) +* feature: [PHP8.2] Support for new standalone types (`null`, `true`, `false`) (#6623) +* minor: GitHub Workflows security hardening (#6644) +* minor: prevent BC break in ErrorOutput (#6633) +* minor: prevent BC break in Runner (#6634) +* minor: Revert "minor: prevent BC break in Runner" (#6637) +* minor: Update dev tools (#6554) + +Changelog for v3.11.0 +--------------------- + +* bug: DateTimeCreateFromFormatCallFixer - Mark as risky (#6575) +* bug: Do not treat implements list comma as array comma (#6595) +* bug: Fix MethodChainingIndentationFixer with arrow functions and class instantiation (#5587) +* bug: MethodChainingIndentationFixer - Fix bug with attribute access (#6573) +* bug: NoMultilineWhitespaceAroundDoubleArrowFixer - fix for single line comment (#6589) +* bug: TypeAlternationTransformer - TypeIntersectionTransforme - Bug: handle attributes (#6579) +* bug: [BinaryOperatorFixer] Fix more issues with scoped operators (#6559) +* docs: Remove `$` from console command snippets (#6600) +* docs: Remove `$` from console command snippets in documentation (#6599) +* DX: AllowedValueSubset::getAllowedValues - fix method prototype (#6585) +* DX: Narrow docblock types in FixerConfiguration (#6580) +* DX: updagte @PhpCsFixer set config for phpdoc_order rule (#6555) +* DX: Update PHPUnit config (#6566) +* feature: Introduce configurability to PhpdocSeparationFixer (#6501) +* feature: Introduce PER set (#6545) +* feature: NoTrailingCommaInSinglelineFixer - Introduction (#6529) +* feature: Support removing superfluous PHPDocs involving `self` (#6583) +* minor: NoUnneededControlParenthesesFixer - Support instanceof static cases (#6587) +* minor: PhpdocToCommentFixer - allow phpdoc comments before trait use statement. Fixes #6092 (#6565) + +Changelog for v3.10.0 +--------------------- + +* bug: Fix error in `regular_callable_call` with static property (#6539) +* bug: Fix indentation for multiline class definition (#6540) +* bug: Fix indentation for switch ending with empty case (#6538) +* bug: Fix indentation of comment at end of switch case (#6493) +* bug: PhpdocAlignFixer - fix static `@method` (#6366) +* bug: SingleSpaceAfterConstructFixer - fix handling open tag (#6549) +* bug: VisibilityRequiredFixer must run before ClassAttributesSeparationFixer (#6548) +* DX: Assert dataproviders of tests of project itself return "array" or "iterable". (#6524) +* feature: Introduce configurability to PhpdocOrderFixer (#6466) +* feature: WhitespaceAfterCommaInArrayFixer - add option "ensure_single_space" (#6527) +* minor: Add test for indentation of trait conflict resolution (#6541) +* minor: Split BracesFixer (#4884) +* minor: TrailingCommaInMultilineFixer - Add comma to multiline `new static` (#6380) + +Changelog for v3.9.6 +-------------------- + +* bug: BinaryOperatorSpacesFixer: Solve issues with scoped arrow and equal alignments (#6515) +* bug: Fix 3 weird behavior about BinaryOperatorSpacesFixer (#6450) +* docs: Add intersection type to types_spaces rule description (#6479) +* DX: no need to use forked diff anymore (#6526) +* DX: remove unused FixerFileProcessedEvent::STATUS_UNKNOWN (#6516) +* Improve `statement_indentation` compatibility with `braces` (#6401) +* minor: add test: multi-line comments before else indented correctly. (#3573) +* minor: ReturnAssignmentFixer - Support for anonymous classes, lambda and match (#6391) + +Changelog for v3.9.5 +-------------------- + +* bug: AlternativeSyntaxAnalyzer - fix for nested else (#6495) +* bug: Fix cases related to binary strings (#6432) +* bug: Fix trailing whitespace after moving brace (#6489) +* bug: NoUnneededControlParenthesesFixer - Fix some curly close cases (#6502) +* bug: TypeColonTransformer - fix for backed enum types (#6494) +* DX: Add tests for type colon in backed enums (#6497) +* DX: Fix CI static analysis workflow (#6506) +* DX: Fix PHPStan errors (#6504) +* DX: Increase PHPStan level to 6 (#6468) +* DX: Narrow docblock types in Runner and Report (#6465) +* DX: Narrow docblock types in Tokenizer (#6293) +* minor: extract NoMultipleStatementsPerLineFixer from BracesFixer (#6458) +* minor: Let PhpdocLineSpan fixer detect docblocks when seperator from token with attribute (#6343) + +Changelog for v3.9.4 +-------------------- + +* bug: Fix various indentation issues (#6480) +* bug: Fix wrong brace position after static return type (#6485) +* bug: Prevent breaking functions returning by reference (#6487) + +Changelog for v3.9.3 +-------------------- + +* bug: Fix BinaryOperatorSpacesFixer adding whitespace outside PHP blocks (#6476) +* bug: Fix brace location after multiline function signature (#6475) + +Changelog for v3.9.2 +-------------------- + +* bug: Fix indentation after control structure in switch (#6473) + +Changelog for v3.9.1 +-------------------- + +* bug: Add attributes support to `statement_indentation` (#6429) +* bug: BinaryOperatorSpacesFixer - Allow to align `=` inside array definitions (#6444) +* bug: BinaryOperatorSpacesFixer - Fix align of operator with function declaration (#6445) +* bug: ConstantCaseFixer - Do not touch enum case (#6367) +* bug: CurlyBracesPositionFixer - multiple elseifs (#6459) +* bug: Fix #6439 issue in `StaticLambda` fixer (#6440) +* bug: FullOpeningTagFixer - fix substr check for pre PHP8 (#6388) +* bug: IncrementStyleFixer - NoSpacesInsideParenthesisFixer - prio (#6416) +* bug: LambdaNotUsedImportFixer must run before MethodArgumentSpaceFixer (#6453) +* bug: MethodArgumentSpaceFixer - first element in same line, space before comma and inconsistent indent (#6438) +* bug: NoSuperfluousPhpdocTagsFixer - fix for promoted properties (#6403) +* bug: StatementIndentationFixer - Fix indentation for multiline traits use (#6402) +* bug: StrictComparisonFixer must rune before ModernizeStrposFixer (#6455) +* bug: TokensAnalyzer - fix intersection types considered as binary operator (#6414) +* DX: `ISSUE_TEMPLATE` hints to check applied rules (#6398) +* DX: Add more type hints (#6383) +* DX: Fix CI/CD issues (#6411) +* DX: cleanup test (#6410) +* DX: integrate PRLint (#6406) +* feature: BlankLineBetweenImportGroupsFixer - Introduction (#6365) +* feature: DateTimeCreateFromFormatCallFixer - Add DateTimeImmutable support (#6350) +* feature: Extract StatementIndentationFixer from BracesFixer (#5960) +* feature: ModernizeStrposFixer - fix leading backslash with yoda (#6377) +* feature: NoExtraBlankLinesFixer - Add `attributes` option - Fix support for `enum` `case` (#6426) +* feature: NoUnneededControlParenthesesFixer - Fix more cases (#6409) +* feature: NoUselessNullsafeOperatorFixer - Introduction (#6425) +* feature: OrderedTrait - Move Phpdoc with trait import (#6361) +* feature: PhpdocOrderByValueFixer - Allow sorting of mixin annotations by value (#6446) +* feature: TrailingCommaInMultiline - Add `match` support (#6381) +* minor: Allow Composer Normalize plugin (#6454) +* minor: ExplicitStringVariableFixer - Fix to PHP8.2 compat code (#6424) +* minor: Extract ControlStructureBracesFixer from BracesFixer (#6399) +* minor: NoBinaryStringFixer - Fix more cases (#6442) +* minor: NoSuperfluousPhpdocTagsFixer - Attribute handling (#6382) +* minor: PhpCsFixerSet - Update blank_line_before_statement config (#6389) +* minor: Remove unnecessary PHP version constraints (#6461) +* minor: SingleImportPerStatementFixer - fix PSR12 set (#6415) +* minor: SingleSpaceAfterConstructFixer - add option `type_colon` (#6434) +* minor: SymfonySet - Add SimpleToComplexStringVariableFixer (#6423) +* minor: Update PHPStan (#6467) +* minor: extract CurlyBracesPositionFixer from BracesFixer (#6452) + +Changelog for v3.8.0 +-------------------- + +* bug #6322 PhpdocTypesFixer - fix recognizing callable (kubawerlos) +* bug #6331 ClassReferenceNameCasingFixer - Fix false hits (SpacePossum) +* bug #6333 BinaryOperatorSpacesFixer - Fix for alignment in `elseif` (paulbalandan, SpacePossum) +* bug #6337 PhpdocTypesFixer - fix recognising callable without return type (kubawerlos) +* feature #6286 DateTimeCreateFromFormatCallFixer - Introduction (liquid207) +* feature #6312 TypesSpacesFixer - add option for CS of catching multiple types of exceptions (SpacePossum) +* minor #6326 Bump migration sets used to PHP7.4 (SpacePossum) +* minor #6328 DX: .gitignore ASC file (keradus) + +Changelog for v3.7.0 +-------------------- + +* bug #6112 [BinaryOperatorSpacesFixer] Fix align of `=` inside calls of methods (VincentLanglet) +* bug #6279 ClassReferenceNameCasingFixer - Fix for double arrow (SpacePossum) +* bug #6280 Fix bunch of enum issus (SpacePossum) +* bug #6283 ClassReferenceNameCasingFixer - detect imports (SpacePossum) +* feature #5892 NewWithBracesFixer - option to remove braces (jrmajor) +* feature #6081 Allow multiline constructor arguments in an anonymous classes (jrmajor, SpacePossum) +* feature #6274 SingleLineCommentSpacingFixer - Introduction (SpacePossum) +* feature #6300 OrderedClassElementsFixer - handle enums (gharlan) +* feature #6304 NoTrailingCommaInSinglelineFunctionCallFixer - Introduction (SpacePossum) +* minor #6277 Add `is_scalar`, `sizeof`, `ini_get` in list of compiled functions (jderusse) +* minor #6284 ClassReferenceNameCasingFixer - Update doc (SpacePossum) +* minor #6289 PHP7.4 - clean up tests (SpacePossum) +* minor #6290 PHP7.4 - properties types (SpacePossum) +* minor #6291 PHP7.4 - remove run time checks (SpacePossum) +* minor #6292 PhpUnitDedicateAssertFixer - Fix more count cases (SpacePossum) +* minor #6294 PhpUnitDedicateAssertFixer - add assertInstanceOf support (SpacePossum) +* minor #6295 PhpUnitTestCaseIndicator - Check if PHPUnit-test class extends anothe… (SpacePossum) +* minor #6298 Fix checkbashisms download ans SCA violations (SpacePossum) +* minor #6301 BracesFixer - handle enums (gharlan) +* minor #6302 Bump checkbashisms version (kubawerlos) +* minor #6303 PHP8 - Utilize "get_debug_type" (SpacePossum) +* minor #6316 bump xdebug-handler (SpacePossum) +* minor #6327 bump polyfills (SpacePossum) + +Changelog for v3.6.0 +-------------------- + +* bug #6063 PhpdocTypesOrderFixer - Improve nested types support (ruudk, julienfalque) +* bug #6197 FullyQualifiedStrictTypesFixer - fix same classname is imported from … (SpacePossum) +* bug #6241 NoSuperfluousPhpdocTagsFixer - fix for reference and splat operator (kubawerlos) +* bug #6243 PhpdocTypesOrderFixer - fix for intersection types (kubawerlos) +* bug #6254 PhpUnitDedicateAssertFixer - remove `is_resource`. (drupol) +* bug #6264 TokensAnalyzer - fix isConstantInvocation detection for mulitple exce… (SpacePossum) +* bug #6265 NullableTypeDeclarationForDefaultNullValueFixer - handle "readonly" a… (SpacePossum) +* bug #6266 SimplifiedIfReturnFixer - handle statement in loop without braces (SpacePossum) +* feature #6262 ClassReferenceNameCasingFixer - introduction (SpacePossum) +* feature #6267 NoUnneededImportAliasFixer - Introduction (SpacePossum) +* minor #6199 HeaderCommentFixer - support monolithic files with shebang (kubawerlos, keradus) +* minor #6231 Fix priority descriptions and tests. (SpacePossum) +* minor #6237 DX: Application - better display version when displaying gitSha (keradus) +* minor #6242 Annotation - improve on recognising types with reference and splat operator (kubawerlos) +* minor #6250 Tokens - optimize cache clear (SpacePossum) +* minor #6269 Docs: redo warnings in RST docs to fix issue on website docs (keradus) +* minor #6270 ClassReferenceNameCasingFixer - Add missing test cases for catch (SpacePossum) +* minor #6273 Add priority test (SpacePossum) + +Changelog for v3.5.0 +-------------------- + +* bug #6058 Fix `Tokens::insertSlices` not moving around all affected tokens (paulbalandan, SpacePossum) +* bug #6160 NonPrintableCharacterFixer - fix for when removing non-printable character break PHP syntax (kubawerlos) +* bug #6165 DeclareEqualNormalizeFixer - fix for declare having multiple directives (kubawerlos) +* bug #6170 NonPrintableCharacterFixer - fix for string in single quotes, having non-breaking space, linebreak, and single quote inside (kubawerlos) +* bug #6181 UseTransformer - Trait import in enum fix (PHP8.1) (SpacePossum) +* bug #6188 PhpdocTo(Param|Property|Return)TypeFixer - fix for type intersections (kubawerlos) +* bug #6202 SquareBraceTransformer - fix for destructing square brace after double arrow (kubawerlos) +* bug #6209 OrderedClassElementsFixer - PHP8.0 support abstract private methods in traits (SpacePossum) +* bug #6224 ArgumentsAnalyzer - support PHP8.1 readonly (SpacePossum) +* feature #4571 BlankLineBeforeStatementFixer - can now add blank lines before doc-comments (addiks, SpacePossum) +* feature #5953 GetClassToClassKeywordFixer - introduction (paulbalandan) +* minor #6108 Drop support for Symfony v4 (keradus) +* minor #6163 CI: update used PHP version (keradus) +* minor #6167 SingleSpaceAfterConstructFixer - allow multiline const (y_ahiru, SpacePossum) +* minor #6168 indexes -> indices (SpacePossum) +* minor #6171 Fix tests and CS (SpacePossum) +* minor #6172 DX: Tokens::insertSlices - groom code and fix tests (keradus) +* minor #6174 PhpdocAlignFixer: fix property-read/property-write descriptions not getting aligned (antichris) +* minor #6177 DX: chmod +x for benchmark.sh file (keradus) +* minor #6180 gitlab reporter - add fixed severity to match format (cbourreau) +* minor #6183 Simplify DiffConsoleFormatter (kubawerlos) +* minor #6184 Do not support array of patterns in Preg methods (kubawerlos) +* minor #6185 Upgrade PHPStan (kubawerlos) +* minor #6189 Finder - fix usage of ignoreDotFiles (kubawerlos) +* minor #6190 DX: DiffConsoleFormatter - escape - (keradus) +* minor #6194 Update Docker setup (julienfalque) +* minor #6196 clean ups (SpacePossum) +* minor #6198 DX: format dot files (kubawerlos) +* minor #6200 DX: Composer's branch-alias leftovers cleanup (kubawerlos) +* minor #6203 Bump required PHP to 7.4 (keradus) +* minor #6205 DX: bump PHPUnit to v9, PHPUnit bridge to v6 and Prophecy-PHPUnit to v2 (keradus) +* minor #6210 NullableTypeDeclarationForDefaultNullValueFixer - fix tests (HypeMC) +* minor #6212 bump year 2021 -> 2022 (SpacePossum) +* minor #6215 DX: Doctrine\Annotation\Tokens - fix phpstan violations (keradus) +* minor #6216 DX: Doctrine\Annotation\Tokens - drop unused methods (keradus) +* minor #6217 DX: lock SCA tools for PR builds (keradus) +* minor #6218 Use composer/xdebug-handler v3 (gharlan) +* minor #6222 Show runtime on version command (SpacePossum) +* minor #6229 Simplify Tokens::isMonolithicPhp tests (kubawerlos) +* minor #6232 Use expectNotToPerformAssertions where applicable (SpacePossum) +* minor #6233 Update Tokens::isMonolithicPhp (kubawerlos) +* minor #6236 Annotation - improve getting variable name (kubawerlos) + +Changelog for v3.4.0 +-------------------- + +* bug #6117 SingleSpaceAfterConstruct - handle before destructuring close brace (liquid207) +* bug #6122 NoMultilineWhitespaceAroundDoubleArrowFixer - must run before MethodArgumentSpaceFixer (kubawerlos) +* bug #6130 StrictParamFixer - must run before MethodArgumentSpaceFixer (kubawerlos) +* bug #6137 NewWithBracesFixer - must run before ClassDefinitionFixer (kubawerlos) +* bug #6139 PhpdocLineSpanFixer - must run before NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #6143 OperatorLinebreakFixer - fix for alternative syntax (kubawerlos) +* bug #6159 ImportTransformer - fix for grouped constant and function imports (kubawerlos) +* bug #6161 NoUnreachableDefaultArgumentValueFixer - fix for attributes (kubawerlos) +* feature #5776 DX: test on PHP 8.1 (kubawerlos) +* feature #6152 PHP8.1 support (SpacePossum) +* minor #6095 Allow Symfony 6 (derrabus, keradus) +* minor #6107 Drop support of PHPUnit v7 dependency (keradus) +* minor #6109 Add return type to `DummyTestSplFileInfo::getRealPath()` (derrabus) +* minor #6115 Remove PHP 7.2 polyfill (derrabus) +* minor #6116 CI: remove installation of mbstring polyfill in build script, it's required dependency now (keradus) +* minor #6119 OrderedClassElementsFixer - PHPUnit assert(Pre|Post)Conditions methods support (meyerbaptiste) +* minor #6121 Use Tokens::ensureWhitespaceAtIndex to simplify code (kubawerlos) +* minor #6127 Remove 2nd parameter to XdebugHandler constructor (phil-davis) +* minor #6129 clean ups (SpacePossum) +* minor #6138 PHP8.1 - toString cannot return type hint void (SpacePossum) +* minor #6146 PHP 8.1: add new_in_initializers to PHP 8.1 integration test (keradus) +* minor #6147 DX: update composer-normalize (keradus) +* minor #6156 DX: drop hack for Prophecy incompatibility (keradus) + +Changelog for v3.3.1 +-------------------- + +* minor #6067 Bump minimum PHP version to 7.2 (keradus) + +Changelog for v3.3.0 +-------------------- + +* bug #6054 Utils - Add multibyte and UTF-8 support (paulbalandan) +* bug #6061 ModernizeStrposFixer - fix for negated with leading slash (kubawerlos) +* bug #6064 SquareBraceTransformer - fix detect array destructing in foreach (SpacePossum) +* bug #6082 PhpUnitDedicateAssertFixer must run before NoUnusedImportsFixer (kubawerlos) +* bug #6089 TokensAnalyzer.php - Fix T_ENCAPSED_AND_WHITESPACE handling in isBina… (SpacePossum) +* feature #5123 PhpdocTypesFixer - support generic types (kubawerlos) +* minor #5775 DX: run static code analysis on PHP 8.0 (kubawerlos) +* minor #6050 DX: TypeIntersectionTransformer - prove to not touch T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG (keradus) +* minor #6051 NoExtraBlankLinesFixer - Improve deprecation message (paulbalandan) +* minor #6060 DX: Add upgrade guide link when next Major is available (keradus) +* minor #6066 Clean ups (SpacePossum, kubawerlos) +* minor #6069 DX: cleanup stub file (keradus) +* minor #6070 Update UPGRADE-v3.md with php_unit_test_annotation/case deprecation (kubawerlos) +* minor #6072 Update usage doc to reflect change to PSR12 default. (hannob, keradus) +* minor #6084 Change: Remove __constructor() from RuleSetDescriptionInterface (niklam) +* minor #6085 Dx: reuse WhitespacesAnalyzer::detectIndent (kubawerlos) +* minor #6087 AbstractProxyFixer - more tests (SpacePossum) + +Changelog for v3.2.1 +--------------------- + +experimental release + +* Require PHP 7.2 + +Changelog for v3.2.0 +-------------------- + +* bug #5809 FunctionsAnalyzer - fix for recognizing global functions in attributes (kubawerlos) +* bug #5909 NativeFunctionCasingFixer - fix for attributes and imported functions (kubawerlos) +* bug #5920 ClassAttributesSeparationFixer - fixes & enhancements (SpacePossum) +* bug #5923 TypeAlternationTransformer - fix for promoted properties (kubawerlos) +* bug #5938 NoAliasFunctionsFixer - remove dir -> getdir mapping (SpacePossum) +* bug #5941 TokensAnalyzer - isAnonymousClass bug on PHP8 (SpacePossum) +* bug #5942 TokensAnalyzer - isConstantInvocation PHP 8 issue (SpacePossum) +* bug #5943 NoUnusedImportsFixer - use in attribute (SpacePossum) +* bug #5955 Fixed `class_attributes_separation` processing class with multiple trait imports (GrahamCampbell) +* bug #5977 LowercaseStaticReference - SingleClassElementPerStatement - union types (SpacePossum) +* bug #5984 RegularCallableCallFixer must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5986 CurlyBraceTransformer - count T_CURLY_OPEN itself as level as well (SpacePossum) +* bug #5989 NoAliasFunctionsFixer - Correct mapping (weshooper) +* bug #6004 SwitchContinueToBreakFixer - Fix candidate check (SpacePossum) +* bug #6005 CommentsAnalyzer - before static call (SpacePossum) +* bug #6007 YodaStyleFixer - PHP8 named arguments support (liquid207) +* bug #6015 CommentsAnalyzer - constructor property promotion support (liquid207) +* bug #6020 RegularCallableCallFixer - case insensitive fixing (SpacePossum) +* bug #6037 PhpdocLineSpanFixer - do not crash on trait imports (SpacePossum) +* feature #4834 AssignNullCoalescingToCoalesceEqualFixer - introduction (SpacePossum) +* feature #5754 ModernizeStrposFixer - introduction (derrabus, SpacePossum, keradus) +* feature #5858 EmptyLoopConditionFixer - introduction (SpacePossum) +* feature #5967 PHP8.1 - type "never" support (SpacePossum) +* feature #5968 PHP8.1 - "readonly" property modifier support (SpacePossum) +* feature #5970 IntegerLiteralCaseFixer - introduction (SpacePossum) +* feature #5971 PHP8.1 - Explicit octal integer literal notation (SpacePossum) +* feature #5997 NoSuperfluousPhpdocTagsFixer - Add union types support (julienfalque) +* feature #6026 TypeIntersectionTransformer - introduction (kubawerlos, SpacePossum) +* feature #6031 NoSpaceAroundDoubleColonFixer - introduction (SpacePossum) +* feature #6047 StringLengthToEmptyFixer - introduction (SpacePossum) +* minor #5773 NoAlternativeSyntaxFixer - Add option to not fix non-monolithic PHP code (paulbalandan) +* minor #5887 Detect renamed rules in configuration resolver (shakaran) +* minor #5901 DX: update PHPStan (kubawerlos) +* minor #5906 Remove references to PHP 7.0 in tests (with updates) (kubawerlos) +* minor #5918 Remove PHP version specific code sample constraint when not needed (kubawerlos) +* minor #5924 PSR12 - ClassDefinition - space_before_parenthesis (SpacePossum) +* minor #5925 DX: ProjectCodeTest - fix detection by testExpectedInputOrder (keradus) +* minor #5926 DX: remove not needed requirements from fixtures (kubawerlos) +* minor #5927 Symfonyset - EmptyLoopBody (SpacePossum) +* minor #5928 PhpdocTo*TypeFixer - add more test cases (keradus) +* minor #5929 Remove not needed PHP version checks (kubawerlos) +* minor #5930 simplify code, more tests (SpacePossum) +* minor #5931 logo copyright - bump year (SpacePossum) +* minor #5932 Extract ControlStructureContinuationPositionFixer from BracesFixer (julienfalque) +* minor #5933 Consistency invalid configuration exception for test (shakaran) +* minor #5934 Add return types (SpacePossum) +* minor #5949 Removed PHP 5 exception catch (GrahamCampbell) +* minor #5952 ClassAttributesSeparationFixer - Re-add omitted `only_if_meta` option (paulbalandan) +* minor #5957 Keep PHPStan cache between Docker runs (julienfalque) +* minor #5958 Fix STDIN test when path is one level deep (julienfalque) +* minor #5959 SymfonySet - add EmptyLoopConditionFixer (SpacePossum) +* minor #5961 Remove duplicated method (julienfalque) +* minor #5962 DX: Add return types (kubawerlos) +* minor #5963 DX: extract config for special CI jobs (keradus) +* minor #5964 DX: use modernize_strpos (keradus) +* minor #5965 CI: don't try to execute jobs with Symfony:^3 (keradus) +* minor #5972 PHP8.1 - FirstClassCallable (SpacePossum) +* minor #5973 PHP8.1 - "final const" support (SpacePossum) +* minor #5975 Tree shake PHP8.1 PRs (SpacePossum) +* minor #5978 PHP8.1 - Enum (start) (SpacePossum) +* minor #5982 Fix test warning (SpacePossum) +* minor #5987 PHP8.1 - Enum (start) (SpacePossum) +* minor #5995 Fix link to Code Climate SPEC.md in GitlabReporter (astehlik) +* minor #5996 Fix URL to Doctrine Annotations documentation (astehlik) +* minor #6000 Prevent PHP CS Fixer from fixing PHPStan cache files (julienfalque) +* minor #6006 SCA/utilize PHP8.1 (SpacePossum) +* minor #6008 SCA (SpacePossum) +* minor #6010 SCA (SpacePossum) +* minor #6011 NoSuperfluousPhpdocTagsFixer - Remove superfluous annotation `@abstract` and `@final` (liquid207, SpacePossum) +* minor #6018 PhpdocLineSpan - Allow certain types to be ignored (devfrey) +* minor #6019 Improve test coverage (SpacePossum) +* minor #6021 Linter/*Exception - Tag as final (SpacePossum) +* minor #6023 OrderedClassElementsFixer - PHP8.1 readonly properties support (SpacePossum) +* minor #6027 MbStrFunctionsFixer - more details about risky (SpacePossum) +* minor #6028 BinaryOperatorSpacesFixer - list all operators in doc (SpacePossum) +* minor #6029 PhpUnitDedicateAssertFixer - add "assertStringContainsString" and "as… (SpacePossum) +* minor #6030 SingleSpaceAfterConstructFixer - Add `switch` support (SpacePossum) +* minor #6033 ArgumentsAnalyzerTest - add more tests (SpacePossum) +* minor #6034 7.0|7.1 - cleanup tests (SpacePossum) +* minor #6035 Documentation generation split up and add list. (SpacePossum) +* minor #6048 Fix "can not" spelling (mvorisek) + +Changelog for v3.1.0 +-------------------- + +* feature #5572 PhpdocToCommentFixer - Add `ignored_tags` option (VincentLanglet) +* feature #5588 NoAliasFunctionsFixer - Add more function aliases (danog) +* feature #5704 ClassAttributesSeparationFixer - Introduce `only_if_meta` spacing option (paulbalandan) +* feature #5734 TypesSpacesFixer - Introduction (kubawerlos) +* feature #5745 EmptyLoopBodyFixer - introduction (SpacePossum, keradus) +* feature #5751 Extract DeclareParenthesesFixer from BracesFixer (julienfalque, keradus) +* feature #5877 ClassDefinitionFixer - PSR12 for anonymous class (SpacePossum) +* minor #5875 EmptyLoopBodyFixer - NoTrailingWhitespaceFixer - priority test (SpacePossum) +* minor #5914 Deprecate ClassKeywordRemoveFixer (kubawerlos) + +Changelog for v3.0.3 +-------------------- + +* bug #4927 PhpdocAlignFixer - fix for whitespace in type (kubawerlos) +* bug #5720 NoUnusedImportsFixer - Fix undetected unused imports when type mismatch (julienfalque, SpacePossum) +* bug #5806 DoctrineAnnotationFixer - Add template to ignored_tags (akalineskou) +* bug #5849 PhpdocTagTypeFixer - must not remove inlined tags within other tags (boesing) +* bug #5853 BracesFixer - handle alternative short foreach with if (SpacePossum) +* bug #5855 GlobalNamespaceImportFixer - fix for attributes imported as constants (kubawerlos) +* bug #5881 SelfUpdateCommand - fix link to UPGRADE docs (keradus) +* bug #5884 CurlyBraceTransformer - fix handling dynamic property with string with variable (kubawerlos, keradus) +* bug #5912 TypeAlternationTransformer - fix for "callable" type (kubawerlos) +* bug #5913 SingleSpaceAfterConstructFixer - improve comma handling (keradus) +* minor #5829 DX: Fix SCA with PHPMD (paulbalandan) +* minor #5838 PHP7 - use spaceship (SpacePossum, keradus) +* minor #5848 Docs: update PhpStorm integration link (keradus) +* minor #5856 Add AttributeAnalyzer (kubawerlos) +* minor #5857 DX: PHPMD - exclude fixtures (keradus) +* minor #5859 Various fixes (kubawerlos) +* minor #5864 DX: update dev tools (kubawerlos) +* minor #5876 AttributeTransformerTest - add more tests (SpacePossum) +* minor #5879 Update UPGRADE-v3.md adding relative links (shakaran, keradus) +* minor #5882 Docs: don't use v2 for installation example (keradus) +* minor #5883 Docs: typo (brianteeman, keradus) +* minor #5890 DX: use PHP 8.1 polyfill (keradus) +* minor #5902 Remove references to PHP 7.0 in tests (only removing lines) (kubawerlos) +* minor #5905 DX: Use "yield from" in tests (kubawerlos, keradus) +* minor #5917 Use `@PHP71Migration` rules (kubawerlos, keradus) + +Changelog for v3.0.2 +-------------------- + +* bug #5816 FullyQualifiedStrictTypesFixer - fix for union types (kubawerlos, keradus) +* bug #5835 PhpdocTypesOrderFixer: fix for array shapes (kubawerlos) +* bug #5837 SingleImportPerStatementFixer - fix const and function imports (SpacePossum) +* bug #5844 PhpdocTypesOrderFixer: handle callable() type (Slamdunk) +* minor #5839 DX: automate checking 7.0 types on project itself (keradus) +* minor #5840 DX: drop v2 compatible config in project itself (keradus) + +Changelog for v3.0.1 +-------------------- + +* bug #5395 PhpdocTagTypeFixer: Do not modify array shapes (localheinz, julienfalque) +* bug #5678 UseArrowFunctionsFixer - fix for return without value (kubawerlos) +* bug #5679 PhpUnitNamespacedFixer - do not try to fix constant usage (kubawerlos) +* bug #5681 RegularCallableCallFixer - fix for function name with escaped slash (kubawerlos) +* bug #5687 FinalInternalClassFixer - fix for annotation with space after "@" (kubawerlos) +* bug #5688 ArrayIndentationFixer - fix for really long arrays (kubawerlos) +* bug #5690 PhpUnitNoExpectationAnnotationFixer - fix "expectedException" annotation with message below (kubawerlos) +* bug #5693 YodaStyleFixer - fix for assignment operators (kubawerlos) +* bug #5697 StrictParamFixer - fix for method definition (kubawerlos) +* bug #5702 CommentToPhpdocFixer - fix for single line comments starting with more than 2 slashes (kubawerlos) +* bug #5703 DateTimeImmutableFixer - fix for method definition (kubawerlos) +* bug #5718 VoidReturnFixer - do not break syntax with magic methods (kubawerlos) +* bug #5727 SingleSpaceAfterConstructFixer - Add support for `namespace` (julienfalque) +* bug #5730 Fix transforming deprecations into exceptions (julienfalque) +* bug #5738 TokensAnalyzer - fix for union types (kubawerlos) +* bug #5741 Fix constant invocation detection cases (kubawerlos) +* bug #5769 Fix priority between `phpdoc_to_property_type` and `no_superfluous_phpdoc_tags` (julienfalque) +* bug #5774 FunctionsAnalyzer::isTheSameClassCall - fix for $this with double colon following (kubawerlos) +* bug #5779 SingleLineThrowFixer - fix for throw in match (kubawerlos) +* bug #5781 ClassDefinition - fix for anonymous class with trailing comma (kubawerlos) +* bug #5783 StaticLambdaFixer - consider parent:: as a possible reference to $this (fancyweb) +* bug #5791 NoBlankLinesAfterPhpdoc - Add T_NAMESPACE in array of forbidden successors (paulbalandan) +* bug #5799 TypeAlternationTransformer - fix for multiple function parameters (kubawerlos) +* bug #5804 NoBreakCommentFixer - fix for "default" in "match" (kubawerlos) +* bug #5805 SingleLineCommentStyleFixer - run after HeaderCommentFixer (kubawerlos) +* bug #5817 NativeFunctionTypeDeclarationCasingFixer - fix for union types (kubawerlos) +* bug #5823 YodaStyleFixer - yield support (SpacePossum) +* minor #4914 Improve PHPDoc types support (julienfalque, keradus) +* minor #5592 Fix checking for default config used in rule sets (kubawerlos) +* minor #5675 Docs: extend Upgrade Guide (keradus) +* minor #5680 DX: benchmark.sh - ensure deps are updated to enable script working across less-similar branches (keradus) +* minor #5689 Calculate code coverage on PHP 8 (kubawerlos) +* minor #5694 DX: fail on risky tests (kubawerlos) +* minor #5695 Utils - save only unique deprecations to avoid memory issues (PetrHeinz) +* minor #5710 [typo] add correct backquotes (PhilETaylor) +* minor #5711 Fix doc, "run-in" show-progress option is no longer present (mvorisek) +* minor #5713 Upgrade-Guide: fix typo (staabm) +* minor #5717 Run migration rules on PHP 8 (kubawerlos, keradus) +* minor #5721 Fix reStructuredText markup (julienfalque) +* minor #5725 Update LICENSE (exussum12) +* minor #5731 CI - Fix checkbashisms installation (julienfalque) +* minor #5736 Remove references to PHP 5.6 (kubawerlos, keradus) +* minor #5739 DX: more typehinting (keradus) +* minor #5740 DX: more type-related docblocks (keradus) +* minor #5746 Config - Improve deprecation message with details (SpacePossum) +* minor #5747 RandomApiMigrationFixer - better docs and better "random_int" support (SpacePossum) +* minor #5748 Updated the link to netbeans plugins page (cyberguroo) +* minor #5750 Test all const are in uppercase (SpacePossum) +* minor #5752 NoNullPropertyInitializationFixer - fix static properties as well (HypeMC) +* minor #5756 Fix rule sets descriptions (kubawerlos) +* minor #5761 Fix links in custom rules documentation (julienfalque) +* minor #5771 doc(config): change set's name (Kocal) +* minor #5777 DX: update PHPStan (kubawerlos) +* minor #5789 DX: update PHPStan (kubawerlos) +* minor #5808 Update PHPStan to 0.12.92 (kubawerlos) +* minor #5813 Docs: point to v3 in installation description (Jimbolino) +* minor #5824 Deprecate v2 (keradus) +* minor #5825 DX: update checkbashisms to v2.21.3 (keradus) +* minor #5826 SCA: check both composer files (keradus) +* minor #5827 ClassAttributesSeparationFixer - Add `trait_import` support (SpacePossum) +* minor #5831 DX: fix SCA violations (keradus) + +Changelog for v3.0.0 +-------------------- + +* bug #5164 Differ - surround file name with double quotes if it contains spacing. (SpacePossum) +* bug #5560 PSR2: require visibility only for properties and methods (kubawerlos) +* bug #5576 ClassAttributesSeparationFixer: do not allow using v2 config (kubawerlos) +* feature #4979 Pass file to differ (paulhenri-l, SpacePossum) +* minor #3374 show-progress option: drop run-in and estimating, rename estimating-max to dots (keradus) +* minor #3375 Fixers - stop exposing extra properties/consts (keradus) +* minor #3376 Tokenizer - remove deprecations and legacy mode (keradus) +* minor #3377 rules - change default options (keradus) +* minor #3378 SKIP_LINT_TEST_CASES - drop env (keradus) +* minor #3379 MethodArgumentSpaceFixer - fixSpace is now private (keradus) +* minor #3380 rules - drop rootless configurations (keradus) +* minor #3381 rules - drop deprecated configurations (keradus) +* minor #3382 DefinedFixerInterface - incorporate into FixerInterface (keradus) +* minor #3383 FixerDefinitionInterface - drop getConfigurationDescription and getDefaultConfiguration (keradus) +* minor #3384 diff-format option: drop sbd diff, use udiffer by default, drop SebastianBergmannDiffer and SebastianBergmannShortDiffer classes (keradus) +* minor #3385 ConfigurableFixerInterface::configure - param is now not nullable and not optional (keradus) +* minor #3386 ConfigurationDefinitionFixerInterface - incorporate into ConfigurableFixerInterface (keradus) +* minor #3387 FixCommand - forbid passing 'config' and 'rules' options together (keradus) +* minor #3388 Remove Helpers (keradus) +* minor #3389 AccessibleObject - drop class (keradus) +* minor #3390 Drop deprecated rules: blank_line_before_return, hash_to_slash_comment, method_separation, no_extra_consecutive_blank_lines, no_multiline_whitespace_before_semicolons and pre_increment (keradus) +* minor #3456 AutoReview - drop references to removed rule (keradus) +* minor #3659 use php-cs-fixer/diff ^2.0 (SpacePossum) +* minor #3681 CiIntegrationTest - fix incompatibility from 2.x line (keradus) +* minor #3740 NoUnusedImportsFixer - remove SF exception (SpacePossum) +* minor #3771 UX: always set error_reporting in entry file, not Application (keradus) +* minor #3922 Make some more classes final (ntzm, SpacePossum) +* minor #3995 Change default config of native_function_invocation (dunglas, SpacePossum) +* minor #4432 DX: remove empty sets from RuleSet (kubawerlos) +* minor #4489 Fix ruleset @PHPUnit50Migration:risky (kubawerlos) +* minor #4620 DX: cleanup additional, not used parameters (keradus) +* minor #4666 Remove deprecated rules: lowercase_constants, php_unit_ordered_covers, silenced_deprecation_error (keradus) +* minor #4697 Remove deprecated no_short_echo_tag rule (julienfalque) +* minor #4851 fix phpstan on 3.0 (SpacePossum) +* minor #4901 Fix SCA (SpacePossum) +* minor #5069 Fixed failing tests on 3.0 due to unused import after merge (GrahamCampbell) +* minor #5096 NativeFunctionInvocationFixer - BacktickToShellExecFixer - fix integration test (SpacePossum) +* minor #5171 Fix test (SpacePossum) +* minor #5245 Fix CI for 3.0 line (keradus) +* minor #5351 clean ups (SpacePossum) +* minor #5364 DX: Do not display runtime twice on 3.0 line (keradus) +* minor #5412 3.0 - cleanup (SpacePossum, keradus) +* minor #5417 Further BC cleanup for 3.0 (keradus) +* minor #5418 Drop src/Test namespace (keradus) +* minor #5436 Drop mapping of strings to boolean option other than yes/no (keradus) +* minor #5440 Change default ruleset to PSR-12 (keradus) +* minor #5477 Drop diff-format (keradus) +* minor #5478 Docs: Cleanup UPGRADE markdown files (keradus) +* minor #5479 ArraySyntaxFixer, ListSyntaxFixer - change default syntax to short (keradus) +* minor #5480 Tokens::findBlockEnd - drop deprecated argument (keradus) +* minor #5485 ClassAttributesSeparationFixer - drop deprecated flat list configuration (keradus) +* minor #5486 CI: drop unused env variables (keradus) +* minor #5488 Do not distribute documentation (szepeviktor) +* minor #5513 DX: Tokens::warnPhp8SplFixerArrayChange - drop unused method (keradus) +* minor #5520 DX: Drop IsIdenticalConstraint (keradus) +* minor #5521 DX: apply rules configuration cleanups for PHP 7.1+ (keradus) +* minor #5524 DX: drop support of very old deps (keradus) +* minor #5525 Drop phpunit-legacy-adapter (keradus) +* minor #5527 Bump required PHP to 7.1 (keradus) +* minor #5529 DX: bump required PHPUnit to v7+ (keradus) +* minor #5532 Apply PHP 7.1 typing (keradus) +* minor #5541 RuleSet - disallow null usage to disable the rule (keradus) +* minor #5555 DX: further typing improvements (keradus) +* minor #5562 Fix table row rendering for default values of array_syntax and list_syntax (derrabus) +* minor #5608 DX: new cache filename (keradus) +* minor #5609 Forbid old config filename usage (keradus) +* minor #5638 DX: remove Utils::calculateBitmask (keradus) +* minor #5641 DX: use constants for PHPUnit version on 3.0 line (keradus) +* minor #5643 FixCommand - simplify help (keradus) +* minor #5644 Token::toJson() - remove parameter (keradus) +* minor #5645 DX: YodaStyleFixerTest - fix CI (keradus) +* minor #5649 DX: YodaStyleFixerTest - fix 8.0 compat (keradus) +* minor #5650 DX: FixCommand - drop outdated/duplicated docs (keradus) +* minor #5656 DX: mark some constants as internal or private (keradus) +* minor #5657 DX: convert some properties to constants (keradus) +* minor #5669 Remove TrailingCommaInMultilineArrayFixer (kubawerlos, keradus) + +Changelog for v2.19.3 +--------------------- + +* minor #6060 DX: Add upgrade guide link when next Major is available (keradus) + +Changelog for v2.19.2 +--------------------- + +* bug #5881 SelfUpdateCommand - fix link to UPGRADE docs (keradus) + +Changelog for v2.19.1 +--------------------- + +* bug #5395 PhpdocTagTypeFixer: Do not modify array shapes (localheinz, julienfalque) +* bug #5678 UseArrowFunctionsFixer - fix for return without value (kubawerlos) +* bug #5679 PhpUnitNamespacedFixer - do not try to fix constant usage (kubawerlos) +* bug #5681 RegularCallableCallFixer - fix for function name with escaped slash (kubawerlos) +* bug #5687 FinalInternalClassFixer - fix for annotation with space after "@" (kubawerlos) +* bug #5688 ArrayIndentationFixer - fix for really long arrays (kubawerlos) +* bug #5690 PhpUnitNoExpectationAnnotationFixer - fix "expectedException" annotation with message below (kubawerlos) +* bug #5693 YodaStyleFixer - fix for assignment operators (kubawerlos) +* bug #5697 StrictParamFixer - fix for method definition (kubawerlos) +* bug #5702 CommentToPhpdocFixer - fix for single line comments starting with more than 2 slashes (kubawerlos) +* bug #5703 DateTimeImmutableFixer - fix for method definition (kubawerlos) +* bug #5718 VoidReturnFixer - do not break syntax with magic methods (kubawerlos) +* bug #5727 SingleSpaceAfterConstructFixer - Add support for `namespace` (julienfalque) +* bug #5730 Fix transforming deprecations into exceptions (julienfalque) +* bug #5738 TokensAnalyzer - fix for union types (kubawerlos) +* bug #5741 Fix constant invocation detection cases (kubawerlos) +* bug #5769 Fix priority between `phpdoc_to_property_type` and `no_superfluous_phpdoc_tags` (julienfalque) +* bug #5774 FunctionsAnalyzer::isTheSameClassCall - fix for $this with double colon following (kubawerlos) +* bug #5779 SingleLineThrowFixer - fix for throw in match (kubawerlos) +* bug #5781 ClassDefinition - fix for anonymous class with trailing comma (kubawerlos) +* bug #5783 StaticLambdaFixer - consider parent:: as a possible reference to $this (fancyweb) +* bug #5791 NoBlankLinesAfterPhpdoc - Add T_NAMESPACE in array of forbidden successors (paulbalandan) +* bug #5799 TypeAlternationTransformer - fix for multiple function parameters (kubawerlos) +* bug #5804 NoBreakCommentFixer - fix for "default" in "match" (kubawerlos) +* bug #5805 SingleLineCommentStyleFixer - run after HeaderCommentFixer (kubawerlos) +* bug #5817 NativeFunctionTypeDeclarationCasingFixer - fix for union types (kubawerlos) +* bug #5823 YodaStyleFixer - yield support (SpacePossum) +* minor #4914 Improve PHPDoc types support (julienfalque, keradus) +* minor #5680 DX: benchmark.sh - ensure deps are updated to enable script working across less-similar branches (keradus) +* minor #5689 Calculate code coverage on PHP 8 (kubawerlos) +* minor #5694 DX: fail on risky tests (kubawerlos) +* minor #5695 Utils - save only unique deprecations to avoid memory issues (PetrHeinz) +* minor #5710 [typo] add correct backquotes (PhilETaylor) +* minor #5717 Run migration rules on PHP 8 (kubawerlos, keradus) +* minor #5721 Fix reStructuredText markup (julienfalque) +* minor #5725 Update LICENSE (exussum12) +* minor #5731 CI - Fix checkbashisms installation (julienfalque) +* minor #5740 DX: more type-related docblocks (keradus) +* minor #5746 Config - Improve deprecation message with details (SpacePossum) +* minor #5747 RandomApiMigrationFixer - better docs and better "random_int" support (SpacePossum) +* minor #5748 Updated the link to netbeans plugins page (cyberguroo) +* minor #5750 Test all const are in uppercase (SpacePossum) +* minor #5752 NoNullPropertyInitializationFixer - fix static properties as well (HypeMC) +* minor #5756 Fix rule sets descriptions (kubawerlos) +* minor #5761 Fix links in custom rules documentation (julienfalque) +* minor #5777 DX: update PHPStan (kubawerlos) +* minor #5789 DX: update PHPStan (kubawerlos) +* minor #5808 Update PHPStan to 0.12.92 (kubawerlos) +* minor #5824 Deprecate v2 (keradus) +* minor #5825 DX: update checkbashisms to v2.21.3 (keradus) +* minor #5826 SCA: check both composer files (keradus) +* minor #5827 ClassAttributesSeparationFixer - Add `trait_import` support (SpacePossum) + +Changelog for v2.19.0 +--------------------- + +* feature #4238 TrailingCommaInMultilineFixer - introduction (kubawerlos) +* feature #4592 PhpdocToPropertyTypeFixer - introduction (julienfalque) +* feature #5390 feature #4024 added a `list-files` command (clxmstaab, keradus) +* feature #5635 Add list-sets command (keradus) +* feature #5674 UX: Display deprecations to end-user (keradus) +* minor #5601 Always stop when "PHP_CS_FIXER_FUTURE_MODE" is used (kubawerlos) +* minor #5607 DX: new config filename (keradus) +* minor #5613 DX: UtilsTest - add missing teardown (keradus) +* minor #5631 DX: config deduplication (keradus) +* minor #5633 fix typos (staabm) +* minor #5642 Deprecate parameter of Token::toJson() (keradus) +* minor #5672 DX: do not test deprecated fixer (kubawerlos) + +Changelog for v2.18.7 +--------------------- + +* bug #5593 SingleLineThrowFixer - fix handling anonymous classes (kubawerlos) +* bug #5654 SingleLineThrowFixer - fix for match expression (kubawerlos) +* bug #5660 TypeAlternationTransformer - fix for "array" type in type alternation (kubawerlos) +* bug #5665 NullableTypeDeclarationForDefaultNullValueFixer - fix for nullable with attribute (kubawerlos) +* bug #5670 PhpUnitNamespacedFixer - do not try to fix constant (kubawerlos) +* bug #5671 PhpdocToParamTypeFixer - do not change function call (kubawerlos) +* bug #5673 GroupImportFixer - Fix failing case (julienfalque) +* minor #4591 Refactor conversion of PHPDoc to type declarations (julienfalque, keradus) +* minor #5611 DX: use method expectDeprecation from Symfony Bridge instead of annotation (kubawerlos) +* minor #5658 DX: use constants in tests for Fixer configuration (keradus) +* minor #5661 DX: remove PHPStan exceptions for "tests" from phpstan.neon (kubawerlos) +* minor #5662 Change wording from "merge" to "intersect" (jschaedl) +* minor #5663 DX: do not abuse "inheritdoc" tag (kubawerlos) +* minor #5664 DX: code grooming (keradus) + +Changelog for v2.18.6 +--------------------- + +* bug #5586 Add support for nullsafe object operator ("?->") (kubawerlos) +* bug #5597 Tokens - fix for checking block edges (kubawerlos) +* bug #5604 Custom annotations @type changed into @var (Leprechaunz) +* bug #5606 DoctrineAnnotationBracesFixer false positive (Leprechaunz) +* bug #5610 BracesFixer - fix braces of match expression (Leprechaunz) +* bug #5615 GroupImportFixer severely broken (Leprechaunz) +* bug #5617 ClassAttributesSeparationFixer - fix for using visibility for class elements (kubawerlos) +* bug #5618 GroupImportFixer - fix removal of import type when mixing multiple types (Leprechaunz) +* bug #5622 Exclude Doctrine documents from final fixer (ossinkine) +* bug #5630 PhpdocTypesOrderFixer - handle complex keys (Leprechaunz) +* minor #5554 DX: use tmp file in sys_temp_dir for integration tests (keradus) +* minor #5564 DX: make integration tests matching entries in FixerFactoryTest (kubawerlos) +* minor #5603 DX: DocumentationGenerator - no need to re-configure Differ (keradus) +* minor #5612 DX: use ::class whenever possible (kubawerlos) +* minor #5619 DX: allow XDebugHandler v2 (keradus) +* minor #5623 DX: when displaying app version, don't put extra space if there is no CODENAME available (keradus) +* minor #5626 DX: update PHPStan and way of ignoring flickering PHPStan exception (keradus) +* minor #5629 DX: fix CiIntegrationTest (keradus) +* minor #5636 DX: remove 'create' method in internal classes (keradus) +* minor #5637 DX: do not calculate bitmap via helper anymore (keradus) +* minor #5639 Move fix reports (classes and schemas) (keradus) +* minor #5640 DX: use constants for PHPUnit version (keradus) +* minor #5646 Cleanup YodaStyleFixerTest (kubawerlos) + +Changelog for v2.18.5 +--------------------- + +* bug #5561 NoMixedEchoPrintFixer: fix for conditions without curly brackets (kubawerlos) +* bug #5563 Priority fix: SingleSpaceAfterConstructFixer must run before BracesFixer (kubawerlos) +* bug #5567 Fix order of BracesFixer and ClassDefinitionFixer (Daeroni) +* bug #5596 NullableTypeTransformer - fix for attributes (kubawerlos, jrmajor) +* bug #5598 GroupImportFixer - fix breaking code when fixing root classes (Leprechaunz) +* minor #5571 DX: add test to make sure SingleSpaceAfterConstructFixer runs before FunctionDeclarationFixer (kubawerlos) +* minor #5577 Extend priority test for "class_definition" vs "braces" (kubawerlos) +* minor #5585 DX: make doc examples prettier (kubawerlos) +* minor #5590 Docs: HeaderCommentFixer - document example how to remove header comment (keradus) +* minor #5602 DX: regenerate docs (keradus) + +Changelog for v2.18.4 +--------------------- + +* bug #4085 Priority: AlignMultilineComment should run before every PhpdocFixer (dmvdbrugge) +* bug #5421 PsrAutoloadingFixer - Fix PSR autoloading outside configured directory (kelunik, keradus) +* bug #5464 NativeFunctionInvocationFixer - PHP 8 attributes (HypeMC, keradus) +* bug #5548 NullableTypeDeclarationForDefaultNullValueFixer - fix handling promoted properties (jrmajor, keradus) +* bug #5550 TypeAlternationTransformer - fix for typed static properties (kubawerlos) +* bug #5551 ClassAttributesSeparationFixer - fix for properties with type alternation (kubawerlos, keradus) +* bug #5552 DX: test relation between function_declaration and method_argument_space (keradus) +* minor #5540 DX: RuleSet - convert null handling to soft-warning (keradus) +* minor #5545 DX: update checkbashisms (keradus) + +Changelog for v2.18.3 +--------------------- + +* bug #5484 NullableTypeDeclarationForDefaultNullValueFixer - handle mixed pseudotype (keradus) +* minor #5470 Disable CI fail-fast (mvorisek) +* minor #5491 Support php8 static return type for NoSuperfluousPhpdocTagsFixer (tigitz) +* minor #5494 BinaryOperatorSpacesFixer - extend examples (keradus) +* minor #5499 DX: add TODOs for PHP requirements cleanup (keradus) +* minor #5500 DX: Test that Transformers are adding only CustomTokens that they define and nothing else (keradus) +* minor #5507 Fix quoting in exception message (gquemener) +* minor #5514 DX: PHP 7.0 integration test - solve TODO for random_api_migration usage (keradus) +* minor #5515 DX: do not override getConfigurationDefinition (keradus) +* minor #5516 DX: AbstractDoctrineAnnotationFixer - no need for import aliases (keradus) +* minor #5518 DX: minor typing and validation fixes (keradus) +* minor #5522 Token - add handling json_encode crash (keradus) +* minor #5523 DX: EregToPregFixer - fix sorting (keradus) +* minor #5528 DX: code cleanup (keradus) + +Changelog for v2.18.2 +--------------------- + +* bug #5466 Fix runtime check of PHP version (keradus) +* minor #4250 POC Tokens::insertSlices (keradus) + +Changelog for v2.18.1 +--------------------- + +* bug #5447 switch_case_semicolon_to_colon should skip match/default statements (derrabus) +* bug #5453 SingleSpaceAfterConstructFixer - better handling of closing parenthesis and brace (keradus) +* bug #5454 NullableTypeDeclarationForDefaultNullValueFixer - support property promotion via constructor (keradus) +* bug #5455 PhpdocToCommentFixer - add support for attributes (keradus) +* bug #5462 NullableTypeDeclarationForDefaultNullValueFixer - support union types (keradus) +* minor #5444 Fix PHP version number in PHP54MigrationSet description (jdreesen, keradus) +* minor #5445 DX: update usage of old TraversableContains in tests (keradus) +* minor #5456 DX: Fix CiIntegrationTest (keradus) +* minor #5457 CI: fix params order (keradus) +* minor #5458 CI: fix migration workflow (keradus) +* minor #5459 DX: cleanup PHP Migration rulesets (keradus) + +Changelog for v2.18.0 +--------------------- + +* feature #4943 Add PSR12 ruleset (julienfalque, keradus) +* feature #5426 Update Symfony ruleset (keradus) +* feature #5428 Add/Change PHP.MigrationSet to update array/list syntax to short one (keradus) +* minor #5441 Allow execution under PHP 8 (keradus) + +Changelog for v2.17.5 +--------------------- + +* bug #5447 switch_case_semicolon_to_colon should skip match/default statements (derrabus) +* bug #5453 SingleSpaceAfterConstructFixer - better handling of closing parenthesis and brace (keradus) +* bug #5454 NullableTypeDeclarationForDefaultNullValueFixer - support property promotion via constructor (keradus) +* bug #5455 PhpdocToCommentFixer - add support for attributes (keradus) +* bug #5462 NullableTypeDeclarationForDefaultNullValueFixer - support union types (keradus) +* minor #5445 DX: update usage of old TraversableContains in tests (keradus) +* minor #5456 DX: Fix CiIntegrationTest (keradus) +* minor #5457 CI: fix params order (keradus) +* minor #5459 DX: cleanup PHP Migration rulesets (keradus) + +Changelog for v2.17.4 +--------------------- + +* bug #5379 PhpUnitMethodCasingFixer - Do not modify class name (localheinz) +* bug #5404 NullableTypeTransformer - constructor property promotion support (Wirone) +* bug #5433 PhpUnitTestCaseStaticMethodCallsFixer - fix for abstract static method (kubawerlos) +* minor #5234 DX: Add Docker dev setup (julienfalque, keradus) +* minor #5391 PhpdocOrderByValueFixer - Add additional annotations to sort (localheinz) +* minor #5392 PhpdocScalarFixer - Fix description (localheinz) +* minor #5397 NoExtraBlankLinesFixer - PHP8 throw support (SpacePossum) +* minor #5399 Add PHP8 integration test (keradus) +* minor #5405 TypeAlternationTransformer - add support for PHP8 (SpacePossum) +* minor #5406 SingleSpaceAfterConstructFixer - Attributes, comments and PHPDoc support (SpacePossum) +* minor #5407 TokensAnalyzer::getClassyElements - return trait imports (SpacePossum) +* minor #5410 minors (SpacePossum) +* minor #5411 bump year in LICENSE file (SpacePossum) +* minor #5414 TypeAlternationTransformer - T_FN support (SpacePossum) +* minor #5415 Forbid execution under PHP 8.0.0 (keradus) +* minor #5416 Drop Travis CI (keradus) +* minor #5419 CI: separate SCA checks to dedicated jobs (keradus) +* minor #5420 DX: unblock PHPUnit 9.5 (keradus) +* minor #5423 DX: PHPUnit - disable verbose by default (keradus) +* minor #5425 Cleanup 3.0 todos (keradus) +* minor #5427 Plan changing defaults for array_syntax and list_syntax in 3.0 release (keradus) +* minor #5429 DX: Drop speedtrap PHPUnit listener (keradus) +* minor #5432 Don't allow unserializing classes with a destructor (jderusse) +* minor #5435 DX: PHPUnit - groom configuration of time limits (keradus) +* minor #5439 VisibilityRequiredFixer - support type alternation for properties (keradus) +* minor #5442 DX: FunctionsAnalyzerTest - add missing 7.0 requirement (keradus) + +Changelog for v2.17.3 +--------------------- + +* bug #5384 PsrAutoloadingFixer - do not remove directory structure from the Class name (kubawerlos, keradus) +* bug #5385 SingleLineCommentStyleFixer- run before NoUselessReturnFixer (kubawerlos) +* bug #5387 SingleSpaceAfterConstructFixer - do not touch multi line implements (SpacePossum) +* minor #5329 DX: collect coverage with Github Actions (kubawerlos) +* minor #5380 PhpdocOrderByValueFixer - Allow sorting of throws annotations by value (localheinz, keradus) +* minor #5383 DX: fail PHPUnit tests on warning (kubawerlos) +* minor #5386 DX: remove incorrect priority relations (kubawerlos) + +Changelog for v2.17.2 +--------------------- + +* bug #5345 CleanNamespaceFixer - preserve traling comments (SpacePossum) +* bug #5348 PsrAutoloadingFixer - fix for class without namespace (kubawerlos) +* bug #5362 SingleSpaceAfterConstructFixer: Do not adjust whitespace before multiple multi-line extends (localheinz, SpacePossum) +* minor #5314 Enable testing with PHPUnit 9.x (sanmai) +* minor #5319 Clean ups (SpacePossum) +* minor #5338 clean ups (SpacePossum) +* minor #5339 NoEmptyStatementFixer - fix more cases (SpacePossum) +* minor #5340 NamedArgumentTransformer - Introduction (SpacePossum) +* minor #5344 Update docs: do not use deprecated create method (SpacePossum) +* minor #5353 Fix typo in issue template (stof) +* minor #5355 OrderedTraitsFixer - mark as risky (SpacePossum) +* minor #5356 RuleSet description fixes (SpacePossum) +* minor #5359 Add application version to "fix" out put when verbosity flag is set (SpacePossum) +* minor #5360 DX: clean up detectIndent methods (kubawerlos) +* minor #5363 Added missing self return type to ConfigInterface::registerCustomFixers() (vudaltsov) +* minor #5366 PhpUnitDedicateAssertInternalTypeFixer - recover target option (keradus) +* minor #5368 DX: PHPUnit 9 compatibility for 2.17 (keradus) +* minor #5370 DX: update PHPUnit usage to use external Prophecy trait and solve warning (keradus) +* minor #5371 Update documentation about PHP_CS_FIXER_IGNORE_ENV (SanderSander, keradus) +* minor #5373 DX: MagicMethodCasingFixerTest - fix test case description (keradus) +* minor #5374 DX: PhpUnitDedicateAssertInternalTypeFixer - add code sample for non-default config (keradus) + +Changelog for v2.17.1 +--------------------- + +* bug #5325 NoBreakCommentFixer - better throw handling (SpacePossum) +* bug #5327 StaticLambdaFixer - fix for arrow function used in class with $this (kubawerlos, SpacePossum) +* bug #5332 Fix file missing for php8 (jderusse) +* bug #5333 Fix file missing for php8 (jderusse) +* minor #5328 Fixed deprecation message version (GrahamCampbell) +* minor #5330 DX: cleanup Github Actions configs (kubawerlos) + +Changelog for v2.17.0 +--------------------- + +* bug #4752 SimpleLambdaCallFixer - bug fixes (SpacePossum) +* bug #4794 TernaryToElvisOperatorFixer - fix open tag with echo (SpacePossum) +* bug #5084 Fix for variables within string interpolation in lambda_not_used_import (GrahamCampbell) +* bug #5094 SwitchContinueToBreakFixer - do not support alternative syntax (SpacePossum) +* feature #2619 PSR-5 @inheritDoc support (julienfalque) +* feature #3253 Add SimplifiedIfReturnFixer (Slamdunk, SpacePossum) +* feature #4005 GroupImportFixer - introduction (greeflas) +* feature #4012 BracesFixer - add "allow_single_line_anonymous_class_with_empty_body" option (kubawerlos) +* feature #4021 OperatorLinebreakFixer - Introduction (kubawerlos, SpacePossum) +* feature #4259 PsrAutoloadingFixer - introduction (kubawerlos) +* feature #4375 extend ruleset "@PHP73Migration" (gharlan) +* feature #4435 SingleSpaceAfterConstructFixer - Introduction (localheinz) +* feature #4493 Add echo_tag_syntax rule (mlocati, kubawerlos) +* feature #4544 SimpleLambdaCallFixer - introduction (keradus) +* feature #4569 PhpdocOrderByValueFixer - Introduction (localheinz) +* feature #4590 SwitchContinueToBreakFixer - Introduction (SpacePossum) +* feature #4679 NativeConstantInvocationFixer - add "strict" flag (kubawerlos) +* feature #4701 OrderedTraitsFixer - introduction (julienfalque) +* feature #4704 LambdaNotUsedImportFixer - introduction (SpacePossum) +* feature #4740 NoAliasLanguageConstructCallFixer - introduction (SpacePossum) +* feature #4741 TernaryToElvisOperatorFixer - introduction (SpacePossum) +* feature #4778 UseArrowFunctionsFixer - introduction (gharlan) +* feature #4790 ArrayPushFixer - introduction (SpacePossum) +* feature #4800 NoUnneededFinalMethodFixer - Add "private_methods" option (SpacePossum) +* feature #4831 BlankLineBeforeStatementFixer - add yield from (SpacePossum) +* feature #4832 NoUnneededControlParenthesesFixer - add yield from (SpacePossum) +* feature #4863 NoTrailingWhitespaceInStringFixer - introduction (gharlan) +* feature #4875 ClassAttributesSeparationFixer - add option for no new lines between properties (adri, ruudk) +* feature #4880 HeredocIndentationFixer - config option for indentation level (gharlan) +* feature #4908 PhpUnitExpectationFixer - update for Phpunit 8.4 (ktomk) +* feature #4942 OrderedClassElementsFixer - added support for abstract method sorting (carlalexander, SpacePossum) +* feature #4947 NativeConstantInvocation - Add "PHP_INT_SIZE" to SF rule set (kubawerlos) +* feature #4953 Add support for custom differ (paulhenri-l, SpacePossum) +* feature #5264 CleanNamespaceFixer - Introduction (SpacePossum) +* feature #5280 NoUselessSprintfFixer - Introduction (SpacePossum) +* minor #4634 Make all options snake_case (kubawerlos) +* minor #4667 PhpUnitOrderedCoversFixer - stop using deprecated fixer (keradus) +* minor #4673 FinalStaticAccessFixer - deprecate (julienfalque) +* minor #4762 Rename simple_lambda_call to regular_callable_call (julienfalque) +* minor #4782 Update RuleSets (SpacePossum) +* minor #4802 Master cleanup (SpacePossum) +* minor #4828 Deprecate Config::create() (DocFX) +* minor #4872 Update RuleSet SF and PHP-CS-Fixer with new config for `no_extra_blan… (SpacePossum) +* minor #4900 Move "no_trailing_whitespace_in_string" to SF ruleset. (SpacePossum) +* minor #4903 Docs: extend regular_callable_call rule docs (keradus, SpacePossum) +* minor #4910 Add use_arrow_functions rule to PHP74Migration:risky set (keradus) +* minor #5025 PhpUnitDedicateAssertInternalTypeFixer - deprecate "target" option (kubawerlos) +* minor #5037 FinalInternalClassFixer- Rename option (SpacePossum) +* minor #5093 LambdaNotUsedImportFixer - add heredoc test (SpacePossum) +* minor #5163 Fix CS (SpacePossum) +* minor #5169 PHP8 care package master (SpacePossum) +* minor #5186 Fix tests (SpacePossum) +* minor #5192 GotoLabelAnalyzer - introduction (SpacePossum) +* minor #5230 Fix: Reference (localheinz) +* minor #5240 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5244 Fix 2.17 build (keradus) +* minor #5251 PHP8 - match support (SpacePossum) +* minor #5252 Update RuleSets (SpacePossum) +* minor #5278 PHP8 constructor property promotion support (SpacePossum) +* minor #5284 PHP8 - Attribute support (SpacePossum) +* minor #5323 NoUselessSprintfFixer - Fix test on PHP5.6 (SpacePossum) +* minor #5326 DX: relax composer requirements to not block installation under PHP v8, support for PHP v8 is not yet ready (keradus) + + +Changelog for v2.16.10 +---------------------- + +* minor #5314 Enable testing with PHPUnit 9.x (sanmai) +* minor #5338 clean ups (SpacePossum) +* minor #5339 NoEmptyStatementFixer - fix more cases (SpacePossum) +* minor #5340 NamedArgumentTransformer - Introduction (SpacePossum) +* minor #5344 Update docs: do not use deprecated create method (SpacePossum) +* minor #5356 RuleSet description fixes (SpacePossum) +* minor #5360 DX: clean up detectIndent methods (kubawerlos) +* minor #5370 DX: update PHPUnit usage to use external Prophecy trait and solve warning (keradus) +* minor #5373 DX: MagicMethodCasingFixerTest - fix test case description (keradus) +* minor #5374 DX: PhpUnitDedicateAssertInternalTypeFixer - add code sample for non-default config (keradus) + +Changelog for v2.16.9 +--------------------- + +* bug #5095 Annotation - fix for Windows line endings (SpacePossum) +* bug #5221 NoSuperfluousPhpdocTagsFixer - fix for single line PHPDoc (kubawerlos) +* bug #5225 TernaryOperatorSpacesFixer - fix for alternative control structures (kubawerlos) +* bug #5235 ArrayIndentationFixer - fix for nested arrays (kubawerlos) +* bug #5248 NoBreakCommentFixer - fix throw detect (SpacePossum) +* bug #5250 SwitchAnalyzer - fix for semicolon after case/default (kubawerlos) +* bug #5253 IO - fix cache info message (SpacePossum) +* bug #5273 Fix PHPDoc line span fixer when property has array typehint (ossinkine) +* bug #5274 TernaryToNullCoalescingFixer - concat precedence fix (SpacePossum) +* feature #5216 Add RuleSets to docs (SpacePossum) +* minor #5226 Applied CS fixes from 2.17-dev (GrahamCampbell) +* minor #5229 Fixed incorrect phpdoc (GrahamCampbell) +* minor #5231 CS: unify styling with younger branches (keradus) +* minor #5232 PHP8 - throw expression support (SpacePossum) +* minor #5233 DX: simplify check_file_permissions.sh (kubawerlos) +* minor #5236 Improve handling of unavailable code samples (julienfalque, keradus) +* minor #5239 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5254 PHP8 - mixed type support (SpacePossum) +* minor #5255 Tests: do not skip documentation test (keradus) +* minor #5256 Docs: phpdoc_to_return_type - add new example in docs (keradus) +* minor #5261 Do not update Composer twice (sanmai) +* minor #5263 PHP8 support (SpacePossum) +* minor #5266 PhpUnitTestCaseStaticMethodCallsFixer - PHPUnit 9.x support (sanmai) +* minor #5267 Improve InstallViaComposerTest (sanmai) +* minor #5268 Add GitHub Workflows CI, including testing on PHP 8 and on macOS/Windows/Ubuntu (sanmai) +* minor #5269 Prep work to migrate to PHPUnit 9.x (sanmai, keradus) +* minor #5275 remove not supported verbose options (SpacePossum) +* minor #5276 PHP8 - add NoUnreachableDefaultArgumentValueFixer to risky set (SpacePossum) +* minor #5277 PHP8 - Constructor Property Promotion support (SpacePossum) +* minor #5292 Disable blank issue template and expose community chat (keradus) +* minor #5293 Add documentation to "yoda_style" sniff to convert Yoda style to non-Yoda style (Luc45) +* minor #5295 Run static code analysis off GitHub Actions (sanmai) +* minor #5298 Add yamllint workflow, validates .yaml files (sanmai) +* minor #5302 SingleLineCommentStyleFixer - do not fix possible attributes (PHP8) (SpacePossum) +* minor #5303 Drop CircleCI and AppVeyor (keradus) +* minor #5304 DX: rename TravisTest, as we no longer test only Travis there (keradus) +* minor #5305 Groom GitHub CI and move some checks from TravisCI to GitHub CI (keradus) +* minor #5308 Only run yamllint when a YAML file is changed (julienfalque, keradus) +* minor #5309 CICD: create yamllint config file (keradus) +* minor #5311 OrderedClassElementsFixer - PHPUnit Bridge support (ktomk) +* minor #5316 PHP8 - Attribute support (SpacePossum) +* minor #5321 DX: little code grooming (keradus) + +Changelog for v2.16.8 +--------------------- + +* bug #5325 NoBreakCommentFixer - better throw handling (SpacePossum) +* bug #5327 StaticLambdaFixer - fix for arrow function used in class with $this (kubawerlos, SpacePossum) +* bug #5333 Fix file missing for php8 (jderusse) +* minor #5328 Fixed deprecation message version (GrahamCampbell) +* minor #5330 DX: cleanup Github Actions configs (kubawerlos) + +Changelog for v2.16.5 +--------------------- + +* bug #4378 PhpUnitNoExpectationAnnotationFixer - annotation in single line doc comment (kubawerlos) +* bug #4936 HeaderCommentFixer - Fix unexpected removal of regular comments (julienfalque) +* bug #5006 PhpdocToParamTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos) +* bug #5016 NoSuperfluousPhpdocTagsFixer - fix for @return with @inheritDoc in description (kubawerlos) +* bug #5017 PhpdocTrimConsecutiveBlankLineSeparationFixer - must run after AlignMultilineCommentFixer (kubawerlos) +* bug #5032 SingleLineAfterImportsFixer - fix for line after import (and before another import) already added using CRLF (kubawerlos) +* bug #5033 VoidReturnFixer - must run after NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #5038 HelpCommandTest - toString nested array (SpacePossum) +* bug #5040 LinebreakAfterOpeningTagFixer - do not change code if linebreak already present (kubawerlos) +* bug #5044 StandardizeIncrementFixer - fix handling static properties (kubawerlos) +* bug #5045 BacktickToShellExecFixer - add priority relation to NativeFunctionInvocationFixer and SingleQuoteFixer (kubawerlos) +* bug #5054 PhpdocTypesFixer - fix for multidimensional array (kubawerlos) +* bug #5065 TernaryOperatorSpacesFixer - fix for discovering ":" correctly (kubawerlos) +* bug #5068 Fixed php-cs-fixer crashes on input file syntax error (GrahamCampbell) +* bug #5087 NoAlternativeSyntaxFixer - add support for switch and declare (SpacePossum) +* bug #5092 PhpdocToParamTypeFixer - remove not used option (SpacePossum) +* bug #5105 ClassKeywordRemoveFixer - fix for fully qualified class (kubawerlos) +* bug #5113 TernaryOperatorSpacesFixer - handle goto labels (SpacePossum) +* bug #5124 Fix TernaryToNullCoalescingFixer when dealing with object properties (HypeMC) +* bug #5137 DoctrineAnnotationSpacesFixer - fix for typed properties (kubawerlos) +* bug #5180 Always lint test cases with the stricter process linter (GrahamCampbell) +* bug #5190 PhpUnit*Fixers - Only fix in unit test class scope (SpacePossum) +* bug #5195 YodaStyle - statements in braces should be treated as variables in strict … (SpacePossum) +* bug #5220 NoUnneededFinalMethodFixer - do not fix private constructors (SpacePossum) +* feature #3475 Rework documentation (julienfalque, SpacePossum) +* feature #5166 PHP8 (SpacePossum) +* minor #4878 ArrayIndentationFixer - refactor (julienfalque) +* minor #5031 CI: skip_cleanup: true (keradus) +* minor #5035 PhpdocToParamTypeFixer - Rename attribute (SpacePossum) +* minor #5048 Allow composer/semver ^2.0 and ^3.0 (thomasvargiu) +* minor #5050 DX: moving integration test for braces, indentation_type and no_break_comment into right place (kubawerlos) +* minor #5051 DX: move all tests from AutoReview\FixerTest to Test\AbstractFixerTestCase (kubawerlos) +* minor #5053 DX: cleanup FunctionTypehintSpaceFixer (kubawerlos) +* minor #5056 DX: add missing priority test for indentation_type and phpdoc_indent (kubawerlos) +* minor #5077 DX: add missing priority test between NoUnsetCastFixer and BinaryOperatorSpacesFixer (kubawerlos) +* minor #5083 Update composer.json to prevent issue #5030 (mvorisek) +* minor #5088 NoBreakCommentFixer - NoUselessElseFixer - priority test (SpacePossum) +* minor #5100 Fixed invalid PHP 5.6 syntax (GrahamCampbell) +* minor #5106 Symfony's finder already ignores vcs and dot files by default (GrahamCampbell) +* minor #5112 DX: check file permissions (kubawerlos, SpacePossum) +* minor #5122 Show runtime PHP version (kubawerlos) +* minor #5132 Do not allow assignments in if statements (SpacePossum) +* minor #5133 RuleSetTest - Early return for boolean and detect more defaults (SpacePossum) +* minor #5139 revert some unneeded exclusions (SpacePossum) +* minor #5148 Upgrade Xcode (kubawerlos) +* minor #5149 NoUnsetOnPropertyFixer - risky description tweaks (SpacePossum) +* minor #5161 minors (SpacePossum) +* minor #5170 Fix test on PHP8 (SpacePossum) +* minor #5172 Remove accidentally inserted newlines (GrahamCampbell) +* minor #5173 Fix PHP8 RuleSet inherit (SpacePossum) +* minor #5174 Corrected linting error messages (GrahamCampbell) +* minor #5177 PHP8 (SpacePossum) +* minor #5178 Fix tests (SpacePossum) +* minor #5184 [FinalStaticAccessFixer] Handle new static() in final class (localheinz) +* minor #5188 DX: Update sibling debs to version supporting PHP8/PHPUnit9 (keradus) +* minor #5189 Create temporary linting file in system temp dir (keradus) +* minor #5191 MethodArgumentSpaceFixer - support use/import of anonymous functions. (undefinedor) +* minor #5193 DX: add AbstractPhpUnitFixer (kubawerlos) +* minor #5204 DX: cleanup NullableTypeTransformerTest (kubawerlos) +* minor #5207 Add © for logo (keradus) +* minor #5208 DX: cleanup php-cs-fixer entry file (keradus) +* minor #5210 CICD - temporarily disable problematic test (keradus) +* minor #5211 CICD: fix file permissions (keradus) +* minor #5213 DX: move report schemas to dedicated dir (keradus) +* minor #5214 CICD: fix file permissions (keradus) +* minor #5215 CICD: update checkbashisms (keradus) +* minor #5217 CICD: use Composer v2 and drop hirak/prestissimo plugin (keradus) +* minor #5218 DX: .gitignore - add .phpunit.result.cache (keradus) +* minor #5222 Upgrade Xcode (kubawerlos) +* minor #5223 Docs: regenerate docs on 2.16 line (keradus) + +Changelog for v2.16.4 +--------------------- + +* bug #3893 Fix handling /** and */ on the same line as the first and/or last annotation (dmvdbrugge) +* bug #4919 PhpUnitTestAnnotationFixer - fix function starting with "test" and having lowercase letter after (kubawerlos) +* bug #4929 YodaStyleFixer - handling equals empty array (kubawerlos) +* bug #4934 YodaStyleFixer - fix for conditions weird are (kubawerlos) +* bug #4958 OrderedImportsFixer - fix for trailing comma in group (kubawerlos) +* bug #4959 BlankLineBeforeStatementFixer - handle comment case (SpacePossum) +* bug #4962 MethodArgumentSpaceFixer - must run after MethodChainingIndentationFixer (kubawerlos) +* bug #4963 PhpdocToReturnTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos, Slamdunk) +* bug #4978 ArrayIndentationFixer - must run after MethodArgumentSpaceFixer (kubawerlos) +* bug #4994 FinalInternalClassFixer - must run before ProtectedToPrivateFixer (kubawerlos) +* bug #4996 NoEmptyCommentFixer - handle multiline comments (kubawerlos) +* bug #4999 BlankLineBeforeStatementFixer - better comment handling (SpacePossum) +* bug #5009 NoEmptyCommentFixer - better handle comments sequence (kubawerlos) +* bug #5010 SimplifiedNullReturnFixer - must run before VoidReturnFixer (kubawerlos) +* bug #5011 SingleClassElementPerStatementFixer - must run before ClassAttributesSeparationFixer (kubawerlos) +* bug #5012 StrictParamFixer - must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5014 PhpdocToParamTypeFixer - fix for void as param (kubawerlos) +* bug #5018 PhpdocScalarFixer - fix for comment with Windows line endings (kubawerlos) +* bug #5029 SingleLineAfterImportsFixer - fix for line after import already added using CRLF (kubawerlos) +* minor #4904 Increase PHPStan level to 8 with strict rules (julienfalque) +* minor #4920 Enhancement: Use DocBlock itself to make it multi-line (localheinz) +* minor #4930 DX: ensure PhpUnitNamespacedFixer handles all classes (kubawerlos) +* minor #4931 DX: add test to ensure each target version in PhpUnitTargetVersion has its set in RuleSet (kubawerlos) +* minor #4932 DX: Travis CI config - fix warnings and infos (kubawerlos) +* minor #4940 Reject empty path (julienfalque) +* minor #4944 Fix grammar (julienfalque) +* minor #4946 Allow "const" option on PHP <7.1 (julienfalque) +* minor #4948 Added describe command to readme (david, 8ctopus) +* minor #4949 Fixed build readme on Windows fails if using Git Bash (Mintty) (8ctopus) +* minor #4954 Config - Trim path (julienfalque) +* minor #4957 DX: Check trailing spaces in project files only (ktomk) +* minor #4961 Assert all project source files are monolithic. (SpacePossum) +* minor #4964 Fix PHPStan baseline (julienfalque) +* minor #4965 Fix PHPStan baseline (julienfalque) +* minor #4973 DX: test "isRisky" method in fixer tests, not as auto review (kubawerlos) +* minor #4974 Minor: Fix typo (ktomk) +* minor #4975 Revert PHPStan level to 5 (julienfalque) +* minor #4976 Add instructions for PHPStan (julienfalque) +* minor #4980 Introduce new issue templates (julienfalque) +* minor #4981 Prevent error in CTTest::testConstants (for PHP8) (guilliamxavier) +* minor #4982 Remove PHIVE (kubawerlos) +* minor #4985 Fix tests with Symfony 5.1 (julienfalque) +* minor #4987 PhpdocAnnotationWithoutDotFixer - handle unicode characters using mb_* (SpacePossum) +* minor #5008 Enhancement: Social justification applied (gbyrka-fingo) +* minor #5023 Fix issue templates (kubawerlos) +* minor #5024 DX: add missing non-default code samples (kubawerlos) + +Changelog for v2.16.3 +--------------------- + +* bug #4915 Fix handling property PHPDocs with unsupported type (julienfalque) +* minor #4916 Fix AppVeyor build (julienfalque) +* minor #4917 CircleCI - Bump xcode to 11.4 (GrahamCampbell) +* minor #4918 DX: do not fix ".phpt" files by default (kubawerlos) + +Changelog for v2.16.2 +--------------------- + +* bug #3820 Braces - (re)indenting comment issues (SpacePossum) +* bug #3911 PhpdocVarWithoutNameFixer - fix for properties only (dmvdbrugge) +* bug #4601 ClassKeywordRemoveFixer - Fix for namespace (yassine-ah, kubawerlos) +* bug #4630 FullyQualifiedStrictTypesFixer - Ignore partial class names which look like FQCNs (localheinz, SpacePossum) +* bug #4661 ExplicitStringVariableFixer - variables pair if one is already explicit (kubawerlos) +* bug #4675 NonPrintableCharacterFixer - fix for backslash and quotes when changing to escape sequences (kubawerlos) +* bug #4678 TokensAnalyzer::isConstantInvocation - fix for importing multiple classes with single "use" (kubawerlos) +* bug #4682 Fix handling array type declaration in properties (julienfalque) +* bug #4685 Improve Symfony 5 compatibility (keradus) +* bug #4688 TokensAnalyzer::isConstantInvocation - Fix detection for fully qualified return type (julienfalque) +* bug #4689 DeclareStrictTypesFixer - fix for "strict_types" set to "0" (kubawerlos) +* bug #4690 PhpdocVarAnnotationCorrectOrderFixer - fix for multiline `@var` without type (kubawerlos) +* bug #4710 SingleTraitInsertPerStatement - fix formatting for multiline "use" (kubawerlos) +* bug #4711 Ensure that files from "tests" directory in release are autoloaded (kubawerlos) +* bug #4749 TokensAnalyze::isUnaryPredecessorOperator fix for CT::T_ARRAY_INDEX_C… (SpacePossum) +* bug #4759 Add more priority cases (SpacePossum) +* bug #4761 NoSuperfluousElseifFixer - handle single line (SpacePossum) +* bug #4783 NoSuperfluousPhpdocTagsFixer - fix for really big PHPDoc (kubawerlos, mvorisek) +* bug #4787 NoUnneededFinalMethodFixer - Mark as risky (SpacePossum) +* bug #4795 OrderedClassElementsFixer - Fix (SpacePossum) +* bug #4801 GlobalNamespaceImportFixer - fix docblock handling (gharlan) +* bug #4804 TokensAnalyzer::isUnarySuccessorOperator fix for array curly braces (SpacePossum) +* bug #4807 IncrementStyleFixer - handle after ")" (SpacePossum) +* bug #4808 Modernize types casting fixer array curly (SpacePossum) +* bug #4809 Fix "braces" and "method_argument_space" priority (julienfalque) +* bug #4813 BracesFixer - fix invalid code generation on alternative syntax (SpacePossum) +* bug #4822 fix 2 bugs in phpdoc_line_span (lmichelin) +* bug #4823 ReturnAssignmentFixer - repeat fix (SpacePossum) +* bug #4824 NoUnusedImportsFixer - SingleLineAfterImportsFixer - fix priority (SpacePossum) +* bug #4825 GlobalNamespaceImportFixer - do not import global into global (SpacePossum) +* bug #4829 YodaStyleFixer - fix precedence for T_MOD_EQUAL and T_COALESCE_EQUAL (SpacePossum) +* bug #4830 TernaryToNullCoalescingFixer - handle yield from (SpacePossum) +* bug #4835 Remove duplicate "function_to_constant" from RuleSet (SpacePossum) +* bug #4840 LineEndingFixer - T_CLOSE_TAG support, StringLineEndingFixer - T_INLI… (SpacePossum) +* bug #4846 FunctionsAnalyzer - better isGlobalFunctionCall detection (SpacePossum) +* bug #4852 Priority issues (SpacePossum) +* bug #4870 HeaderCommentFixer - do not remove class docs (gharlan) +* bug #4871 NoExtraBlankLinesFixer - handle cases on same line (SpacePossum) +* bug #4895 Fix conflict between header_comment and declare_strict_types (BackEndTea, julienfalque) +* bug #4911 PhpdocSeparationFixer - fix regression with lack of next line (keradus) +* feature #4742 FunctionToConstantFixer - get_class($this) support (SpacePossum) +* minor #4377 CommentsAnalyzer - fix for declare before header comment (kubawerlos) +* minor #4636 DX: do not check for PHPDBG when collecting coverage (kubawerlos) +* minor #4644 Docs: add info about "-vv..." (voku) +* minor #4691 Run Travis CI on stable PHP 7.4 (kubawerlos) +* minor #4693 Increase Travis CI Git clone depth (julienfalque) +* minor #4699 LineEndingFixer - handle "\r\r\n" (kubawerlos) +* minor #4703 NoSuperfluousPhpdocTagsFixer,PhpdocAddMissingParamAnnotationFixer - p… (SpacePossum) +* minor #4707 Fix typos (TysonAndre) +* minor #4712 NoBlankLinesAfterPhpdocFixer — Do not strip newline between docblock and use statements (mollierobbert) +* minor #4715 Enhancement: Install ergebnis/composer-normalize via Phive (localheinz) +* minor #4722 Fix Circle CI build (julienfalque) +* minor #4724 DX: Simplify installing PCOV (kubawerlos) +* minor #4736 NoUnusedImportsFixer - do not match variable name as import (SpacePossum) +* minor #4746 NoSuperfluousPhpdocTagsFixer - Remove for typed properties (PHP 7.4) (ruudk) +* minor #4753 Do not apply any text/.git filters to fixtures (mvorisek) +* minor #4757 Test $expected is used before $input (SpacePossum) +* minor #4758 Autoreview the PHPDoc of *Fixer::getPriority based on the priority map (SpacePossum) +* minor #4765 Add test on some return types (SpacePossum) +* minor #4766 Remove false test skip (SpacePossum) +* minor #4767 Remove useless priority comments (kubawerlos) +* minor #4769 DX: add missing priority tests (kubawerlos) +* minor #4772 NoUnneededFinalMethodFixer - update description (kubawerlos) +* minor #4774 DX: simplify Utils::camelCaseToUnderscore (kubawerlos) +* minor #4781 NoUnneededCurlyBracesFixer - handle namespaces (SpacePossum) +* minor #4784 Travis CI - Use multiple keyservers (ktomk) +* minor #4785 Improve static analysis (enumag) +* minor #4788 Configurable fixers code sample (SpacePossum) +* minor #4791 Increase PHPStan level to 3 (julienfalque) +* minor #4797 clean ups (SpacePossum) +* minor #4803 FinalClassFixer - Doctrine\ORM\Mapping as ORM alias should not be required (localheinz) +* minor #4839 2.15 - clean ups (SpacePossum) +* minor #4842 ReturnAssignmentFixer - Support more cases (julienfalque) +* minor #4843 NoSuperfluousPhpdocTagsFixer - fix typo in option description (OndraM) +* minor #4844 Same requirements for descriptions (SpacePossum) +* minor #4849 Increase PHPStan level to 5 (julienfalque) +* minor #4850 Fix phpstan (SpacePossum) +* minor #4857 Fixed the unit tests (GrahamCampbell) +* minor #4865 Use latest xcode image (GrahamCampbell) +* minor #4892 CombineNestedDirnameFixer - Add space after comma (julienfalque) +* minor #4894 DX: PhpdocToParamTypeFixer - improve typing (keradus) +* minor #4898 FixerTest - yield the data in AutoReview (Nyholm) +* minor #4899 Fix exception message format for fabbot.io (SpacePossum) +* minor #4905 Support composer v2 installed.json files (GrahamCampbell) +* minor #4906 CI: use Composer stable release for AppVeyor (kubawerlos) +* minor #4909 DX: HeaderCommentFixer - use non-aliased version of option name in code (keradus) +* minor #4912 CI: Fix AppVeyor integration (keradus) + +Changelog for v2.16.1 +--------------------- + +* bug #4476 FunctionsAnalyzer - add "isTheSameClassCall" for correct verifying of function calls (kubawerlos) +* bug #4605 PhpdocToParamTypeFixer - cover more cases (keradus, julienfalque) +* bug #4626 FinalPublicMethodForAbstractClassFixer - Do not attempt to mark abstract public methods as final (localheinz) +* bug #4632 NullableTypeDeclarationForDefaultNullValueFixer - fix for not lowercase "null" (kubawerlos) +* bug #4638 Ensure compatibility with PHP 7.4 (julienfalque) +* bug #4641 Add typed properties test to VisibilityRequiredFixerTest (GawainLynch, julienfalque) +* bug #4654 ArrayIndentationFixer - Fix array indentation for multiline values (julienfalque) +* bug #4660 TokensAnalyzer::isConstantInvocation - fix for extending multiple interfaces (kubawerlos) +* bug #4668 TokensAnalyzer::isConstantInvocation - fix for interface method return type (kubawerlos) +* minor #4608 Allow Symfony 5 components (l-vo) +* minor #4622 Disallow PHP 7.4 failures on Travis CI (julienfalque) +* minor #4623 README - Mark up as code (localheinz) +* minor #4637 PHP 7.4 integration test (GawainLynch, julienfalque) +* minor #4643 DX: Update .gitattributes and move ci-integration.sh to root of the project (kubawerlos, keradus) +* minor #4645 Check PHP extensions on runtime (kubawerlos) +* minor #4655 Improve docs - README (mvorisek) +* minor #4662 DX: generate headers in README.rst (kubawerlos) +* minor #4669 Enable execution under PHP 7.4 (keradus) +* minor #4670 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) +* minor #4671 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) + +Changelog for v2.16.0 +--------------------- + +* feature #3810 PhpdocLineSpanFixer - Introduction (BackEndTea) +* feature #3928 Add FinalPublicMethodForAbstractClassFixer (Slamdunk) +* feature #4000 FinalStaticAccessFixer - Introduction (ntzm) +* feature #4275 Issue #4274: Let lowercase_constants directive to be configurable. (drupol) +* feature #4355 GlobalNamespaceImportFixer - Introduction (gharlan) +* feature #4358 SelfStaticAccessorFixer - Introduction (SpacePossum) +* feature #4385 CommentToPhpdocFixer - allow to ignore tags (kubawerlos) +* feature #4401 Add NullableTypeDeclarationForDefaultNullValueFixer (HypeMC) +* feature #4452 Add SingleLineThrowFixer (kubawerlos) +* feature #4500 NoSuperfluousPhpdocTags - Add remove_inheritdoc option (julienfalque) +* feature #4505 NoSuperfluousPhpdocTagsFixer - allow params that aren't on the signature (azjezz) +* feature #4531 PhpdocAlignFixer - add "property-read" and "property-write" to allowed tags (kubawerlos) +* feature #4583 Phpdoc to param type fixer rebase (jg-development) +* minor #4033 Raise deprecation warnings on usage of deprecated aliases (ntzm) +* minor #4423 DX: update branch alias (keradus) +* minor #4537 SelfStaticAccessor - extend itests (keradus) +* minor #4607 Configure no_superfluous_phpdoc_tags for Symfony (keradus) +* minor #4618 DX: fix usage of deprecated options (0x450x6c) +* minor #4619 Fix PHP 7.3 strict mode warnings (keradus) +* minor #4621 Add single_line_throw to Symfony ruleset (keradus) + +Changelog for v2.15.10 +---------------------- + +* bug #5095 Annotation - fix for Windows line endings (SpacePossum) +* bug #5221 NoSuperfluousPhpdocTagsFixer - fix for single line PHPDoc (kubawerlos) +* bug #5225 TernaryOperatorSpacesFixer - fix for alternative control structures (kubawerlos) +* bug #5235 ArrayIndentationFixer - fix for nested arrays (kubawerlos) +* bug #5248 NoBreakCommentFixer - fix throw detect (SpacePossum) +* bug #5250 SwitchAnalyzer - fix for semicolon after case/default (kubawerlos) +* bug #5253 IO - fix cache info message (SpacePossum) +* bug #5274 TernaryToNullCoalescingFixer - concat precedence fix (SpacePossum) +* feature #5216 Add RuleSets to docs (SpacePossum) +* minor #5226 Applied CS fixes from 2.17-dev (GrahamCampbell) +* minor #5229 Fixed incorrect phpdoc (GrahamCampbell) +* minor #5231 CS: unify styling with younger branches (keradus) +* minor #5232 PHP8 - throw expression support (SpacePossum) +* minor #5233 DX: simplify check_file_permissions.sh (kubawerlos) +* minor #5236 Improve handling of unavailable code samples (julienfalque, keradus) +* minor #5239 PHP8 - Allow trailing comma in parameter list support (SpacePossum) +* minor #5254 PHP8 - mixed type support (SpacePossum) +* minor #5255 Tests: do not skip documentation test (keradus) +* minor #5261 Do not update Composer twice (sanmai) +* minor #5263 PHP8 support (SpacePossum) +* minor #5266 PhpUnitTestCaseStaticMethodCallsFixer - PHPUnit 9.x support (sanmai) +* minor #5267 Improve InstallViaComposerTest (sanmai) +* minor #5276 PHP8 - add NoUnreachableDefaultArgumentValueFixer to risky set (SpacePossum) + +Changelog for v2.15.9 +--------------------- + +* bug #4378 PhpUnitNoExpectationAnnotationFixer - annotation in single line doc comment (kubawerlos) +* bug #4936 HeaderCommentFixer - Fix unexpected removal of regular comments (julienfalque) +* bug #5017 PhpdocTrimConsecutiveBlankLineSeparationFixer - must run after AlignMultilineCommentFixer (kubawerlos) +* bug #5033 VoidReturnFixer - must run after NoSuperfluousPhpdocTagsFixer (kubawerlos) +* bug #5038 HelpCommandTest - toString nested array (SpacePossum) +* bug #5040 LinebreakAfterOpeningTagFixer - do not change code if linebreak already present (kubawerlos) +* bug #5044 StandardizeIncrementFixer - fix handling static properties (kubawerlos) +* bug #5045 BacktickToShellExecFixer - add priority relation to NativeFunctionInvocationFixer and SingleQuoteFixer (kubawerlos) +* bug #5054 PhpdocTypesFixer - fix for multidimensional array (kubawerlos) +* bug #5065 TernaryOperatorSpacesFixer - fix for discovering ":" correctly (kubawerlos) +* bug #5068 Fixed php-cs-fixer crashes on input file syntax error (GrahamCampbell) +* bug #5087 NoAlternativeSyntaxFixer - add support for switch and declare (SpacePossum) +* bug #5105 ClassKeywordRemoveFixer - fix for fully qualified class (kubawerlos) +* bug #5113 TernaryOperatorSpacesFixer - handle goto labels (SpacePossum) +* bug #5124 Fix TernaryToNullCoalescingFixer when dealing with object properties (HypeMC) +* bug #5137 DoctrineAnnotationSpacesFixer - fix for typed properties (kubawerlos) +* bug #5180 Always lint test cases with the stricter process linter (GrahamCampbell) +* bug #5190 PhpUnit*Fixers - Only fix in unit test class scope (SpacePossum) +* bug #5195 YodaStyle - statements in braces should be treated as variables in strict … (SpacePossum) +* bug #5220 NoUnneededFinalMethodFixer - do not fix private constructors (SpacePossum) +* feature #3475 Rework documentation (julienfalque, SpacePossum) +* feature #5166 PHP8 (SpacePossum) +* minor #4878 ArrayIndentationFixer - refactor (julienfalque) +* minor #5031 CI: skip_cleanup: true (keradus) +* minor #5048 Allow composer/semver ^2.0 and ^3.0 (thomasvargiu) +* minor #5050 DX: moving integration test for braces, indentation_type and no_break_comment into right place (kubawerlos) +* minor #5051 DX: move all tests from AutoReview\FixerTest to Test\AbstractFixerTestCase (kubawerlos) +* minor #5053 DX: cleanup FunctionTypehintSpaceFixer (kubawerlos) +* minor #5056 DX: add missing priority test for indentation_type and phpdoc_indent (kubawerlos) +* minor #5077 DX: add missing priority test between NoUnsetCastFixer and BinaryOperatorSpacesFixer (kubawerlos) +* minor #5083 Update composer.json to prevent issue #5030 (mvorisek) +* minor #5088 NoBreakCommentFixer - NoUselessElseFixer - priority test (SpacePossum) +* minor #5100 Fixed invalid PHP 5.6 syntax (GrahamCampbell) +* minor #5106 Symfony's finder already ignores vcs and dot files by default (GrahamCampbell) +* minor #5112 DX: check file permissions (kubawerlos, SpacePossum) +* minor #5122 Show runtime PHP version (kubawerlos) +* minor #5132 Do not allow assignments in if statements (SpacePossum) +* minor #5133 RuleSetTest - Early return for boolean and detect more defaults (SpacePossum) +* minor #5139 revert some unneeded exclusions (SpacePossum) +* minor #5148 Upgrade Xcode (kubawerlos) +* minor #5149 NoUnsetOnPropertyFixer - risky description tweaks (SpacePossum) +* minor #5161 minors (SpacePossum) +* minor #5172 Remove accidentally inserted newlines (GrahamCampbell) +* minor #5173 Fix PHP8 RuleSet inherit (SpacePossum) +* minor #5174 Corrected linting error messages (GrahamCampbell) +* minor #5177 PHP8 (SpacePossum) +* minor #5188 DX: Update sibling debs to version supporting PHP8/PHPUnit9 (keradus) +* minor #5189 Create temporary linting file in system temp dir (keradus) +* minor #5191 MethodArgumentSpaceFixer - support use/import of anonymous functions. (undefinedor) +* minor #5193 DX: add AbstractPhpUnitFixer (kubawerlos) +* minor #5204 DX: cleanup NullableTypeTransformerTest (kubawerlos) +* minor #5207 Add © for logo (keradus) +* minor #5208 DX: cleanup php-cs-fixer entry file (keradus) +* minor #5210 CICD - temporarily disable problematic test (keradus) +* minor #5211 CICD: fix file permissions (keradus) +* minor #5213 DX: move report schemas to dedicated dir (keradus) +* minor #5214 CICD: fix file permissions (keradus) +* minor #5215 CICD: update checkbashisms (keradus) +* minor #5217 CICD: use Composer v2 and drop hirak/prestissimo plugin (keradus) +* minor #5218 DX: .gitignore - add .phpunit.result.cache (keradus) +* minor #5222 Upgrade Xcode (kubawerlos) + +Changelog for v2.15.8 +--------------------- + +* bug #3893 Fix handling /** and */ on the same line as the first and/or last annotation (dmvdbrugge) +* bug #4919 PhpUnitTestAnnotationFixer - fix function starting with "test" and having lowercase letter after (kubawerlos) +* bug #4929 YodaStyleFixer - handling equals empty array (kubawerlos) +* bug #4934 YodaStyleFixer - fix for conditions weird are (kubawerlos) +* bug #4958 OrderedImportsFixer - fix for trailing comma in group (kubawerlos) +* bug #4959 BlankLineBeforeStatementFixer - handle comment case (SpacePossum) +* bug #4962 MethodArgumentSpaceFixer - must run after MethodChainingIndentationFixer (kubawerlos) +* bug #4963 PhpdocToReturnTypeFixer - fix for breaking PHP syntax for type having reserved name (kubawerlos, Slamdunk) +* bug #4978 ArrayIndentationFixer - must run after MethodArgumentSpaceFixer (kubawerlos) +* bug #4994 FinalInternalClassFixer - must run before ProtectedToPrivateFixer (kubawerlos) +* bug #4996 NoEmptyCommentFixer - handle multiline comments (kubawerlos) +* bug #4999 BlankLineBeforeStatementFixer - better comment handling (SpacePossum) +* bug #5009 NoEmptyCommentFixer - better handle comments sequence (kubawerlos) +* bug #5010 SimplifiedNullReturnFixer - must run before VoidReturnFixer (kubawerlos) +* bug #5011 SingleClassElementPerStatementFixer - must run before ClassAttributesSeparationFixer (kubawerlos) +* bug #5012 StrictParamFixer - must run before NativeFunctionInvocationFixer (kubawerlos) +* bug #5029 SingleLineAfterImportsFixer - fix for line after import already added using CRLF (kubawerlos) +* minor #4904 Increase PHPStan level to 8 with strict rules (julienfalque) +* minor #4930 DX: ensure PhpUnitNamespacedFixer handles all classes (kubawerlos) +* minor #4931 DX: add test to ensure each target version in PhpUnitTargetVersion has its set in RuleSet (kubawerlos) +* minor #4932 DX: Travis CI config - fix warnings and infos (kubawerlos) +* minor #4940 Reject empty path (julienfalque) +* minor #4944 Fix grammar (julienfalque) +* minor #4946 Allow "const" option on PHP <7.1 (julienfalque) +* minor #4948 Added describe command to readme (david, 8ctopus) +* minor #4949 Fixed build readme on Windows fails if using Git Bash (Mintty) (8ctopus) +* minor #4954 Config - Trim path (julienfalque) +* minor #4957 DX: Check trailing spaces in project files only (ktomk) +* minor #4961 Assert all project source files are monolithic. (SpacePossum) +* minor #4964 Fix PHPStan baseline (julienfalque) +* minor #4973 DX: test "isRisky" method in fixer tests, not as auto review (kubawerlos) +* minor #4974 Minor: Fix typo (ktomk) +* minor #4975 Revert PHPStan level to 5 (julienfalque) +* minor #4976 Add instructions for PHPStan (julienfalque) +* minor #4980 Introduce new issue templates (julienfalque) +* minor #4981 Prevent error in CTTest::testConstants (for PHP8) (guilliamxavier) +* minor #4982 Remove PHIVE (kubawerlos) +* minor #4985 Fix tests with Symfony 5.1 (julienfalque) +* minor #4987 PhpdocAnnotationWithoutDotFixer - handle unicode characters using mb_* (SpacePossum) +* minor #5008 Enhancement: Social justification applied (gbyrka-fingo) +* minor #5023 Fix issue templates (kubawerlos) +* minor #5024 DX: add missing non-default code samples (kubawerlos) + +Changelog for v2.15.7 +--------------------- + +* bug #4915 Fix handling property PHPDocs with unsupported type (julienfalque) +* minor #4916 Fix AppVeyor build (julienfalque) +* minor #4917 CircleCI - Bump xcode to 11.4 (GrahamCampbell) +* minor #4918 DX: do not fix ".phpt" files by default (kubawerlos) + +Changelog for v2.15.6 +--------------------- + +* bug #3820 Braces - (re)indenting comment issues (SpacePossum) +* bug #3911 PhpdocVarWithoutNameFixer - fix for properties only (dmvdbrugge) +* bug #4601 ClassKeywordRemoveFixer - Fix for namespace (yassine-ah, kubawerlos) +* bug #4630 FullyQualifiedStrictTypesFixer - Ignore partial class names which look like FQCNs (localheinz, SpacePossum) +* bug #4661 ExplicitStringVariableFixer - variables pair if one is already explicit (kubawerlos) +* bug #4675 NonPrintableCharacterFixer - fix for backslash and quotes when changing to escape sequences (kubawerlos) +* bug #4678 TokensAnalyzer::isConstantInvocation - fix for importing multiple classes with single "use" (kubawerlos) +* bug #4682 Fix handling array type declaration in properties (julienfalque) +* bug #4685 Improve Symfony 5 compatibility (keradus) +* bug #4688 TokensAnalyzer::isConstantInvocation - Fix detection for fully qualified return type (julienfalque) +* bug #4689 DeclareStrictTypesFixer - fix for "strict_types" set to "0" (kubawerlos) +* bug #4690 PhpdocVarAnnotationCorrectOrderFixer - fix for multiline `@var` without type (kubawerlos) +* bug #4710 SingleTraitInsertPerStatement - fix formatting for multiline "use" (kubawerlos) +* bug #4711 Ensure that files from "tests" directory in release are autoloaded (kubawerlos) +* bug #4749 TokensAnalyze::isUnaryPredecessorOperator fix for CT::T_ARRAY_INDEX_C… (SpacePossum) +* bug #4759 Add more priority cases (SpacePossum) +* bug #4761 NoSuperfluousElseifFixer - handle single line (SpacePossum) +* bug #4783 NoSuperfluousPhpdocTagsFixer - fix for really big PHPDoc (kubawerlos, mvorisek) +* bug #4787 NoUnneededFinalMethodFixer - Mark as risky (SpacePossum) +* bug #4795 OrderedClassElementsFixer - Fix (SpacePossum) +* bug #4804 TokensAnalyzer::isUnarySuccessorOperator fix for array curly braces (SpacePossum) +* bug #4807 IncrementStyleFixer - handle after ")" (SpacePossum) +* bug #4808 Modernize types casting fixer array curly (SpacePossum) +* bug #4809 Fix "braces" and "method_argument_space" priority (julienfalque) +* bug #4813 BracesFixer - fix invalid code generation on alternative syntax (SpacePossum) +* bug #4823 ReturnAssignmentFixer - repeat fix (SpacePossum) +* bug #4824 NoUnusedImportsFixer - SingleLineAfterImportsFixer - fix priority (SpacePossum) +* bug #4829 YodaStyleFixer - fix precedence for T_MOD_EQUAL and T_COALESCE_EQUAL (SpacePossum) +* bug #4830 TernaryToNullCoalescingFixer - handle yield from (SpacePossum) +* bug #4835 Remove duplicate "function_to_constant" from RuleSet (SpacePossum) +* bug #4840 LineEndingFixer - T_CLOSE_TAG support, StringLineEndingFixer - T_INLI… (SpacePossum) +* bug #4846 FunctionsAnalyzer - better isGlobalFunctionCall detection (SpacePossum) +* bug #4852 Priority issues (SpacePossum) +* bug #4870 HeaderCommentFixer - do not remove class docs (gharlan) +* bug #4871 NoExtraBlankLinesFixer - handle cases on same line (SpacePossum) +* bug #4895 Fix conflict between header_comment and declare_strict_types (BackEndTea, julienfalque) +* bug #4911 PhpdocSeparationFixer - fix regression with lack of next line (keradus) +* feature #4742 FunctionToConstantFixer - get_class($this) support (SpacePossum) +* minor #4377 CommentsAnalyzer - fix for declare before header comment (kubawerlos) +* minor #4636 DX: do not check for PHPDBG when collecting coverage (kubawerlos) +* minor #4644 Docs: add info about "-vv..." (voku) +* minor #4691 Run Travis CI on stable PHP 7.4 (kubawerlos) +* minor #4693 Increase Travis CI Git clone depth (julienfalque) +* minor #4699 LineEndingFixer - handle "\r\r\n" (kubawerlos) +* minor #4703 NoSuperfluousPhpdocTagsFixer,PhpdocAddMissingParamAnnotationFixer - p… (SpacePossum) +* minor #4707 Fix typos (TysonAndre) +* minor #4712 NoBlankLinesAfterPhpdocFixer — Do not strip newline between docblock and use statements (mollierobbert) +* minor #4715 Enhancement: Install ergebnis/composer-normalize via Phive (localheinz) +* minor #4722 Fix Circle CI build (julienfalque) +* minor #4724 DX: Simplify installing PCOV (kubawerlos) +* minor #4736 NoUnusedImportsFixer - do not match variable name as import (SpacePossum) +* minor #4746 NoSuperfluousPhpdocTagsFixer - Remove for typed properties (PHP 7.4) (ruudk) +* minor #4753 Do not apply any text/.git filters to fixtures (mvorisek) +* minor #4757 Test $expected is used before $input (SpacePossum) +* minor #4758 Autoreview the PHPDoc of *Fixer::getPriority based on the priority map (SpacePossum) +* minor #4765 Add test on some return types (SpacePossum) +* minor #4766 Remove false test skip (SpacePossum) +* minor #4767 Remove useless priority comments (kubawerlos) +* minor #4769 DX: add missing priority tests (kubawerlos) +* minor #4772 NoUnneededFinalMethodFixer - update description (kubawerlos) +* minor #4774 DX: simplify Utils::camelCaseToUnderscore (kubawerlos) +* minor #4781 NoUnneededCurlyBracesFixer - handle namespaces (SpacePossum) +* minor #4784 Travis CI - Use multiple keyservers (ktomk) +* minor #4785 Improve static analysis (enumag) +* minor #4788 Configurable fixers code sample (SpacePossum) +* minor #4791 Increase PHPStan level to 3 (julienfalque) +* minor #4797 clean ups (SpacePossum) +* minor #4803 FinalClassFixer - Doctrine\ORM\Mapping as ORM alias should not be required (localheinz) +* minor #4839 2.15 - clean ups (SpacePossum) +* minor #4842 ReturnAssignmentFixer - Support more cases (julienfalque) +* minor #4844 Same requirements for descriptions (SpacePossum) +* minor #4849 Increase PHPStan level to 5 (julienfalque) +* minor #4857 Fixed the unit tests (GrahamCampbell) +* minor #4865 Use latest xcode image (GrahamCampbell) +* minor #4892 CombineNestedDirnameFixer - Add space after comma (julienfalque) +* minor #4898 FixerTest - yield the data in AutoReview (Nyholm) +* minor #4899 Fix exception message format for fabbot.io (SpacePossum) +* minor #4905 Support composer v2 installed.json files (GrahamCampbell) +* minor #4906 CI: use Composer stable release for AppVeyor (kubawerlos) +* minor #4909 DX: HeaderCommentFixer - use non-aliased version of option name in code (keradus) +* minor #4912 CI: Fix AppVeyor integration (keradus) + +Changelog for v2.15.5 +--------------------- + +* bug #4476 FunctionsAnalyzer - add "isTheSameClassCall" for correct verifying of function calls (kubawerlos) +* bug #4641 Add typed properties test to VisibilityRequiredFixerTest (GawainLynch, julienfalque) +* bug #4654 ArrayIndentationFixer - Fix array indentation for multiline values (julienfalque) +* bug #4660 TokensAnalyzer::isConstantInvocation - fix for extending multiple interfaces (kubawerlos) +* bug #4668 TokensAnalyzer::isConstantInvocation - fix for interface method return type (kubawerlos) +* minor #4608 Allow Symfony 5 components (l-vo) +* minor #4622 Disallow PHP 7.4 failures on Travis CI (julienfalque) +* minor #4637 PHP 7.4 integration test (GawainLynch, julienfalque) +* minor #4643 DX: Update .gitattributes and move ci-integration.sh to root of the project (kubawerlos, keradus) +* minor #4645 Check PHP extensions on runtime (kubawerlos) +* minor #4655 Improve docs - README (mvorisek) +* minor #4662 DX: generate headers in README.rst (kubawerlos) +* minor #4669 Enable execution under PHP 7.4 (keradus) +* minor #4671 TravisTest - rewrite tests to allow last supported by tool PHP version to be snapshot (keradus) + +Changelog for v2.15.4 +--------------------- + +* bug #4183 IndentationTypeFixer - fix handling 2 spaces indent (kubawerlos) +* bug #4406 NoSuperfluousElseifFixer - fix invalid escape sequence in character class (remicollet, SpacePossum) +* bug #4416 NoUnusedImports - Fix imports detected as used in namespaces (julienfalque, SpacePossum) +* bug #4518 PhpUnitNoExpectationAnnotationFixer - fix handling expect empty exception message (ktomk) +* bug #4548 HeredocIndentationFixer - remove whitespace in empty lines (gharlan) +* bug #4556 ClassKeywordRemoveFixer - fix for self,static and parent keywords (kubawerlos) +* bug #4572 TokensAnalyzer - handle nested anonymous classes (SpacePossum) +* bug #4573 CombineConsecutiveIssetsFixer - fix stop based on precedence (SpacePossum) +* bug #4577 Fix command exit code on lint error after fixing fix. (SpacePossum) +* bug #4581 FunctionsAnalyzer: fix for comment in type (kubawerlos) +* bug #4586 BracesFixer - handle dynamic static method call (SpacePossum) +* bug #4594 Braces - fix both single line comment styles (SpacePossum) +* bug #4609 PhpdocTypesOrderFixer - Prevent unexpected default value change (laurent35240) +* minor #4458 Add PHPStan (julienfalque) +* minor #4479 IncludeFixer - remove braces when the statement is wrapped in block (kubawerlos) +* minor #4490 Allow running if installed as project specific (ticktackk) +* minor #4517 Verify PCRE pattern before use (ktomk) +* minor #4521 Remove superfluous leading backslash, closes 4520 (ktomk) +* minor #4532 DX: ensure data providers are used (kubawerlos) +* minor #4534 Redo PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus, Slamdunk) +* minor #4536 DX: use PHIVE for dev tools (keradus) +* minor #4538 Docs: update Cookbook (keradus) +* minor #4541 Enhancement: Use default name property to configure command names (localheinz) +* minor #4546 DX: removing unnecessary variable initialization (kubawerlos) +* minor #4549 DX: use ::class whenever possible (keradus, kubawerlos) +* minor #4550 DX: travis_retry for dev-tools install (ktomk, keradus) +* minor #4559 Allow 7.4snapshot to fail due to a bug on it (kubawerlos) +* minor #4563 GitlabReporter - fix report output (mjanser) +* minor #4564 Move readme-update command to Section 3 (iwasherefirst2) +* minor #4566 Update symfony ruleset (gharlan) +* minor #4570 Command::execute() should always return an integer (derrabus) +* minor #4580 Add suport for true/false return type hints. (SpacePossum) +* minor #4584 Increase PHPStan level to 1 (julienfalque) +* minor #4585 Fix deprecation notices (julienfalque) +* minor #4587 Output details - Explain why a file was skipped (SpacePossum) +* minor #4588 Fix STDIN test when path is one level deep (julienfalque) +* minor #4589 PhpdocToReturnType - Add support for Foo[][] (SpacePossum) +* minor #4593 Ensure compatibility with PHP 7.4 typed properties (julienfalque) +* minor #4595 Import cannot be used after `::` so can be removed (SpacePossum) +* minor #4596 Ensure compatibility with PHP 7.4 numeric literal separator (julienfalque) +* minor #4597 Fix PHP 7.4 deprecation notices (julienfalque) +* minor #4600 Ensure compatibility with PHP 7.4 arrow functions (julienfalque) +* minor #4602 Ensure compatibility with PHP 7.4 spread operator in array expression (julienfalque) +* minor #4603 Ensure compatibility with PHP 7.4 null coalescing assignment operator (julienfalque) +* minor #4606 Configure no_superfluous_phpdoc_tags for Symfony (keradus) +* minor #4610 Travis CI - Update known files list (julienfalque) +* minor #4615 Remove workaround for dev-tools install reg. Phive (ktomk) + +Changelog for v2.15.3 +--------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.15.2 +--------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4440 SimpleToComplexStringVariableFixer - Fix $ bug (dmvdbrugge) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.15.1 +--------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4424 DX: cleanup of composer.json - no need for branch-alias (keradus) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) +* minor #4428 DX: update dev-tools (keradus) +* minor #4429 DX: MethodArgumentSpaceFixerTest - fix hidden merge conflict (keradus) + +Changelog for v2.15.0 +--------------------- + +* feature #3927 Add FinalClassFixer (Slamdunk) +* feature #3939 Add PhpUnitSizeClassFixer (Jefersson Nathan) +* feature #3942 SimpleToComplexStringVariableFixer - Introduction (dmvdbrugge, SpacePossum) +* feature #4113 OrderedInterfacesFixer - Introduction (dmvdbrugge) +* feature #4121 SingleTraitInsertPerStatementFixer - Introduction (SpacePossum) +* feature #4126 NativeFunctionTypeDeclarationCasingFixer - Introduction (SpacePossum) +* feature #4167 PhpUnitMockShortWillReturnFixer - Introduction (michadam-pearson) +* feature #4191 [7.3] NoWhitespaceBeforeCommaInArrayFixer - fix comma after heredoc-end (gharlan) +* feature #4288 Add Gitlab Reporter (hco) +* feature #4328 Add PhpUnitDedicateAssertInternalTypeFixer (Slamdunk) +* feature #4341 [7.3] TrailingCommaInMultilineArrayFixer - fix comma after heredoc-end (gharlan) +* feature #4342 [7.3] MethodArgumentSpaceFixer - fix comma after heredoc-end (gharlan) +* minor #4112 NoSuperfluousPhpdocTagsFixer - Add missing code sample, groom tests (keradus, SpacePossum) +* minor #4360 Add gitlab as output format in the README/help doc. (SpacePossum) +* minor #4386 Add PhpUnitMockShortWillReturnFixer to @Symfony:risky rule set (kubawerlos) +* minor #4398 New ruleset "@PHP73Migration" (gharlan) +* minor #4399 Fix 2.15 line (keradus) + +Changelog for v2.14.6 +--------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.14.5 +--------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.14.4 +--------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) +* minor #4428 DX: update dev-tools (keradus) + +Changelog for v2.14.3 +--------------------- + +* bug #4298 NoTrailingWhitespaceInCommentFixer - fix for non-Unix line separators (kubawerlos) +* bug #4303 FullyQualifiedStrictTypesFixer - Fix the short type detection when a question mark (nullable) is prefixing it. (drupol) +* bug #4313 SelfAccessorFixer - fix for part qualified class name (kubawerlos, SpacePossum) +* bug #4314 PhpUnitTestCaseStaticMethodCallsFixer - fix for having property with name as method to update (kubawerlos, SpacePossum) +* bug #4316 NoUnsetCastFixer - Test for higher-precedence operators (SpacePossum) +* bug #4327 TokensAnalyzer - add concat operator to list of binary operators (SpacePossum) +* bug #4335 Cache - add indent and line ending to cache signature (dmvdbrugge) +* bug #4344 VoidReturnFixer - handle yield from (SpacePossum) +* bug #4346 BracesFixer - Do not pull close tag onto same line as a comment (SpacePossum) +* bug #4350 StrictParamFixer - Don't detect functions in use statements (bolmstedt) +* bug #4357 Fix short list syntax detection. (SpacePossum) +* bug #4365 Fix output escaping of diff for text format when line is not changed (SpacePossum) +* bug #4370 PhpUnitConstructFixer - Fix handle different casing (SpacePossum) +* bug #4379 ExplicitStringVariableFixer - add test case for variable as an array key (kubawerlos, Slamdunk) +* feature #4337 PhpUnitTestCaseStaticMethodCallsFixer - prepare for PHPUnit 8 (kubawerlos) +* minor #3799 DX: php_unit_test_case_static_method_calls - use default config (keradus) +* minor #4103 NoExtraBlankLinesFixer - fix candidate detection (SpacePossum) +* minor #4245 LineEndingFixer - BracesFixer - Priority (dmvdbrugge) +* minor #4325 Use lowercase mikey179/vfsStream in composer.json (lolli42) +* minor #4336 Collect coverage with PCOV (kubawerlos) +* minor #4338 Fix wording (kmvan, kubawerlos) +* minor #4339 Change BracesFixer to avoid indenting PHP inline braces (alecgeatches) +* minor #4340 Travis: build against 7.4snapshot instead of nightly (Slamdunk) +* minor #4351 code grooming (SpacePossum) +* minor #4353 Add more priority tests (SpacePossum) +* minor #4364 DX: MethodChainingIndentationFixer - remove unneccesary loop (Sijun Zhu) +* minor #4366 Unset the auxillary variable $a (GrahamCampbell) +* minor #4368 Fixed TypeShortNameResolverTest::testResolver (GrahamCampbell) +* minor #4380 PHP7.4 - Add "str_split" => "mb_str_split" mapping. (SpacePossum) +* minor #4381 PHP7.4 - Add support for magic methods (un)serialize. (SpacePossum) +* minor #4393 DX: add missing explicit return types (kubawerlos) + +Changelog for v2.14.2 +--------------------- + +* minor #4306 DX: Drop HHVM conflict on Composer level to help Composer with HHVM compatibility, we still prevent HHVM on runtime (keradus) + +Changelog for v2.14.1 +--------------------- + +* bug #4240 ModernizeTypesCastingFixer - fix for operators with higher precedence (kubawerlos) +* bug #4254 PhpUnitDedicateAssertFixer - fix for count with additional operations (kubawerlos) +* bug #4260 Psr0Fixer and Psr4Fixer - fix for multiple classes in file with anonymous class (kubawerlos) +* bug #4262 FixCommand - fix help (keradus) +* bug #4276 MethodChainingIndentationFixer, ArrayIndentationFixer - Fix priority issue (dmvdbrugge) +* bug #4280 MethodArgumentSpaceFixer - Fix method argument alignment (Billz95) +* bug #4286 IncrementStyleFixer - fix for static statement (kubawerlos) +* bug #4291 ArrayIndentationFixer - Fix indentation after trailing spaces (julienfalque, keradus) +* bug #4292 NoSuperfluousPhpdocTagsFixer - Make null only type not considered superfluous (julienfalque) +* minor #4204 DX: Tokens - do not unregister/register found tokens when collection is not changing (kubawerlos) +* minor #4235 DX: more specific @param types (kubawerlos) +* minor #4263 DX: AppVeyor - bump PHP version (keradus) +* minor #4293 Add official support for PHP 7.3 (keradus) +* minor #4295 DX: MethodArgumentSpaceFixerTest - fix edge case for handling different line ending when only expected code is provided (keradus) +* minor #4296 DX: cleanup testing with fixer config (keradus) +* minor #4299 NativeFunctionInvocationFixer - add array_key_exists (deguif, keradus) +* minor #4300 DX: cleanup testing with fixer config (keradus) + +Changelog for v2.14.0 +--------------------- + +* bug #4220 NativeFunctionInvocationFixer - namespaced strict to remove backslash (kubawerlos) +* feature #3881 Add PhpdocVarAnnotationCorrectOrderFixer (kubawerlos) +* feature #3915 Add HeredocIndentationFixer (gharlan) +* feature #4002 NoSuperfluousPhpdocTagsFixer - Allow `mixed` in superfluous PHPDoc by configuration (MortalFlesh) +* feature #4030 Add get_required_files and user_error aliases (ntzm) +* feature #4043 NativeFunctionInvocationFixer - add option to remove redundant backslashes (kubawerlos) +* feature #4102 Add NoUnsetCastFixer (SpacePossum) +* minor #4025 Add phpdoc_types_order rule to Symfony's ruleset (carusogabriel) +* minor #4213 [7.3] PHP7.3 integration tests (SpacePossum) +* minor #4233 Add official support for PHP 7.3 (keradus) + +Changelog for v2.13.3 +--------------------- + +* bug #4216 Psr4Fixer - fix for multiple classy elements in file (keradus, kubawerlos) +* bug #4217 Psr0Fixer - class with anonymous class (kubawerlos) +* bug #4219 NativeFunctionCasingFixer - handle T_RETURN_REF (kubawerlos) +* bug #4224 FunctionToConstantFixer - handle T_RETURN_REF (SpacePossum) +* bug #4229 IsNullFixer - fix parenthesis not closed (guilliamxavier) +* minor #4193 [7.3] CombineNestedDirnameFixer - support PHP 7.3 (kubawerlos) +* minor #4198 [7.3] PowToExponentiationFixer - adding to PHP7.3 integration test (kubawerlos) +* minor #4199 [7.3] MethodChainingIndentationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4200 [7.3] ModernizeTypesCastingFixer - support PHP 7.3 (kubawerlos) +* minor #4201 [7.3] MultilineWhitespaceBeforeSemicolonsFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4202 [7.3] ErrorSuppressionFixer - support PHP 7.3 (kubawerlos) +* minor #4205 DX: PhpdocAlignFixer - refactor to use DocBlock (kubawerlos) +* minor #4206 DX: enable multiline_whitespace_before_semicolons (keradus) +* minor #4207 [7.3] RandomApiMigrationFixerTest - tests for 7.3 (SpacePossum) +* minor #4208 [7.3] NativeFunctionCasingFixerTest - tests for 7.3 (SpacePossum) +* minor #4209 [7.3] PhpUnitStrictFixerTest - tests for 7.3 (SpacePossum) +* minor #4210 [7.3] PhpUnitConstructFixer - add test for PHP 7.3 (kubawerlos) +* minor #4211 [7.3] PhpUnitDedicateAssertFixer - support PHP 7.3 (kubawerlos) +* minor #4214 [7.3] NoUnsetOnPropertyFixerTest - tests for 7.3 (SpacePossum) +* minor #4222 [7.3] PhpUnitExpectationFixer - support PHP 7.3 (kubawerlos) +* minor #4223 [7.3] PhpUnitMockFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4230 [7.3] IsNullFixer - fix trailing comma (guilliamxavier) +* minor #4232 DX: remove Utils::splitLines (kubawerlos) +* minor #4234 [7.3] Test that "LITERAL instanceof X" is valid (guilliamxavier) + +Changelog for v2.13.2 +--------------------- + +* bug #3968 SelfAccessorFixer - support FQCN (kubawerlos) +* bug #3974 Psr4Fixer - class with anonymous class (kubawerlos) +* bug #3987 Run HeaderCommentFixer after NoBlankLinesAfterPhpdocFixer (StanAngeloff) +* bug #4009 TypeAlternationTransformer - Fix pipes in function call with constants being classified incorrectly (ntzm, SpacePossum) +* bug #4022 NoUnsetOnPropertyFixer - refactor and bugfixes (kubawerlos) +* bug #4036 ExplicitStringVariableFixer - fixes for backticks and for 2 variables next to each other (kubawerlos, Slamdunk) +* bug #4038 CommentToPhpdocFixer - handling nested PHPDoc (kubawerlos) +* bug #4064 Ignore invalid mode strings, add option to remove the "b" flag. (SpacePossum) +* bug #4071 DX: do not insert Token when calling removeLeadingWhitespace/removeTrailingWhitespace from Tokens (kubawerlos) +* bug #4073 IsNullFixer - fix function detection (kubawerlos) +* bug #4074 FileFilterIterator - do not filter out files that need fixing (SpacePossum) +* bug #4076 EregToPregFixer - fix function detection (kubawerlos) +* bug #4084 MethodChainingIndentation - fix priority with Braces (dmvdbrugge) +* bug #4099 HeaderCommentFixer - throw exception on invalid header configuration (SpacePossum) +* bug #4100 PhpdocAddMissingParamAnnotationFixer - Handle variable number of arguments and pass by reference cases (SpacePossum) +* bug #4101 ReturnAssignmentFixer - do not touch invalid code (SpacePossum) +* bug #4104 Change transformers order, fixing untransformed T_USE (dmvdbrugge) +* bug #4107 Preg::split - fix for non-UTF8 subject (ostrolucky, kubawerlos) +* bug #4109 NoBlankLines*: fix removing lines consisting only of spaces (kubawerlos, keradus) +* bug #4114 VisibilityRequiredFixer - don't remove comments (kubawerlos) +* bug #4116 OrderedImportsFixer - fix sorting without any grouping (SpacePossum) +* bug #4119 PhpUnitNoExpectationAnnotationFixer - fix extracting content from annotation (kubawerlos) +* bug #4127 LowercaseConstantsFixer - Fix case with properties using constants as their name (srathbone) +* bug #4134 [7.3] SquareBraceTransformer - nested array destructuring not handled correctly (SpacePossum) +* bug #4153 PhpUnitFqcnAnnotationFixer - handle only PhpUnit classes (kubawerlos) +* bug #4169 DirConstantFixer - Fixes for PHP7.3 syntax (SpacePossum) +* bug #4181 MultilineCommentOpeningClosingFixer - fix handling empty comment (kubawerlos) +* bug #4186 Tokens - fix removal of leading/trailing whitespace with empty token in collection (kubawerlos) +* minor #3436 Add a handful of integration tests (BackEndTea) +* minor #3774 PhpUnitTestClassRequiresCoversFixer - Remove unneeded loop and use phpunit indicator class (BackEndTea, SpacePossum) +* minor #3778 DX: Throw an exception if FileReader::read fails (ntzm) +* minor #3916 New ruleset "@PhpCsFixer" (gharlan) +* minor #4007 Fixes cookbook for fixers (greeflas) +* minor #4031 Correct FixerOptionBuilder::getOption return type (ntzm) +* minor #4046 Token - Added fast isset() path to token->equals() (staabm) +* minor #4047 Token - inline $other->getPrototype() to speedup equals() (staabm, keradus) +* minor #4048 Tokens - inlined extractTokenKind() call on the hot path (staabm) +* minor #4069 DX: Add dev-tools directory to gitattributes as export-ignore (alexmanno) +* minor #4070 Docs: Add link to a VS Code extension in readme (jakebathman) +* minor #4077 DX: cleanup - NoAliasFunctionsFixer - use FunctionsAnalyzer (kubawerlos) +* minor #4088 Add Travis test with strict types (kubawerlos) +* minor #4091 Adjust misleading sentence in CONTRIBUTING.md (ostrolucky) +* minor #4092 UseTransformer - simplify/optimize (SpacePossum) +* minor #4095 DX: Use ::class (keradus) +* minor #4096 DX: fixing typo (kubawerlos) +* minor #4097 DX: namespace casing (kubawerlos) +* minor #4110 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4115 Changes for upcoming Travis' infra migration (sergeyklay) +* minor #4122 DX: AppVeyor - Update Composer download link (SpacePossum) +* minor #4128 DX: cleanup - AbstractFunctionReferenceFixer - use FunctionsAnalyzer (SpacePossum, kubawerlos) +* minor #4129 Fix: Symfony 4.2 deprecations (kubawerlos) +* minor #4139 DX: Fix CircleCI (kubawerlos) +* minor #4142 [7.3] NoAliasFunctionsFixer - mbregex_encoding' => 'mb_regex_encoding (SpacePossum) +* minor #4143 PhpUnitTestCaseStaticMethodCallsFixer - Add PHPUnit 7.5 new assertions (Slamdunk) +* minor #4149 [7.3] ArgumentsAnalyzer - PHP7.3 support (SpacePossum) +* minor #4161 DX: CI - show packages installed via Composer (keradus) +* minor #4162 DX: Drop symfony/lts (keradus) +* minor #4166 DX: do not use AbstractFunctionReferenceFixer when no need to (kubawerlos) +* minor #4168 DX: FopenFlagsFixer - remove useless proxy method (SpacePossum) +* minor #4171 Fix CircleCI cache (kubawerlos) +* minor #4173 [7.3] PowToExponentiationFixer - add support for PHP7.3 (SpacePossum) +* minor #4175 Fixing typo (kubawerlos) +* minor #4177 CI: Check that tag is matching version of PHP CS Fixer during deployment (keradus) +* minor #4180 Fixing typo (kubawerlos) +* minor #4182 DX: update php-cs-fixer file style (kubawerlos) +* minor #4185 [7.3] ImplodeCallFixer - add tests for PHP7.3 (kubawerlos) +* minor #4187 [7.3] IsNullFixer - support PHP 7.3 (kubawerlos) +* minor #4188 DX: cleanup (keradus) +* minor #4189 Travis - add PHP 7.3 job (keradus) +* minor #4190 Travis CI - fix config (kubawerlos) +* minor #4192 [7.3] MagicMethodCasingFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4194 [7.3] NativeFunctionInvocationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4195 [7.3] SetTypeToCastFixer - support PHP 7.3 (kubawerlos) +* minor #4196 Update website (keradus) +* minor #4197 [7.3] StrictParamFixer - support PHP 7.3 (kubawerlos) + +Changelog for v2.13.1 +--------------------- + +* bug #3977 NoSuperfluousPhpdocTagsFixer - Fix handling of description with variable (julienfalque) +* bug #4027 PhpdocAnnotationWithoutDotFixer - add failing cases (keradus) +* bug #4028 PhpdocNoEmptyReturnFixer - handle single line PHPDoc (kubawerlos) +* bug #4034 PhpUnitTestCaseIndicator - handle anonymous class (kubawerlos) +* bug #4037 NativeFunctionInvocationFixer - fix function detection (kubawerlos) +* feature #4019 PhpdocTypesFixer - allow for configuration (keradus) +* minor #3980 Clarifies allow-risky usage (josephzidell) +* minor #4016 Bump console component due to it's bug (keradus) +* minor #4023 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4049 use parent::offset*() methods when moving items around in insertAt() (staabm) + +Changelog for v2.13.0 +--------------------- + +* feature #3739 Add MagicMethodCasingFixer (SpacePossum) +* feature #3812 Add FopenFlagOrderFixer & FopenFlagsFixer (SpacePossum) +* feature #3826 Add CombineNestedDirnameFixer (gharlan) +* feature #3833 BinaryOperatorSpacesFixer - Add "no space" fix strategy (SpacePossum) +* feature #3841 NoAliasFunctionsFixer - add opt in option for ext-mbstring aliasses (SpacePossum) +* feature #3876 NativeConstantInvocationFixer - add the scope option (stof, keradus) +* feature #3886 Add PhpUnitMethodCasingFixer (Slamdunk) +* feature #3907 Add ImplodeCallFixer (kubawerlos) +* feature #3914 NoUnreachableDefaultArgumentValueFixer - remove `null` for nullable typehints (gharlan, keradus) +* minor #3813 PhpUnitDedicateAssertFixer - fix "sizeOf" same as "count". (SpacePossum) +* minor #3873 Add the native_function_invocation fixer in the Symfony:risky ruleset (stof) +* minor #3979 DX: enable php_unit_method_casing (keradus) + +Changelog for v2.12.12 +---------------------- + +* bug #4533 Revert PHP7.4 - Add "str_split" => "mb_str_split" mapping (keradus) +* minor #4264 DX: AutoReview - ensure Travis handle all needed PHP versions (keradus) +* minor #4524 MethodArgumentSpaceFixerTest - make explicit configuration to prevent fail on configuration change (keradus) + +Changelog for v2.12.11 +---------------------- + +* bug #4132 BlankLineAfterNamespaceFixer - do not remove indent, handle comments (kubawerlos) +* bug #4384 MethodArgumentSpaceFixer - fix for on_multiline:ensure_fully_multiline with trailing comma in function call (kubawerlos) +* bug #4404 FileLintingIterator - fix current value on end/invalid (SpacePossum) +* bug #4421 FunctionTypehintSpaceFixer - Ensure single space between type declaration and parameter (localheinz) +* bug #4436 MethodArgumentSpaceFixer - handle misplaced ) (keradus) +* bug #4439 NoLeadingImportSlashFixer - Add space if needed (SpacePossum) +* bug #4453 Fix preg_match error on 7.4snapshot (kubawerlos) +* bug #4461 IsNullFixer - fix null coalescing operator handling (linniksa) +* bug #4467 ToolInfo - fix access to reference without checking existence (black-silence) +* bug #4472 Fix non-static closure unbinding this on PHP 7.4 (kelunik) +* minor #3726 Use Box 3 to build the PHAR (theofidry, keradus) +* minor #4412 PHP 7.4 - Tests for support (SpacePossum) +* minor #4431 DX: test that default config is not passed in RuleSet (kubawerlos) +* minor #4433 DX: test to ensure @PHPUnitMigration rule sets are correctly defined (kubawerlos) +* minor #4445 DX: static call of markTestSkippedOrFail (kubawerlos) +* minor #4463 Add apostrophe to possessive "team's" (ChandlerSwift) +* minor #4471 ReadmeCommandTest - use CommandTester (kubawerlos) +* minor #4477 DX: control names of public methods in test's classes (kubawerlos) +* minor #4483 NewWithBracesFixer - Fix object operator and curly brace open cases (SpacePossum) +* minor #4484 fix typos in README (Sven Ludwig) +* minor #4494 DX: Fix shell script syntax in order to fix Travis builds (drupol) +* minor #4516 DX: Lock binary SCA tools versions (keradus) + +Changelog for v2.12.10 +---------------------- + +* bug #4418 PhpUnitNamespacedFixer - properly translate classes which do not follow translation pattern (ktomk) +* bug #4419 PhpUnitTestCaseStaticMethodCallsFixer - skip anonymous classes and lambda (SpacePossum) +* bug #4420 MethodArgumentSpaceFixer - PHP7.3 trailing commas in function calls (SpacePossum) +* minor #4345 Travis: PHP 7.4 isn't allowed to fail anymore (Slamdunk) +* minor #4403 LowercaseStaticReferenceFixer - Fix invalid PHP version in example (HypeMC) +* minor #4425 DX: assertions are static, adjust custom assertions (keradus) +* minor #4426 DX: handle deprecations of symfony/event-dispatcher:4.3 (keradus) +* minor #4427 DX: stop using reserved T_FN in code samples (keradus) + +Changelog for v2.12.9 +--------------------- + +* bug #4298 NoTrailingWhitespaceInCommentFixer - fix for non-Unix line separators (kubawerlos) +* bug #4303 FullyQualifiedStrictTypesFixer - Fix the short type detection when a question mark (nullable) is prefixing it. (drupol) +* bug #4313 SelfAccessorFixer - fix for part qualified class name (kubawerlos, SpacePossum) +* bug #4314 PhpUnitTestCaseStaticMethodCallsFixer - fix for having property with name as method to update (kubawerlos, SpacePossum) +* bug #4327 TokensAnalyzer - add concat operator to list of binary operators (SpacePossum) +* bug #4335 Cache - add indent and line ending to cache signature (dmvdbrugge) +* bug #4344 VoidReturnFixer - handle yield from (SpacePossum) +* bug #4346 BracesFixer - Do not pull close tag onto same line as a comment (SpacePossum) +* bug #4350 StrictParamFixer - Don't detect functions in use statements (bolmstedt) +* bug #4357 Fix short list syntax detection. (SpacePossum) +* bug #4365 Fix output escaping of diff for text format when line is not changed (SpacePossum) +* bug #4370 PhpUnitConstructFixer - Fix handle different casing (SpacePossum) +* bug #4379 ExplicitStringVariableFixer - add test case for variable as an array key (kubawerlos, Slamdunk) +* feature #4337 PhpUnitTestCaseStaticMethodCallsFixer - prepare for PHPUnit 8 (kubawerlos) +* minor #3799 DX: php_unit_test_case_static_method_calls - use default config (keradus) +* minor #4103 NoExtraBlankLinesFixer - fix candidate detection (SpacePossum) +* minor #4245 LineEndingFixer - BracesFixer - Priority (dmvdbrugge) +* minor #4325 Use lowercase mikey179/vfsStream in composer.json (lolli42) +* minor #4336 Collect coverage with PCOV (kubawerlos) +* minor #4338 Fix wording (kmvan, kubawerlos) +* minor #4339 Change BracesFixer to avoid indenting PHP inline braces (alecgeatches) +* minor #4340 Travis: build against 7.4snapshot instead of nightly (Slamdunk) +* minor #4351 code grooming (SpacePossum) +* minor #4353 Add more priority tests (SpacePossum) +* minor #4364 DX: MethodChainingIndentationFixer - remove unneccesary loop (Sijun Zhu) +* minor #4366 Unset the auxillary variable $a (GrahamCampbell) +* minor #4368 Fixed TypeShortNameResolverTest::testResolver (GrahamCampbell) +* minor #4380 PHP7.4 - Add "str_split" => "mb_str_split" mapping. (SpacePossum) +* minor #4393 DX: add missing explicit return types (kubawerlos) + +Changelog for v2.12.8 +--------------------- + +* minor #4306 DX: Drop HHVM conflict on Composer level to help Composer with HHVM compatibility, we still prevent HHVM on runtime (keradus) + +Changelog for v2.12.7 +--------------------- + +* bug #4240 ModernizeTypesCastingFixer - fix for operators with higher precedence (kubawerlos) +* bug #4254 PhpUnitDedicateAssertFixer - fix for count with additional operations (kubawerlos) +* bug #4260 Psr0Fixer and Psr4Fixer - fix for multiple classes in file with anonymous class (kubawerlos) +* bug #4262 FixCommand - fix help (keradus) +* bug #4276 MethodChainingIndentationFixer, ArrayIndentationFixer - Fix priority issue (dmvdbrugge) +* bug #4280 MethodArgumentSpaceFixer - Fix method argument alignment (Billz95) +* bug #4286 IncrementStyleFixer - fix for static statement (kubawerlos) +* bug #4291 ArrayIndentationFixer - Fix indentation after trailing spaces (julienfalque, keradus) +* bug #4292 NoSuperfluousPhpdocTagsFixer - Make null only type not considered superfluous (julienfalque) +* minor #4204 DX: Tokens - do not unregister/register found tokens when collection is not changing (kubawerlos) +* minor #4235 DX: more specific @param types (kubawerlos) +* minor #4263 DX: AppVeyor - bump PHP version (keradus) +* minor #4293 Add official support for PHP 7.3 (keradus) +* minor #4295 DX: MethodArgumentSpaceFixerTest - fix edge case for handling different line ending when only expected code is provided (keradus) +* minor #4296 DX: cleanup testing with fixer config (keradus) +* minor #4299 NativeFunctionInvocationFixer - add array_key_exists (deguif, keradus) + +Changelog for v2.12.6 +--------------------- + +* bug #4216 Psr4Fixer - fix for multiple classy elements in file (keradus, kubawerlos) +* bug #4217 Psr0Fixer - class with anonymous class (kubawerlos) +* bug #4219 NativeFunctionCasingFixer - handle T_RETURN_REF (kubawerlos) +* bug #4224 FunctionToConstantFixer - handle T_RETURN_REF (SpacePossum) +* bug #4229 IsNullFixer - fix parenthesis not closed (guilliamxavier) +* minor #4198 [7.3] PowToExponentiationFixer - adding to PHP7.3 integration test (kubawerlos) +* minor #4199 [7.3] MethodChainingIndentationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4200 [7.3] ModernizeTypesCastingFixer - support PHP 7.3 (kubawerlos) +* minor #4201 [7.3] MultilineWhitespaceBeforeSemicolonsFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4202 [7.3] ErrorSuppressionFixer - support PHP 7.3 (kubawerlos) +* minor #4205 DX: PhpdocAlignFixer - refactor to use DocBlock (kubawerlos) +* minor #4206 DX: enable multiline_whitespace_before_semicolons (keradus) +* minor #4207 [7.3] RandomApiMigrationFixerTest - tests for 7.3 (SpacePossum) +* minor #4208 [7.3] NativeFunctionCasingFixerTest - tests for 7.3 (SpacePossum) +* minor #4209 [7.3] PhpUnitStrictFixerTest - tests for 7.3 (SpacePossum) +* minor #4210 [7.3] PhpUnitConstructFixer - add test for PHP 7.3 (kubawerlos) +* minor #4211 [7.3] PhpUnitDedicateAssertFixer - support PHP 7.3 (kubawerlos) +* minor #4214 [7.3] NoUnsetOnPropertyFixerTest - tests for 7.3 (SpacePossum) +* minor #4222 [7.3] PhpUnitExpectationFixer - support PHP 7.3 (kubawerlos) +* minor #4223 [7.3] PhpUnitMockFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4230 [7.3] IsNullFixer - fix trailing comma (guilliamxavier) +* minor #4232 DX: remove Utils::splitLines (kubawerlos) +* minor #4234 [7.3] Test that "LITERAL instanceof X" is valid (guilliamxavier) + +Changelog for v2.12.5 +--------------------- + +* bug #3968 SelfAccessorFixer - support FQCN (kubawerlos) +* bug #3974 Psr4Fixer - class with anonymous class (kubawerlos) +* bug #3987 Run HeaderCommentFixer after NoBlankLinesAfterPhpdocFixer (StanAngeloff) +* bug #4009 TypeAlternationTransformer - Fix pipes in function call with constants being classified incorrectly (ntzm, SpacePossum) +* bug #4022 NoUnsetOnPropertyFixer - refactor and bugfixes (kubawerlos) +* bug #4036 ExplicitStringVariableFixer - fixes for backticks and for 2 variables next to each other (kubawerlos, Slamdunk) +* bug #4038 CommentToPhpdocFixer - handling nested PHPDoc (kubawerlos) +* bug #4071 DX: do not insert Token when calling removeLeadingWhitespace/removeTrailingWhitespace from Tokens (kubawerlos) +* bug #4073 IsNullFixer - fix function detection (kubawerlos) +* bug #4074 FileFilterIterator - do not filter out files that need fixing (SpacePossum) +* bug #4076 EregToPregFixer - fix function detection (kubawerlos) +* bug #4084 MethodChainingIndentation - fix priority with Braces (dmvdbrugge) +* bug #4099 HeaderCommentFixer - throw exception on invalid header configuration (SpacePossum) +* bug #4100 PhpdocAddMissingParamAnnotationFixer - Handle variable number of arguments and pass by reference cases (SpacePossum) +* bug #4101 ReturnAssignmentFixer - do not touch invalid code (SpacePossum) +* bug #4104 Change transformers order, fixing untransformed T_USE (dmvdbrugge) +* bug #4107 Preg::split - fix for non-UTF8 subject (ostrolucky, kubawerlos) +* bug #4109 NoBlankLines*: fix removing lines consisting only of spaces (kubawerlos, keradus) +* bug #4114 VisibilityRequiredFixer - don't remove comments (kubawerlos) +* bug #4116 OrderedImportsFixer - fix sorting without any grouping (SpacePossum) +* bug #4119 PhpUnitNoExpectationAnnotationFixer - fix extracting content from annotation (kubawerlos) +* bug #4127 LowercaseConstantsFixer - Fix case with properties using constants as their name (srathbone) +* bug #4134 [7.3] SquareBraceTransformer - nested array destructuring not handled correctly (SpacePossum) +* bug #4153 PhpUnitFqcnAnnotationFixer - handle only PhpUnit classes (kubawerlos) +* bug #4169 DirConstantFixer - Fixes for PHP7.3 syntax (SpacePossum) +* bug #4181 MultilineCommentOpeningClosingFixer - fix handling empty comment (kubawerlos) +* bug #4186 Tokens - fix removal of leading/trailing whitespace with empty token in collection (kubawerlos) +* minor #3436 Add a handful of integration tests (BackEndTea) +* minor #3774 PhpUnitTestClassRequiresCoversFixer - Remove unneeded loop and use phpunit indicator class (BackEndTea, SpacePossum) +* minor #3778 DX: Throw an exception if FileReader::read fails (ntzm) +* minor #3916 New ruleset "@PhpCsFixer" (gharlan) +* minor #4007 Fixes cookbook for fixers (greeflas) +* minor #4031 Correct FixerOptionBuilder::getOption return type (ntzm) +* minor #4046 Token - Added fast isset() path to token->equals() (staabm) +* minor #4047 Token - inline $other->getPrototype() to speedup equals() (staabm, keradus) +* minor #4048 Tokens - inlined extractTokenKind() call on the hot path (staabm) +* minor #4069 DX: Add dev-tools directory to gitattributes as export-ignore (alexmanno) +* minor #4070 Docs: Add link to a VS Code extension in readme (jakebathman) +* minor #4077 DX: cleanup - NoAliasFunctionsFixer - use FunctionsAnalyzer (kubawerlos) +* minor #4088 Add Travis test with strict types (kubawerlos) +* minor #4091 Adjust misleading sentence in CONTRIBUTING.md (ostrolucky) +* minor #4092 UseTransformer - simplify/optimize (SpacePossum) +* minor #4095 DX: Use ::class (keradus) +* minor #4097 DX: namespace casing (kubawerlos) +* minor #4110 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4115 Changes for upcoming Travis' infra migration (sergeyklay) +* minor #4122 DX: AppVeyor - Update Composer download link (SpacePossum) +* minor #4128 DX: cleanup - AbstractFunctionReferenceFixer - use FunctionsAnalyzer (SpacePossum, kubawerlos) +* minor #4129 Fix: Symfony 4.2 deprecations (kubawerlos) +* minor #4139 DX: Fix CircleCI (kubawerlos) +* minor #4143 PhpUnitTestCaseStaticMethodCallsFixer - Add PHPUnit 7.5 new assertions (Slamdunk) +* minor #4149 [7.3] ArgumentsAnalyzer - PHP7.3 support (SpacePossum) +* minor #4161 DX: CI - show packages installed via Composer (keradus) +* minor #4162 DX: Drop symfony/lts (keradus) +* minor #4166 DX: do not use AbstractFunctionReferenceFixer when no need to (kubawerlos) +* minor #4171 Fix CircleCI cache (kubawerlos) +* minor #4173 [7.3] PowToExponentiationFixer - add support for PHP7.3 (SpacePossum) +* minor #4175 Fixing typo (kubawerlos) +* minor #4177 CI: Check that tag is matching version of PHP CS Fixer during deployment (keradus) +* minor #4182 DX: update php-cs-fixer file style (kubawerlos) +* minor #4187 [7.3] IsNullFixer - support PHP 7.3 (kubawerlos) +* minor #4188 DX: cleanup (keradus) +* minor #4189 Travis - add PHP 7.3 job (keradus) +* minor #4190 Travis CI - fix config (kubawerlos) +* minor #4194 [7.3] NativeFunctionInvocationFixer - add tests for PHP 7.3 (kubawerlos) +* minor #4195 [7.3] SetTypeToCastFixer - support PHP 7.3 (kubawerlos) +* minor #4196 Update website (keradus) +* minor #4197 [7.3] StrictParamFixer - support PHP 7.3 (kubawerlos) + +Changelog for v2.12.4 +--------------------- + +* bug #3977 NoSuperfluousPhpdocTagsFixer - Fix handling of description with variable (julienfalque) +* bug #4027 PhpdocAnnotationWithoutDotFixer - add failing cases (keradus) +* bug #4028 PhpdocNoEmptyReturnFixer - handle single line PHPDoc (kubawerlos) +* bug #4034 PhpUnitTestCaseIndicator - handle anonymous class (kubawerlos) +* bug #4037 NativeFunctionInvocationFixer - fix function detection (kubawerlos) +* feature #4019 PhpdocTypesFixer - allow for configuration (keradus) +* minor #3980 Clarifies allow-risky usage (josephzidell) +* minor #4016 Bump console component due to it's bug (keradus) +* minor #4023 Enhancement: Update localheinz/composer-normalize (localheinz) +* minor #4049 use parent::offset*() methods when moving items around in insertAt() (staabm) + +Changelog for v2.12.3 +--------------------- + +* bug #3867 PhpdocAnnotationWithoutDotFixer - Handle trailing whitespaces (kubawerlos) +* bug #3884 NoSuperfluousPhpdocTagsFixer - handle null in every position (dmvdbrugge, julienfalque) +* bug #3885 AlignMultilineCommentFixer - ArrayIndentationFixer - Priority (dmvdbrugge) +* bug #3887 ArrayIndentFixer - Don't indent empty lines (dmvdbrugge) +* bug #3888 NoExtraBlankLinesFixer - remove blank lines after open tag (kubawerlos) +* bug #3890 StrictParamFixer - make it case-insensitive (kubawerlos) +* bug #3895 FunctionsAnalyzer - false positive for constant and function definition (kubawerlos) +* bug #3908 StrictParamFixer - fix edge case (kubawerlos) +* bug #3910 FunctionsAnalyzer - fix isGlobalFunctionCall (gharlan) +* bug #3912 FullyQualifiedStrictTypesFixer - NoSuperfluousPhpdocTagsFixer - adjust priority (dmvdbrugge) +* bug #3913 TokensAnalyzer - fix isConstantInvocation (gharlan, keradus) +* bug #3921 TypeAnalysis - Fix iterable not being detected as a reserved type (ntzm) +* bug #3924 FullyQualifiedStrictTypesFixer - space bug (dmvdbrugge) +* bug #3937 LowercaseStaticReferenceFixer - Fix "Parent" word in namespace (kubawerlos) +* bug #3944 ExplicitStringVariableFixer - fix array handling (gharlan) +* bug #3951 NoSuperfluousPhpdocTagsFixer - do not call strtolower with null (SpacePossum) +* bug #3954 NoSuperfluousPhpdocTagsFixer - Index invalid or out of range (kubawerlos) +* bug #3957 NoTrailingWhitespaceFixer - trim space after opening tag (kubawerlos) +* minor #3798 DX: enable native_function_invocation (keradus) +* minor #3882 PhpdocAnnotationWithoutDotFixer - Handle empty line in comment (kubawerlos) +* minor #3889 DX: Cleanup - remove unused variables (kubawerlos, SpacePossum) +* minor #3891 PhpdocNoEmptyReturnFixer - account for null[] (dmvdbrugge) +* minor #3892 PhpdocNoEmptyReturnFixer - fix docs (keradus) +* minor #3897 DX: FunctionsAnalyzer - simplifying return expression (kubawerlos) +* minor #3903 DX: cleanup - remove special treatment for PHP <5.6 (kubawerlos) +* minor #3905 DX: Upgrade composer-require-checker to stable version (keradus) +* minor #3919 Simplify single uses of Token::isGivenKind (ntzm) +* minor #3920 Docs: Fix typo (ntzm) +* minor #3940 DX: fix phpdoc parameter type (malukenho) +* minor #3948 DX: cleanup - remove redundant @param annotations (kubawerlos) +* minor #3950 Circle CI v2 yml (siad007) +* minor #3952 DX: AbstractFixerTestCase - drop testing method already provided by trait (keradus) +* minor #3973 Bump xdebug-handler (keradus) + +Changelog for v2.12.2 +--------------------- + +* bug #3823 NativeConstantInvocationFixer - better constant detection (gharlan, SpacePossum, keradus) +* bug #3832 "yield from" as keyword (SpacePossum) +* bug #3835 Fix priority between PHPDoc return type fixers (julienfalque, keradus) +* bug #3839 MethodArgumentSpaceFixer - add empty line incorrectly (SpacePossum) +* bug #3866 SpaceAfterSemicolonFixer - loop over all tokens (SpacePossum) +* minor #3817 Update integrations tests (SpacePossum) +* minor #3829 Fix typos in changelog (mnabialek) +* minor #3848 Add install/update instructions for PHIVE to the README (SpacePossum) +* minor #3877 NamespacesAnalyzer - Optimize performance (stof) +* minor #3878 NativeFunctionInvocationFixer - use the NamespacesAnalyzer to remove duplicated code (stof) + +Changelog for v2.12.1 +--------------------- + +* bug #3808 LowercaseStaticReferenceFixer - Fix constants handling (kubawerlos, keradus) +* bug #3815 NoSuperfluousPhpdocTagsFixer - support array/callable type hints (gharlan) +* minor #3824 DX: Support PHPUnit 7.2 (keradus) +* minor #3825 UX: Provide full diff for code samples (keradus) + +Changelog for v2.12.0 +--------------------- + +* feature #2577 Add LogicalOperatorsFixer (hkdobrev, keradus) +* feature #3060 Add ErrorSuppressionFixer (kubawerlos) +* feature #3127 Add NativeConstantInvocationFixer (Slamdunk, keradus) +* feature #3223 NativeFunctionInvocationFixer - add namespace scope and include sets (SpacePossum) +* feature #3453 PhpdocAlignFixer - add align option (robert.ahmerov) +* feature #3476 Add PhpUnitTestCaseStaticMethodCallsFixer (Slamdunk, keradus) +* feature #3524 MethodArgumentSpaceFixer - Add ensure_single_line option (julienfalque, keradus) +* feature #3534 MultilineWhitespaceBeforeSemicolonsFixer - support static calls (ntzm) +* feature #3585 Add ReturnAssignmentFixer (SpacePossum, keradus) +* feature #3640 Add PhpdocToReturnTypeFixer (Slamdunk, keradus) +* feature #3691 Add PhpdocTrimAfterDescriptionFixer (nobuf, keradus) +* feature #3698 YodaStyleFixer - Add always_move_variable option (julienfalque, SpacePossum) +* feature #3709 Add SetTypeToCastFixer (SpacePossum) +* feature #3724 BlankLineBeforeStatementFixer - Add case and default as options (dmvdbrugge) +* feature #3734 Add NoSuperfluousPhpdocTagsFixer (julienfalque) +* feature #3735 Add LowercaseStaticReferenceFixer (kubawerlos, SpacePossum) +* feature #3737 Add NoUnsetOnPropertyFixer (BackEndTea, SpacePossum) +* feature #3745 Add PhpUnitInternalClassFixer (BackEndTea, SpacePossum, keradus) +* feature #3766 Add NoBinaryStringFixer (ntzm, SpacePossum, keradus) +* feature #3780 ShortScalarCastFixer - Change binary cast to string cast as well (ntzm) +* feature #3785 PhpUnitDedicateAssertFixer - fix to assertCount too (SpacePossum) +* feature #3802 Convert PhpdocTrimAfterDescriptionFixer into PhpdocTrimConsecutiveBlankLineSeparationFixer (keradus) +* minor #3738 ReturnAssignmentFixer description update (kubawerlos) +* minor #3761 Application: when run with FUTURE_MODE, error_reporting(-1) is done in entry file instead (keradus) +* minor #3772 DX: use PhpUnitTestCaseIndicator->isPhpUnitClass to discover PHPUnit classes (keradus) +* minor #3783 CI: Split COLLECT_COVERAGE job (keradus) +* minor #3789 DX: ProjectCodeTest.testThatDataProvidersAreCorrectlyNamed - performance optimization (keradus) +* minor #3791 DX: Fix collecting code coverage (keradus) +* minor #3792 DX: Upgrade DX deps (keradus) +* minor #3797 DX: ProjectCodeTest - shall not depends on xdebug/phpdbg anymore (keradus, SpacePossum) +* minor #3800 Symfony:risky ruleset: include set_type_to_cast rule (keradus) +* minor #3801 NativeFunctionInvocationFixer - fix buggy config validation (keradus, SpacePossum) + +Changelog for v2.11.2 +--------------------- + +* bug #3233 PhpdocAlignFixer - Fix linebreak inconsistency (SpacePossum, keradus) +* bug #3445 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3528 MethodChainingIndentationFixer - nested params bugfix (Slamdunk) +* bug #3547 MultilineWhitespaceBeforeSemicolonsFixer - chained call for a return fix (egircys, keradus) +* bug #3597 DeclareStrictTypesFixer - fix bug of removing line (kubawerlos, keradus) +* bug #3605 DoctrineAnnotationIndentationFixer - Fix indentation with mixed lines (julienfalque) +* bug #3606 PhpdocToCommentFixer - allow multiple ( (SpacePossum) +* bug #3614 Refactor PhpdocToCommentFixer - extract checking to CommentsAnalyzer (kubawerlos) +* bug #3668 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3670 PhpdocTypesOrderFixer - Fix ordering of nested generics (julienfalque) +* bug #3671 ArrayIndentationFixer - Fix indentation in HTML (julienfalque) +* bug #3673 PhpdocScalarFixer - Add "types" option (julienfalque, keradus) +* bug #3674 YodaStyleFixer - Fix variable detection for multidimensional arrays (julienfalque, SpacePossum) +* bug #3684 PhpUnitStrictFixer - Do not fix if not correct # of arguments are used (SpacePossum) +* bug #3708 EspaceImplicitBackslashesFixer - Fix escaping multiple backslashes (julienfalque) +* bug #3715 SingleImportPerStatementFixer - Fix handling whitespace before opening brace (julienfalque) +* bug #3731 PhpdocIndentFixer - crash fix (SpacePossum) +* bug #3755 YodaStyleFixer - handle space between var name and index (SpacePossum) +* bug #3765 Fix binary-prefixed double-quoted strings to single quotes (ntzm) +* bug #3770 Handle binary flags in heredoc_to_nowdoc (ntzm) +* bug #3776 ExplicitStringVariableFixer - handle binary strings (ntzm) +* bug #3777 EscapeImplicitBackslashesFixer - handle binary strings (ntzm) +* bug #3790 ProcessLinter - don't execute external process without timeout! It can freeze! (keradus) +* minor #3188 AppVeyor - add PHP 7.x (keradus, julienfalque) +* minor #3451 Update findPHPUnit functions (BackEndTea, SpacePossum, keradus) +* minor #3548 Make shell scripts POSIX-compatible (EvgenyOrekhov, keradus) +* minor #3568 New Autoreview: Correct option casing (ntzm) +* minor #3578 Add interface for deprecated options (julienfalque, keradus) +* minor #3590 Use XdebugHandler to avoid perormance penalty (AJenbo, keradus) +* minor #3607 PhpdocVarWithoutNameFixer - update sample with @ type (SpacePossum) +* minor #3617 Tests stability patches (Tom Klingenberg, keradus) +* minor #3622 Docs: Update descriptions (localheinz) +* minor #3627 Fix tests execution under phpdbg (keradus) +* minor #3629 ProjectFixerConfigurationTest - test rules are sorted (SpacePossum) +* minor #3639 DX: use benefits of symfony/force-lowest (keradus) +* minor #3641 Update check_trailing_spaces script with upstream (keradus) +* minor #3646 Extract SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3647 DX: Add CachingLinter for tests (keradus) +* minor #3649 Update check_trailing_spaces script with upstream (keradus) +* minor #3652 CiIntegrationTest - run tests with POSIX sh, not Bash (keradus) +* minor #3656 DX: Clean ups (SpacePossum) +* minor #3657 update phpunitgoodpractices/traits (SpacePossum, keradus) +* minor #3658 DX: Clean ups (SpacePossum) +* minor #3660 Fix do not rely on order of fixing in CiIntegrationTest (kubawerlos) +* minor #3661 Fix: covers annotation for NoAlternativeSyntaxFixerTest (kubawerlos) +* minor #3662 DX: Add Smoke/InstallViaComposerTest (keradus) +* minor #3663 DX: During deployment, run all smoke tests and don't allow to skip phar-related ones (keradus) +* minor #3665 CircleCI fix (kubawerlos) +* minor #3666 Use "set -eu" in shell scripts (EvgenyOrekhov) +* minor #3669 Document possible values for subset options (julienfalque, keradus) +* minor #3672 Remove SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3676 RunnerTest - workaround for failing Symfony v2.8.37 (kubawerlos) +* minor #3680 DX: Tokens - removeLeadingWhitespace and removeTrailingWhitespace must act in same way (SpacePossum) +* minor #3686 README.rst - Format all code-like strings in fixer descriptions (ntzm, keradus) +* minor #3692 DX: Optimize tests (julienfalque) +* minor #3700 README.rst - Format all code-like strings in fixer description (ntzm) +* minor #3701 Use correct casing for "PHPDoc" (ntzm) +* minor #3703 DX: InstallViaComposerTest - groom naming (keradus) +* minor #3704 DX: Tokens - fix naming (keradus) +* minor #3706 Update homebrew installation instructions (ntzm) +* minor #3713 Use HTTPS whenever possible (fabpot) +* minor #3723 Extend tests coverage (ntzm) +* minor #3733 Disable Composer optimized autoloader by default (julienfalque) +* minor #3748 PhpUnitStrictFixer - extend risky note (jnvsor) +* minor #3749 Make sure PHPUnit is cased correctly in fixers descriptions (kubawerlos) +* minor #3768 Improve deprecation messages (julienfalque, SpacePossum) +* minor #3773 AbstractFixerWithAliasedOptionsTestCase - don't export (keradus) +* minor #3775 Add tests for binary strings in string_line_ending (ntzm) +* minor #3779 Misc fixes (ntzm, keradus) +* minor #3796 DX: StdinTest - do not assume name of folder, into which project was cloned (keradus) +* minor #3803 NoEmptyPhpdocFixer/PhpdocAddMissingParamAnnotationFixer - missing priority test (SpacePossum, keradus) +* minor #3804 Cleanup: remove useless constructor comment (kubawerlos) +* minor #3805 Cleanup: add missing @param type (kubawerlos, keradus) + +Changelog for v2.11.1 +--------------------- + +* bug #3626 ArrayIndentationFixer: priority bug with BinaryOperatorSpacesFixer and MethodChainingIndentationFixer (Slamdunk) +* bug #3632 DateTimeImmutableFixer bug with adding tokens while iterating over them (kubawerlos) +* minor #3478 PhpUnitDedicateAssertFixer: handle static calls (Slamdunk) +* minor #3618 DateTimeImmutableFixer - grooming (keradus) + +Changelog for v2.11.0 +--------------------- + +* feature #3135 Add ArrayIndentationFixer (julienfalque) +* feature #3235 Implement StandardizeIncrementFixer (ntzm, SpacePossum) +* feature #3260 Add DateTimeImmutableFixer (kubawerlos) +* feature #3276 Transform Fully Qualified parameters and return types to short version (veewee, keradus) +* feature #3299 SingleQuoteFixer - fix single quote char (Slamdunk) +* feature #3340 Verbose LintingException after fixing (Slamdunk) +* feature #3423 FunctionToConstantFixer - add fix "get_called_class" option (SpacePossum) +* feature #3434 Add PhpUnitSetUpTearDownVisibilityFixer (BackEndTea, SpacePossum) +* feature #3442 Add CommentToPhpdocFixer (kubawerlos, keradus) +* feature #3448 OrderedClassElementsFixer - added sortAlgorithm option (meridius) +* feature #3454 Add StringLineEndingFixer (iluuu1994, SpacePossum, keradus, julienfalque) +* feature #3477 PhpUnitStrictFixer: handle static calls (Slamdunk) +* feature #3479 PhpUnitConstructFixer: handle static calls (Slamdunk) +* feature #3507 Add PhpUnitOrderedCoversFixer (Slamdunk) +* feature #3545 Add the 'none' sort algorithm to OrderedImportsFixer (EvgenyOrekhov) +* feature #3588 Add NoAlternativeSyntaxFixer (eddmash, keradus) +* minor #3414 DescribeCommand: add fixer class when verbose (Slamdunk) +* minor #3432 ConfigurationDefinitionFixerInterface - fix deprecation notice (keradus) +* minor #3527 Deprecate last param of Tokens::findBlockEnd (ntzm, keradus) +* minor #3539 Update UnifiedDiffOutputBuilder from gecko-packages/gecko-diff-output-builder usage after it was incorporated into sebastian/diff (keradus) +* minor #3549 DescribeCommand - use our Differ wrapper class, not external one directly (keradus) +* minor #3592 Support PHPUnit 7 (keradus) +* minor #3619 Travis - extend additional files list (keradus) + +Changelog for v2.10.5 +--------------------- + +* bug #3344 Fix method chaining indentation in HTML (julienfalque) +* bug #3594 ElseifFixer - Bug with alternative syntax (kubawerlos) +* bug #3600 StrictParamFixer - Fix issue when functions are imported (ntzm, keradus) +* minor #3589 FixerFactoryTest - add missing test (SpacePossum, keradus) +* minor #3610 make phar extension optional (Tom Klingenberg, keradus) +* minor #3612 Travis - allow for hhvm failures (keradus) +* minor #3615 Detect fabbot.io (julienfalque, keradus) +* minor #3616 FixerFactoryTest - Don't rely on autovivification (keradus) +* minor #3621 FixerFactoryTest - apply CS (keradus) + +Changelog for v2.10.4 +--------------------- + +* bug #3446 Add PregWrapper (kubawerlos) +* bug #3464 IncludeFixer - fix incorrect order of fixing (kubawerlos, SpacePossum) +* bug #3496 Bug in Tokens::removeLeadingWhitespace (kubawerlos, SpacePossum, keradus) +* bug #3557 AbstractDoctrineAnnotationFixer: edge case bugfix (Slamdunk) +* bug #3574 GeneralPhpdocAnnotationRemoveFixer - remove PHPDoc if no content is left (SpacePossum) +* minor #3563 DX add missing covers annotations (keradus) +* minor #3564 Use ::class keyword when possible (keradus) +* minor #3565 Use EventDispatcherInterface instead of EventDispatcher when possible (keradus) +* minor #3566 Update PHPUnitGoodPractices\Traits (keradus) +* minor #3572 DX: allow for more phpunit-speedtrap versions to support more PHPUnit versions (keradus) +* minor #3576 Fix Doctrine Annotation test cases merging (julienfalque) +* minor #3577 DoctrineAnnotationArrayAssignmentFixer - Add test case (julienfalque) + +Changelog for v2.10.3 +--------------------- + +* bug #3504 NoBlankLinesAfterPhpdocFixer - allow blank line before declare statement (julienfalque) +* bug #3522 Remove LOCK_EX (SpacePossum) +* bug #3560 SelfAccessorFixer is risky (Slamdunk) +* minor #3435 Add tests for general_phpdoc_annotation_remove (BackEndTea) +* minor #3484 Create Tokens::findBlockStart (ntzm) +* minor #3512 Add missing array typehints (ntzm) +* minor #3513 Making AppVeyor happy (kubawerlos) +* minor #3516 Use null|type instead of ?type in PHPDocs (ntzm) +* minor #3518 FixerFactoryTest - Test each priority test file is listed as test (SpacePossum) +* minor #3519 Fix typo (SpacePossum) +* minor #3520 Fix typos: ran vs. run (SpacePossum) +* minor #3521 Use HTTPS (carusogabriel) +* minor #3526 Remove gecko dependency (SpacePossum, keradus, julienfalque) +* minor #3531 Backport PHPMD to LTS version to ease maintainability (keradus) +* minor #3532 Implement Tokens::findOppositeBlockEdge (ntzm) +* minor #3533 DX: SCA - drop src/Resources exclusion (keradus) +* minor #3538 Don't use third parameter of Tokens::findBlockStart (ntzm) +* minor #3542 Enhancement: Run composer-normalize on Travis CI (localheinz, keradus) +* minor #3550 AutoReview\FixerFactoryTest - fix missing priority test, mark not fully valid test as incomplete (keradus) +* minor #3555 DX: composer.json - drop branch-alias, branch is already following the version (keradus) +* minor #3556 DX: Add AutoReview/ComposerTest (keradus) +* minor #3559 Don't expose new files under Test namespace (keradus) +* minor #3561 PHPUnit5 - add in place missing compat layer for PHPUnit6 (keradus) + +Changelog for v2.10.2 +--------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.10.1 +--------------------- + +* bug #3265 YodaFixer - fix problems of block statements followed by ternary statements (weareoutman, keradus, SpacePossum) +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3438 PhpUnitTestAnnotationFixer: Do not prepend with test if method is test() (localheinz, SpacePossum) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* bug #3472 YodaStyleFixer - do not un-Yoda if right side is assignment (SpacePossum, keradus) +* bug #3492 PhpdocScalarFixer - Add callback pesudo-type to callable type (carusogabriel) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3430 Fix integration test (SpacePossum) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3443 ConfigurableFixerInterface - not deprecated but TODO (SpacePossum) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.10.0 +--------------------- + +* feature #3290 Add PhpdocOpeningClosingFixer (Slamdunk, keradus) +* feature #3327 Add MultilineWhitespaceBeforeSemicolonsFixer (egircys, keradus) +* feature #3351 PhuUnit: migrate getMock to createPartialMock when arguments count is 2 (Slamdunk) +* feature #3362 Add BacktickToShellExecFixer (Slamdunk) +* minor #3285 PHPUnit - use protective traits (keradus) +* minor #3329 ConfigurationResolver - detect deprecated fixers (keradus, SpacePossum) +* minor #3343 Tokens - improve block end lookup (keradus) +* minor #3360 Adjust Symfony ruleset (keradus) +* minor #3361 no_extra_consecutive_blank_lines - rename to no_extra_blank_lines (with BC layer) (keradus) +* minor #3363 progress-type - name main option value 'dots' (keradus) +* minor #3404 Deprecate "use_yoda_style" in IsNullFixer (kubawerlos, keradus) +* minor #3418 ConfigurableFixerInterface, ConfigurationDefinitionFixerInterface - update deprecations (keradus) +* minor #3419 Dont use deprecated fixer in itest (keradus) + +Changelog for v2.9.3 +-------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.9.2 +-------------------- + +* bug #3265 YodaFixer - fix problems of block statements followed by ternary statements (weareoutman, keradus, SpacePossum) +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3438 PhpUnitTestAnnotationFixer: Do not prepend with test if method is test() (localheinz, SpacePossum) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* bug #3472 YodaStyleFixer - do not un-Yoda if right side is assignment (SpacePossum, keradus) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3430 Fix integration test (SpacePossum) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.9.1 +-------------------- + +* bug #3298 DiffConsoleFormatter - fix output escaping. (SpacePossum) +* bug #3312 PhpUnitTestAnnotationFixer: Only remove prefix if it really is a prefix (localheinz) +* bug #3318 SingleLineCommentStyleFixer - fix closing tag inside comment causes an error (kubawerlos) +* bug #3334 ExplicitStringVariableFixer: handle parsed array and object (Slamdunk) +* bug #3337 BracesFixer: nowdoc bug on template files (Slamdunk) +* bug #3349 Fix stdin handling and add tests for it (keradus) +* bug #3350 PhpUnitNoExpectationAnnotationFixer - fix handling of multiline expectedExceptionMessage annotation (Slamdunk) +* bug #3352 FunctionToConstantFixer - bugfix for get_class with leading backslash (kubawerlos) +* bug #3359 BracesFixer - handle comment for content outside of given block (keradus) +* bug #3371 IsNullFixer must be run before YodaStyleFixer (kubawerlos) +* bug #3373 PhpdocAlignFixer - Fix removing of everything after @ when there is a space after the @ (ntzm) +* bug #3415 FileFilterIterator - input checks and utests (SpacePossum, keradus) +* bug #3420 SingleLineCommentStyleFixer - fix 'strpos() expects parameter 1 to be string, boolean given' (keradus, SpacePossum) +* bug #3428 Fix archive analysing (keradus) +* bug #3429 Fix archive analysing (keradus) +* minor #3137 PHPUnit - use common base class (keradus) +* minor #3311 FinalInternalClassFixer - fix typo (localheinz) +* minor #3328 Remove duplicated space in exceptions (keradus) +* minor #3342 PhpUnitDedicateAssertFixer - Remove unexistent method is_boolean (carusogabriel) +* minor #3345 StdinFileInfo - fix __toString (keradus) +* minor #3346 StdinFileInfo - drop getContents (keradus) +* minor #3347 DX: reapply newest CS (keradus) +* minor #3365 COOKBOOK-FIXERS.md - update to provide definition instead of description (keradus) +* minor #3370 AbstractFixer - FQCN in in exceptions (Slamdunk) +* minor #3372 ProjectCodeTest - fix comment (keradus) +* minor #3393 Method call typos (Slamdunk, keradus) +* minor #3402 Always provide delimiter to `preg_quote` calls (ntzm) +* minor #3403 Remove unused import (ntzm) +* minor #3405 Fix `fopen` mode (ntzm) +* minor #3407 CombineConsecutiveIssetsFixer - Improve description (kubawerlos) +* minor #3408 Improving fixers descriptions (kubawerlos) +* minor #3409 move itests from misc to priority (keradus) +* minor #3411 Better type hinting for AbstractFixerTestCase::$fixer (kubawerlos) +* minor #3412 Convert `strtolower` inside `strpos` to just `stripos` (ntzm) +* minor #3421 DX: Use ::class (keradus) +* minor #3424 AbstractFixerTest: fix expectException arguments (Slamdunk, keradus) +* minor #3425 FixerFactoryTest - test that priority pair fixers have itest (keradus, SpacePossum) +* minor #3427 ConfigurationResolver: fix @return annotation (Slamdunk) + +Changelog for v2.9.0 +-------------------- + +* feature #3063 Method chaining indentation fixer (boliev, julienfalque) +* feature #3076 Add ExplicitStringVariableFixer (Slamdunk, keradus) +* feature #3098 MethodSeparationFixer - add class elements separation options (SpacePossum, keradus) +* feature #3155 Add EscapeImplicitBackslashesFixer (Slamdunk) +* feature #3164 Add ExplicitIndirectVariableFixer (Slamdunk, keradus) +* feature #3183 FinalInternalClassFixer introduction (keradus, SpacePossum) +* feature #3187 StaticLambdaFixer - introduction (SpacePossum, keradus) +* feature #3209 PhpdocAlignFixer - Make @method alignable (ntzm) +* feature #3275 Add PhpUnitTestAnnotationFixer (BackEndTea, keradus) + +Changelog for v2.8.4 +-------------------- + +* bug #3281 SelfAccessorFixer - stop modifying traits (kubawerlos) +* minor #3195 Add self-update command test (julienfalque) +* minor #3287 FileCacheManagerTest - drop duplicated line (keradus) +* minor #3292 PHPUnit - set memory limit (veewee) +* minor #3306 Token - better input validation (keradus) +* minor #3310 Upgrade PHP Coveralls (keradus) + +Changelog for v2.8.3 +-------------------- + +* bug #3173 SimplifiedNullReturnFixer - handle nullable return types (Slamdunk) +* bug #3268 PhpUnitNoExpectationAnnotationFixer - add case with backslashes (keradus, Slamdunk) +* bug #3272 PhpdocTrimFixer - unicode support (SpacePossum) + +Changelog for v2.8.2 +-------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3241 NoExtraConsecutiveBlankLinesFixer - do not crash on ^M LF only (SpacePossum) +* bug #3242 PhpUnitNoExpectationAnnotationFixer - fix ' handling (keradus) +* bug #3243 PhpUnitExpectationFixer - don't create ->expectExceptionMessage(null) (keradus) +* bug #3244 PhpUnitNoExpectationAnnotationFixer - expectation extracted from annotation shall be separated from rest of code with one blank line (keradus) +* bug #3259 PhpUnitNamespacedFixer - fix isCandidate to not rely on class declaration (keradus) +* bug #3261 PhpUnitNamespacedFixer - properly fix next usage of already fixed class (keradus) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3263 NoBreakCommentFixer - Fix handling comment text with PCRE characters (julienfalque) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3249 PhpUnitNoExpectationAnnotationFixerTest - fix hidden conflict (keradus) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) +* minor #3255 IntegrationTest: output exception stack trace (Slamdunk) +* minor #3257 README.rst - Fixed bullet list formatting (moebrowne) + +Changelog for v2.8.1 +-------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3211 Use udiff format in CI (julienfalque) +* minor #3212 Handle rulesets unknown to fabbot.io (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.8.0 +-------------------- + +* feature #3065 Add IncrementStyleFixer (kubawerlos) +* feature #3119 Feature checkstyle reporter (K-Phoen) +* feature #3162 Add udiff as diff format (SpacePossum, keradus) +* feature #3170 Add CompactNullableTypehintFixer (jfcherng) +* feature #3189 Add PHP_CS_FIXER_FUTURE_MODE env (keradus) +* feature #3201 Add PHPUnit Migration rulesets and fixers (keradus) +* minor #3149 AbstractProxyFixer - Support multiple proxied fixers (julienfalque) +* minor #3160 Add DeprecatedFixerInterface (kubawerlos) +* minor #3185 IndentationTypeFixerTest - clean up (SpacePossum, keradus) +* minor #3198 Cleanup: add test that there is no deprecated fixer in rule set (kubawerlos) + +Changelog for v2.7.5 +-------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3241 NoExtraConsecutiveBlankLinesFixer - do not crash on ^M LF only (SpacePossum) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3263 NoBreakCommentFixer - Fix handling comment text with PCRE characters (julienfalque) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) +* minor #3255 IntegrationTest: output exception stack trace (Slamdunk) + +Changelog for v2.7.4 +-------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.7.3 +-------------------- + +* bug #3114 SelfAccessorFixer - Fix type declarations replacement (julienfalque) + +Changelog for v2.7.2 +-------------------- + +* bug #3062 BraceClassInstantiationTransformer - Fix instantiation inside method call braces case (julienfalque, keradus) +* bug #3083 SingleBlankLineBeforeNamespaceFixer - Fix handling namespace right after opening tag (mlocati) +* bug #3109 SwitchCaseSemicolonToColonFixer - Fix bug with nested constructs (SpacePossum) +* bug #3117 Multibyte character in array key makes alignment incorect (kubawerlos) +* bug #3123 Cache - File permissions (SpacePossum) +* bug #3138 NoHomoglyphNamesFixer - fix crash on non-ascii but not mapped either (SpacePossum) +* bug #3172 IndentationTypeFixer - do not touch whitespace that is not indentation (SpacePossum) +* bug #3176 NoMultilineWhitespaceBeforeSemicolonsFixer - SpaceAfterSemicolonFixer - priority fix (SpacePossum) +* bug #3193 TokensAnalyzer::getClassyElements - sort result before returning (SpacePossum) +* bug #3196 SelfUpdateCommand - fix exit status when can't determine newest version (julienfalque) +* minor #3107 ConfigurationResolver - improve error message when rule is not found (SpacePossum) +* minor #3113 Add WordMatcher (keradus) +* minor #3128 README: remove deprecated rule from CLI examples (chteuchteu) +* minor #3133 Unify Reporter tests (keradus) +* minor #3134 Allow Symfony 4 (keradus, garak) +* minor #3136 PHPUnit - call hooks from parent class as well (keradus) +* minor #3141 Unify description of deprecated fixer (kubawerlos) +* minor #3144 PhpUnitDedicateAssertFixer - Sort map and array by function name (localheinz) +* minor #3145 misc - Typo (localheinz) +* minor #3150 Fix CircleCI (julienfalque) +* minor #3151 Update gitattributes to ignore next file (keradus) +* minor #3156 Update php-coveralls (keradus) +* minor #3166 README - add link to new gitter channel. (SpacePossum) +* minor #3174 Update UPGRADE.md (vitek-rostislav) +* minor #3180 Fix usage of static variables (kubawerlos) +* minor #3182 Add support for PHPUnit 6, drop PHPUnit 4 (keradus) +* minor #3184 Code grooming - sort content of arrays (keradus) +* minor #3191 Travis - add nightly build to allow_failures due to Travis issues (keradus) +* minor #3197 DX groom CS (keradus) + +Changelog for v2.7.1 +-------------------- + +* bug #3115 NoUnneededFinalMethodFixer - fix edge case (Slamdunk) + +Changelog for v2.7.0 +-------------------- + +* feature #2573 BinaryOperatorSpaces reworked (SpacePossum, keradus) +* feature #3073 SpaceAfterSemicolonFixer - Add option to remove space in empty for expressions (julienfalque) +* feature #3089 NoAliasFunctionsFixer - add imap aliases (Slamdunk) +* feature #3093 NoUnneededFinalMethodFixer - Remove final keyword from private methods (localheinz, keradus) +* minor #3068 Symfony:risky ruleset - add no_homoglyph_names (keradus) +* minor #3074 [IO] Replace Diff with fork version (SpacePossum) + +Changelog for v2.6.1 +-------------------- + +* bug #3052 Fix false positive warning about paths overridden by provided as command arguments (kubawerlos) +* bug #3053 CombineConsecutiveIssetsFixer - fix priority (SpacePossum) +* bug #3058 IsNullFixer - fix whitespace handling (roukmoute) +* bug #3069 MethodArgumentSpaceFixer - new test case (keradus) +* bug #3072 IsNullFixer - fix non_yoda_style edge case (keradus) +* bug #3088 Drop dedicated Phar stub (keradus) +* bug #3100 NativeFunctionInvocationFixer - Fix test if previous token is already namespace separator (SpacePossum) +* bug #3104 DoctrineAnnotationIndentationFixer - Fix str_repeat() error (julienfalque) +* minor #3038 Support PHP 7.2 (SpacePossum, keradus) +* minor #3064 Fix couple of typos (KKSzymanowski) +* minor #3070 YodaStyleFixer - Clarify configuration parameters (SteveJobzniak) +* minor #3078 ConfigurationResolver - hide context while including config file (keradus) +* minor #3080 Direct function call instead of by string (kubawerlos) +* minor #3085 CiIntegrationTest - skip when no git is available (keradus) +* minor #3087 phar-stub.php - allow PHP 7.2 (keradus) +* minor #3092 .travis.yml - fix matrix for PHP 7.1 (keradus) +* minor #3094 NoUnneededFinalMethodFixer - Add test cases (julienfalque) +* minor #3111 DoctrineAnnotationIndentationFixer - Restore test case (julienfalque) + +Changelog for v2.6.0 +-------------------- + +* bug #3039 YodaStyleFixer - Fix echo case (SpacePossum, keradus) +* feature #2446 Add YodaStyleFixer (SpacePossum) +* feature #2940 Add NoHomoglyphNamesFixer (mcfedr, keradus) +* feature #3012 Add CombineConsecutiveIssetsFixer (SpacePossum) +* minor #3037 Update SF rule set (SpacePossum) + +Changelog for v2.5.1 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3033 Use ::class (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.5.0 +-------------------- + +* feature #2770 DoctrineAnnotationSpaces - split assignments options (julienfalque) +* feature #2843 Add estimating-max progress output type (julienfalque) +* feature #2885 Add NoSuperfluousElseifFixer (julienfalque) +* feature #2929 Add NoUnneededCurlyBracesFixer (SpacePossum) +* feature #2944 FunctionToConstantFixer - handle get_class() -> __CLASS__ as well (SpacePossum) +* feature #2953 BlankLineBeforeStatementFixer - Add more statements (localheinz, keradus) +* feature #2972 Add NoUnneededFinalMethodFixer (Slamdunk, keradus) +* feature #2992 Add Doctrine Annotation ruleset (julienfalque) +* minor #2926 Token::getNameForId (SpacePossum) + +Changelog for v2.4.2 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3033 Use ::class (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.4.1 +-------------------- + +* bug #2925 Improve CI integration suggestion (julienfalque) +* bug #2928 TokensAnalyzer::getClassyElements - Anonymous class support (SpacePossum) +* bug #2931 Psr0Fixer, Psr4Fixer - ignore "new class" syntax (dg, keradus) +* bug #2934 Config - fix handling rule without value (keradus, SpacePossum) +* bug #2939 NoUnusedImportsFixer - Fix extra blank line (julienfalque) +* bug #2941 PHP 7.2 - Group imports with trailing comma support (SpacePossum, julienfalque) +* bug #2954 NoBreakCommentFixer - Disable case sensitivity (julienfalque) +* bug #2959 MethodArgumentSpaceFixer - Skip body of fixed function (greg0ire) +* bug #2984 AlignMultilineCommentFixer - handle uni code (SpacePossum) +* bug #2987 Fix incorrect indentation of comments in `braces` fixer (rob006) +* minor #2924 Add missing Token deprecations (julienfalque) +* minor #2927 WhiteSpaceConfig - update message copy and more strict tests (SpacePossum, keradus) +* minor #2930 Trigger website build (keradus) +* minor #2932 Integrate CircleCI (keradus, aidantwoods) +* minor #2933 ProcessLinterTest - Ensure Windows test only runs on Windows, add a Mac test execution (aidantwoods) +* minor #2935 special handling of fabbot.io service if it's using too old PHP CS Fixer version (keradus) +* minor #2937 Travis: execute 5.3 job on precise (keradus) +* minor #2938 Tests fix configuration of project (SpacePossum, keradus) +* minor #2943 FunctionToConstantFixer - test with diff. arguments than fixable (SpacePossum) +* minor #2945 BlankLineBeforeStatementFixerTest - Fix covered class (julienfalque) +* minor #2946 Detect extra old installations (keradus) +* minor #2947 Test suggested CI integration (keradus) +* minor #2951 AccessibleObject - remove most of usage (keradus) +* minor #2952 BlankLineBeforeStatementFixer - Reference fixer instead of test class (localheinz) +* minor #2955 Travis - stop using old TASK_SCA residue (keradus) +* minor #2968 AssertTokensTrait - don't use AccessibleObject (keradus) +* minor #2969 Shrink down AccessibleObject usage (keradus) +* minor #2982 TrailingCommaInMultilineArrayFixer - simplify isMultilineArray condition (TomasVotruba) +* minor #2989 CiIntegrationTest - fix min supported PHP versions (keradus) + +Changelog for v2.4.0 +-------------------- + +* bug #2880 NoBreakCommentFixer - fix edge case (julienfalque) +* bug #2900 VoidReturnFixer - handle functions containing anonymous functions/classes (bendavies, keradus) +* bug #2902 Fix test classes constructor (julienfalque) +* feature #2384 Add BlankLineBeforeStatementFixer (localheinz, keradus, SpacePossum) +* feature #2440 MethodArgumentSpaceFixer - add ensure_fully_multiline option (greg0ire) +* feature #2649 PhpdocAlignFixer - make fixer configurable (ntzm) +* feature #2664 Add DoctrineAnnotationArrayAssignmentFixer (julienfalque) +* feature #2667 Add NoBreakCommentFixer (julienfalque) +* feature #2684 BracesFixer - new options for braces position after control structures and anonymous constructs (aidantwoods, keradus) +* feature #2701 NoExtraConsecutiveBlankLinesFixer - Add more configuration options related to switch statements (SpacePossum) +* feature #2740 Add VoidReturnFixer (mrmark) +* feature #2765 DoctrineAnnotationIndentationFixer - add option to indent mixed lines (julienfalque) +* feature #2815 NonPrintableCharacterFixer - Add option to replace with escape sequences (julienfalque, keradus) +* feature #2822 Add NoNullPropertyInitializationFixer (ntzm, julienfalque, SpacePossum) +* feature #2825 Add PhpdocTypesOrderFixer (julienfalque, keradus) +* feature #2856 CastSpacesFixer - add space option (kubawerlos, keradus) +* feature #2857 Add AlignMultilineCommentFixer (Slamdunk, keradus) +* feature #2866 Add SingleLineCommentStyleFixer, deprecate HashToSlashCommentFixer (Slamdunk, keradus) +* minor #2773 Travis - use stages (keradus) +* minor #2794 Drop HHVM support (keradus, julienfalque) +* minor #2801 ProjectCodeTest - Fix typo in deprecation message (SpacePossum) +* minor #2818 Token become immutable, performance optimizations (keradus) +* minor #2877 Fix PHPMD report (julienfalque) +* minor #2894 NonPrintableCharacterFixer - fix handling required PHP version on PHPUnit 4.x (keradus) +* minor #2921 InvalidForEnvFixerConfigurationException - fix handling in tests on 2.4 line (keradus) + +Changelog for v2.3.3 +-------------------- + +* bug #2807 NoUselessElseFixer - Fix detection of conditional block (SpacePossum) +* bug #2809 Phar release - fix readme generation (SpacePossum, keradus) +* bug #2827 MethodArgumentSpaceFixer - Always remove trailing spaces (julienfalque) +* bug #2835 SelfAcessorFixer - class property fix (mnabialek) +* bug #2848 PhpdocIndentFixer - fix edge case with inline phpdoc (keradus) +* bug #2849 BracesFixer - Fix indentation issues with comments (julienfalque) +* bug #2851 Tokens - ensureWhitespaceAtIndex (GrahamCampbell, SpacePossum) +* bug #2854 NoLeadingImportSlashFixer - Removing leading slash from import even when in global space (kubawerlos) +* bug #2858 Support generic types (keradus) +* bug #2869 Fix handling required configuration (keradus) +* bug #2881 NoUnusedImportsFixer - Bug when trying to insert empty token (GrahamCampbell, keradus) +* bug #2882 DocBlock\Annotation - Fix parsing of collections with multiple key types (julienfalque) +* bug #2886 NoSpacesInsideParenthesisFixer - Do not remove whitespace if next token is comment (SpacePossum) +* bug #2888 SingleImportPerStatementFixer - Add support for function and const (SpacePossum) +* bug #2901 Add missing files to archive files (keradus) +* bug #2914 HeredocToNowdocFixer - works with CRLF line ending (dg) +* bug #2920 RuleSet - Update deprecated configuration of fixers (SpacePossum, keradus) +* minor #1531 Update docs for few generic types (keradus) +* minor #2793 COOKBOOK-FIXERS.md - update to current version, fix links (keradus) +* minor #2812 ProcessLinter - compatibility with Symfony 3.3 (keradus) +* minor #2816 Tokenizer - better docs and validation (keradus) +* minor #2817 Tokenizer - use future-compatible interface (keradus) +* minor #2819 Fix benchmark (keradus) +* minor #2820 MagicConstantCasingFixer - Remove defined check (SpacePossum) +* minor #2823 Tokenizer - use future-compatible interface (keradus) +* minor #2824 code grooming (keradus) +* minor #2826 Exceptions - provide utests (localheinz) +* minor #2828 Enhancement: Reference phpunit.xsd from phpunit.xml.dist (localheinz) +* minor #2830 Differs - add tests (localheinz) +* minor #2832 Fix: Use all the columns (localheinz) +* minor #2833 Doctrine\Annotation\Token - provide utests (localheinz) +* minor #2839 Use PHP 7.2 polyfill instead of xml one (keradus) +* minor #2842 Move null to first position in PHPDoc types (julienfalque) +* minor #2850 ReadmeCommandTest - Prevent diff output (julienfalque) +* minor #2859 Fixed typo and dead code removal (GrahamCampbell) +* minor #2863 FileSpecificCodeSample - add tests (localheinz) +* minor #2864 WhitespacesAwareFixerInterface clean up (Slamdunk) +* minor #2865 AutoReview\FixerTest - test configuration samples (SpacePossum, keradus) +* minor #2867 VersionSpecification - Fix copy-paste typo (SpacePossum) +* minor #2870 Tokens - ensureWhitespaceAtIndex - Clear tokens before compare. (SpacePossum) +* minor #2874 LineTest - fix typo (keradus) +* minor #2875 HelpCommand - recursive layout fix (SpacePossum) +* minor #2883 DescribeCommand - Show which sample uses the default configuration (SpacePossum) +* minor #2887 Housekeeping - Strict whitespace checks (SpacePossum) +* minor #2895 ProjectCodeTest - check that classes in no-tests exception exist (keradus) +* minor #2896 Move testing related classes from src to tests (keradus) +* minor #2904 Reapply CS (keradus) +* minor #2910 PhpdocAnnotationWithoutDotFixer - Restrict lowercasing (oschwald) +* minor #2913 Tests - tweaks (SpacePossum, keradus) +* minor #2916 FixerFactory - drop return in sortFixers(), never used (TomasVotruba) + +Changelog for v2.3.2 +-------------------- + +* bug #2682 DoctrineAnnotationIndentationFixer - fix handling nested annotations (edhgoose, julienfalque) +* bug #2700 Fix Doctrine Annotation end detection (julienfalque) +* bug #2715 OrderedImportsFixer - handle indented groups (pilgerone) +* bug #2732 HeaderCommentFixer - fix handling blank lines (s7b4) +* bug #2745 Fix Doctrine Annotation newlines (julienfalque) +* bug #2752 FixCommand - fix typo in warning message (mnapoli) +* bug #2757 GeckoPHPUnit is not dev dependency (keradus) +* bug #2759 Update gitattributes (SpacePossum) +* bug #2763 Fix describe command with PSR-0 fixer (julienfalque) +* bug #2768 Tokens::ensureWhitespaceAtIndex - clean up comment check, add check for T_OPEN (SpacePossum) +* bug #2783 Tokens::ensureWhitespaceAtIndex - Fix handling line endings (SpacePossum) +* minor #2304 DX: use PHPMD (keradus) +* minor #2663 Use colors for keywords in commands output (julienfalque, keradus) +* minor #2706 Update README (SpacePossum) +* minor #2714 README.rst - fix wrong value in example (mleko) +* minor #2718 Remove old Symfony exception message expectation (julienfalque) +* minor #2721 Update phpstorm article link to a fresh blog post (valeryan) +* minor #2725 Use method chaining for configuration definitions (julienfalque) +* minor #2727 PHPUnit - use speedtrap (keradus) +* minor #2728 SelfUpdateCommand - verify that it's possible to replace current file (keradus) +* minor #2729 DescribeCommand - add decorated output test (julienfalque) +* minor #2731 BracesFixer - properly pass config in utest dataProvider (keradus) +* minor #2738 Upgrade tests to use new, namespaced PHPUnit TestCase class (keradus) +* minor #2742 Code cleanup (GrahamCampbell, keradus) +* minor #2743 Fixing example and description for GeneralPhpdocAnnotationRemoveFixer (kubawerlos) +* minor #2744 AbstractDoctrineAnnotationFixerTestCase - split fixers test cases (julienfalque) +* minor #2755 Fix compatibility with PHPUnit 5.4.x (keradus) +* minor #2758 Readme - improve CI integration guidelines (keradus) +* minor #2769 Psr0Fixer - remove duplicated example (julienfalque) +* minor #2774 AssertTokens Trait (keradus) +* minor #2775 NoExtraConsecutiveBlankLinesFixer - remove duplicate code sample. (SpacePossum) +* minor #2778 AutoReview - watch that code samples are unique (keradus) +* minor #2787 Add warnings about missing dom ext and require json ext (keradus) +* minor #2792 Use composer-require-checker (keradus) +* minor #2796 Update .gitattributes (SpacePossum) +* minor #2797 Update .gitattributes (SpacePossum) +* minor #2800 PhpdocTypesFixerTest - Fix typo in covers annotation (SpacePossum) + +Changelog for v2.3.1 +-------------------- + +Port of v2.2.3. + +* bug #2724 Revert #2554 Add short diff. output format (keradus) + +Changelog for v2.3.0 +-------------------- + +* feature #2450 Add ListSyntaxFixer (SpacePossum) +* feature #2708 Add PhpUnitTestClassRequiresCoversFixer (keradus) +* minor #2568 Require PHP 5.6+ (keradus) +* minor #2672 Bump symfony/* deps (keradus) + +Changelog for v2.2.20 +--------------------- + +* bug #3233 PhpdocAlignFixer - Fix linebreak inconsistency (SpacePossum, keradus) +* bug #3445 Rewrite NoUnusedImportsFixer (kubawerlos, julienfalque) +* bug #3597 DeclareStrictTypesFixer - fix bug of removing line (kubawerlos, keradus) +* bug #3605 DoctrineAnnotationIndentationFixer - Fix indentation with mixed lines (julienfalque) +* bug #3606 PhpdocToCommentFixer - allow multiple ( (SpacePossum) +* bug #3684 PhpUnitStrictFixer - Do not fix if not correct # of arguments are used (SpacePossum) +* bug #3715 SingleImportPerStatementFixer - Fix handling whitespace before opening brace (julienfalque) +* bug #3731 PhpdocIndentFixer - crash fix (SpacePossum) +* bug #3765 Fix binary-prefixed double-quoted strings to single quotes (ntzm) +* bug #3770 Handle binary flags in heredoc_to_nowdoc (ntzm) +* bug #3790 ProcessLinter - don't execute external process without timeout! It can freeze! (keradus) +* minor #3548 Make shell scripts POSIX-compatible (EvgenyOrekhov, keradus) +* minor #3568 New Autoreview: Correct option casing (ntzm) +* minor #3590 Use XdebugHandler to avoid performance penalty (AJenbo, keradus) +* minor #3607 PhpdocVarWithoutNameFixer - update sample with @ type (SpacePossum) +* minor #3617 Tests stability patches (Tom Klingenberg, keradus) +* minor #3627 Fix tests execution under phpdbg (keradus) +* minor #3629 ProjectFixerConfigurationTest - test rules are sorted (SpacePossum) +* minor #3639 DX: use benefits of symfony/force-lowest (keradus) +* minor #3641 Update check_trailing_spaces script with upstream (keradus) +* minor #3646 Extract SameStringsConstraint and XmlMatchesXsdConstraint (keradus) +* minor #3647 DX: Add CachingLinter for tests (keradus) +* minor #3649 Update check_trailing_spaces script with upstream (keradus) +* minor #3652 CiIntegrationTest - run tests with POSIX sh, not Bash (keradus) +* minor #3656 DX: Clean ups (SpacePossum) +* minor #3660 Fix do not rely on order of fixing in CiIntegrationTest (kubawerlos) +* minor #3662 DX: Add Smoke/InstallViaComposerTest (keradus) +* minor #3663 DX: During deployment, run all smoke tests and don't allow to skip phar-related ones (keradus) +* minor #3665 CircleCI fix (kubawerlos) +* minor #3666 Use "set -eu" in shell scripts (EvgenyOrekhov) +* minor #3669 Document possible values for subset options (julienfalque, keradus) +* minor #3676 RunnerTest - workaround for failing Symfony v2.8.37 (kubawerlos) +* minor #3680 DX: Tokens - removeLeadingWhitespace and removeTrailingWhitespace must act in same way (SpacePossum) +* minor #3686 README.rst - Format all code-like strings in fixer descriptions (ntzm, keradus) +* minor #3692 DX: Optimize tests (julienfalque) +* minor #3701 Use correct casing for "PHPDoc" (ntzm) +* minor #3703 DX: InstallViaComposerTets - groom naming (keradus) +* minor #3704 DX: Tokens - fix naming (keradus) +* minor #3706 Update homebrew installation instructions (ntzm) +* minor #3713 Use HTTPS whenever possible (fabpot) +* minor #3723 Extend tests coverage (ntzm) +* minor #3733 Disable Composer optimized autoloader by default (julienfalque) +* minor #3748 PhpUnitStrictFixer - extend risky note (jnvsor) +* minor #3749 Make sure PHPUnit is cased correctly in fixers descriptions (kubawerlos) +* minor #3773 AbstractFixerWithAliasedOptionsTestCase - don't export (keradus) +* minor #3796 DX: StdinTest - do not assume name of folder, into which project was cloned (keradus) +* minor #3803 NoEmptyPhpdocFixer/PhpdocAddMissingParamAnnotationFixer - missing priority test (SpacePossum, keradus) +* minor #3804 Cleanup: remove useless constructor comment (kubawerlos) + +Changelog for v2.2.19 +--------------------- + +* bug #3594 ElseifFixer - Bug with alternative syntax (kubawerlos) +* bug #3600 StrictParamFixer - Fix issue when functions are imported (ntzm, keradus) +* minor #3589 FixerFactoryTest - add missing test (SpacePossum, keradus) +* minor #3610 make phar extension optional (Tom Klingenberg, keradus) +* minor #3612 Travis - allow for hhvm failures (keradus) +* minor #3615 Detect fabbot.io (julienfalque, keradus) +* minor #3616 FixerFactoryTest - Don't rely on autovivification (keradus) + +Changelog for v2.2.18 +--------------------- + +* bug #3446 Add PregWrapper (kubawerlos) +* bug #3464 IncludeFixer - fix incorrect order of fixing (kubawerlos, SpacePossum) +* bug #3496 Bug in Tokens::removeLeadingWhitespace (kubawerlos, SpacePossum, keradus) +* bug #3557 AbstractDoctrineAnnotationFixer: edge case bugfix (Slamdunk) +* bug #3574 GeneralPhpdocAnnotationRemoveFixer - remove PHPDoc if no content is left (SpacePossum) +* minor #3563 DX add missing covers annotations (keradus) +* minor #3565 Use EventDispatcherInterface instead of EventDispatcher when possible (keradus) +* minor #3572 DX: allow for more phpunit-speedtrap versions to support more PHPUnit versions (keradus) +* minor #3576 Fix Doctrine Annotation test cases merging (julienfalque) + +Changelog for v2.2.17 +--------------------- + +* bug #3504 NoBlankLinesAfterPhpdocFixer - allow blank line before declare statement (julienfalque) +* bug #3522 Remove LOCK_EX (SpacePossum) +* bug #3560 SelfAccessorFixer is risky (Slamdunk) +* minor #3435 Add tests for general_phpdoc_annotation_remove (BackEndTea) +* minor #3484 Create Tokens::findBlockStart (ntzm) +* minor #3512 Add missing array typehints (ntzm) +* minor #3516 Use null|type instead of ?type in PHPDocs (ntzm) +* minor #3518 FixerFactoryTest - Test each priority test file is listed as test (SpacePossum) +* minor #3520 Fix typos: ran vs. run (SpacePossum) +* minor #3521 Use HTTPS (carusogabriel) +* minor #3526 Remove gecko dependency (SpacePossum, keradus, julienfalque) +* minor #3531 Backport PHPMD to LTS version to ease maintainability (keradus) +* minor #3532 Implement Tokens::findOppositeBlockEdge (ntzm) +* minor #3533 DX: SCA - drop src/Resources exclusion (keradus) +* minor #3538 Don't use third parameter of Tokens::findBlockStart (ntzm) +* minor #3542 Enhancement: Run composer-normalize on Travis CI (localheinz, keradus) +* minor #3555 DX: composer.json - drop branch-alias, branch is already following the version (keradus) +* minor #3556 DX: Add AutoReview/ComposerTest (keradus) +* minor #3559 Don't expose new files under Test namespace (keradus) + +Changelog for v2.2.16 +--------------------- + +* bug #3502 Fix missing file in export (keradus) + +Changelog for v2.2.15 +--------------------- + +* bug #3367 NoUnusedImportsFixer - fix comment handling (SpacePossum, keradus) +* bug #3455 NoEmptyCommentFixer - comment block detection for line ending different than LF (kubawerlos, SpacePossum) +* bug #3458 SilencedDeprecationErrorFixer - fix edge cases (kubawerlos) +* bug #3466 no_whitespace_in_blank_line and no_blank_lines_after_phpdoc fixers bug (kubawerlos, keradus) +* minor #3354 Added missing types to the PhpdocTypesFixer (GrahamCampbell) +* minor #3406 Fix for escaping in README (kubawerlos) +* minor #3431 Add missing tests (SpacePossum) +* minor #3440 Add a handful of integration tests (BackEndTea) +* minor #3444 IntegrationTest - ensure tests in priority dir are priority tests indeed (keradus) +* minor #3494 Add missing PHPDoc param type (ntzm) +* minor #3495 Swap @var type and element (ntzm) +* minor #3498 NoUnusedImportsFixer - fix deprecation (keradus) + +Changelog for v2.2.14 +--------------------- + +* bug #3298 DiffConsoleFormatter - fix output escaping. (SpacePossum) +* bug #3337 BracesFixer: nowdoc bug on template files (Slamdunk) +* bug #3349 Fix stdin handling and add tests for it (keradus) +* bug #3359 BracesFixer - handle comment for content outside of given block (keradus) +* bug #3415 FileFilterIterator - input checks and utests (SpacePossum, keradus) +* bug #3429 Fix archive analysing (keradus) +* minor #3137 PHPUnit - use common base class (keradus) +* minor #3342 PhpUnitDedicateAssertFixer - Remove unexistent method is_boolean (carusogabriel) +* minor #3345 StdinFileInfo - fix `__toString` (keradus) +* minor #3346 StdinFileInfo - drop getContents (keradus) +* minor #3347 DX: reapply newest CS (keradus) +* minor #3365 COOKBOOK-FIXERS.md - update to provide definition instead of description (keradus) +* minor #3370 AbstractFixer - FQCN in in exceptions (Slamdunk) +* minor #3372 ProjectCodeTest - fix comment (keradus) +* minor #3402 Always provide delimiter to `preg_quote` calls (ntzm) +* minor #3403 Remove unused import (ntzm) +* minor #3405 Fix `fopen` mode (ntzm) +* minor #3408 Improving fixers descriptions (kubawerlos) +* minor #3409 move itests from misc to priority (keradus) +* minor #3411 Better type hinting for AbstractFixerTestCase::$fixer (kubawerlos) +* minor #3412 Convert `strtolower` inside `strpos` to just `stripos` (ntzm) +* minor #3425 FixerFactoryTest - test that priority pair fixers have itest (keradus, SpacePossum) +* minor #3427 ConfigurationResolver: fix @return annotation (Slamdunk) + +Changelog for v2.2.13 +--------------------- + +* bug #3281 SelfAccessorFixer - stop modifying traits (kubawerlos) +* minor #3195 Add self-update command test (julienfalque) +* minor #3292 PHPUnit - set memory limit (veewee) +* minor #3306 Token - better input validation (keradus) + +Changelog for v2.2.12 +--------------------- + +* bug #3173 SimplifiedNullReturnFixer - handle nullable return types (Slamdunk) +* bug #3272 PhpdocTrimFixer - unicode support (SpacePossum) + +Changelog for v2.2.11 +--------------------- + +* bug #3225 PhpdocTrimFixer - Fix handling of lines without leading asterisk (julienfalque) +* bug #3262 ToolInfo - support installation by branch as well (keradus) +* bug #3266 PhpUnitConstructFixer - multiple asserts bug (kubawerlos) +* minor #3239 Improve contributing guide and issue template (julienfalque) +* minor #3246 Make ToolInfo methods non-static (julienfalque) +* minor #3250 Travis: fail early, spare resources, save the Earth (Slamdunk, keradus) +* minor #3251 Create Title for config file docs section (IanEdington) +* minor #3254 AutoReview/FixerFactoryTest::testFixersPriority: verbose assertion message (Slamdunk) + +Changelog for v2.2.10 +--------------------- + +* bug #3199 TokensAnalyzer - getClassyElements (SpacePossum) +* bug #3208 BracesFixer - Fix for instantiation in control structures (julienfalque, SpacePossum) +* bug #3215 BinaryOperatorSpacesFixer - Fix spaces around multiple exception catching (|) (ntzm) +* bug #3216 AbstractLinesBeforeNamespaceFixer - add min. and max. option, not only single target count (SpacePossum) +* bug #3217 TokenizerLinter - fix lack of linting when code is cached (SpacePossum, keradus) +* minor #3200 Skip slow test when Xdebug is loaded (julienfalque) +* minor #3219 Normalise references to GitHub in docs (ntzm) +* minor #3226 Remove unused imports (ntzm) +* minor #3231 Fix typos (ntzm) +* minor #3234 Simplify Cache\Signature::equals (ntzm) +* minor #3237 UnconfigurableFixer - use only LF (keradus) +* minor #3238 AbstractFixerTest - fix @cover annotation (keradus) + +Changelog for v2.2.9 +-------------------- + +* bug #3062 BraceClassInstantiationTransformer - Fix instantiation inside method call braces case (julienfalque, keradus) +* bug #3083 SingleBlankLineBeforeNamespaceFixer - Fix handling namespace right after opening tag (mlocati) +* bug #3109 SwitchCaseSemicolonToColonFixer - Fix bug with nested constructs (SpacePossum) +* bug #3123 Cache - File permissions (SpacePossum) +* bug #3172 IndentationTypeFixer - do not touch whitespace that is not indentation (SpacePossum) +* bug #3176 NoMultilineWhitespaceBeforeSemicolonsFixer - SpaceAfterSemicolonFixer - priority fix (SpacePossum) +* bug #3193 TokensAnalyzer::getClassyElements - sort result before returning (SpacePossum) +* bug #3196 SelfUpdateCommand - fix exit status when can't determine newest version (julienfalque) +* minor #3107 ConfigurationResolver - improve error message when rule is not found (SpacePossum) +* minor #3113 Add WordMatcher (keradus) +* minor #3133 Unify Reporter tests (keradus) +* minor #3134 Allow Symfony 4 (keradus, garak) +* minor #3136 PHPUnit - call hooks from parent class as well (keradus) +* minor #3145 misc - Typo (localheinz) +* minor #3150 Fix CircleCI (julienfalque) +* minor #3151 Update gitattributes to ignore next file (keradus) +* minor #3156 Update php-coveralls (keradus) +* minor #3166 README - add link to new gitter channel. (SpacePossum) +* minor #3174 Update UPGRADE.md (vitek-rostislav) +* minor #3180 Fix usage of static variables (kubawerlos) +* minor #3184 Code grooming - sort content of arrays (keradus) +* minor #3191 Travis - add nightly build to allow_failures due to Travis issues (keradus) +* minor #3197 DX groom CS (keradus) + +Changelog for v2.2.8 +-------------------- + +* bug #3052 Fix false positive warning about paths overridden by provided as command arguments (kubawerlos) +* bug #3058 IsNullFixer - fix whitespace handling (roukmoute) +* bug #3072 IsNullFixer - fix non_yoda_style edge case (keradus) +* bug #3088 Drop dedicated Phar stub (keradus) +* bug #3100 NativeFunctionInvocationFixer - Fix test if previous token is already namespace separator (SpacePossum) +* bug #3104 DoctrineAnnotationIndentationFixer - Fix str_repeat() error (julienfalque) +* minor #3038 Support PHP 7.2 (SpacePossum, keradus) +* minor #3064 Fix couple of typos (KKSzymanowski) +* minor #3078 ConfigurationResolver - hide context while including config file (keradus) +* minor #3080 Direct function call instead of by string (kubawerlos) +* minor #3085 CiIntegrationTest - skip when no git is available (keradus) +* minor #3087 phar-stub.php - allow PHP 7.2 (keradus) + +Changelog for v2.2.7 +-------------------- + +* bug #3002 Bugfix braces (mnabialek) +* bug #3010 Fix handling of Github releases (julienfalque, keradus) +* bug #3015 Fix exception arguments (julienfalque) +* bug #3016 Verify phar file (keradus) +* bug #3021 Risky rules cleanup (kubawerlos) +* bug #3023 RandomApiMigrationFixer - "rand();" to "random_int(0, getrandmax());" fixing (SpacePossum) +* bug #3024 ConfigurationResolver - Handle empty "rules" value (SpacePossum, keradus) +* bug #3031 IndentationTypeFixer - fix handling tabs in indented comments (keradus) +* minor #2999 Notice when paths from config file are overridden by command arguments (julienfalque, keradus) +* minor #3007 Add PHP 7.2 to Travis build matrix (Jean85) +* minor #3009 CiIntegrationTest - run local (SpacePossum) +* minor #3013 Adjust phpunit configuration (localheinz) +* minor #3017 Fix: Risky tests (localheinz) +* minor #3018 Fix: Make sure that data providers are named correctly (localheinz, keradus) +* minor #3032 .php_cs.dist - handling UnexpectedValueException (keradus) +* minor #3034 Follow newest CS (keradus) +* minor #3036 Drop not existing Standalone group from PHPUnit configuration and duplicated internal tags (keradus) +* minor #3042 Update gitter address (keradus) + +Changelog for v2.2.6 +-------------------- + +* bug #2925 Improve CI integration suggestion (julienfalque) +* bug #2928 TokensAnalyzer::getClassyElements - Anonymous class support (SpacePossum) +* bug #2931 Psr0Fixer, Psr4Fixer - ignore "new class" syntax (dg, keradus) +* bug #2934 Config - fix handling rule without value (keradus, SpacePossum) +* bug #2939 NoUnusedImportsFixer - Fix extra blank line (julienfalque) +* bug #2941 PHP 7.2 - Group imports with trailing comma support (SpacePossum, julienfalque) +* bug #2987 Fix incorrect indentation of comments in `braces` fixer (rob006) +* minor #2927 WhiteSpaceConfig - update message copy and more strict tests (SpacePossum, keradus) +* minor #2930 Trigger website build (keradus) +* minor #2932 Integrate CircleCI (keradus, aidantwoods) +* minor #2933 ProcessLinterTest - Ensure Windows test only runs on Windows, add a Mac test execution (aidantwoods) +* minor #2935 special handling of fabbot.io service if it's using too old PHP CS Fixer version (keradus) +* minor #2937 Travis: execute 5.3 job on precise (keradus) +* minor #2938 Tests fix configuration of project (SpacePossum, keradus) +* minor #2943 FunctionToConstantFixer - test with diff. arguments than fixable (SpacePossum) +* minor #2946 Detect extra old installations (keradus) +* minor #2947 Test suggested CI integration (keradus) +* minor #2951 AccessibleObject - remove most of usage (keradus) +* minor #2969 Shrink down AccessibleObject usage (keradus) +* minor #2982 TrailingCommaInMultilineArrayFixer - simplify isMultilineArray condition (TomasVotruba) + +Changelog for v2.2.5 +-------------------- + +* bug #2807 NoUselessElseFixer - Fix detection of conditional block (SpacePossum) +* bug #2809 Phar release - fix readme generation (SpacePossum, keradus) +* bug #2827 MethodArgumentSpaceFixer - Always remove trailing spaces (julienfalque) +* bug #2835 SelfAcessorFixer - class property fix (mnabialek) +* bug #2848 PhpdocIndentFixer - fix edge case with inline phpdoc (keradus) +* bug #2849 BracesFixer - Fix indentation issues with comments (julienfalque) +* bug #2851 Tokens - ensureWhitespaceAtIndex (GrahamCampbell, SpacePossum) +* bug #2854 NoLeadingImportSlashFixer - Removing leading slash from import even when in global space (kubawerlos) +* bug #2858 Support generic types (keradus) +* bug #2869 Fix handling required configuration (keradus) +* bug #2881 NoUnusedImportsFixer - Bug when trying to insert empty token (GrahamCampbell, keradus) +* bug #2882 DocBlock\Annotation - Fix parsing of collections with multiple key types (julienfalque) +* bug #2886 NoSpacesInsideParenthesisFixer - Do not remove whitespace if next token is comment (SpacePossum) +* bug #2888 SingleImportPerStatementFixer - Add support for function and const (SpacePossum) +* bug #2901 Add missing files to archive files (keradus) +* bug #2914 HeredocToNowdocFixer - works with CRLF line ending (dg) +* bug #2920 RuleSet - Update deprecated configuration of fixers (SpacePossum, keradus) +* minor #1531 Update docs for few generic types (keradus) +* minor #2793 COOKBOOK-FIXERS.md - update to current version, fix links (keradus) +* minor #2812 ProcessLinter - compatibility with Symfony 3.3 (keradus) +* minor #2816 Tokenizer - better docs and validation (keradus) +* minor #2817 Tokenizer - use future-compatible interface (keradus) +* minor #2819 Fix benchmark (keradus) +* minor #2824 code grooming (keradus) +* minor #2826 Exceptions - provide utests (localheinz) +* minor #2828 Enhancement: Reference phpunit.xsd from phpunit.xml.dist (localheinz) +* minor #2830 Differs - add tests (localheinz) +* minor #2832 Fix: Use all the columns (localheinz) +* minor #2833 Doctrine\Annotation\Token - provide utests (localheinz) +* minor #2839 Use PHP 7.2 polyfill instead of xml one (keradus) +* minor #2842 Move null to first position in PHPDoc types (julienfalque) +* minor #2850 ReadmeCommandTest - Prevent diff output (julienfalque) +* minor #2859 Fixed typo and dead code removal (GrahamCampbell) +* minor #2863 FileSpecificCodeSample - add tests (localheinz) +* minor #2864 WhitespacesAwareFixerInterface clean up (Slamdunk) +* minor #2865 AutoReview\FixerTest - test configuration samples (SpacePossum, keradus) +* minor #2867 VersionSpecification - Fix copy-paste typo (SpacePossum) +* minor #2874 LineTest - fix typo (keradus) +* minor #2875 HelpCommand - recursive layout fix (SpacePossum) +* minor #2883 DescribeCommand - Show which sample uses the default configuration (SpacePossum) +* minor #2887 Housekeeping - Strict whitespace checks (SpacePossum) +* minor #2895 ProjectCodeTest - check that classes in no-tests exception exist (keradus) +* minor #2896 Move testing related classes from src to tests (keradus) +* minor #2904 Reapply CS (keradus) +* minor #2910 PhpdocAnnotationWithoutDotFixer - Restrict lowercasing (oschwald) +* minor #2913 Tests - tweaks (SpacePossum, keradus) +* minor #2916 FixerFactory - drop return in sortFixers(), never used (TomasVotruba) + +Changelog for v2.2.4 +-------------------- + +* bug #2682 DoctrineAnnotationIndentationFixer - fix handling nested annotations (edhgoose, julienfalque) +* bug #2700 Fix Doctrine Annotation end detection (julienfalque) +* bug #2715 OrderedImportsFixer - handle indented groups (pilgerone) +* bug #2732 HeaderCommentFixer - fix handling blank lines (s7b4) +* bug #2745 Fix Doctrine Annotation newlines (julienfalque) +* bug #2752 FixCommand - fix typo in warning message (mnapoli) +* bug #2757 GeckoPHPUnit is not dev dependency (keradus) +* bug #2759 Update gitattributes (SpacePossum) +* bug #2763 Fix describe command with PSR-0 fixer (julienfalque) +* bug #2768 Tokens::ensureWhitespaceAtIndex - clean up comment check, add check for T_OPEN (SpacePossum) +* bug #2783 Tokens::ensureWhitespaceAtIndex - Fix handling line endings (SpacePossum) +* minor #2663 Use colors for keywords in commands output (julienfalque, keradus) +* minor #2706 Update README (SpacePossum) +* minor #2714 README.rst - fix wrong value in example (mleko) +* minor #2721 Update phpstorm article link to a fresh blog post (valeryan) +* minor #2727 PHPUnit - use speedtrap (keradus) +* minor #2728 SelfUpdateCommand - verify that it's possible to replace current file (keradus) +* minor #2729 DescribeCommand - add decorated output test (julienfalque) +* minor #2731 BracesFixer - properly pass config in utest dataProvider (keradus) +* minor #2738 Upgrade tests to use new, namespaced PHPUnit TestCase class (keradus) +* minor #2743 Fixing example and description for GeneralPhpdocAnnotationRemoveFixer (kubawerlos) +* minor #2744 AbstractDoctrineAnnotationFixerTestCase - split fixers test cases (julienfalque) +* minor #2755 Fix compatibility with PHPUnit 5.4.x (keradus) +* minor #2758 Readme - improve CI integration guidelines (keradus) +* minor #2769 Psr0Fixer - remove duplicated example (julienfalque) +* minor #2775 NoExtraConsecutiveBlankLinesFixer - remove duplicate code sample. (SpacePossum) +* minor #2778 AutoReview - watch that code samples are unique (keradus) +* minor #2787 Add warnings about missing dom ext and require json ext (keradus) +* minor #2792 Use composer-require-checker (keradus) +* minor #2796 Update .gitattributes (SpacePossum) +* minor #2800 PhpdocTypesFixerTest - Fix typo in covers annotation (SpacePossum) + +Changelog for v2.2.3 +-------------------- + +* bug #2724 Revert #2554 Add short diff. output format (keradus) + +Changelog for v2.2.2 +-------------------- + +Warning, this release breaks BC due to introduction of: +* minor #2554 Add short diff. output format (SpacePossum, keradus) +That PR was reverted in v2.2.3, which should be used instead of v2.2.2. + +* bug #2545 RuleSet - change resolvement (SpacePossum) +* bug #2686 Commands readme and describe - fix rare casing when not displaying some possible options of configuration (keradus) +* bug #2711 FixCommand - fix diff optional value handling (keradus) +* minor #2688 AppVeyor - Remove github oauth (keradus) +* minor #2703 Clean ups - No mixed annotations (SpacePossum) +* minor #2704 Create PHP70Migration:risky ruleset (keradus) +* minor #2707 Deprecate other than "yes" or "no" for input options (SpacePossum) +* minor #2709 code grooming (keradus) +* minor #2710 Travis - run more rules on TASK_SCA (keradus) + +Changelog for v2.2.1 +-------------------- + +* bug #2621 Tokenizer - fix edge cases with empty code, registered found tokens and code hash (SpacePossum, keradus) +* bug #2674 SemicolonAfterInstructionFixer - Fix case where block ends with an opening curly brace (ntzm) +* bug #2675 ProcessOutputTest - update tests to pass on newest Symfony components under Windows (keradus) +* minor #2651 Fix UPGRADE.md table syntax so it works in GitHub (ntzm, keradus) +* minor #2665 Travis - Improve trailing spaces detection (julienfalque) +* minor #2666 TransformersTest - move test to auto-review group (keradus) +* minor #2668 add covers annotation (keradus) +* minor #2669 TokensTest - grooming (SpacePossum) +* minor #2670 AbstractFixer: use applyFix instead of fix (Slamdunk) +* minor #2677 README: Correct progressbar option support (Laurens St�tzel) + +Changelog for v2.2.0 +-------------------- + +* bug #2640 NoExtraConsecutiveBlankLinesFixer - Fix single indent characters not working (ntzm) +* feature #2220 Doctrine annotation fixers (julienfalque) +* feature #2431 MethodArgumentSpaceFixer: allow to retain multiple spaces after comma (Slamdunk) +* feature #2459 BracesFixer - Add option for keeping opening brackets on the same line (jtojnar, SpacePossum) +* feature #2486 Add FunctionToConstantFixer (SpacePossum, keradus) +* feature #2505 FunctionDeclarationFixer - Make space after anonymous function configurable (jtojnar, keradus) +* feature #2509 FullOpeningTagFixer - Ensure opening PHP tag is lowercase (jtojnar) +* feature #2532 FixCommand - add stop-on-violation option (keradus) +* feature #2591 Improve process output (julienfalque) +* feature #2603 Add InvisibleSymbols Fixer (ivan1986, keradus) +* feature #2642 Add MagicConstantCasingFixer (ntzm) +* feature #2657 PhpdocToCommentFixer - Allow phpdoc for language constructs (ceeram, SpacePossum) +* minor #2500 Configuration resolver (julienfalque, SpacePossum, keradus) +* minor #2566 Show more details on errors and exceptions. (SpacePossum, julienfalque) +* minor #2597 HHVM - bump required version to 3.18 (keradus) +* minor #2606 FixCommand - fix missing comment close tag (keradus) +* minor #2623 OrderedClassElementsFixer - remove dead code (SpacePossum) +* minor #2625 Update Symfony and Symfony:risky rulesets (keradus) +* minor #2626 TernaryToNullCoalescingFixer - adjust ruleset membership and description (keradus) +* minor #2635 ProjectCodeTest - watch that all classes have dedicated tests (keradus) +* minor #2647 DescribeCommandTest - remove deprecated code usage (julienfalque) +* minor #2648 Move non-code covering tests to AutoReview subnamespace (keradus) +* minor #2652 NoSpacesAroundOffsetFixerTest - fix deprecation (keradus) +* minor #2656 Code grooming (keradus) +* minor #2659 Travis - speed up preparation for phar building (keradus) +* minor #2660 Fixed typo in suggest for ext-mbstring (pascal-hofmann) +* minor #2661 NonPrintableCharacterFixer - include into Symfony:risky ruleset (keradus) + +Changelog for v2.1.3 +-------------------- + +* bug #2358 Cache - Deal with signature encoding (keradus, GrahamCampbell) +* bug #2475 Add shorthand array destructing support (SpacePossum, keradus) +* bug #2595 NoUnusedImportsFixer - Fix import usage detection with properties (julienfalque) +* bug #2605 PhpdocAddMissingParamAnnotationFixer, PhpdocOrderFixer - fix priority issue (SpacePossum) +* bug #2607 Fixers - better comments handling (SpacePossum) +* bug #2612 BracesFixer - Fix early bracket close for do-while loop inside an if without brackets (felixgomez) +* bug #2614 Ensure that '*Fixer::fix()' won't crash when running on non-candidate collection (keradus) +* bug #2630 HeaderCommentFixer - Fix trailing whitespace not removed after AliasFunctionsFixer (kalessil) +* feature #1275 Added PhpdocInlineTagFixer (SpacePossum, keradus) +* feature #1292 Added MethodSeparationFixer (SpacePossum) +* feature #1383 Introduce rules and sets (keradus) +* feature #1416 Mark fixers as risky (keradus) +* feature #1440 Made AbstractFixerTestCase and AbstractIntegrationTestCase public (keradus) +* feature #1489 Added Psr4Fixer (GrahamCampbell) +* feature #1497 ExtraEmptyLinesFixer - allow to remove empty blank lines after configured tags (SpacePossum) +* feature #1529 Added PhpdocPropertyFixer, refactored Tag and Annotation (GrahamCampbell) +* feature #1628 Added OrderedClassElementsFixer (gharlan) +* feature #1742 path argument is used to create an intersection with existing finder (keradus, gharlan) +* feature #1779 Added GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocAnnotationRenameFixer (keradus) +* feature #1811 Added NoSpacesInsideOfssetFixer (phansys) +* feature #1819 Added DirConstantFixer, ModernizeTypesCastingFixer, RandomApiMigrationFixer (kalessil, SpacePossum, keradus) +* feature #1825 Added junit format (ekho) +* feature #1862 FixerFactory - Do not allow conflicting fixers (SpacePossum) +* feature #1888 Cache refactoring, better cache handling in dry-run mode (localheinz) +* feature #1889 Added SingleClassElementPerStatementFixer (phansys, SpacePossum) +* feature #1903 FixCommand - allow to pass multiple path argument (keradus) +* feature #1913 Introduce path-mode CLI option (keradus) +* feature #1949 Added DeclareStrictTypesFixer, introduce options for HeaderCommentFixer (Seldaek, SpacePossum, keradus) +* feature #1955 Introduce CT_ARRAY_INDEX_CURLY_BRACE_OPEN and CT_ARRAY_INDEX_CURLY_BRACE_CLOSE (keradus) +* feature #1958 Added NormalizeIndexBraceFixer (keradus) +* feature #2069 Add semicolon after instruction fixer (SpacePossum) +* feature #2089 Add `no_spaces_around_offset` fixer (phansys) +* feature #2179 BinaryOperatorSpacesFixer - add (un)align configuration options (SpacePossum) +* feature #2192 Add PowToExponentiationFixer (SpacePossum, keradus) +* feature #2207 Added ReturnTypeDeclarationFixer (keradus) +* feature #2213 VisibilityRequiredFixer - Add support for class const visibility added in PHP7.1. (SpacePossum) +* feature #2221 Add support for user-defined whitespaces (keradus) +* feature #2244 Config cleanup (keradus, SpacePossum) +* feature #2247 PhpdocAnnotationWithoutDotFixer - support more cases (keradus) +* feature #2289 Add PhpdocAddMissingParamAnnotationFixer (keradus) +* feature #2331 Add DescribeCommand (keradus, SpacePossum) +* feature #2332 New colours of diff on console (keradus) +* feature #829 add support for .php_cs.dist file (keradus) +* feature #998 MethodArgumentSpaceFixer - enhance, now only one space after comma (trilopin, keradus) +* minor #1007 Simplify Transformers (keradus) +* minor #1050 Make Config's setDir() fluent like the rest of methods (gonzaloserrano) +* minor #1062 Added NamespaceOperatorTransformer (gharlan) +* minor #1078 Exit status should be 0 if there are no errors (gharlan) +* minor #1101 CS: fix project itself (localheinz) +* minor #1102 Enhancement: List errors occurred before, during and after fixing (localheinz) +* minor #1105 Token::isStructureAlternativeEnd - remove unused method (keradus) +* minor #1106 readme grooming (SpacePossum, keradus) +* minor #1115 Fixer - simplify flow (keradus) +* minor #1118 Process output refactor (SpacePossum) +* minor #1132 Linter - public methods should be first (keradus) +* minor #1134 Token::isWhitespace - simplify interface (keradus) +* minor #1140 FixerInterface - check if fixer should be applied by isCandidate method (keradus) +* minor #1146 Linter - detect executable (keradus) +* minor #1156 deleted old ConfigurationResolver class (keradus) +* minor #1160 Grammar fix to README (Falkirks) +* minor #1174 DefaultFinder - boost performance by not filtering when files array is empty (keradus) +* minor #1179 Exit with non-zero if invalid files were detected prior to fixing (localheinz) +* minor #1186 Finder - do not search for .xml and .yml files (keradus) +* minor #1206 BracesFixer::getClassyTokens - remove duplicated method (keradus) +* minor #1222 Made fixers final (GrahamCampbell) +* minor #1229 Tokens - Fix PHPDoc (SpacePossum) +* minor #1241 More details on exceptions. (SpacePossum) +* minor #1263 Made internal classes final (GrahamCampbell) +* minor #1272 Readme - Add spaces around PHP-CS-Fixer headers (Soullivaneuh) +* minor #1283 Error - Fixed type phpdoc (GrahamCampbell) +* minor #1284 Token - Fix PHPDoc (SpacePossum) +* minor #1314 Added missing internal annotations (keradus) +* minor #1329 Psr0Fixer - move to contrib level (gharlan) +* minor #1340 Clean ups (SpacePossum) +* minor #1341 Linter - throw exception when write fails (SpacePossum) +* minor #1348 Linter - Prefer error output when throwing a linting exception (GrahamCampbell) +* minor #1350 Add "phpt" as a valid extension (henriquemoody) +* minor #1376 Add time and memory to XML report (junichi11) +* minor #1387 Made all test classes final (keradus) +* minor #1388 Made all tests internal (keradus) +* minor #1390 Added ProjectCodeTest that tests if all classes inside tests are internal and final or abstract (keradus) +* minor #1391 Fixer::getLevelAsString is no longer static (keradus) +* minor #1392 Add report to XML report as the root node (junichi11) +* minor #1394 Stop mixing level from config file and fixers from CLI arg when one of fixers has dash (keradus) +* minor #1426 MethodSeparationFixer - Fix spacing around comments (SpacePossum, keradus) +* minor #1432 Fixer check on factory (Soullivaneuh) +* minor #1434 Add Test\AccessibleObject class (keradus) +* minor #1442 FixerFactory - disallow to register multiple fixers with same name (keradus) +* minor #1477 rename PhpdocShortDescriptionFixer into PhpdocSummaryFixer (keradus) +* minor #1481 Fix running the tests (keradus) +* minor #1482 move AbstractTransformerTestBase class outside Tests dir (keradus) +* minor #1530 Added missing internal annotation (GrahamCampbell) +* minor #1534 Clean ups (SpacePossum) +* minor #1536 Typo fix (fabpot) +* minor #1555 Fixed indentation in composer.json (GrahamCampbell) +* minor #1558 [2.0] Cleanup the tags property in the abstract phpdoc types fixer (GrahamCampbell) +* minor #1567 PrintToEchoFixer - add to symfony rule set (gharlan) +* minor #1607 performance improvement (gharlan) +* minor #1621 Switch to PSR-4 (keradus) +* minor #1631 Configuration exceptions exception cases on master. (SpacePossum) +* minor #1646 Remove non-default Config/Finder classes (keradus) +* minor #1648 Fixer - avoid extra calls to getFileRelativePathname (GrahamCampbell) +* minor #1649 Consider the php version when caching (GrahamCampbell) +* minor #1652 Rename namespace "Symfony\CS" to "PhpCsFixer" (gharlan) +* minor #1666 new Runner, ProcessOutputInterface, DifferInterface and ResultInterface (keradus) +* minor #1674 Config - add addCustomFixers method (PedroTroller) +* minor #1677 Enhance tests (keradus) +* minor #1695 Rename Fixers (keradus) +* minor #1702 Upgrade guide (keradus) +* minor #1707 ExtraEmptyLinesFixer - fix configure docs (keradus) +* minor #1712 NoExtraConsecutiveBlankLinesFixer - Remove blankline after curly brace open (SpacePossum) +* minor #1718 CLI: rename --config-file argument (keradus) +* minor #1722 Renamed not_operators_with_space to not_operator_with_space (GrahamCampbell) +* minor #1728 PhpdocNoSimplifiedNullReturnFixer - rename back to PhpdocNoEmptyReturnFixer (keradus) +* minor #1729 Renamed whitespacy_lines to no_whitespace_in_blank_lines (GrahamCampbell) +* minor #1731 FixCommand - value for config option is required (keradus) +* minor #1732 move fixer classes from level subdirs to thematic subdirs (gharlan, keradus) +* minor #1733 ConfigurationResolver - look for .php_cs file in cwd as well (keradus) +* minor #1737 RuleSet/FixerFactory - sort arrays content (keradus) +* minor #1751 FixerInterface::configure - method should always override configuration, not patch it (keradus) +* minor #1752 Remove unused code (keradus) +* minor #1756 Finder - clean up code (keradus) +* minor #1757 Psr0Fixer - change way of configuring the fixer (keradus) +* minor #1762 Remove ConfigInterface::getDir, ConfigInterface::setDir, Finder::setDir and whole FinderInterface (keradus) +* minor #1764 Remove ConfigAwareInterface (keradus) +* minor #1780 AbstractFixer - throw error on configuring non-configurable Fixer (keradus) +* minor #1782 rename fixers (gharlan) +* minor #1815 NoSpacesInsideParenthesisFixer - simplify implementation (keradus) +* minor #1821 Ensure that PhpUnitDedicateAssertFixer runs after NoAliasFunctionsFixer, clean up NoEmptyCommentFixer (SpacePossum) +* minor #1824 Reporting extracted to separate classes (ekho, keradus, SpacePossum) +* minor #1826 Fixer - remove measuring fixing time per file (keradus) +* minor #1843 FileFilterIterator - add missing import (GrahamCampbell) +* minor #1845 FileCacheManager - Allow linting to determine the cache state too (GrahamCampbell) +* minor #1846 FileFilterIterator - Corrected an iterator typehint (GrahamCampbell) +* minor #1848 DocBlock - Remove some old unused phpdoc tags (GrahamCampbell) +* minor #1856 NoDuplicateSemicolonsFixer - Remove overcomplete fixer (SpacePossum) +* minor #1861 Fix: Ofsset should be Offset (localheinz) +* minor #1867 Print non-report output to stdErr (SpacePossum, keradus) +* minor #1873 Enhancement: Show path to cache file if it exists (localheinz) +* minor #1875 renamed Composer package (fabpot) +* minor #1882 Runner - Handle throwables too (GrahamCampbell) +* minor #1886 PhpdocScalarFixer - Fix lowercase str to string too (GrahamCampbell) +* minor #1940 README.rst - update CI example (keradus) +* minor #1947 SCA, CS, add more tests (SpacePossum, keradus) +* minor #1954 tests - stop using deprecated method (sebastianbergmann) +* minor #1962 TextDiffTest - tests should not produce cache file (keradus) +* minor #1973 Introduce fast PHP7 based linter (keradus) +* minor #1999 Runner - No need to determine relative file name twice (localheinz) +* minor #2002 FileCacheManagerTest - Adjust name of test and variable (localheinz) +* minor #2010 NoExtraConsecutiveBlankLinesFixer - SF rule set, add 'extra' (SpacePossum) +* minor #2013 no_whitespace_in_blank_lines -> no_whitespace_in_blank_line (SpacePossum) +* minor #2024 AbstractFixerTestCase - check if there is no duplicated Token instance inside Tokens collection (keradus) +* minor #2031 COOKBOOK-FIXERS.md - update calling doTest method (keradus) +* minor #2032 code grooming (keradus) +* minor #2068 Code grooming (keradus) +* minor #2073 DeclareStrictTypesFixer - Remove fix CS fix logic from fixer. (SpacePossum) +* minor #2088 TokenizerLintingResult - expose line number of parsing error (keradus) +* minor #2093 Tokens - add block type BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE (SpacePossum) +* minor #2095 Transformers - add required PHP version (keradus) +* minor #2096 Introduce CT for PHP7 (keradus) +* minor #2119 Create @Symfony:risky ruleset (keradus) +* minor #2163 ClassKeywordRemoveFixerTest - Fix tests (SpacePossum) +* minor #2180 FixCommand - don't refer to renamed rules (keradus) +* minor #2181 Disallow to disable linter (keradus) +* minor #2194 semicolon_after_instruction,no_unneeded_control_parentheses prio issue (SpacePossum) +* minor #2199 make fixers less risky (SpacePossum) +* minor #2206 Add PHP70Migration ruleset (keradus) +* minor #2217 SelfUpdateCommand - Print version of update fixer (SpacePossum) +* minor #2223 update integration test format (keradus) +* minor #2227 Stop polluting global namespace with CT (keradus) +* minor #2237 DX: extend integration tests for PSR2 and Symfony rulesets (keradus) +* minor #2240 Make some objects immutable (keradus) +* minor #2251 ProtectedToPrivateFixer - fix priority, fix comments with new fixer names (SpacePossum) +* minor #2252 ClassDefinitionFixer - Set configuration of the fixer in the RuleSet of SF. (SpacePossum) +* minor #2257 extend Symfony_whitespaces itest (keradus) +* minor #2258 README.rst - indicate configurable rules (keradus) +* minor #2267 RuleSet - validate set (keradus) +* minor #2268 Use strict parameters for PHP functions (keradus) +* minor #2273 fixed typo (fabpot) +* minor #2274 ShortArraySyntaxFixer/LongArraySyntaxFixer - Merge conflicting fixers (SpacePossum) +* minor #2275 Clean ups (SpacePossum) +* minor #2278 Concat*Fixer - unify concat fixers (SpacePossum, keradus) +* minor #2279 Use Prophecy (keradus) +* minor #2284 Code grooming (SpacePossum) +* minor #2285 IntegrationCase is now aware about RuleSet but not Fixers (keradus, SpacePossum) +* minor #2286 Phpdoc*Fixer - unify rename fixers (SpacePossum, keradus) +* minor #2288 FixerInterface::configure(null) reset fixer to use default configuration (keradus) +* minor #2291 Make fixers ready to use directly after creation (keradus) +* minor #2295 Code grooming (keradus) +* minor #2296 ProjectCodeTest - make test part of regular testsuite, not standalone one (keradus) +* minor #2298 ConfigurationResolver - grooming (SpacePossum) +* minor #2300 Simplify rule set (SpacePossum, keradus) +* minor #2306 DeclareStrictTypesFixer - do not move tokens (SpacePossum) +* minor #2312 RuleSet - sort rules (localheinz) +* minor #2313 DX: provide doctyping for tests (keradus) +* minor #2317 Add utests (keradus) +* minor #2318 *TestCase - Reduce visibility of setUp() (localheinz) +* minor #2319 Code grooming (keradus) +* minor #2322 DX: use whitemessy aware assertion (keradus) +* minor #2324 Echo|Print*Fixer - unify printing fixers (SpacePossum, keradus) +* minor #2337 Normalize rule naming (keradus) +* minor #2338 Drop hacks for unsupported HHVM (keradus) +* minor #2339 Add some Fixer descriptions (SpacePossum, keradus) +* minor #2343 PowToExponentiationFixer - allow to run on 5.6.0 as well (keradus) +* minor #767 Add @internal tag (keradus) +* minor #807 Tokens::isMethodNameIsMagic - remove unused method (keradus) +* minor #809 Split Tokens into Tokens and TokensAnalyzer (keradus) +* minor #844 Renamed phpdoc_params to phpdoc_align (GrahamCampbell) +* minor #854 Change default level to PSR2 (keradus) +* minor #873 Config - using cache by default (keradus) +* minor #902 change FixerInterface (keradus) +* minor #911 remove Token::$line (keradus) +* minor #914 All Transformer classes should be named with Transformer as suffix (keradus) +* minor #915 add UseTransformer (keradus) +* minor #916 add ArraySquareBraceTransformer (keradus) +* minor #917 clean up Transformer tests (keradus) +* minor #919 CurlyBraceTransformer - one transformer to handle all curly braces transformations (keradus) +* minor #928 remove Token::getLine (keradus) +* minor #929 add WhitespacyCommentTransformer (keradus) +* minor #937 fix docs/typehinting in few classes (keradus) +* minor #958 FileCacheManager - remove code for BC support (keradus) +* minor #979 Improve Tokens::clearEmptyTokens performance (keradus) +* minor #981 Tokens - code grooming (keradus) +* minor #988 Fixers - no need to search for tokens of given kind in extra loop (keradus) +* minor #989 No need for loop in Token::equals (keradus) + +Changelog for v1.13.3 +--------------------- + +* minor #3042 Update gitter address (keradus) + +Changelog for v1.13.2 +--------------------- + +* minor #2946 Detect extra old installations (keradus) + +Changelog for v1.13.1 +--------------------- + +* minor #2342 Application - adjust test to not depend on symfony/console version (keradus) +* minor #2344 AppVeyor: enforce PHP version (keradus) + +Changelog for v1.13.0 +--------------------- + +* bug #2303 ClassDefinitionFixer - Anonymous classes fixing (SpacePossum) +* feature #2208 Added fixer for PHPUnit's @expectedException annotation (ro0NL) +* feature #2249 Added ProtectedToPrivateFixer (Slamdunk, SpacePossum) +* feature #2264 SelfUpdateCommand - Do not update to next major version by default (SpacePossum) +* feature #2328 ClassDefinitionFixer - Anonymous classes format by PSR12 (SpacePossum) +* feature #2333 PhpUnitFqcnAnnotationFixer - support more annotations (keradus) +* minor #2256 EmptyReturnFixer - it's now risky fixer due to null vs void (keradus) +* minor #2281 Add issue template (SpacePossum) +* minor #2307 Update .editorconfig (SpacePossum) +* minor #2310 CI: update AppVeyor to use newest PHP, silence the composer (keradus) +* minor #2315 Token - Deprecate getLine() (SpacePossum) +* minor #2320 Clear up status code on 1.x (SpacePossum) + +Changelog for v1.12.4 +--------------------- + +* bug #2235 OrderedImportsFixer - PHP 7 group imports support (SpacePossum) +* minor #2276 Tokens cleanup (keradus) +* minor #2277 Remove trailing spaces (keradus) +* minor #2294 Improve Travis configuration (keradus) +* minor #2297 Use phpdbg instead of xdebug (keradus) +* minor #2299 Travis: proper xdebug disabling (keradus) +* minor #2301 Travis: update platform adjusting (keradus) + +Changelog for v1.12.3 +--------------------- + +* bug #2155 ClassDefinitionFixer - overhaul (SpacePossum) +* bug #2187 MultipleUseFixer - Fix handling comments (SpacePossum) +* bug #2209 LinefeedFixer - Fix in a safe way (SpacePossum) +* bug #2228 NoEmptyLinesAfterPhpdocs, SingleBlankLineBeforeNamespace - Fix priority (SpacePossum) +* bug #2230 FunctionDeclarationFixer - Fix T_USE case (SpacePossum) +* bug #2232 Add a test for style of varaible decalration : var (daiglej) +* bug #2246 Fix itest requirements (keradus) +* minor #2238 .gitattributes - specified line endings (keradus) +* minor #2239 IntegrationCase - no longer internal (keradus) + +Changelog for v1.12.2 +--------------------- + +* bug #2191 PhpdocToCommentFixer - fix false positive for docblock of variable (keradus) +* bug #2193 UnneededControlParenthesesFixer - Fix more return cases. (SpacePossum) +* bug #2198 FileCacheManager - fix exception message and undefined property (j0k3r) +* minor #2170 Add dollar sign prefix for consistency (bcremer) +* minor #2190 .travis.yml - improve Travis speed for tags (keradus) +* minor #2196 PhpdocTypesFixer - support iterable type (GrahamCampbell) +* minor #2197 Update cookbook and readme (g105b, SpacePossum) +* minor #2203 README.rst - change formatting (ro0NL) +* minor #2204 FixCommand - clean unused var (keradus) +* minor #2205 Add integration test for iterable type (keradus) + +Changelog for v1.12.1 +--------------------- + +* bug #2144 Remove temporary files not deleted by destructor on failure (adawolfa) +* bug #2150 SelfUpdateCommand: resolve symlink (julienfalque) +* bug #2162 Fix issue where an exception is thrown if the cache file exists but is empty. (ikari7789) +* bug #2164 OperatorsSpacesFixer - Do not unalign double arrow and equals operators (SpacePossum) +* bug #2167 Rewrite file removal (keradus) +* minor #2152 Code cleanup (keradus) +* minor #2154 ShutdownFileRemoval - Fixed file header (GrahamCampbell) + +Changelog for v1.12.0 +--------------------- + +* feature #1493 Added MethodArgumentDefaultValueFixer (lmanzke) +* feature #1495 BracesFixer - added support for declare (EspadaV8) +* feature #1518 Added ClassDefinitionFixer (SpacePossum) +* feature #1543 [PSR-2] Switch case space fixer (Soullivaneuh) +* feature #1577 Added SpacesAfterSemicolonFixer (SpacePossum) +* feature #1580 Added HeredocToNowdocFixer (gharlan) +* feature #1581 UnneededControlParenthesesFixer - add "break" and "continue" support (gharlan) +* feature #1610 HashToSlashCommentFixer - Add (SpacePossum) +* feature #1613 ScalarCastFixer - LowerCaseCastFixer - Add (SpacePossum) +* feature #1659 NativeFunctionCasingFixer - Add (SpacePossum) +* feature #1661 SwitchCaseSemicolonToColonFixer - Add (SpacePossum) +* feature #1662 Added CombineConsecutiveUnsetsFixer (SpacePossum) +* feature #1671 Added NoEmptyStatementFixer (SpacePossum) +* feature #1705 Added NoUselessReturnFixer (SpacePossum, keradus) +* feature #1735 Added NoTrailingWhitespaceInCommentFixer (keradus) +* feature #1750 Add PhpdocSingleLineVarSpacingFixer (SpacePossum) +* feature #1765 Added NoEmptyPhpdocFixer (SpacePossum) +* feature #1773 Add NoUselessElseFixer (gharlan, SpacePossum) +* feature #1786 Added NoEmptyCommentFixer (SpacePossum) +* feature #1792 Add PhpUnitDedicateAssertFixer. (SpacePossum) +* feature #1894 BracesFixer - correctly fix indents of anonymous functions/classes (gharlan) +* feature #1985 Added ClassKeywordRemoveFixer (Soullivaneuh) +* feature #2020 Added PhpdocAnnotationWithoutDotFixer (keradus) +* feature #2067 Added DeclareEqualNormalizeFixer (keradus) +* feature #2078 Added SilencedDeprecationErrorFixer (HeahDude) +* feature #2082 Added MbStrFunctionsFixer (Slamdunk) +* bug #1657 SwitchCaseSpaceFixer - Fix spacing between 'case' and semicolon (SpacePossum) +* bug #1684 SpacesAfterSemicolonFixer - fix loops handling (SpacePossum, keradus) +* bug #1700 Fixer - resolve import conflict (keradus) +* bug #1836 NoUselessReturnFixer - Do not remove return if last statement in short if statement (SpacePossum) +* bug #1879 HeredocToNowdocFixer - Handle space in heredoc token (SpacePossum) +* bug #1896 FixCommand - Fix escaping of diff output (SpacePossum) +* bug #2034 IncludeFixer - fix support for close tag (SpacePossum) +* bug #2040 PhpdocAnnotationWithoutDotFixer - fix crash on odd character (keradus) +* bug #2041 DefaultFinder should implement FinderInterface (keradus) +* bug #2050 PhpdocAnnotationWithoutDotFixer - handle ellipsis (keradus) +* bug #2051 NativeFunctionCasingFixer - call to constructor with default NS of class with name matching native function name fix (SpacePossum) +* minor #1538 Added possibility to lint tests (gharlan) +* minor #1569 Add sample to get a specific version of the fixer (Soullivaneuh) +* minor #1571 Enhance integration tests (keradus) +* minor #1578 Code grooming (keradus) +* minor #1583 Travis - update matrix (keradus) +* minor #1585 Code grooming - Improve utests code coverage (SpacePossum) +* minor #1586 Add configuration exception classes and exit codes (SpacePossum) +* minor #1594 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1597 MethodArgumentDefaultValueFixer - refactoring and fix closures with "use" clause (gharlan) +* minor #1600 Added more integration tests (SpacePossum, keradus) +* minor #1605 integration tests - swap EXPECT and INPUT (optional INPUT) (gharlan) +* minor #1608 Travis - change matrix order for faster results (gharlan) +* minor #1609 CONTRIBUTING.md - Don't rebase always on master (SpacePossum) +* minor #1616 IncludeFixer - fix and test more cases (SpacePossum) +* minor #1622 AbstractIntegratationTest - fix linting test cases (gharlan) +* minor #1624 fix invalid code in test cases (gharlan) +* minor #1625 Travis - switch to trusty (keradus) +* minor #1627 FixCommand - fix output (keradus) +* minor #1630 Pass along the exception code. (SpacePossum) +* minor #1632 Php Inspections (EA Extended): SCA for 1.12 (kalessil) +* minor #1633 Fix CS for project itself (keradus) +* minor #1634 Backport some minor changes from 2.x line (keradus) +* minor #1637 update PHP Coveralls (keradus) +* minor #1639 Revert "Travis - set dist to trusty" (keradus) +* minor #1641 AppVeyor/Travis - use GITHUB_OAUTH_TOKEN (keradus) +* minor #1642 AppVeyor - install dev deps as well (keradus) +* minor #1647 Deprecate non-default Configs and Finders (keradus) +* minor #1654 Split output to stderr and stdout (SpacePossum) +* minor #1660 update phpunit version (gharlan) +* minor #1663 DuplicateSemicolonFixer - Remove duplicate semicolons even if there are comments between those (SpacePossum) +* minor #1664 IncludeFixer - Add missing test case (SpacePossum) +* minor #1668 Code grooming (keradus) +* minor #1669 NativeFunctionCasingFixer - move to Symfony level (keradus) +* minor #1670 Backport Finder and Config classes from 2.x line (keradus) +* minor #1682 ElseifFixer - handle comments (SpacePossum) +* minor #1689 AbstractIntegrationTest - no need for single-char group and docs grooming (keradus) +* minor #1690 Integration tests - allow to not check priority, introduce IntegrationCase (keradus) +* minor #1701 Fixer - Renamed import alias (GrahamCampbell) +* minor #1708 Update composer.json requirements (keradus) +* minor #1734 Travis: Turn on linting (keradus) +* minor #1736 Integration tests - don't check priority for tests using short_tag fixer (keradus) +* minor #1739 NoTrailingWhitespaceInCommentFixer - move to PSR2 level (keradus) +* minor #1763 Deprecate ConfigInterface::getDir, ConfigInterface::setDir, Finder::setDir (keradus) +* minor #1777 NoTrailingWhitespaceInCommentFixer - fix parent class (keradus) +* minor #1816 PhpUnitDedicateAssertFixer - configuration is not required anymore (keradus) +* minor #1849 DocBlock - The category tag should be together with package (GrahamCampbell) +* minor #1870 Update README.rst (glensc) +* minor #1880 FixCommand - fix stdErr detection (SpacePossum) +* minor #1881 NoEmptyStatementFixer - handle anonymous classes correctly (gharlan) +* minor #1906 .php_cs - use no_useless_else rule (keradus) +* minor #1915 NoEmptyComment - move to Symfony level (SpacePossum) +* minor #1917 BracesFixer - fixed comment handling (gharlan) +* minor #1919 EmptyReturnFixer - move fixer outside of Symfony level (keradus) +* minor #2036 OrderedUseFixer - adjust tests (keradus) +* minor #2056 Travis - run nightly PHP (keradus) +* minor #2061 UnusedUseFixer and LineAfterNamespace - add new integration test (keradus) +* minor #2097 Add lambda tests for 7.0 and 7.1 (SpacePossum) +* minor #2111 .travis.yml - rename PHP 7.1 env (keradus) +* minor #2112 Fix 1.12 line (keradus) +* minor #2118 SilencedDeprecationErrorFixer - adjust level (keradus) +* minor #2132 composer.json - rename package name (keradus) +* minor #2133 Apply ordered_class_elements rule (keradus) +* minor #2138 composer.json - disallow to run on PHP 7.2+ (keradus) + +Changelog for v1.11.8 +--------------------- + +* bug #2143 ReadmeCommand - fix running command on phar file (keradus) +* minor #2129 Add .gitattributes to remove unneeded files (Slamdunk) +* minor #2141 Move phar building to PHP 5.6 job as newest box.phar is no longer working on 5.3 (keradus) + +Changelog for v1.11.7 +--------------------- + +* bug #2108 ShortArraySyntaxFixer, TernarySpacesFixer, UnalignEqualsFixer - fix priority bug (SpacePossum) +* bug #2092 ConcatWithoutSpacesFixer, OperatorsSpacesFixer - fix too many spaces, fix incorrect fixing of lines with comments (SpacePossum) + +Changelog for v1.11.6 +--------------------- + +* bug #2086 Braces - fix bug with comment in method prototype (keradus) +* bug #2077 SingleLineAfterImportsFixer - Do not remove lines between use cases (SpacePossum) +* bug #2079 TernarySpacesFixer - Remove multiple spaces (SpacePossum) +* bug #2087 Fixer - handle PHP7 Errors as well (keradus) +* bug #2072 LowercaseKeywordsFixer - handle CT_CLASS_CONSTANT (tgabi333) +* bug #2066 LineAfterNamespaceFixer - Handle close tag (SpacePossum) +* bug #2057 LineAfterNamespaceFixer - adding too much extra lines where namespace is last statement (keradus) +* bug #2059 OperatorsSpacesFixer - handle declare statement (keradus) +* bug #2060 UnusedUseFixer - fix handling whitespaces around removed import (keradus) +* minor #2071 ShortEchoTagFixer - allow to run tests on PHP 5.3 (keradus) + +Changelog for v1.11.5 +--------------------- + +* bug #2012 Properly build phar file for lowest supported PHP version (keradus) +* bug #2037 BracesFixer - add support for anonymous classes (keradus) +* bug #1989 Add support for PHP 7 namespaces (SpacePossum) +* bug #2019 Fixing newlines added after curly brace string index access (jaydiablo) +* bug #1840 [Bug] BracesFixer - Do add a line before close tag (SpacePossum) +* bug #1994 EchoToPrintFixer - Fix T_OPEN_TAG_WITH_ECHO on hhvm (keradus) +* bug #1970 Tokens - handle semi-reserved PHP 7 keywords (keradus) +* minor #2017 PHP7 integration tests (keradus) +* minor #1465 Bump supported HHVM version, improve ShortEchoTagFixer on HHVM (keradus) +* minor #1995 Rely on own phpunit, not one from CI service (keradus) + +Changelog for v1.11.4 +--------------------- + +* bug #1956 SelfUpdateCommand - don't update to non-stable version (keradus) +* bug #1963 Fix not wanted unneeded_control_parentheses fixer for clone (Soullivaneuh) +* bug #1960 Fix invalid test cases (keradus) +* bug #1939 BracesFixer - fix handling comment around control token (keradus) +* minor #1927 NewWithBracesFixer - remove invalid testcase (keradus) + +Changelog for v1.11.3 +--------------------- + +* bug #1868 NewWithBracesFixer - fix handling more neighbor tokens (keradus) +* bug #1893 BracesFixer - handle comments inside lambda function prototype (keradus) +* bug #1806 SelfAccessorFixer - skip anonymous classes (gharlan) +* bug #1813 BlanklineAfterOpenTagFixer, NoBlankLinesBeforeNamespaceFixer - fix priority (SpacePossum) +* minor #1807 Tokens - simplify isLambda() (gharlan) + +Changelog for v1.11.2 +--------------------- + +* bug #1776 EofEndingFixer - new line on end line comment is allowed (Slamdunk) +* bug #1775 FileCacheManager - ignore corrupted serialized data (keradus) +* bug #1769 FunctionDeclarationFixer - fix more cases (keradus) +* bug #1747 Fixer - Fix ordering of fixer when both level and custom fixers are used (SpacePossum) +* bug #1744 Fixer - fix rare situation when file was visited twice (keradus) +* bug #1710 LowercaseConstantFixer - Fix comment cases. (SpacePossum) +* bug #1711 FunctioncallSpaceFixer - do not touch function declarations. (SpacePossum) +* minor #1798 LintManager - meaningful tempnam (Slamdunk) +* minor #1759 UniqueFileIterator - performance improvement (GrahamCampbell) +* minor #1745 appveyor - fix build (keradus) + +Changelog for v1.11.1 +--------------------- + +* bug #1680 NewWithBracesFixer - End tags (SpacePossum) +* bug #1685 EmptyReturnFixer - Make independent of LowercaseConstantsFixer (SpacePossum) +* bug #1640 IntegrationTest - fix directory separator (keradus) +* bug #1595 ShortTagFixer - fix priority (keradus) +* bug #1576 SpacesBeforeSemicolonFixer - do not remove space before semicolon if that space is after a semicolon (SpacePossum) +* bug #1570 UnneededControlParenthesesFixer - fix test samples (keradus) +* minor #1653 Update license year (gharlan) + +Changelog for v1.11 +------------------- + +* feature #1550 Added UnneededControlParenthesesFixer (Soullivaneuh, keradus) +* feature #1532 Added ShortBoolCastFixer (SpacePossum) +* feature #1523 Added EchoToPrintFixer and PrintToEchoFixer (Soullivaneuh) +* feature #1552 Warn when running with xdebug extension (SpacePossum) +* feature #1484 Added ArrayElementNoSpaceBeforeCommaFixer and ArrayElementWhiteSpaceAfterCommaFixer (amarczuk) +* feature #1449 PhpUnitConstructFixer - Fix more use cases (SpacePossum) +* feature #1382 Added PhpdocTypesFixer (GrahamCampbell) +* feature #1384 Add integration tests (SpacePossum) +* feature #1349 Added FunctionTypehintSpaceFixer (keradus) +* minor #1562 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1560 Fixed project name in xdebug warning (gharlan) +* minor #1545 Fix invalid PHP code samples in utests (SpacePossum) +* minor #1554 Alphabetically sort entries in .gitignore (GrahamCampbell) +* minor #1527 Refactor the way types work on annotations (GrahamCampbell) +* minor #1546 Update coding guide in cookbook (keradus) +* minor #1526 Support more annotations when fixing types in phpdoc (GrahamCampbell) +* minor #1535 clean ups (SpacePossum) +* minor #1510 Added Symfony 3.0 support (Ener-Getick) +* minor #1520 Code grooming (keradus) +* minor #1515 Support property, property-read and property-write tags (GrahamCampbell) +* minor #1488 Added more inline phpdoc tests (GrahamCampbell) +* minor #1496 Add docblock to AbstractFixerTestBase::makeTest (lmanzke) +* minor #1467 PhpdocShortDescriptionFixer - add support for Japanese sentence-ending characters (fritz-c) +* minor #1453 remove calling array_keys in foreach loops (keradus) +* minor #1448 Code grooming (keradus) +* minor #1437 Added import fixers integration test (GrahamCampbell) +* minor #1433 phpunit.xml.dist - disable gc (keradus) +* minor #1427 Change arounded to surrounded in README.rst (36degrees) +* minor #1420 AlignDoubleArrowFixer, AlignEqualsFixer - add integration tests (keradus) +* minor #1423 appveyor.yml - do not cache C:\tools, its internal forAppVeyor (keradus) +* minor #1400 appveyor.yml - add file (keradus) +* minor #1396 AbstractPhpdocTypesFixer - instance method should be called on instance (keradus) +* minor #1395 code grooming (keradus) +* minor #1393 boost .travis.yml file (keradus) +* minor #1372 Don't allow PHP 7 to fail (GrahamCampbell) +* minor #1332 PhpUnitConstructFixer - fix more functions (keradus) +* minor #1339 CONTRIBUTING.md - add link to PSR-5 (keradus) +* minor #1346 Core grooming (SpacePossum) +* minor #1328 Tokens: added typehint for Iterator elements (gharlan) + +Changelog for v1.10.3 +--------------------- + +* bug #1559 WhitespacyLinesFixer - fix bug cases (SpacePossum, keradus) +* bug #1541 Psr0Fixer - Ignore filenames that are a reserved keyword or predefined constant (SpacePossum) +* bug #1537 Psr0Fixer - ignore file without name or with name started by digit (keradus) +* bug #1516 FixCommand - fix wrong message for dry-run (SpacePossum) +* bug #1486 ExtraEmptyLinesFixer - Remove extra lines after comment lines too (SpacePossum) +* bug #1503 Psr0Fixer - fix case with comments lying around (GrahamCampbell) +* bug #1474 PhpdocToCommentFixer - fix not properly fixing for block right after namespace (GrahamCampbell) +* bug #1478 BracesFixer - do not remove empty lines after class opening (keradus) +* bug #1468 Add missing ConfigInterface::getHideProgress() (Eugene Leonovich, rybakit) +* bug #1466 Fix bad indent on align double arrow fixer (Soullivaneuh, keradus) +* bug #1479 Tokens - fix detection of short array (keradus) + +Changelog for v1.10.2 +--------------------- + +* bug #1461 PhpUnitConstructFixer - fix case when first argument is an expression (keradus) +* bug #1460 AlignDoubleArrowFixer - fix handling of nested arrays (Soullivaneuh, keradus) + +Changelog for v1.10.1 +--------------------- + +* bug #1424 Fixed the import fixer priorities (GrahamCampbell) +* bug #1444 OrderedUseFixer - fix next case (keradus) +* bug #1441 BracesFixer - fix next case (keradus) +* bug #1422 AlignDoubleArrowFixer - fix handling of nested array (SpacePossum) +* bug #1425 PhpdocInlineTagFixerTest - fix case when met inalid PHPDoc (keradus) +* bug #1419 AlignDoubleArrowFixer, AlignEqualsFixer - fix priorities (keradus) +* bug #1415 BlanklineAfterOpenTagFixer - Do not add a line break if there is one already. (SpacePossum) +* bug #1410 PhpdocIndentFixer - Fix for open tag (SpacePossum) +* bug #1401 PhpdocVarWithoutNameFixer - Fixed the var without name fixer for inline docs (keradus, GrahamCampbell) +* bug #1369 Fix not well-formed XML output (junichi11) +* bug #1356 Psr0Fixer - disallow run on StdinFileInfo (keradus) + +Changelog for v1.10 +------------------- + +* feature #1306 Added LogicalNotOperatorsWithSuccessorSpaceFixer (phansys) +* feature #1286 Added PhpUnitConstructFixer (keradus) +* feature #1316 Added PhpdocInlineTagFixer (SpacePossum, keradus) +* feature #1303 Added LogicalNotOperatorsWithSpacesFixer (phansys) +* feature #1279 Added PhpUnitStrictFixer (keradus) +* feature #1267 SingleQuoteFixer fix more use cases (SpacePossum) +* minor #1319 PhpUnitConstructFixer - fix performance and add to local .php_cs (keradus) +* minor #1280 Fix non-utf characters in docs (keradus) +* minor #1274 Cookbook - No change auto-test note (Soullivaneuh) + +Changelog for v1.9.3 +-------------------- + +* bug #1327 DocBlock\Tag - keep the case of tags (GrahamCampbell) + +Changelog for v1.9.2 +-------------------- + +* bug #1313 AlignDoubleArrowFixer - fix aligning after UTF8 chars (keradus) +* bug #1296 PhpdocScalarFixer - fix property annotation too (GrahamCampbell) +* bug #1299 WhitespacyLinesFixer - spaces on next valid line must not be fixed (Slamdunk) + +Changelog for v1.9.1 +-------------------- + +* bug #1288 TrimArraySpacesFixer - fix moving first comment (keradus) +* bug #1287 PhpdocParamsFixer - now works on any indentation level (keradus) +* bug #1278 Travis - fix PHP7 build (keradus) +* bug #1277 WhitespacyLinesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus) +* bug #1224 TrailingSpacesFixer - stop changing non-whitespacy tokens (SpacePossum, SamBurns-awin, keradus) +* bug #1266 FunctionCallSpaceFixer - better detection of function call (funivan) +* bug #1255 make sure some phpdoc fixers are run in right order (SpacePossum) + +Changelog for v1.9 +------------------ + +* feature #1097 Added ShortEchoTagFixer (vinkla) +* minor #1238 Fixed error handler to respect current error_reporting (JanJakes) +* minor #1234 Add class to exception message, use sprintf for exceptions (SpacePossum) +* minor #1210 set custom error handler for application run (keradus) +* minor #1214 Tokens::isMonolithicPhp - enhance performance (keradus) +* minor #1207 Update code documentation (keradus) +* minor #1202 Update IDE tool urls (keradus) +* minor #1195 PreIncrementFixer - move to Symfony level (gharlan) + +Changelog for v1.8.1 +-------------------- + +* bug #1193 EofEndingFixer - do not add an empty line at EOF if the PHP tags have been closed (SpacePossum) +* bug #1209 PhpdocParamsFixer - fix corrupting following custom annotation (keradus) +* bug #1205 BracesFixer - fix missing indentation fixes for class level (keradus) +* bug #1204 Tag - fix treating complex tag as simple PhpDoc tag (keradus) +* bug #1198 Tokens - fixed unary/binary operator check for type-hinted reference arguments (gharlan) +* bug #1201 Php4ConstructorFixer - fix invalid handling of subnamespaces (gharlan) +* minor #1221 Add more tests (SpacePossum) +* minor #1216 Tokens - Add unit test for array detection (SpacePossum) + +Changelog for v1.8 +------------------ + +* feature #1168 Added UnalignEqualsFixer (keradus) +* feature #1167 Added UnalignDoubleArrowFixer (keradus) +* bug #1169 ToolInfo - Fix way to find script dir (sp-ian-monge) +* minor #1181 composer.json - Update description (SpacePossum) +* minor #1180 create Tokens::overrideAt method (keradus) + +Changelog for v1.7.1 +-------------------- + +* bug #1165 BracesFixer - fix bug when comment is a first statement in control structure without braces (keradus) + +Changelog for v1.7 +------------------ + +* feature #1113 Added PreIncrementFixer (gharlan) +* feature #1144 Added PhpdocNoAccessFixer (GrahamCampbell) +* feature #1116 Added SelfAccessorFixer (gharlan) +* feature #1064 OperatorsSpacesFixer enhancements (gharlan) +* bug #1151 Prevent token collection corruption by fixers (stof, keradus) +* bug #1152 LintManager - fix handling of temporary file (keradus) +* bug #1139 NamespaceNoLeadingWhitespaceFixer - remove need for ctype extension (keradus) +* bug #1117 Tokens - fix iterator used with foreach by reference (keradus) +* minor #1148 code grooming (keradus) +* minor #1142 We are actually PSR-4, not PSR-0 (GrahamCampbell) +* minor #1131 Phpdocs and typos (SpacePossum) +* minor #1069 state min HHVM version (keradus) +* minor #1129 [DX] Help developers choose the right branch (SpacePossum) +* minor #1138 PhpClosingTagFixer - simplify flow, no need for loop (keradus) +* minor #1123 Reference mismatches fixed, SCA (kalessil) +* minor #1109 SingleQuoteFixer - made fixer more accurate (gharlan) +* minor #1110 code grooming (kalessil) + +Changelog for v1.6.2 +-------------------- + +* bug #1149 UnusedUseFixer - must be run before LineAfterNamespaceFixer, fix token collection corruption (keradus) +* minor #1145 AbstractLinesBeforeNamespaceFixer - fix docs for fixLinesBeforeNamespace (GrahamCampbell) + +Changelog for v1.6.1 +-------------------- + +* bug #1108 UnusedUseFixer - fix false positive when name is used as part of another namespace (gharlan) +* bug #1114 Fixed PhpdocParamsFixer with malformed doc block (gharlan) +* minor #1135 PhpdocTrimFixer - fix doc typo (localheinz) +* minor #1093 Travis - test lowest dependencies (boekkooi) + +Changelog for v1.6 +------------------ + +* feature #1089 Added NewlineAfterOpenTagFixer and BlanklineAfterOpenTagFixer (ceeram, keradus) +* feature #1090 Added TrimArraySpacesFixer (jaredh159, keradus) +* feature #1058 Added SingleQuoteFixer (gharlan) +* feature #1059 Added LongArraySyntaxFixer (gharlan) +* feature #1037 Added PhpdocScalarFixer (GrahamCampbell, keradus) +* feature #1028 Add ListCommasFixer (keradus) +* bug #1047 Utils::camelCaseToUnderscore - fix regexp (odin-delrio) +* minor #1073 ShortTagFixer enhancement (gharlan) +* minor #1079 Use LongArraySyntaxFixer for this repo (gharlan) +* minor #1070 Tokens::isMonolithicPhp - remove unused T_CLOSE_TAG search (keradus) +* minor #1049 OrderedUseFixer - grooming (keradus) + +Changelog for v1.5.2 +-------------------- + +* bug #1025 Fixer - ignore symlinks (kix) +* bug #1071 Psr0Fixer - fix bug for fixing file with long extension like .class.php (keradus) +* bug #1080 ShortTagFixer - fix false positive (gharlan) +* bug #1066 Php4ConstructorFixer - fix causing infinite recursion (mbeccati) +* bug #1056 VisibilityFixer - fix T_VAR with multiple props (localheinz, keradus) +* bug #1065 Php4ConstructorFixer - fix detection of a PHP4 parent constructor variant (mbeccati) +* bug #1060 Tokens::isShortArray: tests and bugfixes (gharlan) +* bug #1057 unused_use: fix false positive when name is only used as variable name (gharlan) + +Changelog for v1.5.1 +-------------------- + +* bug #1054 VisibilityFixer - fix var with array value assigned (localheinz, keradus) +* bug #1048 MultilineArrayTrailingCommaFixer, SingleArrayNoTrailingCommaFixer - using heredoc inside array not cousing to treat it as multiline array (keradus) +* bug #1043 PhpdocToCommentFixer - also check other control structures, besides foreach (ceeram) +* bug #1045 OrderedUseFixer - fix namespace order for trailing digits (rusitschka) +* bug #1035 PhpdocToCommentFixer - Add static as valid keyword for structural element (ceeram) +* bug #1020 BracesFixer - fix missing braces for nested if elseif else (malengrin) +* minor #1036 Added php7 to travis build (fonsecas72) +* minor #1026 Fix typo in ShortArraySyntaxFixer (tommygnr) +* minor #1024 code grooming (keradus) + +Changelog for v1.5 +------------------ + +* feature #887 Added More Phpdoc Fixers (GrahamCampbell, keradus) +* feature #1002 Add HeaderCommentFixer (ajgarlag) +* feature #974 Add EregToPregFixer (mbeccati) +* feature #970 Added Php4ConstructorFixer (mbeccati) +* feature #997 Add PhpdocToCommentFixer (ceeram, keradus) +* feature #932 Add NoBlankLinesAfterClassOpeningFixer (ceeram) +* feature #879 Add SingleBlankLineBeforeNamespaceFixer and NoBlankLinesBeforeNamespaceFixer (GrahamCampbell) +* feature #860 Add single_line_after_imports fixer (ceeram) +* minor #1014 Fixed a few file headers (GrahamCampbell) +* minor #1011 Fix HHVM as it works different than PHP (keradus) +* minor #1010 Fix invalid UTF-8 char in docs (ajgarlag) +* minor #1003 Fix header comment in php files (ajgarlag) +* minor #1005 Add Utils::calculateBitmask method (keradus) +* minor #973 Add Tokens::findSequence (mbeccati) +* minor #991 Longer explanation of how to use blacklist (bmitch, networkscraper) +* minor #972 Add case sensitive option to the tokenizer (mbeccati) +* minor #986 Add benchmark script (dericofilho) +* minor #985 Fix typo in COOKBOOK-FIXERS.md (mattleff) +* minor #978 Token - fix docs (keradus) +* minor #957 Fix Fixers methods order (GrahamCampbell) +* minor #944 Enable caching of composer downloads on Travis (stof) +* minor #941 EncodingFixer - enhance tests (keradus) +* minor #938 Psr0Fixer - remove unneded assignment (keradus) +* minor #936 FixerTest - test description consistency (keradus) +* minor #933 NoEmptyLinesAfterPhpdocsFixer - remove unneeded code, clarify description (ceeram) +* minor #934 StdinFileInfo::getFilename - Replace phpdoc with normal comment and add back empty line before return (ceeram) +* minor #927 Exclude the resources folder from coverage reports (GrahamCampbell) +* minor #926 Update Token::isGivenKind phpdoc (GrahamCampbell) +* minor #925 Improved AbstractFixerTestBase (GrahamCampbell) +* minor #922 AbstractFixerTestBase::makeTest - test if input is different than expected (keradus) +* minor #904 Refactoring Utils (GrahamCampbell) +* minor #901 Improved Readme Formatting (GrahamCampbell) +* minor #898 Tokens::getImportUseIndexes - simplify function (keradus) +* minor #897 phpunit.xml.dist - split testsuite (keradus) + +Changelog for v1.4.2 +-------------------- + +* bug #994 Fix detecting of short arrays (keradus) +* bug #995 DuplicateSemicolonFixer - ignore duplicated semicolons inside T_FOR (keradus) + +Changelog for v1.4.1 +-------------------- + +* bug #990 MultilineArrayTrailingCommaFixer - fix case with short array on return (keradus) +* bug #975 NoEmptyLinesAfterPhpdocsFixer - fix only when documentation documents sth (keradus) +* bug #976 PhpdocIndentFixer - fix error when there is a comment between docblock and next meaningful token (keradus, ceeram) + +Changelog for v1.4 +------------------ + +* feature #841 PhpdocParamsFixer: added aligning var/type annotations (GrahamCampbell) +* bug #965 Fix detection of lambda function that returns a reference (keradus) +* bug #962 PhpdocIndentFixer - fix bug when documentation is on the end of braces block (keradus) +* bug #961 Fixer - fix handling of empty file (keradus) +* bug #960 IncludeFixer - fix bug when include is part of condition statement (keradus) +* bug #954 AlignDoubleArrowFixer - fix new buggy case (keradus) +* bug #955 ParenthesisFixer - fix case with list call with trailing comma (keradus) +* bug #950 Tokens::isLambda - fix detection near comments (keradus) +* bug #951 Tokens::getImportUseIndexes - fix detection near comments (keradus) +* bug #949 Tokens::isShortArray - fix detection near comments (keradus) +* bug #948 NewWithBracesFixer - fix case with multidimensional array (keradus) +* bug #945 Skip files containing __halt_compiler() on PHP 5.3 (stof) +* bug #946 BracesFixer - fix typo in exception name (keradus) +* bug #940 Tokens::setCode - apply missing transformation (keradus) +* bug #908 BracesFixer - fix invalide inserting brace for control structure without brace and lambda inside of it (keradus) +* bug #903 NoEmptyLinesAfterPhpdocsFixer - fix bug with Windows style lines (GrahamCampbell) +* bug #895 [PSR-2] Preserve blank line after control structure opening brace (marcaube) +* bug #892 Fixed the double arrow multiline whitespace fixer (GrahamCampbell) +* bug #874 BracesFixer - fix bug of removing empty lines after class' opening { (ceeram) +* bug #868 BracesFixer - fix missing braces when statement is not followed by ; (keradus) +* bug #861 Updated PhpdocParamsFixer not to change line endings (keradus, GrahamCampbell) +* bug #837 FixCommand - stop corrupting xml/json format (keradus) +* bug #846 Made phpdoc_params run after phpdoc_indent (GrahamCampbell) +* bug #834 Correctly handle tab indentation (ceeram) +* bug #822 PhpdocIndentFixer - Ignore inline docblocks (ceeram) +* bug #813 MultilineArrayTrailingCommaFixer - do not move array end to new line (keradus) +* bug #817 LowercaseConstantsFixer - ignore class' constants TRUE/FALSE/NULL (keradus) +* bug #821 JoinFunctionFixer - stop changing declaration method name (ceeram) +* minor #963 State the minimum version of PHPUnit in CONTRIBUTING.md (SpacePossum) +* minor #943 Improve the cookbook to use relative links (stof) +* minor #921 Add changelog file (keradus) +* minor #909 BracesFixerTest - no \n line in \r\n test (keradus) +* minor #864 Added NoEmptyLinesAfterPhpdocsFixer (GrahamCampbell) +* minor #871 Added missing author (GrahamCampbell) +* minor #852 Fixed the coveralls version constraint (GrahamCampbell) +* minor #863 Tweaked testRetainsNewLineCharacters (GrahamCampbell) +* minor #849 Removed old alias (GrahamCampbell) +* minor #843 integer should be int (GrahamCampbell) +* minor #830 Remove whitespace before opening tag (ceeram) +* minor #835 code grooming (keradus) +* minor #828 PhpdocIndentFixerTest - code grooming (keradus) +* minor #827 UnusedUseFixer - code grooming (keradus) +* minor #825 improve code coverage (keradus) +* minor #810 improve code coverage (keradus) +* minor #811 ShortArraySyntaxFixer - remove not needed if statement (keradus) + +Changelog for v1.3 +------------------ + +* feature #790 Add docblock indent fixer (ceeram) +* feature #771 Add JoinFunctionFixer (keradus) +* bug #798 Add DynamicVarBrace Transformer for properly handling ${$foo} syntax (keradus) +* bug #796 LowercaseConstantsFixer - rewrite to handle new test cases (keradus) +* bug #789 T_CASE is not succeeded by parentheses (dericofilho) +* minor #814 Minor improvements to the phpdoc_params fixer (GrahamCampbell) +* minor #815 Minor fixes (GrahamCampbell) +* minor #782 Cookbook on how to make a new fixer (dericofilho) +* minor #806 Fix Tokens::detectBlockType call (keradus) +* minor #758 travis - disable sudo (keradus) +* minor #808 Tokens - remove commented code (keradus) +* minor #802 Address Sensiolabs Insight's warning of code cloning. (dericofilho) +* minor #803 README.rst - fix \` into \`\` (keradus) + +Changelog for v1.2 +------------------ + +* feature #706 Remove lead slash (dericofilho) +* feature #740 Add EmptyReturnFixer (GrahamCampbell) +* bug #775 PhpClosingTagFixer - fix case with T_OPEN_TAG_WITH_ECHO (keradus) +* bug #756 Fix broken cases for AlignDoubleArrowFixer (dericofilho) +* bug #763 MethodArgumentSpaceFixer - fix receiving data in list context with omitted values (keradus) +* bug #759 Fix Tokens::isArrayMultiLine (stof, keradus) +* bug #754 LowercaseKeywordsFixer - __HALT_COMPILER must not be lowercased (keradus) +* bug #753 Fix for double arrow misalignment in deeply nested arrays. (dericofilho) +* bug #752 OrderedUseFixer should be case-insensitive (rusitschka) +* minor #779 Fixed a docblock type (GrahamCampbell) +* minor #765 Typehinting in FileCacheManager, remove unused variable in Tokens (keradus) +* minor #764 SelfUpdateCommand - get local version only if remote version was successfully obtained (keradus) +* minor #761 aling => (keradus) +* minor #757 Some minor code simplify and extra test (keradus) +* minor #713 Download php-cs-fixer.phar without sudo (michaelsauter) +* minor #742 Various Minor Improvements (GrahamCampbell) + +Changelog for v1.1 +------------------ + +* feature #749 remove the --no-progress option (replaced by the standard -v) (fabpot, keradus) +* feature #728 AlignDoubleArrowFixer - standardize whitespace after => (keradus) +* feature #647 Add DoubleArrowMultilineWhitespacesFixer (dericofilho, keradus) +* bug #746 SpacesBeforeSemicolonFixerTest - fix bug with semicolon after comment (keradus) +* bug #741 Fix caching when composer is installed in custom path (cmodijk) +* bug #725 DuplicateSemicolonFixer - fix clearing whitespace after duplicated semicolon (keradus) +* bug #730 Cache busting when fixers list changes (Seldaek) +* bug #722 Fix lint for STDIN-files (ossinkine) +* bug #715 TrailingSpacesFixer - fix bug with french UTF-8 chars (keradus) +* bug #718 Fix package name for composer cache (Seldaek) +* bug #711 correct vendor name (keradus) +* minor #745 Show progress by default and allow to disable it (keradus) +* minor #731 Add a way to disable all default filters and really provide a whitelist (Seldaek) +* minor #737 Extract tool info into new class, self-update command works now only for PHAR version (keradus) +* minor #739 fix fabbot issues (keradus) +* minor #726 update CONTRIBUTING.md for installing dependencies (keradus) +* minor #736 Fix fabbot issues (GrahamCampbell) +* minor #727 Fixed typos (pborreli) +* minor #719 Add update instructions for composer and caching docs (Seldaek) + +Changelog for v1.0 +------------------ + +First stable release. diff --git a/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md b/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md new file mode 100644 index 00000000000..a9c27e34ed0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/CONTRIBUTING.md @@ -0,0 +1,104 @@ +# Contributions Are Welcome! + +If you need any help, don't hesitate to ask the community on [Gitter](https://gitter.im/PHP-CS-Fixer/Lobby). + +## Quick Guide + +### Fixer + +A *fixer* is a class that tries to fix one code style issue (a ``Fixer`` class +must implement ``FixerInterface``). + +### Config + +A *config* knows about the code style rules and the files and directories that +must be scanned by the tool when run in the directory of your project. It is +useful for projects that follow a well-known directory structures (like for +Symfony projects for instance). + +### How-To + +* [Fork](https://help.github.com/articles/fork-a-repo/) the repo. +* [Checkout](https://git-scm.com/docs/git-checkout) the branch you want to make changes on: + * If you are fixing a bug or typo, improving tests or for any small tweak: the lowest branch where the changes can be applied. Once your Pull Request is accepted, the changes will get merged up to highest branches. + * `master` in other cases (new feature, deprecation, or backwards compatibility breaking changes). Note that most of the time, `master` represents the next minor release of PHP CS Fixer, so Pull Requests that break backwards compatibility might be postponed. +* Install dependencies: `composer install`. +* Create a new branch, e.g. `feature-foo` or `bugfix-bar`. +* Make changes. +* If you are adding functionality or fixing a bug - add a test! Prefer adding new test cases over modifying existing ones. +* Make sure there is no wrong file permissions in the repository: `./dev-tools/check_file_permissions.sh`. +* Make sure there is no trailing spaces in the code: `./dev-tools/check_trailing_spaces.sh`. +* Update documentation: `php dev-tools/doc.php`. This requires the highest version of PHP supported by PHP CS Fixer. If it is not installed on your system, you can run it in a Docker container instead: `docker-compose run php-8.2 php dev-tools/doc.php`. +* Install dev tools: `dev-tools/install.sh` +* Run static analysis using PHPStan: `php -d memory_limit=256M dev-tools/vendor/bin/phpstan analyse` +* Check if tests pass: `vendor/bin/phpunit`. +* Fix project itself: `php php-cs-fixer fix`. + +## Working With Docker + +This project provides a Docker setup that allows working on it using any of the supported PHP versions. + +To use it, you first need to install: + + * [Docker](https://docs.docker.com/get-docker/) + * [Docker Compose](https://docs.docker.com/compose/install/) + +Make sure the versions installed support [Compose file format 3.8](https://docs.docker.com/compose/compose-file/). + +Next, copy [`docker-compose.override.yaml.dist`](./docker-compose.override.yaml.dist) to `docker-compose.override.yaml` +and edit it to your needs. The relevant parameters that might require some tweaking have comments to help you. + +You can then build the images: + +```console +docker-compose build --parallel +``` + +Now you can run commands needed to work on the project. For example, say you want to run PHPUnit tests on PHP 7.4: + +```console +docker-compose run php-7.4 vendor/bin/phpunit +``` + +Sometimes it can be more convenient to have a shell inside the container: + +```console +docker-compose run php-7.4 sh +/app vendor/bin/phpunit +``` + +The images come with an [`xdebug` script](github.com/julienfalque/xdebug/) that allows running any PHP command with +Xdebug enabled to help debug problems. + +```console +docker-compose run php-7.4 xdebug vendor/bin/phpunit +``` + +If you're using PhpStorm, you need to create a [server](https://www.jetbrains.com/help/phpstorm/servers.html) with a +name that matches the `PHP_IDE_CONFIG` environment variable defined in the Docker Compose configuration files, which is +`php-cs-fixer` by default. + +All images use port 9003 for debug connections. + +## Opening a [Pull Request](https://help.github.com/articles/about-pull-requests/) + +You can do some things to increase the chance that your Pull Request is accepted the first time: + +* Submit one Pull Request per fix or feature. +* If your changes are not up to date, [rebase](https://git-scm.com/docs/git-rebase) your branch onto the parent branch. +* Follow the conventions used in the project. +* Remember about tests and documentation. +* Don't bump version. + +## Making New Fixers + +There is a [cookbook](doc/cookbook_fixers.rst) with basic instructions on how to build a new fixer. Consider reading it +before opening a PR. + +## Project's Standards + +* [PSR-1: Basic Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md) +* [PSR-2: Coding Style Guide](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md) +* [PSR-4: Autoloading Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md) +* [PSR-5: PHPDoc (draft)](https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md) +* [Symfony Coding Standards](https://symfony.com/doc/current/contributing/code/standards.html) diff --git a/vendor/friendsofphp/php-cs-fixer/LICENSE b/vendor/friendsofphp/php-cs-fixer/LICENSE new file mode 100644 index 00000000000..871def02eb9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012+ 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. diff --git a/vendor/friendsofphp/php-cs-fixer/README.md b/vendor/friendsofphp/php-cs-fixer/README.md new file mode 100644 index 00000000000..0be52542512 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/README.md @@ -0,0 +1,89 @@ +

+ + PHP CS Fixer logo + +

+ +PHP Coding Standards Fixer +========================== + +The PHP Coding Standards Fixer (PHP CS Fixer) tool fixes your code to follow standards; +whether you want to follow PHP coding standards as defined in the PSR-1, PSR-2, etc., +or other community driven ones like the Symfony one. +You can **also** define your (team's) style through configuration. + +It can modernize your code (like converting the ``pow`` function to the ``**`` operator on PHP 5.6) +and (micro) optimize it. + +If you are already using a linter to identify coding standards problems in your +code, you know that fixing them by hand is tedious, especially on large +projects. This tool does not only detect them, but also fixes them for you. + +## Supported PHP Versions + +* PHP 7.4 +* PHP 8.0 (except PHP 8.0.0 due to [bug in PHP tokenizer](https://bugs.php.net/bug.php?id=80462)) +* PHP 8.1 +* PHP 8.2 + +> **Note** +> Each new PHP version requires a huge effort to support the new syntax. +> That's why the latest PHP version might not be supported yet. If you need it, +> please, consider supporting the project in any convenient way, for example +> with code contribution or reviewing existing PRs. To run PHP CS Fixer on yet +> unsupported versions "at your own risk" - leverage the +> [PHP_CS_FIXER_IGNORE_ENV](./doc/usage.rst#environment-options). + +## Documentation + +### Installation + +The recommended way to install PHP CS Fixer is to use [Composer](https://getcomposer.org/download/) +in a dedicated `composer.json` file in your project, for example in the +`tools/php-cs-fixer` directory: + +```console +mkdir -p tools/php-cs-fixer +composer require --working-dir=tools/php-cs-fixer friendsofphp/php-cs-fixer +``` + +For more details and other installation methods, see +[installation instructions](./doc/installation.rst). + +### Usage + +Assuming you installed PHP CS Fixer as instructed above, you can run the +following command to fix the files PHP files in the `src` directory: + +```console +tools/php-cs-fixer/vendor/bin/php-cs-fixer fix src +``` + +See [usage](./doc/usage.rst), list of [built-in rules](./doc/rules/index.rst), list of [rule sets](./doc/ruleSets/index.rst) +and [configuration file](./doc/config.rst) documentation for more details. + +If you need to apply code styles that are not supported by the tool, you can +[create custom rules](./doc/custom_rules.rst). + +## Editor Integration + +Dedicated plugins exist for: + +* [NetBeans](https://plugins.netbeans.apache.org/catalogue/?id=36) +* [PhpStorm](https://www.jetbrains.com/help/phpstorm/using-php-cs-fixer.html) +* [Sublime Text](https://github.com/benmatselby/sublime-phpcs) +* [Vim](https://github.com/stephpy/vim-php-cs-fixer) +* [VS Code](https://github.com/junstyle/vscode-php-cs-fixer) + +## Community + +The PHP CS Fixer is maintained on GitHub at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer. +Bug reports and ideas about new features are welcome there. + +You can reach us at https://gitter.im/PHP-CS-Fixer/Lobby about the project, +configuration, possible improvements, ideas and questions, please visit us! + +## Contribute + +The tool comes with quite a few built-in fixers, but everyone is more than +welcome to [contribute](CONTRIBUTING.md) more of them. diff --git a/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md b/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md new file mode 100644 index 00000000000..00e0a9c5d94 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/UPGRADE-v3.md @@ -0,0 +1,167 @@ +UPGRADE GUIDE FROM 2.x to 3.0 +============================= + +This is guide for upgrade from version 2.x to 3.0 for using the CLI tool. + +*Before following this guide, install [v2.19](https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases/tag/v2.19.0) and run in verbose mode (`php-cs-fixer fix -v`) or in future mode (`PHP_CS_FIXER_FUTURE_MODE=1 php-cs-fixer fix`) to identify deprecations and fix them first.* + +Rename of files +--------------- + +| 2.x | 3.0 | Description | +| ---------------- | ------------------------ | -------------------------------------- | +| `.php_cs` | `.php-cs-fixer.php` | Configuration file (local) | +| `.php_cs.dist` | `.php-cs-fixer.dist.php` | Configuration file (to be distributed) | +| `.php_cs.cache` | `.php-cs-fixer.cache` | Cache file | + +CLI options +----------- + +| 2.x | 3.0 | Description | Note | +| ---------------- | --------------- | ----------------------------------------------- | -------------------------------------- | +| --diff-format | | Type of differ | Option was removed, all diffs are now | +| | | | `udiff` | +| --show-progress | --show-progress | Type of progress indicator | Allowed values were modified: | +| | | | `run-in` and `estimating` was removed, | +| | | | `estimating-max` was renamed to `dots` | +| --rules | --rules | Default value changed from @PSR2 to @PSR12 | | +| --config --rules | | | No longer allowed to pass both | + +Changes to rules +---------------- + +### Renamed rules + +Old name | New name | Note +-------- | -------- | ---- +`blank_line_before_return` | `blank_line_before_statement` | use configuration `['statements' => ['return']]` +`final_static_access` | `self_static_accessor` | +`hash_to_slash_comment` | `single_line_comment_style` | use configuration `['comment_types' => ['hash']]` +`lowercase_constants` | `constant_case` | use configuration `['case' => 'lower']` +`method_separation` | `class_attributes_separation` | use configuration `['elements' => ['method']]` +`no_extra_consecutive_blank_lines` | `no_extra_blank_lines` | +`no_multiline_whitespace_before_semicolons` | `multiline_whitespace_before_semicolons` | +`no_short_echo_tag` | `echo_tag_syntax` | use configuration `['format' => 'long']` +`php_unit_ordered_covers` | `phpdoc_order_by_value` | use configuration `['annotations' => [ 'covers' ]]` +`phpdoc_inline_tag` | `general_phpdoc_tag_rename`, `phpdoc_inline_tag_normalizer` and `phpdoc_tag_type` | +`pre_increment` | `increment_style` | use configuration `['style' => 'pre']` +`psr0` | `psr_autoloading` | use configuration `['dir' => x ]` +`psr4` | `psr_autoloading` | +`silenced_deprecation_error` | `error_suppression` | +`trailing_comma_in_multiline_array` | `trailing_comma_in_multiline` | use configuration `['elements' => ['arrays']]` + +### Removed rootless configuration + +Rule | Root option | Note +------------------------------------ | -------------- | ---- +`general_phpdoc_annotation_remove` | `annotations` +`no_extra_consecutive_blank_lines` | `tokens` +`no_spaces_around_offset` | `positions` +`no_unneeded_control_parentheses` | `statements` +`ordered_class_elements` | `order` +`php_unit_construct` | `assertions` +`php_unit_dedicate_assert` | `target` | root option works differently than rootless configuration +`php_unit_strict` | `assertions` +`phpdoc_no_alias_tag` | `replacements` +`phpdoc_return_self_reference` | `replacements` +`random_api_migration` | `replacements` +`single_class_element_per_statement` | `elements` +`visibility_required` | `elements` + +### Changed options + +Rule | Option | Change +---- | ------ | ------ +`binary_operator_spaces` | `align_double_arrow` | option was removed, use `operators` instead +`binary_operator_spaces` | `align_equals` | option was removed use `operators` instead +`blank_line_before_statement` | `statements: die` | option `die` was removed from `statements`, use `exit` instead +`class_attributes_separation` | `elements` | option does no longer accept flat array as a value, use map instead +`class_definition` | `multiLineExtendsEachSingleLine` | option was renamed to `multi_line_extends_each_single_line` +`class_definition` | `singleItemSingleLine` | option was renamed to `single_item_single_line` +`class_definition` | `singleLine` | option was renamed to `single_line` +`doctrine_annotation_spaces` | `around_argument_assignments` | option was removed, use `before_argument_assignments` and `after_argument_assignments` instead +`doctrine_annotation_spaces` | `around_array_assignments` | option was removed, use `after_array_assignments_colon`, `after_array_assignments_equals`, `before_array_assignments_colon` and `before_array_assignments_equals` instead +`final_internal_class` | `annotation-black-list` | option was renamed, use `annotation_exclude` +`final_internal_class` | `annotation-white-list` | option was renamed, use `annotation_include` +`final_internal_class` | `consider-absent-docblock-as-internal-class` | option was renamed, use `consider_absent_docblock_as_internal_class` +`header_comment` | `commentType` | option was renamed to `comment_type` +`is_null` | `use_yoda_style` | option was removed, use `yoda_style` rule instead +`no_extra_consecutive_blank_lines` | `tokens` | one of possible values, `useTrait`, was renamed to `use_trait` +`ordered_class_elements` | `sortAlgorithm` | option was renamed, use `sort_algorithm` instead +`ordered_imports` | `importsOrder` | option was renamed, use `imports_order` +`ordered_imports` | `sortAlgorithm` | option was renamed, use `sort_algorithm` +`php_unit_dedicate_assert` | `functions` | option was removed, use `target` instead +`php_unit_test_annotation` | `case` | option was removed, use `php_unit_method_casing` rule instead + +### Changed default values of options + +Rule | Option | Old value | New value +---- | ---- | ---- | ---- +`array_syntax` | `syntax` | `'long'` | `'short'` +`function_to_constant` | `functions` | `['get_class', 'php_sapi_name', 'phpversion', 'pi']` | `['get_called_class', 'get_class', 'php_sapi_name', 'phpversion', 'pi']` +`list_syntax` | `syntax` | `'long'` | `'short'` +`method_argument_space` | `on_multiline` | `'ignore'` | `'ensure_fully_multiline'` +`native_constant_invocation` | `strict` | `false` | `true` +`native_function_casing` | `include` | `'@internal'` | `'@compiler_optimized'` +`native_function_invocation` | `include` | `'@internal'` | `'@compiler_optimized'` +`native_function_invocation` | `strict` | `false` | `true` +`non_printable_character` | `use_escape_sequences_in_strings` | `false` | `true` (when running on PHP 7.0 and up) +`php_unit_dedicate_assert` | `target` | `'5.0'` | `'newest'` +`phpdoc_align` | `tags` | `['param', 'return', 'throws', 'type', 'var']` | `['method', 'param', 'property', 'return', 'throws', 'type', 'var']` +`phpdoc_scalar` | `types` | `['boolean', 'double', 'integer', 'real', 'str']` | `['boolean', 'callback', 'double', 'integer', 'real', 'str']` + +### Removed rule sets + +Rule set | Note +-------- | ---- +`@PHP56Migration` | was empty + +### Rule behavior changes + +- `no_unused_imports` now runs all files defined in the configuration (used to exclude some hardcoded directories) + +### Various + +- `udiff` output now includes the file name in the output (if applicable) + +Code BC changes +=============== + +### Removed; various + +- class `AbstractAlignFixerHelper` has been removed +- class `AccessibleObject` has been removed +- class `AlignDoubleArrowFixerHelper` has been removed +- class `AlignEqualsFixerHelper` has been removed +- class `FixerConfigurationResolverRootless` has been removed +- `HeaderCommentFixer` deprecated properties have been removed +- `MethodArgumentSpaceFixer` deprecated methods have been removed +- `NoMixedEchoPrintFixer` the property `$defaultConfig` has been removed +- class `Tokens`, the following methods has been removed: + - `current()` + - `key()` + - `next()` + - `rewind()` + - `valid()` +- namespace `PhpCsFixer\Test\` and each class in it has been removed, as it served pure development purpose and should not be part of production code - reach out to community if you are willing to help building dev package + +### Interface changes + +- `ConfigurableFixerInterface` has been updated +- `ConfigurationDefinitionFixerInterface` has been removed in favor of the updated `ConfigurableFixerInterface` +- `DefinedFixerInterface` has been removed, related methods are now part of the updated `FixerInterface` interface +- `DifferInterface` has been updated +- `FixerInterface` interface has been updated +- `PhpCsFixer\RuleSetInterface` has been removed in favor of `\PhpCsFixer\RuleSet\RuleSetInterface` + +### BC breaks; various + +- class `Token` is now `final` +- class `Tokens` is now `final` +- method `create` of class `Config` has been removed, [use the constructor](./doc/config.rst) +- method `create` of class `RuleSet` has been removed, [use the constructor](./doc/custom_rules.rst) + +### BC breaks; common internal classes + +- method `getClassyElements` of class `TokensAnalyzer` parameter `$returnTraitsImports` has been removed; now always returns trait import information +- method `getSetDefinitionNames` of class `RuleSet` has been removed, use `RuleSets::getSetDefinitionNames()` diff --git a/vendor/friendsofphp/php-cs-fixer/ci-integration.sh b/vendor/friendsofphp/php-cs-fixer/ci-integration.sh new file mode 100644 index 00000000000..2521e2494c9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/ci-integration.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +IFS=' +' +CHANGED_FILES=$(git diff --name-only --diff-filter=ACMRTUXB "${COMMIT_RANGE}") +if ! echo "${CHANGED_FILES}" | grep -qE "^(\\.php-cs-fixer(\\.dist)?\\.php|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-fixer.dist.php -v --dry-run --stop-on-violation --using-cache=no ${EXTRA_ARGS} diff --git a/vendor/friendsofphp/php-cs-fixer/composer.json b/vendor/friendsofphp/php-cs-fixer/composer.json new file mode 100644 index 00000000000..9f3be025463 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/composer.json @@ -0,0 +1,82 @@ +{ + "name": "friendsofphp\/php-cs-fixer", + "description": "A tool to automatically fix PHP code style", + "license": "MIT", + "type": "application", + "keywords": [ + "fixer", + "standards", + "static analysis", + "static code analysis" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Dariusz Rumi\u0144ski", + "email": "dariusz.ruminski@gmail.com" + } + ], + "require": { + "php": "^7.4 || ^8.0", + "ext-json": "*", + "ext-tokenizer": "*", + "composer\/semver": "^3.3", + "composer\/xdebug-handler": "^3.0.3", + "doctrine\/annotations": "^2", + "doctrine\/lexer": "^2 || ^3", + "sebastian\/diff": "^4.0 || ^5.0", + "symfony\/console": "^5.4 || ^6.0", + "symfony\/event-dispatcher": "^5.4 || ^6.0", + "symfony\/filesystem": "^5.4 || ^6.0", + "symfony\/finder": "^5.4 || ^6.0", + "symfony\/options-resolver": "^5.4 || ^6.0", + "symfony\/polyfill-mbstring": "^1.27", + "symfony\/polyfill-php80": "^1.27", + "symfony\/polyfill-php81": "^1.27", + "symfony\/process": "^5.4 || ^6.0", + "symfony\/stopwatch": "^5.4 || ^6.0" + }, + "require-dev": { + "facile-it\/paraunit": "^1.3 || ^2.0", + "justinrainbow\/json-schema": "^5.2", + "keradus\/cli-executor": "^2.0", + "mikey179\/vfsstream": "^1.6.11", + "php-coveralls\/php-coveralls": "^2.5.3", + "php-cs-fixer\/accessible-object": "^1.1", + "php-cs-fixer\/phpunit-constraint-isidenticalstring": "^1.2", + "php-cs-fixer\/phpunit-constraint-xmlmatchesxsd": "^1.2.1", + "phpspec\/prophecy": "^1.16", + "phpspec\/prophecy-phpunit": "^2.0", + "phpunit\/phpunit": "^9.5", + "phpunitgoodpractices\/polyfill": "^1.6", + "phpunitgoodpractices\/traits": "^1.9.2", + "symfony\/phpunit-bridge": "^6.2.3", + "symfony\/yaml": "^5.4 || ^6.0" + }, + "suggest": { + "ext-dom": "For handling output formats in XML", + "ext-mbstring": "For handling non-UTF8 characters." + }, + "autoload": { + "psr-4": { + "PhpCsFixer\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "PhpCsFixer\\Tests\\": "tests\/" + } + }, + "bin": [ + "php-cs-fixer" + ], + "config": { + "allow-plugins": { + "ergebnis\/composer-normalize": true + }, + "sort-packages": true + } +} \ No newline at end of file diff --git a/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst b/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst new file mode 100644 index 00000000000..e5959422cc7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/feature-or-bug.rst @@ -0,0 +1,24 @@ +========================== +Is it a feature or a bug ? +========================== + +Sometimes it's a bit tricky to define if given change proposal or change request is adding new feature or fixing existing issue. This document is providing more clarity about categorisation we use. + +Bug +--- + +Example of bugs: + +- crash during application or rule execution +- wrong changes are applied during "fixing codebase" process +- issue with generated report + +Feature +------- + +Example of features: + +- introduction of new rule +- enhancement of existing rule to cover more cases (for example adding support for newly introduced PHP syntax) +- introduction of new ruleset +- update of existing ruleset (for example adjusting it to match newest style of given community or adding newly implemented rule that was supposed to be followed by style of given community, yet not implemented as a rule before) diff --git a/vendor/friendsofphp/php-cs-fixer/logo.md b/vendor/friendsofphp/php-cs-fixer/logo.md new file mode 100644 index 00000000000..c2877f718a2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/logo.md @@ -0,0 +1,3 @@ +The logo is © 2010+ Sensio Labs. + +Original resolution can be found at https://github.com/PHP-CS-Fixer/logo . diff --git a/vendor/friendsofphp/php-cs-fixer/logo.png b/vendor/friendsofphp/php-cs-fixer/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..0ee90a821322b4bbb293cb466fd717f8a2ef44df GIT binary patch literal 18627 zcmd2?Wm6nouwL99f(Ccj;6XxQae}+E$l~skRYcl|VKHeu@7}zUH(r=(s$e4`mis>?>l*JtWlg|q8rxL|1a-~43?h~9mQ35W$ zR1aixbI^FMr(a70K|>7l1>oS|qU;=x{r(GAyU*QzHP-E()a@ML*D1vgf*CoW`Dx$kL#23QNT^SAThYVxV&W@sBfQq<@Zd^90ufw3XMAVQm&I{uQxbP zJojO#C*f{8ZF2;%0$+w)miBlj;KE*oxQq)_uKTcz^ZpJv64&SFVJl)u;i>)h_8Tw@ zx&CAh(KQ?Qy21~2TprjP<=xXD+PQEO9{cmfoZmhYn3+apGO zqW4DG9*)e@AXdapK1lBzvHi69B+U_1}PU zFBEYF0LTH-5@M?E%cmV~nbaB{tS{{cnPtbT!ZV2)_55HwETBIC3l%<$$+517mWbFo zXp5*AocVa_6^+%%u?ahXe;OH{5?#S8inLcT?f{~jym2mbUO$gLRuVQUHg{EDUMrRA znx9ZzP<7Loo0;@lN0bQ1q!15A#G?Fvbz|nAuYzd=xj?b=>VU%j3~NpMht~gUEY^`KOh;vk@Fya^5#B|lotFtwFcVaJWO&slac7)(BvI%K$o_k5kKaq|`_p?S#J5V- zxlKZoe`?(@KKB>YjWnfaXA-A0bvU9S2ms)crF>&2Xo7C`sm$TRTKj^f?tA|iBC&lU zL&(M}$3;^}O^F;|Db|h-@O#X5Yj2_BWT2AJgkQhhUx+W=W;32vME+FGjk@#BXhtyB zD#^Y^PTc)hJ19-eAGEJ%IiB-YTy1bJiHuJnPF$n4(t!Sf=1qSZOX zXD1iEDaUN)R&GYbQV6(je~sqwf95s{Chs&S8emH1{8yDUnuDvnT7pUi4`QFBA?;mg z-J>-bkRN-Be!qd7m{WyBVj7{ZzczyL{0*QY6tSt$?VD7Q$#qRr2RuPl%#vT=n|yzB z1$DF0{8j9D{%ltiZjVJ7ya2ZI6h=z0^UvLg9^BE$05L0&>rtux41VyS2u9~96Kjm) ziQw<-5p- z#Xx2;CJ=;b-_x^eQI`mg#DwZT_uf3yA-GX2vb@bGLINoS9p0j@mO}2pADPQ^EvX{0 zGS7k{qC6v&XIh%_sV0e&42$(o`rw)0Ew}~W`rk{2>gp<1WIv`mMOx}(mP}cgw}Ik< zi8V?Bi?uqXM1#O(VAqO7@UPAT8xdKoEy@b5)vGiEp43A(N2C+HHiS0BS!$$i7@1OD zi?fYC6(^Frfg=M>xU3C*<>%&{JLYMqc>jH`uX5p4ARbplOyXQaeRXjvLsB<_$O8bP z#q83P@lXW|FH;+rn*<+Jtzc?*L5yLzB0uanPaR&X<^T00aimqQ2G>Z+t-VN7Yyc5V z9e(IDMqqA>re?)eZ70I+>Nt)_{%I1n#mxpXI?Ls46-3Pa1{*fr+d zRJsshr;-YE{#H7Vf%Tt!J<)!b6qNaH*bxg1ObW2MbY|NTdC;kZ z_;)lE;opXbP-o@EvWdNR`o{)6kOwzAh?ZkNLPWlYv+}e5gRoh@$*r}YEPR32gFDn? zLBM)aK#IFgB;N3~-+oKuzL3{6ynPUw$cLXHL4seOr(nasvJ`03C1E+Pa6NI->P`;g ze1kjv7u|~~y2hlX(F8aAsgc;@$HZFySd-7|$wsu?2qGA!$!~ulA^;rGSFXmafLJ*b z*e-A15n7!o&4%X3TDCS>z){_yk3L zC~8x(a^U+dpwBKrRVUaIIz3~5J9G24XoBF%Ap!hHwdQk)Mh(Xa{3R?_D>kxXEG`GApMPki-e2qEB=XPaLX^t7n9$xCvn^5<)>Orx;lvc|d|vimT|zhq{IEby zOhVTiLBJ6Ub>H`qD4xXlZ)r46Su|VwqL#9oG{h?I&dq^LRh^h#7@4A_O5);J)KD_8 z7|_3Wp-5ryhJi$)0{{sssg{()(jQY}@zR7_LOf>NPZ1X!W;Cdn0T7I_AN8N=co-oW zyIimr`6$m0J*})lSFp$azo=1H~M(8@WUEgsl+GCLEnNm2ec#k$%$cryVo_-mQiOSiwQQPD6~DkwI@*WTW$?ZA%g~hKq5Fh zOOV6C8&RP&Ds*ai+(&yEjz#rh+z@`_&t{kD#Yxv)Z4M9RpYMFtJJ?V*76bUXVqc1Tdh#dRAhj%E&==_RD(9^WGFHTy%0 zxsH;HA4LMx`A-p%iG=r8-|3jpbFYQAxoJNxux)x$OTP2pdwAKSOsiG5e`+$TTppoJoDnl{#EVym^3CZltiQ-*(gE! z+iD#h3Xq%P3P{kCwn9_uTgJYrFm5i^s0(G<`JcaBUR!OpT&7CzE9qe>VN7U$Osy<^ zv40}73mTqDe%RzI)&wPXMo4aTL2K(5tBrU3Nr>G+4Ov%}MS2EDL)`gquV>fhs>lc` zDecd!6fV|3c*pYwYI}^h=g^mcm&O30?@=-m9~i+{OI4v3H9R%C=;~8$X}HT&thtjs z@TBFSt4>HWDw-a;xixti;^5m;j&#EzQU9Ke^L^7EW3-=LBKW`HQH=WS9oIhuyN}QL zaGsP#aA)&etqJ}$wXB{8;m4%vvSb1xqMohkWX!D*ssC*y6&JNo3*$e5qc?m%0H(MHFvFBPm9bWz=TzCJUSB_Znq;L4Rl`Fw)#BQw3ndQFS7_*NWT z=j2YRdvO(=3v)^0BB91*>v!P7`$0GC-$d(uVNvPqtpWZifcH$*`R9iDu72&9e;*YlIU zv&gV9p%7O(?de7U&StEvnSPnx0a@zOw^47~P)uk&ou*zVy(m(lzo>+>xN-}m^4N{( z@mr#N-21dFV9;B_ffvqypqXjjt0$w9et=`x74*Gv>!Jgs8*PZpGxuAj1|h+}N5mat zKEJ`}#{Qa<8`Z3WiLm~pLiM|3OpaGhS~AfBjYk5kKoiCUudS?3l<5`NW8ibY;cf7r z*%ZEEdxjtKj!8VJNHRhk97igl-Q#?6de6@J>`hIfp1zI07*u#Lp5~3&Eh7UXcD#ZX zb%g&F^`a;8hm?teGeYf!73fFU$HvGWTTW~V^vf6MDOVr!Z5Mo!U@yL4J4V(S2N}L) zb;`fOce~Zz1>wzQsv{Gvev>$#OD8i0k)Z--#2ftpu7y7@wNK?wlxlRYUtkYI!yy97 zM1;(Jh8GlQucYJuFuGp0a_ZjRUaPVGGe_Go{0P@nSd_cW{O+DSwtM{Di#0u{Bg{W0!uMb)^;^Bp{k1k+b9!G+=}Jg0XRb zPCayh^v9)$;p%_iP2Qdoyvi(J-f24``s~L#-uxRPQl^D~9<%%nOm_O*)1~cJ2Z9+p zT&}|dm{`2~S_~p>+bxI96ZLRFUsTd|&IxBT z+n&~Lm-`VJat&zmx%+Ji?b86Rd&w@Orc6KR7^y1_HI~tRAcD5C#qQ$+6bafEV6DS(3=Ldt?~RX%&7%{ zE@F{t<<#&F^zMI{w*5)G#YtH!rFE&~SPQSo1n80uZIylQ1kL}s7P6QOyAyu!RkHe4 z(NhtByasQkO(4t>JUvU@a1exu8Q3jHPKk&-Bw4wS1)~aQkGQFm>Jc7ZWqjc!Is~Ic z&Rx$!DB=n^_zz3-{w*Eb$z-qBIYhn=+rOt9wk4p)d|9ws=79mXo)oInPS(?>y>7zp z*(hf%f8`7}DtTBbc6n{!xpw*jU}{E_{WT>p#YGVVF<}v*prA$nqRIzD`+tM|Dk+NG zoe^G=2o-7dv~W=j+ohiN5OM!@CQtG~YqX@xRC?I(zd&u%NHX&mcbQTt$&an}1H320 z&Rf~J^cKD6z;UOCe`YT@PTzab$hRowrl8ui`!52hfOpogND}kc8}el>c13WYzCg;2Ld-A z*6AEhG`@z7^l{Kb1F?Z%QA7Z6p0si%BLQ>T}t%P#$6H8x1NbQ1ni zy&a_7O@9{6cpmp+=W0p*qei_;YdP@ua7eA|wM9!HNa;&g-8KNC@5+E@e1s}A`JHoR zhFnJ!_~%Iv|69MZ7%+FLtldK{dcH0Tv|(XxtG29ZIs&4ntOBVoyg~~iQ<`lRj1O_AiiBk& zAdQ|p-ZENRFd6$JvTW{ zhpUJ-_QrE8AQ#j|{pAa9C*fD_fw0h;`!L?$+KgKXzdDGhsk1u|&`H|QL2)mPwM}^WkgA|(%g+X z0r73=#RJKMgX4&P5-eACS58oJ)j)xmW0Z|h6TkIh!jkx1d?E2Wj7d)`p(yajgjS7p z|82HR99}xmba4+GBpOXX1|~K6J5Kg6UHK7u;%yS(Fr`torb1ks^-Ec*FgDv=`NrA2 z@uSRDK0pA_KiEGGSpru6t0v|Zag#r+kt>L(KLUxKp+}s1Kpsni>Oo#2H}oeYvzQzP zPE0UNn*dNUxE=U=O(Wwq`h)1C$TrMSte4KawI>bpd%Wb{tX(}9SZYb&Qe&AYWL%}F zYvESRwxsane?X?=XVMUcEdWf$g@a>1Vur|&p`rvX_!bSCrEI5glcTS$%d>-!1s)Y& z0AA71Rw5Abx17TpmA6^&ur+Z9N!wd;(hSOsBMeJ}(_?)UBCjw%2MPf(n~TH)mN`^~ zLNoXpd|~2(jC<0?&YRnB+9!6k^Q)XfzxS~!+;Hf|wB+V6 zlvG$KsOvgl3@d-6W(Mmq@|gY%{}2Be5G6^ zQiJSa+d!n73bvQ}32DY3{GMISV8?n+&)`&xwze@T1lbB48MFP9WqR&~#}wrM)MxQm zFOtihP10Xze!*B&_K`tT{z8Td1={MaL9bkCOg!*SfdB<+=fgj>4xz+@X(V)zjx6A0 zqyUG1^>}r+lg&kXx|>oVwgU7Xd4=lXh!(hU(7~FGFw^Xt{Ax*{qMlCM2TC2dC~Xp& zo-b46YHP#F7=%g|pQZcA18I%aP-nC+UaEK?IN%8Da=EI#ic5X-GUw~2+VII8p9mK1Z~Op45OJ>xgV#yt z?r|`w(|2hQGGh^Y zpNK(vP#$P2~5kOw8tj!k84VECEf1*n^+JoE;9><_no$J&2Tc~}d z42%bgrE@%V#yT3oXP?dEBC(W(z&q@hYXuqRU5J^mNWqG_OKhjyv{s&b-y(eFs2yW# zzfN(sLW{5b3|-}{(IiaWTU-EThqO*wjMh(T7wIge;Va-1auu}wFSMMh!6CGL3XqWd(WLj`a}u^^0v^s(YE zJISkptA@fvvESr?O^qLO3j*e9v-XrGfstOXf7`hj<6yZ@EXNViGKEm0nzvtZw-nmD{S&9X++<3pHXS4OGe3;Vwr!&)!mc4zAtBAq#6G!BolOAuf?&`wj z4z0;<==94v0jA(wLvCHYcD|uJIpi$SAa*I(P5*Hk2gSS5 z713QkK_RQyR8a4V*)3;}alKA$vVN2SlT|ro$_&3_upnvjpmhZHi>dsGGmGZuiWT4j za1a(Tw9Z(m2o991%G~X=+Re{N2M$)e6$^AUCGKU|X$9BkBZ9Wic?BLLuszC#HBqI5MQ~LYqr5yo5a2L8r)W27f#4 zbhmG+qdHsY=7Cu2#0G#Z#vCI`KFT_=4@III4Acy?ZcnY>)1}S&IdoT%n#Dw+I~rYN zjFdqx1nN-pzqilYRwiarN_1fjO4Q2;goh`6+xBThP+ z?#}b3|I9`z+|D*XHDmA|x zPoReV5myD5ZD1^^DPDZ%(A=>?vw@_M`2)9zFGKkUM$jwFb>+yT@DmW_K-dtgA`SlL0 z(W74Iyw6RV|M`|FibM-TOjuQs9sP^!T?beiNF#R*kDbrXw$v;}9>^(=$N&XeOm=kI zG&cEbtWp|i!y`T%XWU5rWg$X}JmLD9MNE7p*-hAWFnW!thB?LTIERUmZsJEBjTUdu?rw1FQJ3xF!{+OK=YmsaWU}SgH4*!saSh$a zd<3?(7Y~(TRT-1y>CS2%g|(7KjNvV3E_ zt!tlO;uLOOeBz>uM^m9*zP(TU?zHwzr1N~OzMjj@$+}Gk%wj#*V*Jjf*zvg8Ssc6J z-s{%saLZHO{Fbiq(kDGy=N^(hI`D-mz6#k4T{h42;Oz623?~pvGw*9d*`2rW=qQjH z04+2bG*6oA!Y5yzLi~xEU*+$5RlnDg^Yg;V37;m@m*o>45i53jwXcasTJI~9e!Xpe zsbrexCXbIvvS#_2PT8^oQi%7~i8kwBKt+S39(+DC(Y!CSW3#)}kDXmp_d;5ws<|%g zN!c#!Hc4qd6ua@!I*qS$VPCIKHsp)BzNX|vDEsL}k$LCW3w>?q6mq?>gSwe}{^96u ztYG4a7D%|!gKoIJ%*-q4yP{w^Un%7PLXKT?VH&_74RC$cK37lYB2CRO3H%1B+=9*q zIpul0s#;s7Zk%o0zH|*$udugXkARV>C1e-I{&p4D+f4aQs{bjyjE!_sD+O z@A9*m!HE^Vq6<88iQ@;IPt6-@7Cc+Jo|BNyG87~Mf)CF#b^!Q;SN>}AW_0B1 zXV36iZCawzZxGp`U{yV~%J0D#38nmNSLnx<3d?Cf_sjBr3g|s)G`I;%^KNn@DuZX{ z()4XC%M=(Lp10LBEL2;SeMN)ncI)zZg~ND#SZAYCDLv~vhqUuD&sLaVp>lCWZ~%L2VzFMfbaUk|>Q=b33*%J8|=si%3I4;Mvip# z3W&q^s-rY&RI4)b!-Zob-_L*7N8dz7>HObb0B7^IUsujql*RI20M3(oZtYV)`y1IL zeoB@@q4Stk%F}0(kok2TwBSE>F8B=EG+DpSD8AlRqkk451#@x#T?FA5DYx{n++#ko z@$4KWQqOg$o`@|>S5<9M;5xO3iD|`f2i_f4nFMKtt^3gr%)8^~A4N!jWkXto6-u-M z(r2r#>rcIY!DN=4t*8(X#~2ZI=%hHDEw?D<*K{+cC5-aW{UUCF2TW_LK$KhTefgb- zEh%;XGl)9krVoOPlDiA&yy9m9fAYd&1SqW~!IgbmrYc^HYIp^uZtb3}WdC zqiG~0GXls070`@)Wh%tF6GfS!w^SWlvo(iKJ;2|&aqwUQFA>`&ov>Wy3xNBJfK~fu z8UDsEU{N(O88OR4XPA9gz!Uuje%GNfB6g)pV_LFaW&6;5JBy2kWY3{CGVI^Ebuw(8bNqDX zQapeh;W6R9(XUlu%f#Sk>6X*DlKg&%;HGPTecyGDq0@Apy54TKa{dW9q?mE9ZY8xG z4R#AKPH;GhQ1zHTn2=^NX3YWflOQ9JNV?zMI^ns?<(2pCVl&`1jb>aMBxZY*?oMki zuxD&w^sqT-lJ)ABHM9>ZFtV)}jp4Sk)Nu-&y>$LG!Vbki#0tORLJ=$~umIKD5IFBq z%U74>!4Bq|8_BGnIR!Jo_B1dTIAsBgW-dtZvrouVfD|ipK@tLMs?VaA5ovSS2Yxh2 zNCyR$3=^Dnm3@|VB-bWOzl-m_-u9{Yva@|A`}`PW1$m0^xh4KLWLo!by>d6xX!A=8 z43C9QLi8tlP3L&tRJO}ch27IQiX)?@nqKKvtZ@7Ey7NiV?_F}RcCVC#&ee$Xx85_| zP8zzhI;yL~e%(mla1Qs3UXH@PKx8N$N|~KEhB{}oCMOPNwJ!mvK(Nh7^Kuzz_|cr| zX}6=;YC}&*BT-Hx(OnTMRJHP?Ju#(%DnzALwlr;Pjh8duQe~q5^^?7l!10l_V49Gg zBIB|rg%D`TmJO|08-HSXo|TOnqMTfm9%-ajU>e%SePgmr|2=qq z0p#@g+miJ^FY(e9pGm2`*h>>-M*TfwHL~?eMG?*#7!{_B}1 z3*4{0jVsEZdcrsOzyHWMH!q8>{ld!9Ha&V7&H%@1Z* z#8%{OB^6b<9~RjebXt(aAg0~6*-=rPgEq{?pi8ak00rh@7(Up4++~O^?FN(y>6YTd z;;{Gr;GQ}nDHDYk)xt`@g=)tJFUhnS4tpJ6%QlNp^d6m6^;$NvU-~6T=u=i z{4!{MTRDl|4nSqJ{&`^^<)M+xsFv}wkns!ZT_Y_NClxJ$pfZtH9jPO2FPPb>!DTmK z#n;Trl)g6gx(`@zX8N8Yfre{)@*=xg+1u3zN z=WDa(XLra!R4d8P6Q@oezA1$w<*5##Ea|rWu&G=)ek}-Lg8gG9rOI9L&{fs-V%9Y^ zC1O#%iDFL!zG$5N*P_brfL^lVh-X`hGCLpAIQqTieZtOazhsv(la zQgYsuo`Y=^daS#rw|5cZWU^xj&jF7UCF@9}mB?X)LXwJS@0{4K0I7M-%jj}~OYNsT z;ivY54>NuY*w6^&foFe7U!o5l!wZe|UcJ{UH~r@%PW1cIIfm=e@GaxKl?TH_zE%^a z;sC3VVT%H6zs_rVGC6xCu_J8&yfrQIn~{2QGr08VhN&+yONdg~Nza+fgK~%|S&`{F zTc%kSDinO``{rSMPD3rB{=AM7oa8YYH>5)($VueoNOYn?ltoMRo4^4nHGy47C^Vqc zmU{aWqNtl3RTV*)Ec7#2f>_R?01Z6{_4*>n&D+BGLBcVx5w^05F; zAwq#{-bGM(d4+IZ%>wsI=sZ<+o`q}xFb)Iz4Fdy71Fg-HtJU2Oy4IQ-AL(O&LRH9+ zysDOK$4Ku_7!7|PWK+|&ux6)+xVp;`ipSy$Hf6wAs2)b@=hrT(B%(%aX;H3Jo?z8F zK7P+yooo+3mRN_n5c*Bbd|G@U zriQ<<E;ed&JBye+?4BwQFlXfm={r8g1%Y_l@AGnMM+?dN6D-+Y zTFSUg_$@VK;)jwVV9nv(zG`w-#A*!2yfqTyw^) z@7G=<8CPj;Q3qXnSg}{@^JC7^WBw2uFm|Km%xY?#liAqaDt_z!U>0Knk}|@bTXnyD zSkq3NIl893I5;mT7o68K1NfhrZ(b4#g(tuB1PBby+R${($N(2PntiODH(t#^S(YEY zArmnGJ2eHElT-N{80`#PGq0pV$6^0??LcYt$IWIo%eBE?1>he{Jn6dOGzDINa#JYG zHy(DDMN+hU*aSmVS}50f9_}yyp`ZhM9aUa4?n>Q{aSHQ%x?l%=lanWC$4rTAAyHNi z@U^C)Nk(7vtG|AhTEL4DpK;Z;l}DBz*NVgY8lRa`bZcU!jUY6*E+qK%MyJAsj++Tk zrMe%BaHspIlfmlIbHSh*`b#OlFdQ;_9vSa!!>|h7cx{EzqZwrw8E-9?VB5U=NHw{7 zXNR#^xCE{+4c-6sZJGr8%a63I03(8MH)ms4(-KKO{mn1NhWnHax)zFbn}cS)gNl9`K6Y0(EqhF9<) zQPe)Goj(N8**;m3MhSx`8A{BUafxWv50AyTdaKnp)tQEF(F{R{?(#~|bBGWcLo*t5 zH=EVh+wGghs$##3A;F%C#I)6e{mwztjeW8S5>IC`|E!BlFw<`-1FbB+%MuxoZIqcO zsp5@I>&BR?hzhCjlS-%F8=>)&S@lMp`Y_JKLs9-tl{zX zVxVS5HIL9j$a!lj>DK_&PMoR}I2f*Q@l!t!zCpNGi6| z#cF5?3iOX)^>R4ot>=nUdalZ&WpRU9YHvPNdI`j}F!O^~o3-UryQg?}`ItVZlkvt% z0iob}hwlnT!-0>3tMMUcld^lZs$@!m(iZX3JrBtsl$K?mBYzYbnWXQGWNM4=Y3CD! zUO~}tL+>5wPH&^8!lcRuV{vciS6+&=qPV)N?(2*J-^(HlzFd~j@^u1l*ZI2kP8K=( zLfabv=~5^8a;FP*vV&xkPZU12t=spP>+5I(cp(&2gNPsPNFUGd-8IK0`6;Rr4%QU2 zMM5=hnvWjsI+uNnW1i$bbEN3cVJ${&_4Sy*#NR+*<`|mwQzDANoyt8TMQtG4X#WsI zQ?MhsY}ILB=!bb)>lXK%4L@i%|CtyRMPZt(rL*kT#8+54K1M&Na>POY9Ce^B-=s}w zxN%|(f-$`EA!A$$(P%&CjXyda_}e*Hd*5@u!*l*fKY!j#p#2=DygjV*7Oh*{Du$SV z+sd=uvX0c&3gI1q46m#=G z2`uB)sKS4TYrex8U-TX4pv+P|BU~08|G_kr%E(rp*?%cnU1|>n4^m9CmM;Hj1tm9e z@~uyKfgOxZ*;7XD$~1Mc=u06Ab*{YrOUa>I>=AY6EgYa2%gU*GOS-GqAaY7n>$T`_ zv1>89ihfF1tZ4S-K{Y{`=)ETiF=(ay0KLk|N5J$DG?MU z&g`C2GXF0!&8hQXPbqSHPI?qp9`ifRT!4GkvxsM-uDjRdfDKix=`w%x!-6AHOX>(j zw)5HxZ2{DFr4oPYJZr<>C*j~Y<|rEyFoDwOvr_rVE6ec`nW106C{>IN8-z0k;(8Xb z_{Hn;f(a@fhzFW;_--RE)?fCm@fxp~Ep)TuUmn`LBQcoSJjpAy;^?~C$dP(IRaUrE zxYo^Xh50@_mHR%OVWieJV*td71Uh^dM8-%x>NMJt-Bbr-Is$@)Bu5t6q870zw*tKr zee8t6eqJ3p&=6|FIlP#3VLE)w7Rk>f2ogJnmIqirv>05*WK8|yh!>ruHukf^u$N*u zkxC1dTgNlp3wtc|2Y$H=p0uPKNYM8%BH9x=sW1=Re z=s24}Kp1v0*t94pWO{|z&9pF5STE?m<1H{-abjl@t>R@n)O$&sCSluY6N7caFpB%0 z@RG@dPGyCGJY0_XVZw@TcFVp6zwK&pxx4$)yf?WU*>11vr-klXI2l&7ny^w9s*UGD z%|8P6vTR}XW%j=7rAMNQ356Vn9S6yHzLKKMbBBb&NQ-tg%}7q3G{_K5T2xAr4E3nj z$vQ5NT!MaQ2bXThZEf}K*{|8W_n)jC_zMg)VZ@EK>rB6a3#hpB{1Ywf&FOSV#VaZM z0l|gzkTk_^FuMtY<}+cn_6z2moGfU~Gfk{Jf$8gUi|gQG zyiYaB(z|H_Vked&$*^m+m$%`)Sr|@Q4C6j;i!jy3icQt9!k&{f+te?+b_}yw`2SaXM=4JOw4JLFEW~5jL1>nfB2tOty)EH6u)3-yocAxu@d1 zzk48|HhZQOVUZ<8_PDX@uEb~uW`QSU48e9_$ZECZlVnpYsbG>$lgonX!}W4~V%Eg$ zVWGCyXK^C9gg>+iW|glEtoTove;(lH*Wu?q>3B5z4eyA3$CPHU5%Xn=+%9BKTy-76 zt@U2ZGSoH{1z$r-2P{OwU#&|%v*i1q4IE5>+4ii$peFvdQEQgQeA9OUDM*hntb58f z;`cE8%1aWbOe|l!5X*TFtuELKGkCDQ)NR{2#KExB|B%T!HG&#;&})8!33Ucb*#pqM zjKAz+oUJ$V8sb7DeouN-t;K7+PB9wJ> z>__d_GtfJ1Z9dgt{0|!1k5MHy<>-`8<$g&EpO$YYSTJaRw=4{1UqlmV$^CT0=Fv4C zLFv_q#z2F;WWCcmFYQ+LZ7xxu04qnq#dW+PlbAAfSl5O)QG=y8EA7%o-)x`p%uAXYGnV1)MWFZ8B_ivZ6=C2#|@3YXNy%ouVxQXX7oCWJDF1PJ6<|f z-~xXsPSaC6u3=QK_-+k}=kzx*MO^Jh;6Ef!Ujs|DENODSR6JBF zr`40^K@JKUbk1(e_wX$?d^mb1YwrS0aC*Yf_dR5JY-s9Y3$8jaTq{>DoCP+x3gt%O z0B6q^!itDA9W=PMG<}+-_ui#RHG2gCSvd-cc?%hc{SjLS7@t=cHkJhKa~+gGi(ES= zr+*&Q{zPQ~@9f?X%xHd67l<6_Wy03vK>T94xE#K@xIXMuypF?GO&+sq50AZ${KN>* znux(LP$S@fW5kOjJJRpEjaipp!O*%afa&i2Gb5vM{6jaQtg^^tk3Yl{eQ5UIUGnbt zZ1rxzc01;@E4JsQd%xr1m1;jPm)$_{7Z%w*GR+9=eUc9~r+Lu?#2Pwffl`+{Jq#9rC6k}cp zHJK>jqMBXKX{tS64L)Wc7=NEhs)Z_|kcg?(vBSTizhl>Ow3~Le>2Q`}u8`%v>Gx>= zbM7)-8K(A_Sa2{;vM+A&6-=~RfTxJ~B69wnYB=UaL@|r+s>4Ka-D~c2m`cPX-71mW z!~t>Y5Q2Hf8oJE-d;L^O1}P7>S=&J5XuoQf9DX~3n;`vEnPV`WKV{-8O|r$2d*ODe z7F9e$@V359<*#5)I?ZR+pyUMX#&hCOyz5|9RR0jwYSHy3tO%~-=4gc{CrhJl;#jBxW})6>E0Fk*S>bxs zDFgJmk`ih~t>%C^;L#cxrQ*|(!b0TIV&nb43^xLfYq)F`d0a_!gNXQEJZxj?nW@`? zQ-k-#37ivbl>weiK1t@so}1l zA-s)<_g!XeG`TZ2IX&_~L(?z>Rw(PHQtd}u1ddb!9qDV&;72`F;>;5W%9^gqa4aum z@dS;TRF*6MZICllc#07|T2A(z&y46-Y1pePH%z77K0*aCnNf4`pT1rS|JA1Ivc;LV zS%T_~+B)QlHQDZ?sJY9NlQs96kG5I$ahUtr??$Y?oh^6Yy@)J-lH$-oorF+Xj*3=D zo$52=W)q_MM>v_YYTEPISuI-qA>CX)x!Xysc@7<}Vzxlnk!%AJy*2220E*(nNEL|_uhcQnF&CTqoSGk9=JErPSu;Bat6{3y^9yBP#Z zaE5G;;ob>5voVH9(=$!11qq(LMeEQSM@S%xVu0lVBox|=)+u=wl`FwYtU=`!Fn`3n z9E!E;u#aMp)kTy#R&STnJYVZsC33UP@+(crJih?dKe)~)XlpUij$pC-E3_Dp*XOh?I~{J9&ttnR*R(K2MZpD=PtnbGg2IY^O4or^)?{Q z!FfZ4fd2tiG-|>nqt_tM8k{1-N7smed7C zkmTYfl}zSmzBSzOQ% z8d)WgK-d$}77`c}Aa+x=5#`(nBOceIO)M9E%=1Y(x=6sQlP!6x$>{S1_KFs824)xu zB$7G~WENidqM@ayjt#%5CP1p52s9s2dDI=)vcMZ^Rz4UCoJ3*ZpK5yS8vQNxS@ol? z(7Vczghhu{+7D?&Bp;@H$n_XL6PLZ5yoI1MPAa(c*LA~$N#moXa2C-iAmL7ZJ| ztnPdvJ*?JJLuOd*>CeuWA#t03ZUQHrdvVA7!+iWJobo9dosjfFxbVa7-g~!bA&*J0 zSL46s1>WXMM4$mJ?7T`zNiC0RVW>>q88-MUFwS_%s9 zNsd~9C4yO6tYsvuOogWfE0X*6586r^zOGQ-4)0xDMvE?dRj$r>`==Bqtco#;#BJu0 zbd84{cxg)Hl;{?LSSx`HlhO3sZ|BQHHp)V+(XYsol%F+BG<`VI?BIv&h34Jp-{IPw zzFeWjXuSfg!4>L}Gi**H{l$UpxK;dG#`d62q}KcRZY!Lt4#!1g0SmxsMsqAlv{+R zTNL^dEP*sS=P1TN8VXZrb)gtJbBzn#F{ve1IC*22`ZP8Bek5%~#7Z$`^)dHjqcbnU zVr}1mxcvO>;k15%80KHr0L`?e#0nl5R7;?d2FMX|*D$I_$1?a>J58`?#lV&$&)X;v zi6miu2>C?XT*b4bLg%NQuC9%Q)O-A`stv#Mpy&SMe}sUKf~_i34U-u?4VGe|QEKhu zy)QjgnpO}5!QdHF+dsDlH;NJ-1ra2#9G!7FJEH)p3xX`L6foXcFJC|2w&mRaWmxBh zY-L$%2@h);)WLlzfWyTD!z+{H)A$8H@_EA6KS?T`uNv z>U`JLG9{@E$H{7vZaJZWHJ54fY^mreQ^vGgjRBlmw7Cz5?j>&j`Y`+OeK#0{NI{}A zYX%EcA;hHXR5uckkjf~gI{W@>!zEXJ&-Wa2a_CTh*WlLSC7dKnnUpOzl(G_4keFtz zJCzd9o}JfPIT#m-000KNNklXKxPlV>jp$)4Hg0nhSoafyUu`AMk$uc-QBl!_kS3M3}`h?ww03SyeFM{ zj)`z4y^za$4+Lhfy1__w{18HZ+pm;*wNu>#qMamU2N9WI$VH}KFQ9()R4^Z&=YTc9 zqB&550LO?YpGtRhKP;pnhxb1EPVGAb%CN=;c3l3CJ?pm~TZC+M3N!AMz4S>)HshU7 zxaF~z3W6YbDZ4Ziv*Ky{3^*mu)Y|LWC@MW;#6BCR=RBL9%m$>Dbc|H~HoGwPhssK1 zg)(Nyw2p!C7()|lzk`EDusN_!0g&@mZqAfbFu*=M$7zr;P&$AazH3)6m>D~AWm zDXeN~CJkU@kz+rr=~Qb0XPR()inYaJ-`Jzu%!U(d^jTkqs zT)=`vV~8;|2+>4c)CEyV06}6e9DWau@F*i>KMo)I4Hy5g5HTeHD@5e1H6{=vC2P%)H711E{=t&pw`kc4 zKi22?>$W!@gviD?iqj{L|Gq4aT>HYM@2V4NN;&>ao&UH4u>^#e_il-INgK(RKzs<`OzjvRF}!zhj@}s4CxVZRpk06t0$Tun2SLAq+yZdcw)WNI z(jVoa@>u{KV#L|N&h(XsT@`h>tINy#sdUtQ=78ns&@kuPPa|lww1Y>Ngh};8% z7J3q38Y0JpNCC)@aie!0^nMdyUM5{n+l#M{I0gUZy4Cif7hV|`hr8?XmF(Q`+WUp3 z>~oFThMV^t=t)-{PSZ*q!_^;M-+r3S2AL@olnrcFAgvHi1272BqY$1WI5YGo*Iyhu zH}UYn?j?(szTHtL8I1*yomOnhwXb^i)#=wyc=FBnwk%xR(Rm!e5P)cy_*8(JQr3a< z-MhGSYA`-V&oqD>;djIN4;V)u7w0{?vp9F*{&Ld0oeWQhd3w7HMCktZhN93c5H zj4oJf&Rpf@4lglPLgh`g<&E19oVxS2>B}7)H7_KqJq0Nq46{5m`!5W?MrU39-FAWq+_`MPGD(n zkD}NR+}pN%jn{}MD!4J?=gq5x@N-M0Fd?~BBciC_#*l1dHcPTK3Zv60Bfn@w6cyZ9 z2GyXDByMsXCwqM2`!ym;4V^R@1ESa!qbR!0lWQJ+X0@(SRMg?FAhnyy0f0sTxr0ag z?u(=N$cD{(_Exvo%0emXaLOozCe;|G0ZahU(h%6@hLn9``_BFA-del4h{~#sK>#5t zOQsxZB~X?B9acjyYQYV6xJ)6RNw-WY46OU)s~-l=mxfST*-Z(L$Ev{GFrg`mq9}@@D2k$thCczopJM@zawSXv0000 + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +\error_reporting(\E_ALL & ~\E_DEPRECATED & ~\E_USER_DEPRECATED); +\set_error_handler(static function ($severity, $message, $file, $line) { + if ($severity & \error_reporting()) { + throw new \ErrorException($message, 0, $severity, $file, $line); + } +}); +// check environment requirements +(function () { + if (\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 (\PHP_VERSION_ID < 70400 || \PHP_VERSION_ID >= 80300) { + \fwrite(\STDERR, "PHP needs to be a minimum version of PHP 7.4.0 and maximum version of PHP 8.2.*.\n"); + \fwrite(\STDERR, 'Current PHP version: ' . \PHP_VERSION . ".\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 { + \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/PHP-CS-Fixer/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); + } + } + } +})(); +// load dependencies +(function () { + $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; + } +})(); +use ECSPrefix202307\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'); +$xdebug->check(); +unset($xdebug); +$application = new Application(); +$application->run(); +__halt_compiler(); + diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php new file mode 100644 index 00000000000..0cbdcb17c62 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractDoctrineAnnotationFixer.php @@ -0,0 +1,199 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Doctrine\Annotation\Tokens as DoctrineAnnotationTokens; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @internal + */ +abstract class AbstractDoctrineAnnotationFixer extends \PhpCsFixer\AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private $classyElements; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // fetch indices one time, this is safe as we never add or remove a token during fixing + $analyzer = new TokensAnalyzer($tokens); + $this->classyElements = $analyzer->getClassyElements(); + /** @var Token $docCommentToken */ + foreach ($tokens->findGivenKind(\T_DOC_COMMENT) as $index => $docCommentToken) { + if (!$this->nextElementAcceptsDoctrineAnnotations($tokens, $index)) { + continue; + } + $doctrineAnnotationTokens = DoctrineAnnotationTokens::createFromDocComment($docCommentToken, $this->configuration['ignored_tags']); + $this->fixAnnotations($doctrineAnnotationTokens); + $tokens[$index] = new Token([\T_DOC_COMMENT, $doctrineAnnotationTokens->getCode()]); + } + } + /** + * Fixes Doctrine annotations from the given PHPDoc style comment. + */ + protected abstract function fixAnnotations(DoctrineAnnotationTokens $doctrineAnnotationTokens) : void; + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('ignored_tags', 'List of tags that must not be treated as Doctrine Annotations.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $values) : bool { + foreach ($values as $value) { + if (!\is_string($value)) { + return \false; + } + } + return \true; + }])->setDefault([ + // PHPDocumentor 1 + 'abstract', + 'access', + 'code', + 'deprec', + 'encode', + 'exception', + 'final', + 'ingroup', + 'inheritdoc', + 'inheritDoc', + 'magic', + 'name', + 'toc', + 'tutorial', + 'private', + 'static', + 'staticvar', + 'staticVar', + 'throw', + // PHPDocumentor 2 + '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', + // PHPUnit + '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', + // PHPCheckStyle + 'SuppressWarnings', + // PHPStorm + 'noinspection', + // PEAR + 'package_version', + // PlantUML + 'enduml', + 'startuml', + // Psalm + 'psalm', + // PHPStan + 'phpstan', + 'template', + // other + 'fix', + 'FIXME', + 'fixme', + 'override', + ])->getOption()]); + } + private function nextElementAcceptsDoctrineAnnotations(Tokens $tokens, int $index) : bool + { + $classModifiers = [\T_ABSTRACT, \T_FINAL]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.2+ is required + $classModifiers[] = \T_READONLY; + } + do { + $index = $tokens->getNextMeaningfulToken($index); + if (null === $index) { + return \false; + } + } while ($tokens[$index]->isGivenKind($classModifiers)); + if ($tokens[$index]->isGivenKind(\T_CLASS)) { + return \true; + } + $modifierKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_NS_SEPARATOR, \T_STRING, CT::T_NULLABLE_TYPE]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = \T_READONLY; + } + while ($tokens[$index]->isGivenKind($modifierKinds)) { + $index = $tokens->getNextMeaningfulToken($index); + } + if (!isset($this->classyElements[$index])) { + return \false; + } + return $tokens[$this->classyElements[$index]['classIndex']]->isGivenKind(\T_CLASS); + // interface, enums and traits cannot have doctrine annotations + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php new file mode 100644 index 00000000000..5869b6b9f9f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractFixer.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOption; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\ExceptionInterface; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\MissingOptionsException; +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractFixer implements FixerInterface +{ + /** + * @var null|array + */ + protected $configuration; + /** + * @var WhitespacesFixerConfig + */ + protected $whitespacesConfig; + /** + * @var null|FixerConfigurationResolverInterface + */ + private $configurationDefinition; + public function __construct() + { + if ($this instanceof ConfigurableFixerInterface) { + try { + $this->configure([]); + } catch (RequiredFixerConfigurationException $e) { + // ignore + } + } + if ($this instanceof WhitespacesAwareFixerInterface) { + $this->whitespacesConfig = $this->getDefaultWhitespacesFixerConfig(); + } + } + public final function fix(\SplFileInfo $file, Tokens $tokens) : void + { + 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() : bool + { + return \false; + } + public function getName() : string + { + $nameParts = \explode('\\', static::class); + $name = \substr(\end($nameParts), 0, -\strlen('Fixer')); + return \PhpCsFixer\Utils::camelCaseToUnderscore($name); + } + public function getPriority() : int + { + return 0; + } + public function supports(\SplFileInfo $file) : bool + { + return \true; + } + /** + * @param array $configuration + */ + public function configure(array $configuration) : void + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException('Cannot configure using Abstract parent, child not implementing "PhpCsFixer\\Fixer\\ConfigurableFixerInterface".'); + } + foreach ($this->getConfigurationDefinition()->getOptions() as $option) { + if (!$option instanceof DeprecatedFixerOption) { + continue; + } + $name = $option->getName(); + if (\array_key_exists($name, $configuration)) { + \PhpCsFixer\Utils::triggerDeprecation(new \InvalidArgumentException(\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())))); + } + } + 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() : FixerConfigurationResolverInterface + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException(\sprintf('Cannot get configuration definition using Abstract parent, child "%s" not implementing "PhpCsFixer\\Fixer\\ConfigurableFixerInterface".', static::class)); + } + if (null === $this->configurationDefinition) { + $this->configurationDefinition = $this->createConfigurationDefinition(); + } + return $this->configurationDefinition; + } + public function setWhitespacesConfig(\PhpCsFixer\WhitespacesFixerConfig $config) : void + { + if (!$this instanceof WhitespacesAwareFixerInterface) { + throw new \LogicException('Cannot run method for class not implementing "PhpCsFixer\\Fixer\\WhitespacesAwareFixerInterface".'); + } + $this->whitespacesConfig = $config; + } + protected abstract function applyFix(\SplFileInfo $file, Tokens $tokens) : void; + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + if (!$this instanceof ConfigurableFixerInterface) { + throw new \LogicException('Cannot create configuration definition using Abstract parent, child not implementing "PhpCsFixer\\Fixer\\ConfigurableFixerInterface".'); + } + throw new \LogicException('Not implemented.'); + } + private function getDefaultWhitespacesFixerConfig() : \PhpCsFixer\WhitespacesFixerConfig + { + static $defaultWhitespacesFixerConfig = null; + if (null === $defaultWhitespacesFixerConfig) { + $defaultWhitespacesFixerConfig = new \PhpCsFixer\WhitespacesFixerConfig(' ', "\n"); + } + return $defaultWhitespacesFixerConfig; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php new file mode 100644 index 00000000000..ee09317b26f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractFopenFlagFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +abstract class AbstractFopenFlagFixer extends \PhpCsFixer\AbstractFunctionReferenceFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAllTokenKindsFound([\T_STRING, \T_CONSTANT_ENCAPSED_STRING]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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]; + // proceed to '(' of `fopen` + // fetch arguments + $arguments = $argumentsAnalyzer->getArguments($tokens, $index, $candidate[2]); + $argumentsCount = \count($arguments); + // argument count sanity check + if ($argumentsCount < 2 || $argumentsCount > 4) { + continue; + } + $argumentStartIndex = \array_keys($arguments)[1]; + // get second argument index + $this->fixFopenFlagToken($tokens, $argumentStartIndex, $arguments[$argumentStartIndex]); + } + } + protected abstract function fixFopenFlagToken(Tokens $tokens, int $argumentStartIndex, int $argumentEndIndex) : void; + protected function isValidModeString(string $mode) : bool + { + $modeLength = \strlen($mode); + if ($modeLength < 1 || $modeLength > 13) { + // 13 === length 'r+w+a+x+c+etb' + 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php new file mode 100644 index 00000000000..204f9b9a5c0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractFunctionReferenceFixer.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + * + * @author Vladimir Reznichenko + */ +abstract class AbstractFunctionReferenceFixer extends \PhpCsFixer\AbstractFixer +{ + /** + * @var null|FunctionsAnalyzer + */ + private $functionsAnalyzer; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + /** + * Looks up Tokens sequence for suitable candidates and delivers boundaries information, + * which can be supplied by other methods in this abstract class. + * + * @return null|int[] returns $functionName, $openParenthesis, $closeParenthesis packed into array + */ + protected function find(string $functionNameToSearch, Tokens $tokens, int $start = 0, ?int $end = null) : ?array + { + if (null === $this->functionsAnalyzer) { + $this->functionsAnalyzer = new FunctionsAnalyzer(); + } + // make interface consistent with findSequence + $end = $end ?? $tokens->count(); + // find raw sequence which we can analyse for context + $candidateSequence = [[\T_STRING, $functionNameToSearch], '(']; + $matches = $tokens->findSequence($candidateSequence, $start, $end, \false); + if (null === $matches) { + return null; + // not found, simply return without further attempts + } + // translate results for humans + [$functionName, $openParenthesis] = \array_keys($matches); + if (!$this->functionsAnalyzer->isGlobalFunctionCall($tokens, $functionName)) { + return $this->find($functionNameToSearch, $tokens, $openParenthesis, $end); + } + return [$functionName, $openParenthesis, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis)]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php new file mode 100644 index 00000000000..6969c452f46 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractNoUselessElseFixer.php @@ -0,0 +1,150 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Tokenizer\Tokens; +abstract class AbstractNoUselessElseFixer extends \PhpCsFixer\AbstractFixer +{ + public function getPriority() : int + { + // should be run before NoWhitespaceInBlankLineFixer, NoExtraBlankLinesFixer, BracesFixer and after NoEmptyStatementFixer. + return 39; + } + protected function isSuperfluousElse(Tokens $tokens, int $index) : bool + { + $previousBlockStart = $index; + do { + // Check if all 'if', 'else if ' and 'elseif' blocks above this 'else' always end, + // if so this 'else' is overcomplete. + [$previousBlockStart, $previousBlockEnd] = $this->getPreviousBlock($tokens, $previousBlockStart); + // short 'if' detection + $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]->isGivenKind(\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; + } + // implicit continue, i.e. delete candidate + } while (!$tokens[$previousBlockStart]->isGivenKind(\T_IF)); + return \true; + } + /** + * Return the first and last token index of the previous block. + * + * [0] First is either T_IF, T_ELSE or T_ELSEIF + * [1] Last is either '}' or ';' / T_CLOSE_TAG for short notation blocks + * + * @param int $index T_IF, T_ELSE, T_ELSEIF + * + * @return int[] + */ + private function getPreviousBlock(Tokens $tokens, int $index) : array + { + $close = $previous = $tokens->getPrevMeaningfulToken($index); + // short 'if' detection + 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]; + } + /** + * @param int $index Index of the token to check + * @param int $lowerLimitIndex Lower limit index. Since the token to check will always be in a conditional we must stop checking at this index + */ + private function isInConditional(Tokens $tokens, int $index, int $lowerLimitIndex) : bool + { + $candidateIndex = $tokens->getPrevTokenOfKind($index, [')', ';', ':']); + if ($tokens[$candidateIndex]->equals(':')) { + return \true; + } + if (!$tokens[$candidateIndex]->equals(')')) { + return \false; + // token is ';' or close tag + } + // token is always ')' here. + // If it is part of the condition the token is always in, return false. + // If it is not it is a nested condition so return true + $open = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $candidateIndex); + return $tokens->getPrevMeaningfulToken($open) > $lowerLimitIndex; + } + /** + * For internal use only, as it is not perfect. + * + * Returns if the token at given index is part of an if/elseif/else statement + * without {}. Assumes not passing the last `;`/close tag of the statement, not + * out of range index, etc. + * + * @param int $index Index of the token to check + */ + private function isInConditionWithoutBraces(Tokens $tokens, int $index, int $lowerLimitIndex) : bool + { + 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); + // OK if belongs to: for, do, while, foreach + // Not OK if belongs to: if, else, elseif + if ($tokens[$index]->isGivenKind(\T_DO)) { + --$index; + continue; + } + if (!$tokens[$index]->equals(')')) { + return \false; + // like `else {` + } + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php new file mode 100644 index 00000000000..7e361549bf0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocToTypeDeclarationFixer.php @@ -0,0 +1,157 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +abstract class AbstractPhpdocToTypeDeclarationFixer extends \PhpCsFixer\AbstractFixer implements ConfigurableFixerInterface +{ + private const REGEX_CLASS = '(?:\\\\?+' . TypeExpression::REGEX_IDENTIFIER . '(\\\\' . TypeExpression::REGEX_IDENTIFIER . ')*+)'; + /** + * @var array + */ + private $versionSpecificTypes = ['void' => 70100, 'iterable' => 70100, 'object' => 70200, 'mixed' => 80000]; + /** + * @var array + */ + private $scalarTypes = ['bool' => \true, 'float' => \true, 'int' => \true, 'string' => \true]; + /** + * @var array + */ + private static $syntaxValidationCache = []; + public function isRisky() : bool + { + return \true; + } + protected abstract function isSkippedType(string $type) : bool; + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + /** + * @param int $index The index of the function token + */ + protected function findFunctionDocComment(Tokens $tokens, int $index) : ?int + { + 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 $index; + } + return null; + } + /** + * @return Annotation[] + */ + protected function getAnnotationsFromDocComment(string $name, Tokens $tokens, int $docCommentIndex) : array + { + $namespacesAnalyzer = new NamespacesAnalyzer(); + $namespace = $namespacesAnalyzer->getNamespaceAt($tokens, $docCommentIndex); + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $namespaceUses = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + $doc = new DocBlock($tokens[$docCommentIndex]->getContent(), $namespace, $namespaceUses); + return $doc->getAnnotationsOfType($name); + } + /** + * @return Token[] + */ + protected function createTypeDeclarationTokens(string $type, bool $isNullable) : array + { + static $specialTypes = ['array' => [CT::T_ARRAY_TYPEHINT, 'array'], 'callable' => [\T_CALLABLE, 'callable'], 'static' => [\T_STATIC, 'static']]; + $newTokens = []; + if (\true === $isNullable && 'mixed' !== $type) { + $newTokens[] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + if (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + $typeUnqualified = \ltrim($type, '\\'); + if (isset($this->scalarTypes[$typeUnqualified]) || isset($this->versionSpecificTypes[$typeUnqualified])) { + // 'scalar's, 'void', 'iterable' and 'object' must be unqualified + $newTokens[] = new Token([\T_STRING, $typeUnqualified]); + } else { + foreach (\explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + if (0 < $nsIndex) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + $newTokens[] = new Token([\T_STRING, $value]); + } + } + } + return $newTokens; + } + /** + * @return null|array{string, bool} + */ + protected function getCommonTypeFromAnnotation(Annotation $annotation, bool $isReturnType) : ?array + { + $typesExpression = $annotation->getTypeExpression(); + if (null === $typesExpression) { + return null; + } + $commonType = $typesExpression->getCommonType(); + $isNullable = $typesExpression->allowsNull(); + if (null === $commonType) { + return null; + } + if ($isNullable && 'void' === $commonType) { + return null; + } + if ('static' === $commonType && (!$isReturnType || \PHP_VERSION_ID < 80000)) { + $commonType = 'self'; + } + if ($this->isSkippedType($commonType)) { + return null; + } + if (isset($this->versionSpecificTypes[$commonType]) && \PHP_VERSION_ID < $this->versionSpecificTypes[$commonType]) { + return null; + } + if (isset($this->scalarTypes[$commonType])) { + if (\false === $this->configuration['scalar_types']) { + return null; + } + } elseif (!\PhpCsFixer\Preg::match('/^' . self::REGEX_CLASS . '$/', $commonType)) { + return null; + } + return [$commonType, $isNullable]; + } + protected final function isValidSyntax(string $code) : bool + { + if (!isset(self::$syntaxValidationCache[$code])) { + try { + Tokens::fromCode($code); + self::$syntaxValidationCache[$code] = \true; + } catch (\ParseError $e) { + self::$syntaxValidationCache[$code] = \false; + } + } + return self::$syntaxValidationCache[$code]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php new file mode 100644 index 00000000000..e50b0ba6a01 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractPhpdocTypesFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * This abstract fixer provides a base for fixers to fix types in PHPDoc. + * + * @author Graham Campbell + * + * @internal + */ +abstract class AbstractPhpdocTypesFixer extends \PhpCsFixer\AbstractFixer +{ + /** + * The annotation tags search inside. + * + * @var string[] + */ + protected $tags; + public function __construct() + { + parent::__construct(); + $this->tags = Annotation::getTagsWithTypes(); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType($this->tags); + if (0 === \count($annotations)) { + continue; + } + foreach ($annotations as $annotation) { + $this->fixTypes($annotation); + } + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + /** + * Actually normalize the given type. + */ + protected abstract function normalize(string $type) : string; + /** + * Fix the types at the given line. + * + * We must be super careful not to modify parts of words. + * + * This will be nicely handled behind the scenes for us by the annotation class. + */ + private function fixTypes(Annotation $annotation) : void + { + $types = $annotation->getTypes(); + $new = $this->normalizeTypes($types); + if ($types !== $new) { + $annotation->setTypes($new); + } + } + /** + * @param string[] $types + * + * @return string[] + */ + private function normalizeTypes(array $types) : array + { + foreach ($types as $index => $type) { + $types[$index] = $this->normalizeType($type); + } + return $types; + } + /** + * Prepare the type and normalize it. + */ + private function normalizeType(string $type) : string + { + return \substr_compare($type, '[]', -\strlen('[]')) === 0 ? $this->normalizeType(\substr($type, 0, -2)) . '[]' : $this->normalize($type); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php b/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php new file mode 100644 index 00000000000..29dee7af40e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/AbstractProxyFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractProxyFixer extends \PhpCsFixer\AbstractFixer +{ + /** + * @var array + */ + protected $proxyFixers = []; + public function __construct() + { + foreach (\PhpCsFixer\Utils::sortFixers($this->createProxyFixers()) as $proxyFixer) { + $this->proxyFixers[$proxyFixer->getName()] = $proxyFixer; + } + parent::__construct(); + } + public function isCandidate(Tokens $tokens) : bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isCandidate($tokens)) { + return \true; + } + } + return \false; + } + public function isRisky() : bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->isRisky()) { + return \true; + } + } + return \false; + } + public function getPriority() : int + { + 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) : bool + { + foreach ($this->proxyFixers as $fixer) { + if ($fixer->supports($file)) { + return \true; + } + } + return \false; + } + public function setWhitespacesConfig(\PhpCsFixer\WhitespacesFixerConfig $config) : void + { + parent::setWhitespacesConfig($config); + foreach ($this->proxyFixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($this->proxyFixers as $fixer) { + $fixer->fix($file, $tokens); + } + } + /** + * @return FixerInterface[] + */ + protected abstract function createProxyFixers() : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php new file mode 100644 index 00000000000..40193678c73 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/Cache.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +use PhpCsFixer\Utils; +/** + * @author Andreas Möller + * + * @internal + */ +final class Cache implements \PhpCsFixer\Cache\CacheInterface +{ + /** + * @var \PhpCsFixer\Cache\SignatureInterface + */ + private $signature; + /** + * @var array + */ + private $hashes = []; + public function __construct(\PhpCsFixer\Cache\SignatureInterface $signature) + { + $this->signature = $signature; + } + public function getSignature() : \PhpCsFixer\Cache\SignatureInterface + { + return $this->signature; + } + public function has(string $file) : bool + { + return \array_key_exists($file, $this->hashes); + } + public function get(string $file) : ?string + { + if (!$this->has($file)) { + return null; + } + return $this->hashes[$file]; + } + public function set(string $file, string $hash) : void + { + $this->hashes[$file] = $hash; + } + public function clear(string $file) : void + { + unset($this->hashes[$file]); + } + public function toJson() : string + { + $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('Cannot 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; + } + /** + * @throws \InvalidArgumentException + */ + public static function fromJson(string $json) : self + { + $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) > 0) { + throw new \InvalidArgumentException(\sprintf('JSON data is missing keys %s', Utils::naturalLanguageJoin(\array_keys($missingKeys)))); + } + $signature = new \PhpCsFixer\Cache\Signature($data['php'], $data['version'], $data['indent'], $data['lineEnding'], $data['rules']); + $cache = new self($signature); + $cache->hashes = \array_map(function ($v) : string { + // before v3.11.1 the hashes were crc32 encoded and saved as integers + // @TODO: remove the to string cast/array_map in v4.0 + return \is_int($v) ? (string) $v : $v; + }, $data['hashes']); + return $cache; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php new file mode 100644 index 00000000000..0eb9a234d17 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheInterface.php @@ -0,0 +1,28 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface CacheInterface +{ + public function getSignature() : \PhpCsFixer\Cache\SignatureInterface; + public function has(string $file) : bool; + public function get(string $file) : ?string; + public function set(string $file, string $hash) : void; + public function clear(string $file) : void; + public function toJson() : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php new file mode 100644 index 00000000000..3b8b3660b21 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/CacheManagerInterface.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent) : bool; + public function setFile(string $file, string $fileContent) : void; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php new file mode 100644 index 00000000000..851ccbb71bd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/Directory.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class Directory implements \PhpCsFixer\Cache\DirectoryInterface +{ + /** + * @var string + */ + private $directoryName; + public function __construct(string $directoryName) + { + $this->directoryName = $directoryName; + } + public function getRelativePathTo(string $file) : string + { + $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(string $path) : string + { + return \str_replace(['\\', '/'], \DIRECTORY_SEPARATOR, $path); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php new file mode 100644 index 00000000000..45a62b238df --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/DirectoryInterface.php @@ -0,0 +1,21 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Dariusz Rumiński + */ +interface DirectoryInterface +{ + public function getRelativePathTo(string $file) : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php new file mode 100644 index 00000000000..e243f1f11d9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileCacheManager.php @@ -0,0 +1,130 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * Class supports caching information about state of fixing files. + * + * Cache is supported only for phar version and version installed via composer. + * + * File will be processed by PHP CS Fixer only if any of the following conditions is fulfilled: + * - cache is corrupt + * - fixer version changed + * - rules changed + * - file is new + * - file changed + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FileCacheManager implements \PhpCsFixer\Cache\CacheManagerInterface +{ + public const WRITE_FREQUENCY = 10; + /** + * @var \PhpCsFixer\Cache\FileHandlerInterface + */ + private $handler; + /** + * @var \PhpCsFixer\Cache\SignatureInterface + */ + private $signature; + /** + * @var bool + */ + private $isDryRun; + /** + * @var \PhpCsFixer\Cache\DirectoryInterface + */ + private $cacheDirectory; + /** + * @var int + */ + private $writeCounter = 0; + /** + * @var bool + */ + private $signatureWasUpdated = \false; + /** + * @var CacheInterface + */ + private $cache; + public function __construct(\PhpCsFixer\Cache\FileHandlerInterface $handler, \PhpCsFixer\Cache\SignatureInterface $signature, bool $isDryRun = \false, ?\PhpCsFixer\Cache\DirectoryInterface $cacheDirectory = null) + { + $this->handler = $handler; + $this->signature = $signature; + $this->isDryRun = $isDryRun; + $this->cacheDirectory = $cacheDirectory ?? new \PhpCsFixer\Cache\Directory(''); + $this->readCache(); + } + public function __destruct() + { + if (\true === $this->signatureWasUpdated || 0 !== $this->writeCounter) { + $this->writeCache(); + } + } + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep() : array + { + throw new \BadMethodCallException('Cannot serialize ' . __CLASS__); + } + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup() : void + { + throw new \BadMethodCallException('Cannot unserialize ' . __CLASS__); + } + public function needFixing(string $file, string $fileContent) : bool + { + $file = $this->cacheDirectory->getRelativePathTo($file); + return !$this->cache->has($file) || $this->cache->get($file) !== $this->calcHash($fileContent); + } + public function setFile(string $file, string $fileContent) : void + { + $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); + } else { + $this->cache->set($file, $hash); + } + if (self::WRITE_FREQUENCY === ++$this->writeCounter) { + $this->writeCounter = 0; + $this->writeCache(); + } + } + private function readCache() : void + { + $cache = $this->handler->read(); + if (null === $cache || !$this->signature->equals($cache->getSignature())) { + $cache = new \PhpCsFixer\Cache\Cache($this->signature); + $this->signatureWasUpdated = \true; + } + $this->cache = $cache; + } + private function writeCache() : void + { + $this->handler->write($this->cache); + } + private function calcHash(string $content) : string + { + return \md5($content); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php new file mode 100644 index 00000000000..366b7816cf9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandler.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +use ECSPrefix202307\Symfony\Component\Filesystem\Exception\IOException; +/** + * @author Andreas Möller + * + * @internal + */ +final class FileHandler implements \PhpCsFixer\Cache\FileHandlerInterface +{ + /** + * @var string + */ + private $file; + public function __construct(string $file) + { + $this->file = $file; + } + public function getFile() : string + { + return $this->file; + } + public function read() : ?\PhpCsFixer\Cache\CacheInterface + { + if (!\file_exists($this->file)) { + return null; + } + $content = \file_get_contents($this->file); + try { + $cache = \PhpCsFixer\Cache\Cache::fromJson($content); + } catch (\InvalidArgumentException $exception) { + return null; + } + return $cache; + } + public function write(\PhpCsFixer\Cache\CacheInterface $cache) : void + { + $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); + // Ensure path is created, but ignore if already exists. FYI: ignore EA suggestion in IDE, + // `mkdir()` returns `false` for existing paths, so we can't mix it with `is_dir()` in one condition. + if (!\is_dir($dir)) { + @\mkdir($dir, 0777, \true); + } + if (!\is_dir($dir)) { + throw new IOException(\sprintf('Directory of cache file "%s" does not exists and couldn\'t be created.', $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, $error['message'] ?? 'no reason available'), 0, null, $this->file); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php new file mode 100644 index 00000000000..ea92a0f9201 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/FileHandlerInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface FileHandlerInterface +{ + public function getFile() : string; + public function read() : ?\PhpCsFixer\Cache\CacheInterface; + public function write(\PhpCsFixer\Cache\CacheInterface $cache) : void; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php new file mode 100644 index 00000000000..dba287c546b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/NullCacheManager.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +final class NullCacheManager implements \PhpCsFixer\Cache\CacheManagerInterface +{ + public function needFixing(string $file, string $fileContent) : bool + { + return \true; + } + public function setFile(string $file, string $fileContent) : void + { + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php new file mode 100644 index 00000000000..3ae61c6969d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/Signature.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +final class Signature implements \PhpCsFixer\Cache\SignatureInterface +{ + /** + * @var string + */ + private $phpVersion; + /** + * @var string + */ + private $fixerVersion; + /** + * @var string + */ + private $indent; + /** + * @var string + */ + private $lineEnding; + /** + * @var array|bool> + */ + private $rules; + /** + * @param array|bool> $rules + */ + public function __construct(string $phpVersion, string $fixerVersion, string $indent, string $lineEnding, array $rules) + { + $this->phpVersion = $phpVersion; + $this->fixerVersion = $fixerVersion; + $this->indent = $indent; + $this->lineEnding = $lineEnding; + $this->rules = self::makeJsonEncodable($rules); + } + public function getPhpVersion() : string + { + return $this->phpVersion; + } + public function getFixerVersion() : string + { + return $this->fixerVersion; + } + public function getIndent() : string + { + return $this->indent; + } + public function getLineEnding() : string + { + return $this->lineEnding; + } + public function getRules() : array + { + return $this->rules; + } + /** + * @param \PhpCsFixer\Cache\SignatureInterface $signature + */ + public function equals($signature) : bool + { + return $this->phpVersion === $signature->getPhpVersion() && $this->fixerVersion === $signature->getFixerVersion() && $this->indent === $signature->getIndent() && $this->lineEnding === $signature->getLineEnding() && $this->rules === $signature->getRules(); + } + /** + * @param array|bool> $data + * + * @return array|bool> + */ + private static function makeJsonEncodable(array $data) : array + { + \array_walk_recursive($data, static function (&$item) : void { + if (\is_string($item) && !\mb_detect_encoding($item, 'utf-8', \true)) { + $item = \base64_encode($item); + } + }); + return $data; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php new file mode 100644 index 00000000000..c8ec5b1fb4c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Cache/SignatureInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Cache; + +/** + * @author Andreas Möller + * + * @internal + */ +interface SignatureInterface +{ + public function getPhpVersion() : string; + public function getFixerVersion() : string; + public function getIndent() : string; + public function getLineEnding() : string; + /** + * @return array|bool> + */ + public function getRules() : array; + public function equals(self $signature) : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Config.php b/vendor/friendsofphp/php-cs-fixer/src/Config.php new file mode 100644 index 00000000000..2998fe2307c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Config.php @@ -0,0 +1,192 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +/** + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + */ +class Config implements \PhpCsFixer\ConfigInterface +{ + /** + * @var string + */ + private $cacheFile = '.php-cs-fixer.cache'; + /** + * @var FixerInterface[] + */ + private $customFixers = []; + /** + * @var null|iterable<\SplFileInfo> + */ + private $finder; + /** + * @var string + */ + private $format = 'txt'; + /** + * @var bool + */ + private $hideProgress = \false; + /** + * @var string + */ + private $indent = ' '; + /** + * @var bool + */ + private $isRiskyAllowed = \false; + /** + * @var string + */ + private $lineEnding = "\n"; + /** + * @var string + */ + private $name; + /** + * @var null|string + */ + private $phpExecutable; + /** + * @TODO: 4.0 - update to @PER + * + * @var array|bool> + */ + private $rules = ['@PSR12' => \true]; + /** + * @var bool + */ + private $usingCache = \true; + public function __construct(string $name = 'default') + { + $this->name = $name; + } + public function getCacheFile() : string + { + return $this->cacheFile; + } + public function getCustomFixers() : array + { + return $this->customFixers; + } + /** + * @return Finder + */ + public function getFinder() : iterable + { + if (null === $this->finder) { + $this->finder = new \PhpCsFixer\Finder(); + } + return $this->finder; + } + public function getFormat() : string + { + return $this->format; + } + public function getHideProgress() : bool + { + return $this->hideProgress; + } + public function getIndent() : string + { + return $this->indent; + } + public function getLineEnding() : string + { + return $this->lineEnding; + } + public function getName() : string + { + return $this->name; + } + public function getPhpExecutable() : ?string + { + return $this->phpExecutable; + } + public function getRiskyAllowed() : bool + { + return $this->isRiskyAllowed; + } + public function getRules() : array + { + return $this->rules; + } + public function getUsingCache() : bool + { + return $this->usingCache; + } + public function registerCustomFixers(iterable $fixers) : \PhpCsFixer\ConfigInterface + { + foreach ($fixers as $fixer) { + $this->addCustomFixer($fixer); + } + return $this; + } + public function setCacheFile(string $cacheFile) : \PhpCsFixer\ConfigInterface + { + $this->cacheFile = $cacheFile; + return $this; + } + public function setFinder(iterable $finder) : \PhpCsFixer\ConfigInterface + { + $this->finder = $finder; + return $this; + } + public function setFormat(string $format) : \PhpCsFixer\ConfigInterface + { + $this->format = $format; + return $this; + } + public function setHideProgress(bool $hideProgress) : \PhpCsFixer\ConfigInterface + { + $this->hideProgress = $hideProgress; + return $this; + } + public function setIndent(string $indent) : \PhpCsFixer\ConfigInterface + { + $this->indent = $indent; + return $this; + } + public function setLineEnding(string $lineEnding) : \PhpCsFixer\ConfigInterface + { + $this->lineEnding = $lineEnding; + return $this; + } + public function setPhpExecutable(?string $phpExecutable) : \PhpCsFixer\ConfigInterface + { + $this->phpExecutable = $phpExecutable; + return $this; + } + public function setRiskyAllowed(bool $isRiskyAllowed) : \PhpCsFixer\ConfigInterface + { + $this->isRiskyAllowed = $isRiskyAllowed; + return $this; + } + public function setRules(array $rules) : \PhpCsFixer\ConfigInterface + { + $this->rules = $rules; + return $this; + } + public function setUsingCache(bool $usingCache) : \PhpCsFixer\ConfigInterface + { + $this->usingCache = $usingCache; + return $this; + } + private function addCustomFixer(FixerInterface $fixer) : void + { + $this->customFixers[] = $fixer; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php b/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php new file mode 100644 index 00000000000..a71731aab60 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ConfigInterface.php @@ -0,0 +1,115 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +interface ConfigInterface +{ + /** + * Returns the path to the cache file. + * + * @return null|string Returns null if not using cache + */ + public function getCacheFile() : ?string; + /** + * Returns the custom fixers to use. + * + * @return FixerInterface[] + */ + public function getCustomFixers() : array; + /** + * Returns files to scan. + * + * @return iterable<\SplFileInfo> + */ + public function getFinder() : iterable; + public function getFormat() : string; + /** + * Returns true if progress should be hidden. + */ + public function getHideProgress() : bool; + public function getIndent() : string; + public function getLineEnding() : string; + /** + * Returns the name of the configuration. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the configuration + */ + public function getName() : string; + /** + * Get configured PHP executable, if any. + */ + public function getPhpExecutable() : ?string; + /** + * Check if it is allowed to run risky fixers. + */ + public function getRiskyAllowed() : bool; + /** + * Get rules. + * + * Keys of array are names of fixers/sets, values are true/false. + * + * @return array|bool> + */ + public function getRules() : array; + /** + * Returns true if caching should be enabled. + */ + public function getUsingCache() : bool; + /** + * Adds a suite of custom fixers. + * + * Name of custom fixer should follow `VendorName/rule_name` convention. + * + * @param FixerInterface[]|iterable|\Traversable $fixers + */ + public function registerCustomFixers(iterable $fixers) : self; + /** + * Sets the path to the cache file. + */ + public function setCacheFile(string $cacheFile) : self; + /** + * @param iterable<\SplFileInfo> $finder + */ + public function setFinder(iterable $finder) : self; + public function setFormat(string $format) : self; + public function setHideProgress(bool $hideProgress) : self; + public function setIndent(string $indent) : self; + public function setLineEnding(string $lineEnding) : self; + /** + * Set PHP executable. + */ + public function setPhpExecutable(?string $phpExecutable) : self; + /** + * Set if it is allowed to run risky fixers. + */ + public function setRiskyAllowed(bool $isRiskyAllowed) : self; + /** + * Set rules. + * + * Keys of array are names of fixers or sets. + * Value for set must be bool (turn it on or off). + * Value for fixer may be bool (turn it on or off) or array of configuration + * (turn it on and contains configuration for FixerInterface::configure method). + * + * @param array|bool> $rules + */ + public function setRules(array $rules) : self; + public function setUsingCache(bool $usingCache) : self; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php new file mode 100644 index 00000000000..1de73491fc8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidConfigurationException.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; +/** + * Exceptions of this type are thrown on misconfiguration of the Fixer. + * + * @internal + * + * @final Only internal extending this class is supported + */ +class InvalidConfigurationException extends \InvalidArgumentException +{ + public function __construct(string $message, ?int $code = null, ?\Throwable $previous = null) + { + parent::__construct($message, $code ?? FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_CONFIG, $previous); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php new file mode 100644 index 00000000000..09ea5c41662 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidFixerConfigurationException.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\ConfigurationException; + +use PhpCsFixer\Console\Command\FixCommandExitStatusCalculator; +/** + * Exception thrown by Fixers on misconfiguration. + * + * @internal + * + * @final Only internal extending this class is supported + */ +class InvalidFixerConfigurationException extends \PhpCsFixer\ConfigurationException\InvalidConfigurationException +{ + /** + * @var string + */ + private $fixerName; + public function __construct(string $fixerName, string $message, ?\Throwable $previous = null) + { + parent::__construct(\sprintf('[%s] %s', $fixerName, $message), FixCommandExitStatusCalculator::EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG, $previous); + $this->fixerName = $fixerName; + } + public function getFixerName() : string + { + return $this->fixerName; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php new file mode 100644 index 00000000000..2fa55c1207b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/InvalidForEnvFixerConfigurationException.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class InvalidForEnvFixerConfigurationException extends \PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php new file mode 100644 index 00000000000..b5abf7fcea3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ConfigurationException/RequiredFixerConfigurationException.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\ConfigurationException; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class RequiredFixerConfigurationException extends \PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php new file mode 100644 index 00000000000..8b3f0beeb95 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Application.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console; + +use PhpCsFixer\Console\Command\DescribeCommand; +use PhpCsFixer\Console\Command\FixCommand; +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Console\Command\ListFilesCommand; +use PhpCsFixer\Console\Command\ListSetsCommand; +use PhpCsFixer\Console\Command\SelfUpdateCommand; +use PhpCsFixer\Console\SelfUpdate\GithubClient; +use PhpCsFixer\Console\SelfUpdate\NewVersionChecker; +use PhpCsFixer\PharChecker; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\Console\Application as BaseApplication; +use ECSPrefix202307\Symfony\Component\Console\Command\ListCommand; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\ConsoleOutputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + */ +final class Application extends BaseApplication +{ + public const VERSION = '3.22.0'; + public const VERSION_CODENAME = 'Chips & Pizza'; + /** + * @var \PhpCsFixer\ToolInfo + */ + private $toolInfo; + public function __construct() + { + parent::__construct('PHP CS Fixer', self::VERSION); + $this->toolInfo = new ToolInfo(); + // in alphabetical order + $this->add(new DescribeCommand()); + $this->add(new FixCommand($this->toolInfo)); + $this->add(new ListFilesCommand($this->toolInfo)); + $this->add(new ListSetsCommand()); + $this->add(new SelfUpdateCommand(new NewVersionChecker(new GithubClient()), $this->toolInfo, new PharChecker())); + } + public static function getMajorVersion() : int + { + return (int) \explode('.', self::VERSION)[0]; + } + public function doRun(InputInterface $input, OutputInterface $output) : int + { + $stdErr = $output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : ($input->hasParameterOption('--format', \true) && 'txt' !== $input->getParameterOption('--format', null, \true) ? null : $output); + if (null !== $stdErr) { + $warningsDetector = new \PhpCsFixer\Console\WarningsDetector($this->toolInfo); + $warningsDetector->detectOldVendor(); + $warningsDetector->detectOldMajor(); + $warnings = $warningsDetector->getWarnings(); + if (\count($warnings) > 0) { + foreach ($warnings as $warning) { + $stdErr->writeln(\sprintf($stdErr->isDecorated() ? '%s' : '%s', $warning)); + } + $stdErr->writeln(''); + } + } + $result = parent::doRun($input, $output); + if (null !== $stdErr && $output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $triggeredDeprecations = Utils::getTriggeredDeprecations(); + if (\count($triggeredDeprecations) > 0) { + $stdErr->writeln(''); + $stdErr->writeln($stdErr->isDecorated() ? 'Detected deprecations in use:' : 'Detected deprecations in use:'); + foreach ($triggeredDeprecations as $deprecation) { + $stdErr->writeln(\sprintf('- %s', $deprecation)); + } + } + } + return $result; + } + public function getLongVersion() : string + { + $commit = '@git-commit@'; + $versionCommit = ''; + if ('@' . 'git-commit@' !== $commit) { + /** @phpstan-ignore-line as `$commit` is replaced during phar building */ + $versionCommit = \substr($commit, 0, 7); + } + return \implode('', [ + parent::getLongVersion(), + $versionCommit ? \sprintf(' (%s)', $versionCommit) : '', + // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + self::VERSION_CODENAME ? \sprintf(' %s', self::VERSION_CODENAME) : '', + // @phpstan-ignore-line to avoid `Ternary operator condition is always true|false.` + ' by Fabien Potencier and Dariusz Ruminski.', + "\nPHP runtime: " . \PHP_VERSION . '', + ]); + } + protected function getDefaultCommands() : array + { + return [new HelpCommand(), new ListCommand()]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php new file mode 100644 index 00000000000..8c60f751b3c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeCommand.php @@ -0,0 +1,286 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +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\VersionSpecificCodeSampleInterface; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\ToolInfo; +use PhpCsFixer\Utils; +use PhpCsFixer\WordMatcher; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +use ECSPrefix202307\Symfony\Component\Console\Input\InputArgument; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Input\InputOption; +use ECSPrefix202307\Symfony\Component\Console\Output\ConsoleOutputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class DescribeCommand extends Command +{ + protected static $defaultName = 'describe'; + /** + * @var string[] + */ + private $setNames; + /** + * @var \PhpCsFixer\FixerFactory + */ + private $fixerFactory; + /** + * @var array + */ + private $fixers; + public function __construct(?FixerFactory $fixerFactory = null) + { + parent::__construct(); + if (null === $fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + } + $this->fixerFactory = $fixerFactory; + } + protected function configure() : void + { + $this->setDefinition([new InputArgument('name', InputArgument::REQUIRED, 'Name of rule / set.'), new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.')])->setDescription('Describe rule / ruleset.'); + } + protected function execute(InputInterface $input, OutputInterface $output) : int + { + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln($this->getApplication()->getLongVersion()); + } + $resolver = new ConfigurationResolver(new Config(), ['config' => $input->getOption('config')], \getcwd(), new ToolInfo()); + $this->fixerFactory->registerCustomFixers($resolver->getConfig()->getCustomFixers()); + $name = $input->getArgument('name'); + try { + if (\strncmp($name, '@', \strlen('@')) === 0) { + $this->describeSet($output, $name); + return 0; + } + $this->describeRule($output, $name); + } catch (\PhpCsFixer\Console\Command\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, string $name) : void + { + $fixers = $this->getFixers(); + if (!isset($fixers[$name])) { + throw new \PhpCsFixer\Console\Command\DescribeNameNotFoundException($name, 'rule'); + } + /** @var FixerInterface $fixer */ + $fixer = $fixers[$name]; + $definition = $fixer->getDefinition(); + $summary = $definition->getSummary(); + if ($fixer instanceof DeprecatedFixerInterface) { + $successors = $fixer->getSuccessorsNames(); + $message = [] === $successors ? 'will be removed on next major version' : \sprintf('use %s instead', Utils::naturalLanguageJoinWithBackticks($successors)); + $message = Preg::replace('/(`.+?`)/', '$1', $message); + $summary .= \sprintf(' DEPRECATED: %s.', $message); + } + $output->writeln(\sprintf('Description of %s rule.', $name)); + if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { + $output->writeln(\sprintf('Fixer class: %s.', \get_class($fixer))); + } + $output->writeln($summary); + $description = $definition->getDescription(); + if (null !== $description) { + $output->writeln($description); + } + $output->writeln(''); + if ($fixer->isRisky()) { + $output->writeln('Fixer applying this rule is risky.'); + $riskyDescription = $definition->getRiskyDescription(); + if (null !== $riskyDescription) { + $output->writeln($riskyDescription); + } + $output->writeln(''); + } + if ($fixer instanceof ConfigurableFixerInterface) { + $configurationDefinition = $fixer->getConfigurationDefinition(); + $options = $configurationDefinition->getOptions(); + $output->writeln(\sprintf('Fixer is configurable using following option%s:', 1 === \count($options) ? '' : 's')); + foreach ($options as $option) { + $line = '* ' . OutputFormatter::escape($option->getName()) . ''; + $allowed = \PhpCsFixer\Console\Command\HelpCommand::getDisplayableAllowedValues($option); + if (null === $allowed) { + $allowed = \array_map(static function (string $type) : string { + return '' . $type . ''; + }, $option->getAllowedTypes()); + } else { + $allowed = \array_map(static function ($value) : string { + return $value instanceof AllowedValueSubset ? 'a subset of ' . Utils::toString($value->getAllowedValues()) . '' : '' . Utils::toString($value) . ''; + }, $allowed); + } + $line .= ' (' . Utils::naturalLanguageJoin($allowed, '') . ')'; + $description = Preg::replace('/(`.+?`)/', '$1', OutputFormatter::escape($option->getDescription())); + $line .= ': ' . \lcfirst(Preg::replace('/\\.$/', '', $description)) . '; '; + if ($option->hasDefault()) { + $line .= \sprintf('defaults to %s', Utils::toString($option->getDefault())); + } else { + $line .= 'required'; + } + if ($option instanceof DeprecatedFixerOption) { + $line .= '. DEPRECATED: ' . Preg::replace('/(`.+?`)/', '$1', OutputFormatter::escape(\lcfirst($option->getDeprecationMessage()))); + } + if ($option instanceof AliasedFixerOption) { + $line .= '; DEPRECATED alias: ' . $option->getAlias() . ''; + } + $output->writeln($line); + } + $output->writeln(''); + } + /** @var CodeSampleInterface[] $codeSamples */ + $codeSamples = \array_filter($definition->getCodeSamples(), static function (CodeSampleInterface $codeSample) : bool { + if ($codeSample instanceof VersionSpecificCodeSampleInterface) { + return $codeSample->isSuitableFor(\PHP_VERSION_ID); + } + return \true; + }); + if (0 === \count($codeSamples)) { + $output->writeln(['Fixing examples cannot be demonstrated on the current PHP version.', '']); + } else { + $output->writeln('Fixing examples:'); + $differ = new FullDiffer(); + $diffFormatter = new DiffConsoleFormatter($output->isDecorated(), \sprintf(' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', \PHP_EOL, \PHP_EOL)); + foreach ($codeSamples as $index => $codeSample) { + $old = $codeSample->getCode(); + $tokens = Tokens::fromCode($old); + $configuration = $codeSample->getConfiguration(); + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($configuration ?? []); + } + $file = $codeSample instanceof FileSpecificCodeSampleInterface ? $codeSample->getSplFileInfo() : new StdinFileInfo(); + $fixer->fix($file, $tokens); + $diff = $differ->diff($old, $tokens->generateCode()); + if ($fixer instanceof ConfigurableFixerInterface) { + if (null === $configuration) { + $output->writeln(\sprintf(' * Example #%d. Fixing with the default configuration.', $index + 1)); + } else { + $output->writeln(\sprintf(' * Example #%d. Fixing with configuration: %s.', $index + 1, Utils::toString($codeSample->getConfiguration()))); + } + } else { + $output->writeln(\sprintf(' * Example #%d.', $index + 1)); + } + $output->writeln([$diffFormatter->format($diff, ' %s'), '']); + } + } + } + private function describeSet(OutputInterface $output, string $name) : void + { + if (!\in_array($name, $this->getSetNames(), \true)) { + throw new \PhpCsFixer\Console\Command\DescribeNameNotFoundException($name, 'set'); + } + $ruleSetDefinitions = RuleSets::getSetDefinitions(); + $fixers = $this->getFixers(); + $output->writeln(\sprintf('Description of the %s set.', $ruleSetDefinitions[$name]->getName())); + $output->writeln($this->replaceRstLinks($ruleSetDefinitions[$name]->getDescription())); + if ($ruleSetDefinitions[$name]->isRisky()) { + $output->writeln('This set contains risky rules.'); + } + $output->writeln(''); + $help = ''; + foreach ($ruleSetDefinitions[$name]->getRules() as $rule => $config) { + if (\strncmp($rule, '@', \strlen('@')) === 0) { + $set = $ruleSetDefinitions[$rule]; + $help .= \sprintf(" * %s%s\n | %s\n\n", $rule, $set->isRisky() ? ' risky' : '', $this->replaceRstLinks($set->getDescription())); + continue; + } + /** @var FixerInterface $fixer */ + $fixer = $fixers[$rule]; + $definition = $fixer->getDefinition(); + $help .= \sprintf(" * %s%s\n | %s\n%s\n", $rule, $fixer->isRisky() ? ' risky' : '', $definition->getSummary(), \true !== $config ? \sprintf(" | Configuration: %s\n", Utils::toString($config)) : ''); + } + $output->write($help); + } + /** + * @return array + */ + private function getFixers() : array + { + 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; + } + /** + * @return string[] + */ + private function getSetNames() : array + { + if (null !== $this->setNames) { + return $this->setNames; + } + $this->setNames = RuleSets::getSetDefinitionNames(); + return $this->setNames; + } + /** + * @param string $type 'rule'|'set' + */ + private function describeList(OutputInterface $output, string $type) : void + { + 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; + } + /** @var string[] $items */ + foreach ($describe as $list => $items) { + $output->writeln(\sprintf('Defined %s:', $list)); + foreach ($items as $name => $item) { + $output->writeln(\sprintf('* %s', \is_string($name) ? $name : $item)); + } + } + } + private function replaceRstLinks(string $content) : string + { + return Preg::replaceCallback('/(`[^<]+<[^>]+>`_)/', static function (array $matches) { + return Preg::replaceCallback('/`(.*)<(.*)>`_/', static function (array $matches) : string { + return $matches[1] . '(' . $matches[2] . ')'; + }, $matches[1]); + }, $content); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php new file mode 100644 index 00000000000..91253cfe972 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DescribeNameNotFoundException.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +/** + * @internal + */ +final class DescribeNameNotFoundException extends \InvalidArgumentException +{ + /** + * @var string + */ + private $name; + /** + * 'rule'|'set'. + * @var string + */ + private $type; + public function __construct(string $name, string $type) + { + $this->name = $name; + $this->type = $type; + parent::__construct(); + } + public function getName() : string + { + return $this->name; + } + public function getType() : string + { + return $this->type; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php new file mode 100644 index 00000000000..dee600ea6ce --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/DocumentationCommand.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Documentation\DocumentationLocator; +use PhpCsFixer\Documentation\FixerDocumentGenerator; +use PhpCsFixer\Documentation\ListDocumentGenerator; +use PhpCsFixer\Documentation\RuleSetDocumentationGenerator; +use PhpCsFixer\FixerFactory; +use PhpCsFixer\RuleSet\RuleSets; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +use ECSPrefix202307\Symfony\Component\Filesystem\Filesystem; +use ECSPrefix202307\Symfony\Component\Finder\Finder; +use ECSPrefix202307\Symfony\Component\Finder\SplFileInfo; +/** + * @internal + */ +final class DocumentationCommand extends Command +{ + protected static $defaultName = 'documentation'; + protected function configure() : void + { + $this->setAliases(['doc'])->setDescription('Dumps the documentation of the project into its "/doc" directory.'); + } + protected function execute(InputInterface $input, OutputInterface $output) : int + { + $filesystem = new Filesystem(); + $locator = new DocumentationLocator(); + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixers = $fixerFactory->getFixers(); + $setDefinitions = RuleSets::getSetDefinitions(); + $fixerDocumentGenerator = new FixerDocumentGenerator($locator); + $ruleSetDocumentationGenerator = new RuleSetDocumentationGenerator($locator); + $listDocumentGenerator = new ListDocumentGenerator($locator); + // Array of existing fixer docs. + // We first override existing files, and then we will delete files that are no longer needed. + // We cannot remove all files first, as generation of docs is re-using existing docs to extract code-samples for + // VersionSpecificCodeSample under incompatible PHP version. + $docForFixerRelativePaths = []; + foreach ($fixers as $fixer) { + $docForFixerRelativePaths[] = $locator->getFixerDocumentationFileRelativePath($fixer); + $filesystem->dumpFile($locator->getFixerDocumentationFilePath($fixer), $fixerDocumentGenerator->generateFixerDocumentation($fixer)); + } + /** @var SplFileInfo $file */ + foreach ((new Finder())->files()->in($locator->getFixersDocumentationDirectoryPath())->notPath($docForFixerRelativePaths) as $file) { + $filesystem->remove($file->getPathname()); + } + // Fixer doc. index + $filesystem->dumpFile($locator->getFixersDocumentationIndexFilePath(), $fixerDocumentGenerator->generateFixersDocumentationIndex($fixers)); + // RuleSet docs. + /** @var SplFileInfo $file */ + foreach ((new Finder())->files()->in($locator->getRuleSetsDocumentationDirectoryPath()) as $file) { + $filesystem->remove($file->getPathname()); + } + $paths = []; + foreach ($setDefinitions as $name => $definition) { + $path = $locator->getRuleSetsDocumentationFilePath($name); + $paths[$name] = $path; + $filesystem->dumpFile($path, $ruleSetDocumentationGenerator->generateRuleSetsDocumentation($definition, $fixers)); + } + // RuleSet doc. index + $filesystem->dumpFile($locator->getRuleSetsDocumentationIndexFilePath(), $ruleSetDocumentationGenerator->generateRuleSetsDocumentationIndex($paths)); + // List file / Appendix + $filesystem->dumpFile($locator->getListingFilePath(), $listDocumentGenerator->generateListingDocumentation($fixers)); + $output->writeln('Docs updated.'); + return 0; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php new file mode 100644 index 00000000000..c8fcf30329a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommand.php @@ -0,0 +1,258 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\Console\Output\ErrorOutput; +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\Console\Output\Progress\ProgressOutputFactory; +use PhpCsFixer\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReportSummary; +use PhpCsFixer\Error\ErrorsManager; +use PhpCsFixer\FixerFileProcessedEvent; +use PhpCsFixer\Runner\Runner; +use PhpCsFixer\ToolInfoInterface; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Input\InputArgument; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Input\InputOption; +use ECSPrefix202307\Symfony\Component\Console\Output\ConsoleOutputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +use ECSPrefix202307\Symfony\Component\Console\Terminal; +use ECSPrefix202307\Symfony\Component\EventDispatcher\EventDispatcher; +use ECSPrefix202307\Symfony\Component\EventDispatcher\EventDispatcherInterface; +use ECSPrefix202307\Symfony\Component\Stopwatch\Stopwatch; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + */ +final class FixCommand extends Command +{ + protected static $defaultName = 'fix'; + /** + * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface + */ + private $eventDispatcher; + /** + * @var \PhpCsFixer\Error\ErrorsManager + */ + private $errorsManager; + /** + * @var \Symfony\Component\Stopwatch\Stopwatch + */ + private $stopwatch; + /** + * @var \PhpCsFixer\ConfigInterface + */ + private $defaultConfig; + /** + * @var \PhpCsFixer\ToolInfoInterface + */ + private $toolInfo; + /** + * @var \PhpCsFixer\Console\Output\Progress\ProgressOutputFactory + */ + private $progressOutputFactory; + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct(); + $this->eventDispatcher = new EventDispatcher(); + $this->errorsManager = new ErrorsManager(); + $this->stopwatch = new Stopwatch(); + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + $this->progressOutputFactory = new ProgressOutputFactory(); + } + /** + * {@inheritdoc} + * + * Override here to only generate the help copy when used. + */ + public function getHelp() : string + { + return <<<'EOF' +The %command.name% command tries to fix as much coding standards +problems as possible on a given file or files in a given directory and its subdirectories: + + $ php %command.full_name% /path/to/dir + $ php %command.full_name% /path/to/file + +By default --path-mode is set to `override`, which means, that if you specify the path to a file or a directory via +command arguments, then the paths provided to a `Finder` in config file will be ignored. You can use --path-mode=intersection +to merge paths from the config file and from the argument: + + $ php %command.full_name% --path-mode=intersection /path/to/dir + +The --format option for the output format. Supported formats are `txt` (default one), `json`, `xml`, `checkstyle`, `junit` and `gitlab`. + +NOTE: the output for the following formats are generated in accordance with schemas + +* `checkstyle` follows the common `"checkstyle" XML schema `_ +* `gitlab` follows the `codeclimate JSON schema `_ +* `json` follows the `own JSON schema `_ +* `junit` follows the `JUnit XML schema from Jenkins `_ +* `xml` follows the `own XML schema `_ + +The --quiet Do not output any message. + +The --verbose option will show the applied rules. When using the `txt` format it will also display progress notifications. + +NOTE: if there is an error like "errors reported during linting after fixing", you can use this to be even more verbose for debugging purpose + +* `-v`: verbose +* `-vv`: very verbose +* `-vvv`: debug + +The --rules option limits the rules to apply to the +project: + +EOF + . <<<'EOF' + + $ php %command.full_name% /path/to/project --rules=@PSR12 + +By default the PSR-12 rules are used. + +The --rules option lets you choose the exact rules to +apply (the rule names must be separated by a comma): + + $ php %command.full_name% /path/to/dir --rules=line_ending,full_opening_tag,indentation_type + +You can also exclude the rules you don't want by placing a dash in front of the rule name, if this is more convenient, +using -name_of_fixer: + + $ php %command.full_name% /path/to/dir --rules=-full_opening_tag,-indentation_type + +When using combinations of exact and exclude rules, applying exact rules along with above excluded results: + + $ php %command.full_name% /path/to/project --rules=@Symfony,-@PSR1,-blank_line_before_statement,strict_comparison + +Complete configuration for rules can be supplied using a `json` formatted string. + + $ php %command.full_name% /path/to/project --rules='{"concat_space": {"spacing": "none"}}' + +The --dry-run flag will run the fixer without making changes to your files. + +The --diff flag can be used to let the fixer output all the changes it makes. + +The --allow-risky option (pass `yes` or `no`) allows you to set whether risky rules may run. Default value is taken from config file. +A rule is considered risky if it could change code behaviour. By default no risky rules are run. + +The --stop-on-violation flag stops the execution upon first file that needs to be fixed. + +The --show-progress option allows you to choose the way process progress is rendered: + +* none: disables progress output; +* dots: multiline progress output with number of files and percentage on each line. + +If the option is not provided, it defaults to dots unless a config file that disables output is used, in which case it defaults to none. This option has no effect if the verbosity of the command is less than verbose. + + $ php %command.full_name% --verbose --show-progress=dots + +By using --using-cache option with `yes` or `no` you can set if the caching +mechanism should be used. + +The command can also read from standard input, in which case it won't +automatically fix anything: + + $ cat foo.php | php %command.full_name% --diff - + +Finally, if you don't need BC kept on CLI level, you might use `PHP_CS_FIXER_FUTURE_MODE` to start using options that +would be default in next MAJOR release and to forbid using deprecated configuration: + + $ PHP_CS_FIXER_FUTURE_MODE=1 php %command.full_name% -v --diff + +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; + } + protected function configure() : void + { + $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).', ConfigurationResolver::PATH_MODE_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-fixer.php 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('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, dots).')])->setDescription('Fixes a directory or a file.'); + } + protected function execute(InputInterface $input, OutputInterface $output) : int + { + $verbosity = $output->getVerbosity(); + $passedConfig = $input->getOption('config'); + $passedRules = $input->getOption('rules'); + if (null !== $passedConfig && null !== $passedRules) { + throw new InvalidConfigurationException('Passing both `--config` and `--rules` options is not allowed.'); + } + $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'), '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()); + } + $configFile = $resolver->getConfigFile(); + $stdErr->writeln(\sprintf('Loaded config %s%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)); + } + } + } + $finder = new \ArrayIterator(\iterator_to_array($resolver->getFinder())); + if (null !== $stdErr && $resolver->configFinderIsOverridden()) { + $stdErr->writeln(\sprintf($stdErr->isDecorated() ? '%s' : '%s', 'Paths from configuration file have been overridden by paths provided as command arguments.')); + } + $progressType = $resolver->getProgressType(); + $progressOutput = $this->progressOutputFactory->create($progressType, new OutputContext($stdErr, (new Terminal())->getWidth(), \count($finder))); + $runner = new Runner($finder, $resolver->getFixers(), $resolver->getDiffer(), ProgressOutputType::NONE !== $progressType ? $this->eventDispatcher : null, $this->errorsManager, $resolver->getLinter(), $resolver->isDryRun(), $resolver->getCacheManager(), $resolver->getDirectory(), $resolver->shouldStopOnViolation()); + $this->eventDispatcher->addListener(FixerFileProcessedEvent::NAME, [$progressOutput, 'onFixerFileProcessed']); + $this->stopwatch->start('fixFiles'); + $changed = $runner->fix(); + $this->stopwatch->stop('fixFiles'); + $this->eventDispatcher->removeListener(FixerFileProcessedEvent::NAME, [$progressOutput, 'onFixerFileProcessed']); + $progressOutput->printLegend(); + $fixEvent = $this->stopwatch->getEvent('fixFiles'); + $reportSummary = new ReportSummary($changed, \count($finder), $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 \PhpCsFixer\Console\Command\FixCommandExitStatusCalculator(); + return $exitStatusCalculator->calculate($resolver->isDryRun(), \count($changed) > 0, \count($invalidErrors) > 0, \count($exceptionErrors) > 0, \count($lintErrors) > 0); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php new file mode 100644 index 00000000000..890837c8728 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/FixCommandExitStatusCalculator.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FixCommandExitStatusCalculator +{ + // Exit status 1 is reserved for environment constraints not matched. + public const EXIT_STATUS_FLAG_HAS_INVALID_FILES = 4; + public const EXIT_STATUS_FLAG_HAS_CHANGED_FILES = 8; + public const EXIT_STATUS_FLAG_HAS_INVALID_CONFIG = 16; + public const EXIT_STATUS_FLAG_HAS_INVALID_FIXER_CONFIG = 32; + public const EXIT_STATUS_FLAG_EXCEPTION_IN_APP = 64; + public function calculate(bool $isDryRun, bool $hasChangedFiles, bool $hasInvalidErrors, bool $hasExceptionErrors, bool $hasLintErrorsAfterFixing) : int + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php new file mode 100644 index 00000000000..ebf35a3f117 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/HelpCommand.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerOptionInterface; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\HelpCommand as BaseHelpCommand; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatterStyle; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + * + * @internal + */ +final class HelpCommand extends BaseHelpCommand +{ + protected static $defaultName = 'help'; + /** + * Returns the allowed values of the given option that can be converted to a string. + * + * @return null|list + */ + public static function getDisplayableAllowedValues(FixerOptionInterface $option) : ?array + { + $allowed = $option->getAllowedValues(); + if (null !== $allowed) { + $allowed = \array_filter($allowed, static function ($value) : bool { + return !$value instanceof \Closure; + }); + \usort($allowed, static function ($valueA, $valueB) : int { + if ($valueA instanceof AllowedValueSubset) { + return -1; + } + if ($valueB instanceof AllowedValueSubset) { + return 1; + } + return \strcasecmp(Utils::toString($valueA), Utils::toString($valueB)); + }); + if (0 === \count($allowed)) { + $allowed = null; + } + } + return $allowed; + } + protected function initialize(InputInterface $input, OutputInterface $output) : void + { + $output->getFormatter()->setStyle('url', new OutputFormatterStyle('blue')); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php new file mode 100644 index 00000000000..988dd9dac0e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListFilesCommand.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Config; +use PhpCsFixer\ConfigInterface; +use PhpCsFixer\Console\ConfigurationResolver; +use PhpCsFixer\ToolInfoInterface; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Input\InputOption; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +use ECSPrefix202307\Symfony\Component\Filesystem\Path; +/** + * @author Markus Staab + * + * @internal + */ +final class ListFilesCommand extends Command +{ + protected static $defaultName = 'list-files'; + /** + * @var \PhpCsFixer\ConfigInterface + */ + private $defaultConfig; + /** + * @var \PhpCsFixer\ToolInfoInterface + */ + private $toolInfo; + public function __construct(ToolInfoInterface $toolInfo) + { + parent::__construct(); + $this->defaultConfig = new Config(); + $this->toolInfo = $toolInfo; + } + protected function configure() : void + { + $this->setDefinition([new InputOption('config', '', InputOption::VALUE_REQUIRED, 'The path to a .php-cs-fixer.php file.')])->setDescription('List all files being fixed by the given config.'); + } + protected function execute(InputInterface $input, OutputInterface $output) : int + { + $passedConfig = $input->getOption('config'); + $cwd = \getcwd(); + $resolver = new ConfigurationResolver($this->defaultConfig, ['config' => $passedConfig], $cwd, $this->toolInfo); + $finder = $resolver->getFinder(); + /** @var \SplFileInfo $file */ + foreach ($finder as $file) { + if ($file->isFile()) { + $relativePath = './' . Path::makeRelative($file->getRealPath(), $cwd); + // unify directory separators across operating system + $relativePath = \str_replace('/', \DIRECTORY_SEPARATOR, $relativePath); + $output->writeln(\escapeshellarg($relativePath)); + } + } + return 0; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php new file mode 100644 index 00000000000..2f350adf5ea --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/ListSetsCommand.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterFactory; +use PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface; +use PhpCsFixer\Console\Report\ListSetsReport\ReportSummary; +use PhpCsFixer\Console\Report\ListSetsReport\TextReporter; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Input\InputOption; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ListSetsCommand extends Command +{ + protected static $defaultName = 'list-sets'; + protected function configure() : void + { + $this->setDefinition([new InputOption('format', '', InputOption::VALUE_REQUIRED, 'To output results in other formats.', (new TextReporter())->getFormat())])->setDescription('List all available RuleSets.'); + } + protected function execute(InputInterface $input, OutputInterface $output) + { + $reporter = $this->resolveReporterWithFactory($input->getOption('format'), new ReporterFactory()); + $reportSummary = new ReportSummary(\array_values(RuleSets::getSetDefinitions())); + $report = $reporter->generate($reportSummary); + $output->isDecorated() ? $output->write(OutputFormatter::escape($report)) : $output->write($report, \false, OutputInterface::OUTPUT_RAW); + return 0; + } + private function resolveReporterWithFactory(string $format, ReporterFactory $factory) : ReporterInterface + { + try { + $factory->registerBuiltInReporters(); + $reporter = $factory->getReporter($format); + } catch (\UnexpectedValueException $e) { + $formats = $factory->getFormats(); + \sort($formats); + throw new InvalidConfigurationException(\sprintf('The format "%s" is not defined, supported are %s.', $format, Utils::naturalLanguageJoin($formats))); + } + return $reporter; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php new file mode 100644 index 00000000000..dbb0e2de0f1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Command/SelfUpdateCommand.php @@ -0,0 +1,126 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Command; + +use PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface; +use PhpCsFixer\PharCheckerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\ToolInfoInterface; +use ECSPrefix202307\Symfony\Component\Console\Attribute\AsCommand; +use ECSPrefix202307\Symfony\Component\Console\Command\Command; +use ECSPrefix202307\Symfony\Component\Console\Input\InputInterface; +use ECSPrefix202307\Symfony\Component\Console\Input\InputOption; +use ECSPrefix202307\Symfony\Component\Console\Output\ConsoleOutputInterface; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @author Igor Wiedler + * @author Stephane PY + * @author Grégoire Pineau + * @author Dariusz Rumiński + * + * @internal + */ +final class SelfUpdateCommand extends Command +{ + protected static $defaultName = 'self-update'; + /** + * @var \PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface + */ + private $versionChecker; + /** + * @var \PhpCsFixer\ToolInfoInterface + */ + private $toolInfo; + /** + * @var \PhpCsFixer\PharCheckerInterface + */ + 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() : void + { + $this->setAliases(['selfupdate'])->setDefinition([new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Force update to next major version if available.')])->setDescription('Update php-cs-fixer.phar to the latest stable version.')->setHelp(<<<'EOT' +The %command.name% command replace your php-cs-fixer.phar by the +latest version released on: +https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases + +$ php php-cs-fixer.phar %command.name% + +EOT +); + } + protected function execute(InputInterface $input, OutputInterface $output) : int + { + if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity() && $output instanceof ConsoleOutputInterface) { + $stdErr = $output->getErrorOutput(); + $stdErr->writeln($this->getApplication()->getLongVersion()); + } + if (!$this->toolInfo->isInstalledAsPhar()) { + $output->writeln('Self-update is available only for PHAR version.'); + return 1; + } + $currentVersion = $this->getApplication()->getVersion(); + Preg::match('/^v?(?\\d+)\\./', $currentVersion, $matches); + $currentMajor = (int) $matches['major']; + try { + $latestVersion = $this->versionChecker->getLatestVersion(); + $latestVersionOfCurrentMajor = $this->versionChecker->getLatestVersionOfMajor($currentMajor); + } catch (\Exception $exception) { + $output->writeln(\sprintf('Unable to determine newest version: %s', $exception->getMessage())); + return 1; + } + if (1 !== $this->versionChecker->compareVersions($latestVersion, $currentVersion)) { + $output->writeln('PHP CS Fixer is already up-to-date.'); + return 0; + } + $remoteTag = $latestVersion; + if (0 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $latestVersion) && \true !== $input->getOption('force')) { + $output->writeln(\sprintf('A new major version of PHP CS Fixer is available (%s)', $latestVersion)); + $output->writeln(\sprintf('Before upgrading please read https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/%s/UPGRADE-v%s.md', $latestVersion, $currentMajor + 1)); + $output->writeln('If you are ready to upgrade run this command with -f'); + $output->writeln('Checking for new minor/patch version...'); + if (1 !== $this->versionChecker->compareVersions($latestVersionOfCurrentMajor, $currentVersion)) { + $output->writeln('No minor update for PHP CS Fixer.'); + return 0; + } + $remoteTag = $latestVersionOfCurrentMajor; + } + $localFilename = \realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0]; + if (!\is_writable($localFilename)) { + $output->writeln(\sprintf('No permission to update "%s" file.', $localFilename)); + return 1; + } + $tempFilename = \dirname($localFilename) . '/' . \basename($localFilename, '.phar') . '-tmp.phar'; + $remoteFilename = $this->toolInfo->getPharDownloadUri($remoteTag); + if (\false === @\copy($remoteFilename, $tempFilename)) { + $output->writeln(\sprintf('Unable to download new version %s from the server.', $remoteTag)); + return 1; + } + \chmod($tempFilename, 0777 & ~\umask()); + $pharInvalidityReason = $this->pharChecker->checkFileValidity($tempFilename); + if (null !== $pharInvalidityReason) { + \unlink($tempFilename); + $output->writeln(\sprintf('The download of %s is corrupt (%s).', $remoteTag, $pharInvalidityReason)); + $output->writeln('Please re-run the "self-update" command to try again.'); + return 1; + } + \rename($tempFilename, $localFilename); + $output->writeln(\sprintf('PHP CS Fixer updated (%s -> %s)', $currentVersion, $remoteTag)); + return 0; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php b/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php new file mode 100644 index 00000000000..a4f2813dae2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/ConfigurationResolver.php @@ -0,0 +1,683 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\Console\Output\Progress\ProgressOutputType; +use PhpCsFixer\Console\Report\FixReport\ReporterFactory; +use PhpCsFixer\Console\Report\FixReport\ReporterInterface; +use PhpCsFixer\Differ\DifferInterface; +use PhpCsFixer\Differ\NullDiffer; +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\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSetInterface; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\ToolInfoInterface; +use PhpCsFixer\Utils; +use PhpCsFixer\WhitespacesFixerConfig; +use PhpCsFixer\WordMatcher; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +use ECSPrefix202307\Symfony\Component\Filesystem\Filesystem; +use ECSPrefix202307\Symfony\Component\Finder\Finder as SymfonyFinder; +/** + * The resolver that resolves configuration to use by command line options and config. + * + * @author Fabien Potencier + * @author Katsuhiro Ogawa + * @author Dariusz Rumiński + * + * @internal + */ +final class ConfigurationResolver +{ + public const PATH_MODE_OVERRIDE = 'override'; + public const PATH_MODE_INTERSECTION = 'intersection'; + /** + * @var null|bool + */ + private $allowRisky; + /** + * @var null|ConfigInterface + */ + private $config; + /** + * @var null|string + */ + private $configFile; + /** + * @var string + */ + private $cwd; + /** + * @var \PhpCsFixer\ConfigInterface + */ + private $defaultConfig; + /** + * @var null|ReporterInterface + */ + private $reporter; + /** + * @var null|bool + */ + private $isStdIn; + /** + * @var null|bool + */ + private $isDryRun; + /** + * @var null|FixerInterface[] + */ + private $fixers; + /** + * @var null|bool + */ + private $configFinderIsOverridden; + /** + * @var \PhpCsFixer\ToolInfoInterface + */ + private $toolInfo; + /** + * @var array + */ + private $options = ['allow-risky' => null, 'cache-file' => null, 'config' => null, 'diff' => 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]; + /** + * @var null|string + */ + private $cacheFile; + /** + * @var null|CacheManagerInterface + */ + private $cacheManager; + /** + * @var null|DifferInterface + */ + private $differ; + /** + * @var null|Directory + */ + private $directory; + /** + * @var null|iterable<\SplFileInfo> + */ + private $finder; + /** + * @var string|null + */ + private $format; + /** + * @var null|Linter + */ + private $linter; + /** + * @var null|list + */ + private $path; + /** + * @var null|string + */ + private $progress; + /** + * @var null|RuleSet + */ + private $ruleSet; + /** + * @var null|bool + */ + private $usingCache; + /** + * @var FixerFactory + */ + private $fixerFactory; + /** + * @param array $options + */ + public function __construct(ConfigInterface $config, array $options, string $cwd, ToolInfoInterface $toolInfo) + { + $this->defaultConfig = $config; + $this->cwd = $cwd; + $this->toolInfo = $toolInfo; + foreach ($options as $name => $value) { + $this->setOption($name, $value); + } + } + public function getCacheFile() : ?string + { + 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() : CacheManagerInterface + { + 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() : ConfigInterface + { + if (null === $this->config) { + foreach ($this->computeConfigFiles() as $configFile) { + if (!\file_exists($configFile)) { + continue; + } + $configFileBasename = \basename($configFile); + $deprecatedConfigs = ['.php_cs' => '.php-cs-fixer.php', '.php_cs.dist' => '.php-cs-fixer.dist.php']; + if (isset($deprecatedConfigs[$configFileBasename])) { + throw new InvalidConfigurationException("Configuration file `{$configFileBasename}` is outdated, rename to `{$deprecatedConfigs[$configFileBasename]}`."); + } + $this->config = self::separatedContextLessInclude($configFile); + $this->configFile = $configFile; + break; + } + if (null === $this->config) { + $this->config = $this->defaultConfig; + } + } + return $this->config; + } + public function getConfigFile() : ?string + { + if (null === $this->configFile) { + $this->getConfig(); + } + return $this->configFile; + } + public function getDiffer() : DifferInterface + { + if (null === $this->differ) { + if ($this->options['diff']) { + $this->differ = new UnifiedDiffer(); + } else { + $this->differ = new NullDiffer(); + } + } + return $this->differ; + } + public function getDirectory() : DirectoryInterface + { + 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; + $absolutePath = \dirname($absolutePath); + } + $this->directory = new Directory($absolutePath); + } + return $this->directory; + } + /** + * @return FixerInterface[] An array of FixerInterface + */ + public function getFixers() : array + { + 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) : string { + return $fixer->getName(); + }, \array_filter($this->fixers, static function (FixerInterface $fixer) : bool { + return $fixer->isRisky(); + })); + if (\count($riskyFixers) > 0) { + 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?', Utils::naturalLanguageJoin($riskyFixers))); + } + } + } + return $this->fixers; + } + public function getLinter() : LinterInterface + { + if (null === $this->linter) { + $this->linter = new Linter(); + } + return $this->linter; + } + /** + * Returns path. + * + * @return string[] + */ + public function getPath() : array + { + 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 (string $rawPath) use($cwd, $filesystem) : string { + $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; + } + /** + * @throws InvalidConfigurationException + */ + public function getProgressType() : string + { + if (null === $this->progress) { + if (OutputInterface::VERBOSITY_VERBOSE <= $this->options['verbosity'] && 'txt' === $this->getFormat()) { + $progressType = $this->options['show-progress']; + if (null === $progressType) { + $progressType = $this->getConfig()->getHideProgress() ? ProgressOutputType::NONE : ProgressOutputType::DOTS; + } elseif (!\in_array($progressType, ProgressOutputType::AVAILABLE, \true)) { + throw new InvalidConfigurationException(\sprintf('The progress type "%s" is not defined, supported are %s.', $progressType, Utils::naturalLanguageJoin(ProgressOutputType::AVAILABLE))); + } + $this->progress = $progressType; + } else { + $this->progress = ProgressOutputType::NONE; + } + } + return $this->progress; + } + public function getReporter() : ReporterInterface + { + if (null === $this->reporter) { + $reporterFactory = new ReporterFactory(); + $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, Utils::naturalLanguageJoin($formats))); + } + } + return $this->reporter; + } + public function getRiskyAllowed() : bool + { + 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; + } + /** + * Returns rules. + * + * @return array|bool> + */ + public function getRules() : array + { + return $this->getRuleSet()->getRules(); + } + public function getUsingCache() : bool + { + 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; + } + /** + * @return iterable<\SplFileInfo> + */ + public function getFinder() : iterable + { + if (null === $this->finder) { + $this->finder = $this->resolveFinder(); + } + return $this->finder; + } + /** + * Returns dry-run flag. + */ + public function isDryRun() : bool + { + if (null === $this->isDryRun) { + if ($this->isStdIn()) { + // Can't write to STDIN + $this->isDryRun = \true; + } else { + $this->isDryRun = $this->options['dry-run']; + } + } + return $this->isDryRun; + } + public function shouldStopOnViolation() : bool + { + return $this->options['stop-on-violation']; + } + public function configFinderIsOverridden() : bool + { + if (null === $this->configFinderIsOverridden) { + $this->resolveFinder(); + } + return $this->configFinderIsOverridden; + } + /** + * Compute file candidates for config file. + * + * @return string[] + */ + private function computeConfigFiles() : array + { + $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-fixer.php', + $configDir . \DIRECTORY_SEPARATOR . '.php-cs-fixer.dist.php', + $configDir . \DIRECTORY_SEPARATOR . '.php_cs', + // old v2 config, present here only to throw nice error message later + $configDir . \DIRECTORY_SEPARATOR . '.php_cs.dist', + ]; + if ($configDir !== $this->cwd) { + $candidates[] = $this->cwd . \DIRECTORY_SEPARATOR . '.php-cs-fixer.php'; + $candidates[] = $this->cwd . \DIRECTORY_SEPARATOR . '.php-cs-fixer.dist.php'; + $candidates[] = $this->cwd . \DIRECTORY_SEPARATOR . '.php_cs'; + // old v2 config, present here only to throw nice error message later + $candidates[] = $this->cwd . \DIRECTORY_SEPARATOR . '.php_cs.dist'; + // old v2 config, present here only to throw nice error message later + } + return $candidates; + } + private function createFixerFactory() : FixerFactory + { + if (null === $this->fixerFactory) { + $fixerFactory = new FixerFactory(); + $fixerFactory->registerBuiltInFixers(); + $fixerFactory->registerCustomFixers($this->getConfig()->getCustomFixers()); + $this->fixerFactory = $fixerFactory; + } + return $this->fixerFactory; + } + private function getFormat() : string + { + if (null === $this->format) { + $this->format = $this->options['format'] ?? $this->getConfig()->getFormat(); + } + return $this->format; + } + private function getRuleSet() : RuleSetInterface + { + if (null === $this->ruleSet) { + $rules = $this->parseRules(); + $this->validateRules($rules); + $this->ruleSet = new RuleSet($rules); + } + return $this->ruleSet; + } + private function isStdIn() : bool + { + if (null === $this->isStdIn) { + $this->isStdIn = 1 === \count($this->options['path']) && '-' === $this->options['path'][0]; + } + return $this->isStdIn; + } + /** + * @template T + * + * @param iterable $iterable + * + * @return \Traversable + */ + private function iterableToTraversable(iterable $iterable) : \Traversable + { + return \is_array($iterable) ? new \ArrayIterator($iterable) : $iterable; + } + /** + * @return array + */ + private function parseRules() : array + { + 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 (\strncmp($rules, '{', \strlen('{')) === 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 (\strncmp($rule, '-', \strlen('-')) === 0) { + $rules[\substr($rule, 1)] = \false; + } else { + $rules[$rule] = \true; + } + } + return $rules; + } + /** + * @param array $rules + * + * @throws InvalidConfigurationException + */ + private function validateRules(array $rules) : void + { + /** + * Create a ruleset that contains all configured rules, even when they originally have been disabled. + * + * @see RuleSet::resolveSet() + */ + $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) : string { + return $fixer->getName(); + }, $fixers); + $unknownFixers = \array_diff($configuredFixers, $availableFixers); + if (\count($unknownFixers) > 0) { + $renamedRules = ['blank_line_before_return' => ['new_name' => 'blank_line_before_statement', 'config' => ['statements' => ['return']]], 'final_static_access' => ['new_name' => 'self_static_accessor'], 'hash_to_slash_comment' => ['new_name' => 'single_line_comment_style', 'config' => ['comment_types' => ['hash']]], 'lowercase_constants' => ['new_name' => 'constant_case', 'config' => ['case' => 'lower']], 'no_extra_consecutive_blank_lines' => ['new_name' => 'no_extra_blank_lines'], 'no_multiline_whitespace_before_semicolons' => ['new_name' => 'multiline_whitespace_before_semicolons'], 'no_short_echo_tag' => ['new_name' => 'echo_tag_syntax', 'config' => ['format' => 'long']], 'php_unit_ordered_covers' => ['new_name' => 'phpdoc_order_by_value', 'config' => ['annotations' => ['covers']]], 'phpdoc_inline_tag' => ['new_name' => 'general_phpdoc_tag_rename, phpdoc_inline_tag_normalizer and phpdoc_tag_type'], 'pre_increment' => ['new_name' => 'increment_style', 'config' => ['style' => 'pre']], 'psr0' => ['new_name' => 'psr_autoloading', 'config' => ['dir' => 'x']], 'psr4' => ['new_name' => 'psr_autoloading'], 'silenced_deprecation_error' => ['new_name' => 'error_suppression'], 'trailing_comma_in_multiline_array' => ['new_name' => 'trailing_comma_in_multiline', 'config' => ['elements' => ['arrays']]]]; + $message = 'The rules contain unknown fixers: '; + $hasOldRule = \false; + foreach ($unknownFixers as $unknownFixer) { + if (isset($renamedRules[$unknownFixer])) { + // Check if present as old renamed rule + $hasOldRule = \true; + $message .= \sprintf('"%s" is renamed (did you mean "%s"?%s), ', $unknownFixer, $renamedRules[$unknownFixer]['new_name'], isset($renamedRules[$unknownFixer]['config']) ? ' (note: use configuration "' . Utils::toString($renamedRules[$unknownFixer]['config']) . '")' : ''); + } else { + // Go to normal matcher if it is not a renamed rule + $matcher = new WordMatcher($availableFixers); + $alternative = $matcher->match($unknownFixer); + $message .= \sprintf('"%s"%s, ', $unknownFixer, null === $alternative ? '' : ' (did you mean "' . $alternative . '"?)'); + } + } + $message = \substr($message, 0, -2) . '.'; + if ($hasOldRule) { + $message .= "\nFor more info about updating see: https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v3.0.0/UPGRADE-v3.md#renamed-ruless."; + } + throw new InvalidConfigurationException($message); + } + 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.', \PhpCsFixer\Console\Application::getMajorVersion() + 1) : \sprintf('. Use %s instead.', \str_replace('`', '"', Utils::naturalLanguageJoinWithBackticks($successors))); + Utils::triggerDeprecation(new \RuntimeException("Rule \"{$fixerName}\" is deprecated{$messageEnd}")); + } + } + } + /** + * Apply path on config instance. + * + * @return iterable<\SplFileInfo> + */ + private function resolveFinder() : iterable + { + $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'], Utils::naturalLanguageJoin($modes))); + } + $isIntersectionPathMode = self::PATH_MODE_INTERSECTION === $this->options['path-mode']; + $paths = \array_filter(\array_map(static function (string $path) { + return \realpath($path); + }, $this->getPath())); + if (0 === \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) : bool { + $currentRealPath = $current->getRealPath(); + if (\in_array($currentRealPath, $pathsByType['file'], \true)) { + return \true; + } + foreach ($pathsByType['dir'] as $path) { + if (\strncmp($currentRealPath, $path, \strlen($path)) === 0) { + return \true; + } + } + return \false; + }); + } + if (null !== $this->getConfigFile() && null !== $nestedFinder) { + $this->configFinderIsOverridden = \true; + } + if ($currentFinder instanceof SymfonyFinder && null === $nestedFinder) { + // finder from configuration Symfony finder and it is not fully defined, we may fulfill it + return $currentFinder->in($pathsByType['dir'])->append($pathsByType['file']); + } + return Finder::create()->in($pathsByType['dir'])->append($pathsByType['file']); + } + /** + * Set option that will be resolved. + * + * @param mixed $value + */ + private function setOption(string $name, $value) : void + { + if (!\array_key_exists($name, $this->options)) { + throw new InvalidConfigurationException(\sprintf('Unknown option name: "%s".', $name)); + } + $this->options[$name] = $value; + } + private function resolveOptionBooleanValue(string $optionName) : bool + { + $value = $this->options[$optionName]; + 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; + } + throw new InvalidConfigurationException(\sprintf('Expected "yes" or "no" for option "%s", got "%s".', $optionName, $value)); + } + private static function separatedContextLessInclude(string $path) : ConfigInterface + { + $config = (include $path); + // verify that the config has an instance of Config + if (!$config instanceof ConfigInterface) { + throw new InvalidConfigurationException(\sprintf('The config file: "%s" does not return a "PhpCsFixer\\ConfigInterface" instance. Got: "%s".', $path, \is_object($config) ? \get_class($config) : \gettype($config))); + } + return $config; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php new file mode 100644 index 00000000000..0bc16b25b69 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/ErrorOutput.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output; + +use PhpCsFixer\Differ\DiffConsoleFormatter; +use PhpCsFixer\Error\Error; +use PhpCsFixer\Linter\LintingException; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @internal + */ +final class ErrorOutput +{ + /** + * @var \Symfony\Component\Console\Output\OutputInterface + */ + private $output; + /** + * @var bool + */ + private $isDecorated; + public function __construct(OutputInterface $output) + { + $this->output = $output; + $this->isDecorated = $output->isDecorated(); + } + /** + * @param Error[] $errors + */ + public function listErrors(string $process, array $errors) : void + { + $this->output->writeln(['', \sprintf('Files that were not fixed due to errors reported during %s:', $process)]); + $showDetails = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERY_VERBOSE; + $showTrace = $this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG; + foreach ($errors as $i => $error) { + $this->output->writeln(\sprintf('%4d) %s', $i + 1, $error->getFilePath())); + $e = $error->getSource(); + if (!$showDetails || null === $e) { + continue; + } + $class = \sprintf('[%s]', \get_class($e)); + $message = $e->getMessage(); + $code = $e->getCode(); + if (0 !== $code) { + $message .= " ({$code})"; + } + $length = \max(\strlen($class), \strlen($message)); + $lines = ['', $class, $message, '']; + $this->output->writeln(''); + foreach ($lines as $line) { + if (\strlen($line) < $length) { + $line .= \str_repeat(' ', $length - \strlen($line)); + } + $this->output->writeln(\sprintf(' %s ', $this->prepareOutput($line))); + } + if ($showTrace && !$e instanceof LintingException) { + // stack trace of lint exception is of no interest + $this->output->writeln(''); + $stackTrace = $e->getTrace(); + foreach ($stackTrace as $trace) { + if (isset($trace['class']) && \ECSPrefix202307\Symfony\Component\Console\Command\Command::class === $trace['class'] && 'run' === $trace['function']) { + $this->output->writeln(' [ ... ]'); + break; + } + $this->outputTrace($trace); + } + } + if (Error::TYPE_LINT === $error->getType() && 0 < \count($error->getAppliedFixers())) { + $this->output->writeln(''); + $this->output->writeln(\sprintf(' Applied fixers: %s', \implode(', ', $error->getAppliedFixers()))); + $diff = $error->getDiff(); + if (null !== $diff) { + $diffFormatter = new DiffConsoleFormatter($this->isDecorated, \sprintf(' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', \PHP_EOL, \PHP_EOL)); + $this->output->writeln($diffFormatter->format($diff)); + } + } + } + } + /** + * @param array{ + * function?: string, + * line?: int, + * file?: string, + * class?: class-string, + * type?: '::'|'->', + * args?: mixed[], + * object?: object, + * } $trace + */ + private function outputTrace(array $trace) : void + { + if (isset($trace['class'], $trace['type'], $trace['function'])) { + $this->output->writeln(\sprintf(' %s%s%s()', $this->prepareOutput($trace['class']), $this->prepareOutput($trace['type']), $this->prepareOutput($trace['function']))); + } elseif (isset($trace['function'])) { + $this->output->writeln(\sprintf(' %s()', $this->prepareOutput($trace['function']))); + } + if (isset($trace['file'])) { + $this->output->writeln(\sprintf(' in %s at line %d', $this->prepareOutput($trace['file']), $trace['line'])); + } + } + private function prepareOutput(string $string) : string + { + return $this->isDecorated ? OutputFormatter::escape($string) : $string; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php new file mode 100644 index 00000000000..72ab11053d4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/OutputContext.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output; + +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * @internal + */ +final class OutputContext +{ + /** + * @var \Symfony\Component\Console\Output\OutputInterface|null + */ + private $output; + /** + * @var int + */ + private $terminalWidth; + /** + * @var int + */ + private $filesCount; + public function __construct(?OutputInterface $output, int $terminalWidth, int $filesCount) + { + $this->output = $output; + $this->terminalWidth = $terminalWidth; + $this->filesCount = $filesCount; + } + public function getOutput() : ?OutputInterface + { + return $this->output; + } + public function getTerminalWidth() : int + { + return $this->terminalWidth; + } + public function getFilesCount() : int + { + return $this->filesCount; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php new file mode 100644 index 00000000000..0ba291386f3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/DotsOutput.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; +use PhpCsFixer\FixerFileProcessedEvent; +use ECSPrefix202307\Symfony\Component\Console\Output\OutputInterface; +/** + * Output writer to show the progress of a FixCommand using dots and meaningful letters. + * + * @internal + */ +final class DotsOutput implements \PhpCsFixer\Console\Output\Progress\ProgressOutputInterface +{ + /** + * File statuses map. + * + * @var array + */ + private static $eventStatusMap = [FixerFileProcessedEvent::STATUS_NO_CHANGES => ['symbol' => '.', 'format' => '%s', 'description' => 'no changes'], FixerFileProcessedEvent::STATUS_FIXED => ['symbol' => 'F', 'format' => '%s', 'description' => 'fixed'], FixerFileProcessedEvent::STATUS_SKIPPED => ['symbol' => 'S', 'format' => '%s', 'description' => 'skipped (cached or empty file)'], FixerFileProcessedEvent::STATUS_INVALID => ['symbol' => 'I', 'format' => '%s', 'description' => 'invalid file syntax (file ignored)'], FixerFileProcessedEvent::STATUS_EXCEPTION => ['symbol' => 'E', 'format' => '%s', 'description' => 'error'], FixerFileProcessedEvent::STATUS_LINT => ['symbol' => 'E', 'format' => '%s', 'description' => 'error']]; + /** @readonly + * @var \PhpCsFixer\Console\Output\OutputContext */ + private $context; + /** + * @var int + */ + private $processedFiles = 0; + /** + * @var int + */ + private $symbolsPerLine; + public function __construct(OutputContext $context) + { + $this->context = $context; + // max number of characters per line + // - total length x 2 (e.g. " 1 / 123" => 6 digits and padding spaces) + // - 11 (extra spaces, parentheses and percentage characters, e.g. " x / x (100%)") + $this->symbolsPerLine = \max(1, $context->getTerminalWidth() - \strlen((string) $context->getFilesCount()) * 2 - 11); + } + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep() : array + { + throw new \BadMethodCallException('Cannot serialize ' . __CLASS__); + } + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup() : void + { + throw new \BadMethodCallException('Cannot unserialize ' . __CLASS__); + } + public function onFixerFileProcessed(FixerFileProcessedEvent $event) : void + { + $status = self::$eventStatusMap[$event->getStatus()]; + $this->getOutput()->write($this->getOutput()->isDecorated() ? \sprintf($status['format'], $status['symbol']) : $status['symbol']); + ++$this->processedFiles; + $symbolsOnCurrentLine = $this->processedFiles % $this->symbolsPerLine; + $isLast = $this->processedFiles === $this->context->getFilesCount(); + if (0 === $symbolsOnCurrentLine || $isLast) { + $this->getOutput()->write(\sprintf('%s %' . \strlen((string) $this->context->getFilesCount()) . 'd / %d (%3d%%)', $isLast && 0 !== $symbolsOnCurrentLine ? \str_repeat(' ', $this->symbolsPerLine - $symbolsOnCurrentLine) : '', $this->processedFiles, $this->context->getFilesCount(), \round($this->processedFiles / $this->context->getFilesCount() * 100))); + if (!$isLast) { + $this->getOutput()->writeln(''); + } + } + } + public function printLegend() : void + { + $symbols = []; + foreach (self::$eventStatusMap as $status) { + $symbol = $status['symbol']; + if ('' === $symbol || isset($symbols[$symbol])) { + continue; + } + $symbols[$symbol] = \sprintf('%s-%s', $this->getOutput()->isDecorated() ? \sprintf($status['format'], $symbol) : $symbol, $status['description']); + } + $this->getOutput()->write(\sprintf("\nLegend: %s\n", \implode(', ', $symbols))); + } + private function getOutput() : OutputInterface + { + return $this->context->getOutput(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php new file mode 100644 index 00000000000..ec4ff55ee86 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/NullOutput.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\FixerFileProcessedEvent; +/** + * @internal + */ +final class NullOutput implements \PhpCsFixer\Console\Output\Progress\ProgressOutputInterface +{ + public function printLegend() : void + { + } + public function onFixerFileProcessed(FixerFileProcessedEvent $event) : void + { + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php new file mode 100644 index 00000000000..234b1a2a6c6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputFactory.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\Console\Output\OutputContext; +/** + * @internal + */ +final class ProgressOutputFactory +{ + public function create(string $outputType, OutputContext $context) : \PhpCsFixer\Console\Output\Progress\ProgressOutputInterface + { + if (null === $context->getOutput()) { + $outputType = \PhpCsFixer\Console\Output\Progress\ProgressOutputType::NONE; + } + if (!$this->isBuiltInType($outputType)) { + throw new \InvalidArgumentException(\sprintf('Something went wrong, "%s" output type is not supported', $outputType)); + } + return \PhpCsFixer\Console\Output\Progress\ProgressOutputType::NONE === $outputType ? new \PhpCsFixer\Console\Output\Progress\NullOutput() : new \PhpCsFixer\Console\Output\Progress\DotsOutput($context); + } + private function isBuiltInType(string $outputType) : bool + { + return \in_array($outputType, [\PhpCsFixer\Console\Output\Progress\ProgressOutputType::NONE, \PhpCsFixer\Console\Output\Progress\ProgressOutputType::DOTS], \true); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php new file mode 100644 index 00000000000..a2270c1d8ea --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output\Progress; + +use PhpCsFixer\FixerFileProcessedEvent; +/** + * @internal + */ +interface ProgressOutputInterface +{ + public function printLegend() : void; + public function onFixerFileProcessed(FixerFileProcessedEvent $event) : void; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php new file mode 100644 index 00000000000..bdf078713f9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Output/Progress/ProgressOutputType.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Output\Progress; + +/** + * @internal + */ +final class ProgressOutputType +{ + public const NONE = 'none'; + public const DOTS = 'dots'; + public const AVAILABLE = [self::NONE, self::DOTS]; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php new file mode 100644 index 00000000000..746f421a63e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/CheckstyleReporter.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * @author Kévin Gomez + * + * @internal + */ +final class CheckstyleReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + public function getFormat() : string + { + return 'checkstyle'; + } + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + 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) { + /** @var \DOMElement $file */ + $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, string $appliedFixer) : \DOMElement + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php new file mode 100644 index 00000000000..d76aa6cf847 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/GitlabReporter.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use ECSPrefix202307\SebastianBergmann\Diff\Chunk; +use ECSPrefix202307\SebastianBergmann\Diff\Parser; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * Generates a report according to gitlabs subset of codeclimate json files. + * + * @see https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#data-types + * + * @author Hans-Christian Otto + * + * @internal + */ +final class GitlabReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + /** + * @var \SebastianBergmann\Diff\Parser + */ + private $diffParser; + public function __construct() + { + $this->diffParser = new Parser(); + } + public function getFormat() : string + { + return 'gitlab'; + } + /** + * Process changed files array. Returns generated report. + */ + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + $report = []; + foreach ($reportSummary->getChanged() as $fileName => $change) { + $diffs = $this->diffParser->parse($change['diff']); + $firstChunk = isset($diffs[0]) ? $diffs[0]->getChunks() : []; + $firstChunk = \array_shift($firstChunk); + foreach ($change['appliedFixers'] as $fixerName) { + $report[] = ['check_name' => $fixerName, 'description' => $fixerName, 'categories' => ['Style'], 'fingerprint' => \md5($fileName . $fixerName), 'severity' => 'minor', 'location' => ['path' => $fileName, 'lines' => ['begin' => $firstChunk instanceof Chunk ? $firstChunk->getStart() : 0, 'end' => $firstChunk instanceof Chunk ? $firstChunk->getStartRange() : 0]]]; + } + } + $jsonString = \json_encode($report); + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($jsonString) : $jsonString; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php new file mode 100644 index 00000000000..1cb9ba68537 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JsonReporter.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class JsonReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + public function getFormat() : string + { + return 'json'; + } + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + $jsonFiles = []; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + $jsonFile = ['name' => $file]; + if ($reportSummary->shouldAddAppliedFixers()) { + $jsonFile['appliedFixers'] = $fixResult['appliedFixers']; + } + if ('' !== $fixResult['diff']) { + $jsonFile['diff'] = $fixResult['diff']; + } + $jsonFiles[] = $jsonFile; + } + $json = ['files' => $jsonFiles, 'time' => ['total' => \round($reportSummary->getTime() / 1000, 3)], 'memory' => \round($reportSummary->getMemory() / 1024 / 1024, 3)]; + $json = \json_encode($json); + return $reportSummary->isDecoratedOutput() ? OutputFormatter::escape($json) : $json; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php new file mode 100644 index 00000000000..974478803d9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/JunitReporter.php @@ -0,0 +1,101 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Preg; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class JunitReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + public function getFormat() : string + { + return 'junit'; + } + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + 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')); + /** @var \DOMElement $testsuite */ + $testsuite = $testsuites->appendChild($dom->createElement('testsuite')); + $testsuite->setAttribute('name', 'PHP CS Fixer'); + if (\count($reportSummary->getChanged()) > 0) { + $this->createFailedTestCases($dom, $testsuite, $reportSummary); + } else { + $this->createSuccessTestCase($dom, $testsuite); + } + if ($reportSummary->getTime() > 0) { + $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) : void + { + $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, \PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : void + { + $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'); + } + /** + * @param array{appliedFixers: list, diff: string} $fixResult + */ + private function createFailedTestCase(\DOMDocument $dom, string $file, array $fixResult, bool $shouldAddAppliedFixers) : \DOMElement + { + $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 ('' !== $fixResult['diff']) { + $failureContent .= "\nDiff:\n---------------\n\n" . $fixResult['diff']; + } + $failure->appendChild($dom->createCDATASection(\trim($failureContent))); + return $testcase; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php new file mode 100644 index 00000000000..95a85db5ee2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReportSummary.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ReportSummary +{ + /** + * @var array, diff: string}> + */ + private $changed; + /** + * @var int + */ + private $filesCount; + /** + * @var int + */ + private $time; + /** + * @var int + */ + private $memory; + /** + * @var bool + */ + private $addAppliedFixers; + /** + * @var bool + */ + private $isDryRun; + /** + * @var bool + */ + private $isDecoratedOutput; + /** + * @param array, diff: string}> $changed + * @param int $time duration in milliseconds + * @param int $memory memory usage in bytes + */ + public function __construct(array $changed, int $filesCount, int $time, int $memory, bool $addAppliedFixers, bool $isDryRun, bool $isDecoratedOutput) + { + $this->changed = $changed; + $this->filesCount = $filesCount; + $this->time = $time; + $this->memory = $memory; + $this->addAppliedFixers = $addAppliedFixers; + $this->isDryRun = $isDryRun; + $this->isDecoratedOutput = $isDecoratedOutput; + } + public function isDecoratedOutput() : bool + { + return $this->isDecoratedOutput; + } + public function isDryRun() : bool + { + return $this->isDryRun; + } + /** + * @return array, diff: string}> + */ + public function getChanged() : array + { + return $this->changed; + } + public function getMemory() : int + { + return $this->memory; + } + public function getTime() : int + { + return $this->time; + } + public function getFilesCount() : int + { + return $this->filesCount; + } + public function shouldAddAppliedFixers() : bool + { + return $this->addAppliedFixers; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php new file mode 100644 index 00000000000..2d612546e3f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterFactory.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use ECSPrefix202307\Symfony\Component\Finder\Finder as SymfonyFinder; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class ReporterFactory +{ + /** @var array */ + private $reporters = []; + public function registerBuiltInReporters() : self + { + /** @var null|list $builtInReporters */ + 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; + } + /** + * @return $this + */ + public function registerReporter(\PhpCsFixer\Console\Report\FixReport\ReporterInterface $reporter) : self + { + $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; + } + /** + * @return list + */ + public function getFormats() : array + { + $formats = \array_keys($this->reporters); + \sort($formats); + return $formats; + } + public function getReporter(string $format) : \PhpCsFixer\Console\Report\FixReport\ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is not registered.', $format)); + } + return $this->reporters[$format]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php new file mode 100644 index 00000000000..ef60735e13f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/ReporterInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +/** + * @author Boris Gorbylev + * + * @internal + */ +interface ReporterInterface +{ + public function getFormat() : string; + /** + * Process changed files array. Returns generated report. + */ + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php new file mode 100644 index 00000000000..495a29b873f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/TextReporter.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use PhpCsFixer\Differ\DiffConsoleFormatter; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class TextReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + public function getFormat() : string + { + return 'txt'; + } + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + $output = ''; + $identifiedFiles = 0; + foreach ($reportSummary->getChanged() as $file => $fixResult) { + ++$identifiedFiles; + $output .= \sprintf('%4d) %s', $identifiedFiles, $file); + if ($reportSummary->shouldAddAppliedFixers()) { + $output .= $this->getAppliedFixers($reportSummary->isDecoratedOutput(), $fixResult['appliedFixers']); + } + $output .= $this->getDiff($reportSummary->isDecoratedOutput(), $fixResult['diff']); + $output .= \PHP_EOL; + } + return $output . $this->getFooter($reportSummary->getTime(), $identifiedFiles, $reportSummary->getFilesCount(), $reportSummary->getMemory(), $reportSummary->isDryRun()); + } + /** + * @param list $appliedFixers + */ + private function getAppliedFixers(bool $isDecoratedOutput, array $appliedFixers) : string + { + return \sprintf($isDecoratedOutput ? ' (%s)' : ' (%s)', \implode(', ', $appliedFixers)); + } + private function getDiff(bool $isDecoratedOutput, string $diff) : string + { + if ('' === $diff) { + return ''; + } + $diffFormatter = new DiffConsoleFormatter($isDecoratedOutput, \sprintf(' ---------- begin diff ----------%s%%s%s ----------- end diff -----------', \PHP_EOL, \PHP_EOL)); + return \PHP_EOL . $diffFormatter->format($diff) . \PHP_EOL; + } + private function getFooter(int $time, int $identifiedFiles, int $files, int $memory, bool $isDryRun) : string + { + if (0 === $time || 0 === $memory) { + return ''; + } + return \PHP_EOL . \sprintf('%s %d of %d %s in %.3f seconds, %.3f MB memory used' . \PHP_EOL, $isDryRun ? 'Found' : 'Fixed', $identifiedFiles, $files, $isDryRun ? 'files that can be fixed' : 'files', $time / 1000, $memory / 1024 / 1024); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php new file mode 100644 index 00000000000..e64464a574d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/FixReport/XmlReporter.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\FixReport; + +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class XmlReporter implements \PhpCsFixer\Console\Report\FixReport\ReporterInterface +{ + public function getFormat() : string + { + return 'xml'; + } + public function generate(\PhpCsFixer\Console\Report\FixReport\ReportSummary $reportSummary) : string + { + if (!\extension_loaded('dom')) { + throw new \RuntimeException('Cannot generate report! `ext-dom` is not available!'); + } + $dom = new \DOMDocument('1.0', 'UTF-8'); + // new nodes should be added to this or existing children + $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['appliedFixers'])); + } + if ('' !== $fixResult['diff']) { + $fileXML->appendChild($this->createDiffElement($dom, $fixResult['diff'])); + } + } + 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(); + } + /** + * @param list $appliedFixers + */ + private function createAppliedFixersElement(\DOMDocument $dom, array $appliedFixers) : \DOMElement + { + $appliedFixersXML = $dom->createElement('applied_fixers'); + foreach ($appliedFixers as $appliedFixer) { + $appliedFixerXML = $dom->createElement('applied_fixer'); + $appliedFixerXML->setAttribute('name', $appliedFixer); + $appliedFixersXML->appendChild($appliedFixerXML); + } + return $appliedFixersXML; + } + private function createDiffElement(\DOMDocument $dom, string $diff) : \DOMElement + { + $diffXML = $dom->createElement('diff'); + $diffXML->appendChild($dom->createCDATASection($diff)); + return $diffXML; + } + private function createTimeElement(float $time, \DOMDocument $dom) : \DOMElement + { + $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(float $memory, \DOMDocument $dom) : \DOMElement + { + $memory = \round($memory / 1024 / 1024, 3); + $memoryXML = $dom->createElement('memory'); + $memoryXML->setAttribute('value', (string) $memory); + $memoryXML->setAttribute('unit', 'MB'); + return $memoryXML; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php new file mode 100644 index 00000000000..137730eb746 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/JsonReporter.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class JsonReporter implements \PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface +{ + public function getFormat() : string + { + return 'json'; + } + public function generate(\PhpCsFixer\Console\Report\ListSetsReport\ReportSummary $reportSummary) : string + { + $sets = $reportSummary->getSets(); + \usort($sets, static function (RuleSetDescriptionInterface $a, RuleSetDescriptionInterface $b) : int { + return \strcmp($a->getName(), $b->getName()); + }); + $json = ['sets' => []]; + foreach ($sets as $set) { + $setName = $set->getName(); + $json['sets'][$setName] = ['description' => $set->getDescription(), 'isRisky' => $set->isRisky(), 'name' => $setName]; + } + return \json_encode($json, \JSON_PRETTY_PRINT); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php new file mode 100644 index 00000000000..c1e95c31af6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReportSummary.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ReportSummary +{ + /** + * @var list + */ + private $sets; + /** + * @param list $sets + */ + public function __construct(array $sets) + { + $this->sets = $sets; + } + /** + * @return list + */ + public function getSets() : array + { + return $this->sets; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php new file mode 100644 index 00000000000..3d625f563b1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterFactory.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use ECSPrefix202307\Symfony\Component\Finder\Finder as SymfonyFinder; +/** + * @author Boris Gorbylev + * + * @internal + */ +final class ReporterFactory +{ + /** + * @var array + */ + private $reporters = []; + public function registerBuiltInReporters() : self + { + /** @var null|list $builtInReporters */ + 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(\PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface $reporter) : self + { + $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; + } + /** + * @return list + */ + public function getFormats() : array + { + $formats = \array_keys($this->reporters); + \sort($formats); + return $formats; + } + public function getReporter(string $format) : \PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface + { + if (!isset($this->reporters[$format])) { + throw new \UnexpectedValueException(\sprintf('Reporter for format "%s" is not registered.', $format)); + } + return $this->reporters[$format]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php new file mode 100644 index 00000000000..0b931348d72 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/ReporterInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\ListSetsReport; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface ReporterInterface +{ + public function getFormat() : string; + /** + * Process changed files array. Returns generated report. + */ + public function generate(\PhpCsFixer\Console\Report\ListSetsReport\ReportSummary $reportSummary) : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php new file mode 100644 index 00000000000..b92b275b839 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/Report/ListSetsReport/TextReporter.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\Report\ListSetsReport; + +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class TextReporter implements \PhpCsFixer\Console\Report\ListSetsReport\ReporterInterface +{ + public function getFormat() : string + { + return 'txt'; + } + public function generate(\PhpCsFixer\Console\Report\ListSetsReport\ReportSummary $reportSummary) : string + { + $sets = $reportSummary->getSets(); + \usort($sets, static function (RuleSetDescriptionInterface $a, RuleSetDescriptionInterface $b) : int { + return \strcmp($a->getName(), $b->getName()); + }); + $output = ''; + foreach ($sets as $i => $set) { + $output .= \sprintf('%2d) %s', $i + 1, $set->getName()) . \PHP_EOL . ' ' . $set->getDescription() . \PHP_EOL; + if ($set->isRisky()) { + $output .= ' Set contains risky rules.' . \PHP_EOL; + } + } + return $output; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php new file mode 100644 index 00000000000..0890e5829dd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClient.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +final class GithubClient implements \PhpCsFixer\Console\SelfUpdate\GithubClientInterface +{ + public function getTags() : array + { + $url = 'https://api.github.com/repos/PHP-CS-Fixer/PHP-CS-Fixer/tags'; + $result = @\file_get_contents($url, \false, \stream_context_create(['http' => ['header' => 'User-Agent: PHP-CS-Fixer/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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php new file mode 100644 index 00000000000..aa1cd6854e3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/GithubClientInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +interface GithubClientInterface +{ + /** + * @return list + */ + public function getTags() : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php new file mode 100644 index 00000000000..dd3fd15318f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionChecker.php @@ -0,0 +1,86 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\SelfUpdate; + +use ECSPrefix202307\Composer\Semver\Comparator; +use ECSPrefix202307\Composer\Semver\Semver; +use ECSPrefix202307\Composer\Semver\VersionParser; +/** + * @internal + */ +final class NewVersionChecker implements \PhpCsFixer\Console\SelfUpdate\NewVersionCheckerInterface +{ + /** + * @var \PhpCsFixer\Console\SelfUpdate\GithubClientInterface + */ + private $githubClient; + /** + * @var \Composer\Semver\VersionParser + */ + private $versionParser; + /** + * @var null|string[] + */ + private $availableVersions; + public function __construct(\PhpCsFixer\Console\SelfUpdate\GithubClientInterface $githubClient) + { + $this->githubClient = $githubClient; + $this->versionParser = new VersionParser(); + } + public function getLatestVersion() : string + { + $this->retrieveAvailableVersions(); + return $this->availableVersions[0]; + } + public function getLatestVersionOfMajor(int $majorVersion) : ?string + { + $this->retrieveAvailableVersions(); + $semverConstraint = '^' . $majorVersion; + foreach ($this->availableVersions as $availableVersion) { + if (Semver::satisfies($availableVersion, $semverConstraint)) { + return $availableVersion; + } + } + return null; + } + public function compareVersions(string $versionA, string $versionB) : int + { + $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() : void + { + 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) { + // not a valid version tag + } + } + $this->availableVersions = Semver::rsort($this->availableVersions); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php new file mode 100644 index 00000000000..8c776eda940 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/SelfUpdate/NewVersionCheckerInterface.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console\SelfUpdate; + +/** + * @internal + */ +interface NewVersionCheckerInterface +{ + /** + * Returns the tag of the latest version. + */ + public function getLatestVersion() : string; + /** + * Returns the tag of the latest minor/patch version of the given major version. + */ + public function getLatestVersionOfMajor(int $majorVersion) : ?string; + /** + * Returns -1, 0, or 1 if the first version is respectively less than, + * equal to, or greater than the second. + */ + public function compareVersions(string $versionA, string $versionB) : int; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php b/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php new file mode 100644 index 00000000000..2a90ba46fcb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Console/WarningsDetector.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Console; + +use PhpCsFixer\ToolInfo; +use PhpCsFixer\ToolInfoInterface; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class WarningsDetector +{ + /** + * @var \PhpCsFixer\ToolInfoInterface + */ + private $toolInfo; + /** + * @var string[] + */ + private $warnings = []; + public function __construct(ToolInfoInterface $toolInfo) + { + $this->toolInfo = $toolInfo; + } + public function detectOldMajor() : void + { + // @TODO 3.99 to be activated with new MAJOR release 4.0 + // $currentMajorVersion = \intval(explode('.', Application::VERSION)[0], 10); + // $nextMajorVersion = $currentMajorVersion + 1; + // $this->warnings[] = "You are running PHP CS Fixer v{$currentMajorVersion}, which is not maintained anymore. Please update to v{$nextMajorVersion}."; + // $this->warnings[] = "You may find an UPGRADE guide at https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/blob/v{$nextMajorVersion}.0.0/UPGRADE-v{$nextMajorVersion}.md ."; + } + public function detectOldVendor() : void + { + 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); + } + } + } + /** + * @return string[] + */ + public function getWarnings() : array + { + if (0 === \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!'])); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php b/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php new file mode 100644 index 00000000000..9e7a4ec247d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Differ/DiffConsoleFormatter.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use ECSPrefix202307\Symfony\Component\Console\Formatter\OutputFormatter; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class DiffConsoleFormatter +{ + /** + * @var bool + */ + private $isDecoratedOutput; + /** + * @var string + */ + private $template; + public function __construct(bool $isDecoratedOutput, string $template = '%s') + { + $this->isDecoratedOutput = $isDecoratedOutput; + $this->template = $template; + } + public function format(string $diff, string $lineTemplate = '%s') : string + { + $isDecorated = $this->isDecoratedOutput; + $template = $isDecorated ? $this->template : Preg::replace('/<[^<>]+>/', '', $this->template); + return \sprintf($template, \implode(\PHP_EOL, \array_map(static function (string $line) use($isDecorated, $lineTemplate) : string { + if ($isDecorated) { + $count = 0; + $line = Preg::replaceCallback('/^([+\\-@].*)/', static function (array $matches) : string { + if ('+' === $matches[0][0]) { + $colour = 'green'; + } elseif ('-' === $matches[0][0]) { + $colour = 'red'; + } else { + $colour = 'cyan'; + } + return \sprintf('%s', $colour, OutputFormatter::escape($matches[0]), $colour); + }, $line, 1, $count); + if (0 === $count) { + $line = OutputFormatter::escape($line); + } + } + return \sprintf($lineTemplate, $line); + }, Preg::split('#\\R#u', $diff)))); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php new file mode 100644 index 00000000000..0034f6a7f95 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Differ/DifferInterface.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + */ +interface DifferInterface +{ + /** + * Create diff. + */ + public function diff(string $old, string $new, ?\SplFileInfo $file = null) : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php b/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php new file mode 100644 index 00000000000..23d5da079e4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Differ/FullDiffer.php @@ -0,0 +1,36 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Differ; + +use ECSPrefix202307\SebastianBergmann\Diff\Differ; +use ECSPrefix202307\SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FullDiffer implements \PhpCsFixer\Differ\DifferInterface +{ + /** + * @var \SebastianBergmann\Diff\Differ + */ + private $differ; + public function __construct() + { + $this->differ = new Differ(new StrictUnifiedDiffOutputBuilder(['collapseRanges' => \false, 'commonLineThreshold' => 100, 'contextLines' => 100, 'fromFile' => 'Original', 'toFile' => 'New'])); + } + public function diff(string $old, string $new, ?\SplFileInfo $file = null) : string + { + return $this->differ->diff($old, $new); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php b/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php new file mode 100644 index 00000000000..5bc73cdb46c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Differ/NullDiffer.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Differ; + +/** + * @author Dariusz Rumiński + */ +final class NullDiffer implements \PhpCsFixer\Differ\DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null) : string + { + return ''; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php b/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php new file mode 100644 index 00000000000..653523f216f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Differ/UnifiedDiffer.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Differ; + +use PhpCsFixer\Preg; +use ECSPrefix202307\SebastianBergmann\Diff\Differ; +use ECSPrefix202307\SebastianBergmann\Diff\Output\StrictUnifiedDiffOutputBuilder; +final class UnifiedDiffer implements \PhpCsFixer\Differ\DifferInterface +{ + public function diff(string $old, string $new, ?\SplFileInfo $file = null) : string + { + if (null === $file) { + $options = ['fromFile' => 'Original', 'toFile' => 'New']; + } else { + $filePath = $file->getRealPath(); + if (Preg::match('/\\s/', $filePath)) { + $filePath = '"' . $filePath . '"'; + } + $options = ['fromFile' => $filePath, 'toFile' => $filePath]; + } + $differ = new Differ(new StrictUnifiedDiffOutputBuilder($options)); + return $differ->diff($old, $new); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php new file mode 100644 index 00000000000..234982c4dcf --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Annotation.php @@ -0,0 +1,248 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +/** + * This represents an entire annotation from a docblock. + * + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class Annotation +{ + /** + * All the annotation tag names with types. + * + * @var string[] + */ + private static $tags = ['method', 'param', 'property', 'property-read', 'property-write', 'return', 'throws', 'type', 'var']; + /** + * The lines that make up the annotation. + * + * @var Line[] + */ + private $lines; + /** + * The position of the first line of the annotation in the docblock. + * + * @var int + */ + private $start; + /** + * The position of the last line of the annotation in the docblock. + * + * @var int + */ + private $end; + /** + * The associated tag. + * + * @var null|Tag + */ + private $tag; + /** + * Lazy loaded, cached types content. + * + * @var null|string + */ + private $typesContent; + /** + * The cached types. + * + * @var null|string[] + */ + private $types; + /** + * @var null|NamespaceAnalysis + */ + private $namespace; + /** + * @var NamespaceUseAnalysis[] + */ + private $namespaceUses; + /** + * Create a new line instance. + * + * @param Line[] $lines + * @param null|NamespaceAnalysis $namespace + * @param NamespaceUseAnalysis[] $namespaceUses + */ + public function __construct(array $lines, $namespace = null, array $namespaceUses = []) + { + $this->lines = \array_values($lines); + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + $keys = \array_keys($lines); + $this->start = $keys[0]; + $this->end = \end($keys); + } + /** + * Get the string representation of object. + */ + public function __toString() : string + { + return $this->getContent(); + } + /** + * Get all the annotation tag names with types. + * + * @return string[] + */ + public static function getTagsWithTypes() : array + { + return self::$tags; + } + /** + * Get the start position of this annotation. + */ + public function getStart() : int + { + return $this->start; + } + /** + * Get the end position of this annotation. + */ + public function getEnd() : int + { + return $this->end; + } + /** + * Get the associated tag. + */ + public function getTag() : \PhpCsFixer\DocBlock\Tag + { + if (null === $this->tag) { + $this->tag = new \PhpCsFixer\DocBlock\Tag($this->lines[0]); + } + return $this->tag; + } + /** + * @internal + */ + public function getTypeExpression() : ?\PhpCsFixer\DocBlock\TypeExpression + { + $typesContent = $this->getTypesContent(); + return null === $typesContent ? null : new \PhpCsFixer\DocBlock\TypeExpression($typesContent, $this->namespace, $this->namespaceUses); + } + /** + * @return null|string + * + * @internal + */ + public function getVariableName() + { + $type = \preg_quote($this->getTypesContent() ?? '', '/'); + $regex = "/@{$this->tag->getName()}\\s+({$type}\\s*)?(&\\s*)?(\\.{3}\\s*)?(?\\\$.+?)(?:[\\s*]|\$)/"; + if (Preg::match($regex, $this->lines[0]->getContent(), $matches)) { + return $matches['variable']; + } + return null; + } + /** + * Get the types associated with this annotation. + * + * @return string[] + */ + public function getTypes() : array + { + if (null === $this->types) { + $typeExpression = $this->getTypeExpression(); + $this->types = null === $typeExpression ? [] : $typeExpression->getTypes(); + } + return $this->types; + } + /** + * Set the types associated with this annotation. + * + * @param string[] $types + */ + public function setTypes(array $types) : void + { + $pattern = '/' . \preg_quote($this->getTypesContent(), '/') . '/'; + $this->lines[0]->setContent(Preg::replace($pattern, \implode($this->getTypeExpression()->getTypesGlue(), $types), $this->lines[0]->getContent(), 1)); + $this->clearCache(); + } + /** + * Get the normalized types associated with this annotation, so they can easily be compared. + * + * @return string[] + */ + public function getNormalizedTypes() : array + { + $normalized = \array_map(static function (string $type) : string { + return \strtolower($type); + }, $this->getTypes()); + \sort($normalized); + return $normalized; + } + /** + * Remove this annotation by removing all its lines. + */ + public function remove() : void + { + foreach ($this->lines as $line) { + if ($line->isTheStart() && $line->isTheEnd()) { + // Single line doc block, remove entirely + $line->remove(); + } elseif ($line->isTheStart()) { + // Multi line doc block, but start is on the same line as the first annotation, keep only the start + $content = Preg::replace('#(\\s*/\\*\\*).*#', '$1', $line->getContent()); + $line->setContent($content); + } elseif ($line->isTheEnd()) { + // Multi line doc block, but end is on the same line as the last annotation, keep only the end + $content = Preg::replace('#(\\s*)\\S.*(\\*/.*)#', '$1$2', $line->getContent()); + $line->setContent($content); + } else { + // Multi line doc block, neither start nor end on this line, can be removed safely + $line->remove(); + } + } + $this->clearCache(); + } + /** + * Get the annotation content. + */ + public function getContent() : string + { + return \implode('', $this->lines); + } + public function supportTypes() : bool + { + return \in_array($this->getTag()->getName(), self::$tags, \true); + } + /** + * Get the current types content. + * + * Be careful modifying the underlying line as that won't flush the cache. + */ + private function getTypesContent() : ?string + { + 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+' . \PhpCsFixer\DocBlock\TypeExpression::REGEX_TYPES . '(?:(?:[*\\h\\v]|\\&?[\\.\\$]).*)?\\r?$}is', $this->lines[0]->getContent(), $matches); + $this->typesContent = $matchingResult ? $matches['types'] : null; + } + return $this->typesContent; + } + private function clearCache() : void + { + $this->types = null; + $this->typesContent = null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php new file mode 100644 index 00000000000..2ba2359b506 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/DocBlock.php @@ -0,0 +1,202 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +/** + * This class represents a docblock. + * + * It internally splits it up into "lines" that we can manipulate. + * + * @author Graham Campbell + */ +final class DocBlock +{ + /** + * @var list + */ + private $lines = []; + /** + * @var null|list + */ + private $annotations; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis|null + */ + private $namespace; + /** + * @var list + */ + private $namespaceUses; + /** + * @param list $namespaceUses + */ + public function __construct(string $content, ?NamespaceAnalysis $namespace = null, array $namespaceUses = []) + { + foreach (Preg::split('/([^\\n\\r]+\\R*)/', $content, -1, \PREG_SPLIT_NO_EMPTY | \PREG_SPLIT_DELIM_CAPTURE) as $line) { + $this->lines[] = new \PhpCsFixer\DocBlock\Line($line); + } + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + } + public function __toString() : string + { + return $this->getContent(); + } + /** + * Get this docblock's lines. + * + * @return list + */ + public function getLines() : array + { + return $this->lines; + } + /** + * Get a single line. + */ + public function getLine(int $pos) : ?\PhpCsFixer\DocBlock\Line + { + return $this->lines[$pos] ?? null; + } + /** + * Get this docblock's annotations. + * + * @return list + */ + public function getAnnotations() : array + { + if (null !== $this->annotations) { + return $this->annotations; + } + $this->annotations = []; + $total = \count($this->lines); + for ($index = 0; $index < $total; ++$index) { + if ($this->lines[$index]->containsATag()) { + // get all the lines that make up the annotation + $lines = \array_slice($this->lines, $index, $this->findAnnotationLength($index), \true); + $annotation = new \PhpCsFixer\DocBlock\Annotation($lines, $this->namespace, $this->namespaceUses); + // move the index to the end of the annotation to avoid + // checking it again because we know the lines inside the + // current annotation cannot be part of another annotation + $index = $annotation->getEnd(); + // add the current annotation to the list of annotations + $this->annotations[] = $annotation; + } + } + return $this->annotations; + } + public function isMultiLine() : bool + { + return 1 !== \count($this->lines); + } + /** + * Take a one line doc block, and turn it into a multi line doc block. + */ + public function makeMultiLine(string $indent, string $lineEnd) : void + { + if ($this->isMultiLine()) { + return; + } + $lineContent = $this->getSingleLineDocBlockEntry($this->lines[0]); + if ('' === $lineContent) { + $this->lines = [new \PhpCsFixer\DocBlock\Line('/**' . $lineEnd), new \PhpCsFixer\DocBlock\Line($indent . ' *' . $lineEnd), new \PhpCsFixer\DocBlock\Line($indent . ' */')]; + return; + } + $this->lines = [new \PhpCsFixer\DocBlock\Line('/**' . $lineEnd), new \PhpCsFixer\DocBlock\Line($indent . ' * ' . $lineContent . $lineEnd), new \PhpCsFixer\DocBlock\Line($indent . ' */')]; + } + public function makeSingleLine() : void + { + if (!$this->isMultiLine()) { + return; + } + $usefulLines = \array_filter($this->lines, static function (\PhpCsFixer\DocBlock\Line $line) : bool { + return $line->containsUsefulContent(); + }); + if (1 < \count($usefulLines)) { + return; + } + $lineContent = ''; + if (\count($usefulLines) > 0) { + $lineContent = $this->getSingleLineDocBlockEntry(\array_shift($usefulLines)); + } + $this->lines = [new \PhpCsFixer\DocBlock\Line('/** ' . $lineContent . ' */')]; + } + public function getAnnotation(int $pos) : ?\PhpCsFixer\DocBlock\Annotation + { + $annotations = $this->getAnnotations(); + return $annotations[$pos] ?? null; + } + /** + * Get specific types of annotations only. + * + * @param list|string $types + * + * @return list + */ + public function getAnnotationsOfType($types) : array + { + $typesToSearchFor = (array) $types; + $annotations = []; + foreach ($this->getAnnotations() as $annotation) { + $tagName = $annotation->getTag()->getName(); + if (\in_array($tagName, $typesToSearchFor, \true)) { + $annotations[] = $annotation; + } + } + return $annotations; + } + /** + * Get the actual content of this docblock. + */ + public function getContent() : string + { + return \implode('', $this->lines); + } + private function findAnnotationLength(int $start) : int + { + $index = $start; + while ($line = $this->getLine(++$index)) { + if ($line->containsATag()) { + // we've 100% reached the end of the description if we get here + break; + } + if (!$line->containsUsefulContent()) { + // if next line is also non-useful, or contains a tag, then we're done here + $next = $this->getLine($index + 1); + if (null === $next || !$next->containsUsefulContent() || $next->containsATag()) { + break; + } + // otherwise, continue, the annotation must have contained a blank line in its description + } + } + return $index - $start; + } + private function getSingleLineDocBlockEntry(\PhpCsFixer\DocBlock\Line $line) : string + { + $lineString = $line->getContent(); + if ('' === $lineString) { + return $lineString; + } + $lineString = \str_replace('*/', '', $lineString); + $lineString = \trim($lineString); + if (\strncmp($lineString, '/**', \strlen('/**')) === 0) { + $lineString = \substr($lineString, 3); + } elseif (\strncmp($lineString, '*', \strlen('*')) === 0) { + $lineString = \substr($lineString, 1); + } + return \trim($lineString); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php new file mode 100644 index 00000000000..d365520de12 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Line.php @@ -0,0 +1,114 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +/** + * This represents a line of a docblock. + * + * @author Graham Campbell + */ +final class Line +{ + /** + * The content of this line. + * @var string + */ + private $content; + /** + * Create a new line instance. + */ + public function __construct(string $content) + { + $this->content = $content; + } + /** + * Get the string representation of object. + */ + public function __toString() : string + { + return $this->content; + } + /** + * Get the content of this line. + */ + public function getContent() : string + { + return $this->content; + } + /** + * Does this line contain useful content? + * + * If the line contains text or tags, then this is true. + */ + public function containsUsefulContent() : bool + { + return Preg::match('/\\*\\s*\\S+/', $this->content) && '' !== \trim(\str_replace(['/', '*'], ' ', $this->content)); + } + /** + * Does the line contain a tag? + * + * If this is true, then it must be the first line of an annotation. + */ + public function containsATag() : bool + { + return Preg::match('/\\*\\s*@/', $this->content); + } + /** + * Is the line the start of a docblock? + */ + public function isTheStart() : bool + { + return \strpos($this->content, '/**') !== \false; + } + /** + * Is the line the end of a docblock? + */ + public function isTheEnd() : bool + { + return \strpos($this->content, '*/') !== \false; + } + /** + * Set the content of this line. + */ + public function setContent(string $content) : void + { + $this->content = $content; + } + /** + * Remove this line by clearing its contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function remove() : void + { + $this->content = ''; + } + /** + * Append a blank docblock line to this line's contents. + * + * Note that this method technically brakes the internal state of the + * docblock, but is useful when we need to retain the indices of lines + * during the execution of an algorithm. + */ + public function addBlank() : void + { + $matched = Preg::match('/^(\\h*\\*)[^\\r\\n]*(\\r?\\n)$/', $this->content, $matches); + if (!$matched) { + return; + } + $this->content .= $matches[1] . $matches[2]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php new file mode 100644 index 00000000000..e785987996a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/ShortDescription.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +/** + * This class represents a short description (aka summary) of a docblock. + * + * @internal + */ +final class ShortDescription +{ + /** + * The docblock containing the short description. + * @var \PhpCsFixer\DocBlock\DocBlock + */ + private $doc; + public function __construct(\PhpCsFixer\DocBlock\DocBlock $doc) + { + $this->doc = $doc; + } + /** + * Get the line index of the line containing the end of the short + * description, if present. + */ + public function getEnd() : ?int + { + $reachedContent = \false; + foreach ($this->doc->getLines() as $index => $line) { + // we went past a description, then hit a tag or blank line, so + // the last line of the description must be the one before this one + if ($reachedContent && ($line->containsATag() || !$line->containsUsefulContent())) { + return $index - 1; + } + // no short description was found + if ($line->containsATag()) { + return null; + } + // we've reached content, but need to check the next lines too + // in case the short description is multi-line + if ($line->containsUsefulContent()) { + $reachedContent = \true; + } + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php new file mode 100644 index 00000000000..6e5affffdc2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/Tag.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +/** + * This represents a tag, as defined by the proposed PSR PHPDoc standard. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class Tag +{ + /** + * All the tags defined by the proposed PSR PHPDoc standard. + */ + public const PSR_STANDARD_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']; + /** + * The line containing the tag. + * @var \PhpCsFixer\DocBlock\Line + */ + private $line; + /** + * The cached tag name. + * @var string|null + */ + private $name; + /** + * Create a new tag instance. + */ + public function __construct(\PhpCsFixer\DocBlock\Line $line) + { + $this->line = $line; + } + /** + * Get the tag name. + * + * This may be "param", or "return", etc. + */ + public function getName() : string + { + 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; + } + /** + * Set the tag name. + * + * This will also be persisted to the upstream line and annotation. + */ + public function setName(string $name) : void + { + $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; + } + /** + * Is the tag a known tag? + * + * This is defined by if it exists in the proposed PSR PHPDoc standard. + */ + public function valid() : bool + { + return \in_array($this->getName(), self::PSR_STANDARD_TAGS, \true); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php new file mode 100644 index 00000000000..65a32e0def2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TagComparator.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +/** + * This class is responsible for comparing tags to see if they should be kept + * together, or kept apart. + * + * @author Graham Campbell + * @author Jakub Kwaśniewski + * + * @deprecated + */ +final class TagComparator +{ + /** + * Groups of tags that should be allowed to immediately follow each other. + * + * @internal + */ + public const DEFAULT_GROUPS = [['deprecated', 'link', 'see', 'since'], ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write']]; + /** + * Should the given tags be kept together, or kept apart? + * + * @param string[][] $groups + */ + public static function shouldBeTogether(\PhpCsFixer\DocBlock\Tag $first, \PhpCsFixer\DocBlock\Tag $second, array $groups = self::DEFAULT_GROUPS) : bool + { + @\trigger_error('Method ' . __METHOD__ . ' is deprecated and will be removed in version 4.0.', \E_USER_DEPRECATED); + $firstName = $first->getName(); + $secondName = $second->getName(); + if ($firstName === $secondName) { + return \true; + } + foreach ($groups as $group) { + if (\in_array($firstName, $group, \true) && \in_array($secondName, $group, \true)) { + return \true; + } + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php new file mode 100644 index 00000000000..29e14a0a3e8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/DocBlock/TypeExpression.php @@ -0,0 +1,415 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\DocBlock; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Utils; +/** + * @internal + */ +final class TypeExpression +{ + /** + * Regex to match any PHP identifier. + * + * @internal + */ + public const REGEX_IDENTIFIER = '(?:(?!(?(?x) # one or several types separated by `|` or `&` +' . self::REGEX_TYPE . ' + (?: + \\h*(?[|&])\\h* + (?&type) + )*+ + )'; + private const REGEX_TYPE = '(?(?x) # single type + (?\\??\\h*) + (?: + (? + (?(?i)(?:array|list|object)(?-i)\\h*\\{\\h*) + (? + (? + (?(?:(?&constant)|(?&identifier))\\h*\\??\\h*:\\h*|) + (?(?&types_inner)) + ) + (?: + \\h*,\\h* + (?&array_shape_inner) + )* + (?:\\h*,\\h*)? + |) + \\h*\\} + ) + | + (? # callable syntax, e.g. `callable(string, int...): bool` + (?(?&name)\\h*\\(\\h*) + (? + (? + (?(?&types_inner)) + (?\\h*&|) + (?\\h*\\.\\.\\.|) + (?\\h*\\$(?&identifier)|) + (?\\h*=|) + ) + (?: + \\h*,\\h* + (?&callable_argument) + )* + (?:\\h*,\\h*)? + |) + \\h*\\) + (?: + \\h*\\:\\h* + (?(?&type)) + )? + ) + | + (? # generic syntax, e.g.: `array` + (?(?&name)\\h*<\\h*) + (? + (?&types_inner) + (?: + \\h*,\\h* + (?&types_inner) + )* + (?:\\h*,\\h*)? + ) + \\h*> + ) + | + (? # class constants with optional wildcard, e.g.: `Foo::*`, `Foo::CONST_A`, `FOO::CONST_*` + (?&name)::\\*?(?:(?&identifier)\\*?)* + ) + | + (? # single constant value (case insensitive), e.g.: 1, -1.8E+6, `\'a\'` + (?i) + # all sorts of numbers: with or without sign, supports literal separator and several numeric systems, + # e.g.: 1, +1.1, 1., .1, -1, 123E+8, 123_456_789, 0x7Fb4, 0b0110, 0o777 + [+-]?(?: + (?:0b[01]++(?:_[01]++)*+) + | (?:0o[0-7]++(?:_[0-7]++)*+) + | (?:0x[\\da-f]++(?:_[\\da-f]++)*+) + | (?:(?\\d++(?:_\\d++)*+)|(?=\\.\\d)) + (?:\\.(?&constant_digits)|(?<=\\d)\\.)?+ + (?:e[+-]?(?&constant_digits))?+ + ) + | \'(?:[^\'\\\\]|\\\\.)*+\' + | "(?:[^"\\\\]|\\\\.)*+" + (?-i) + ) + | + (? # self reference, e.g.: $this, $self, @static + (?i) + [@$](?:this | self | static) + (?-i) + ) + | + (? # full name, e.g.: `int`, `\\DateTime`, `\\Foo\\Bar`, `positive-int` + \\\\?+ + (?' . self::REGEX_IDENTIFIER . ') + (?:[\\\\\\-](?&identifier))*+ + ) + | + (? # parenthesized type, e.g.: `(int)`, `(int|\\stdClass)` + (? + \\(\\h* + ) + (?: + (? + (?&types_inner) + ) + | + (? # conditional type, e.g.: `$foo is \\Throwable ? false : $foo` + (? + (?:\\$(?&identifier)) + | + (?(?&types_inner)) + ) + (? + \\h+(?i)is(?:\\h+not)?(?-i)\\h+ + ) + (?(?&types_inner)) + (?\\h*\\?\\h*) + (?(?&types_inner)) + (?\\h*:\\h*) + (?(?&types_inner)) + ) + ) + \\h*\\) + ) + ) + (? # array, e.g.: `string[]`, `array[][]` + (\\h*\\[\\h*\\])* + ) + (?:(?=1)0 + (? + (?&type) + (?: + \\h*[|&]\\h* + (?&type) + )*+ + ) + |) + )'; + /** + * @var string + */ + private $value; + /** + * @var bool + */ + private $isUnionType = \false; + /** + * @var string + */ + private $typesGlue = '|'; + /** + * @var list + */ + private $innerTypeExpressions = []; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis|null + */ + private $namespace; + /** + * @var NamespaceUseAnalysis[] + */ + private $namespaceUses; + /** + * @param NamespaceUseAnalysis[] $namespaceUses + */ + public function __construct(string $value, ?NamespaceAnalysis $namespace, array $namespaceUses) + { + $this->value = $value; + $this->namespace = $namespace; + $this->namespaceUses = $namespaceUses; + $this->parse(); + } + public function toString() : string + { + return $this->value; + } + /** + * @return string[] + */ + public function getTypes() : array + { + if ($this->isUnionType) { + return \array_map(static function (array $type) { + return $type['expression']->toString(); + }, $this->innerTypeExpressions); + } + return [$this->value]; + } + /** + * @param callable(self $a, self $b): int $compareCallback + */ + public function sortTypes(callable $compareCallback) : void + { + foreach (\array_reverse($this->innerTypeExpressions) as ['start_index' => $startIndex, 'expression' => $inner]) { + $initialValueLength = \strlen($inner->toString()); + $inner->sortTypes($compareCallback); + $this->value = \substr_replace($this->value, $inner->toString(), $startIndex, $initialValueLength); + } + if ($this->isUnionType) { + $this->innerTypeExpressions = Utils::stableSort($this->innerTypeExpressions, static function (array $type) : self { + return $type['expression']; + }, $compareCallback); + $this->value = \implode($this->getTypesGlue(), $this->getTypes()); + } + } + public function getTypesGlue() : string + { + return $this->typesGlue; + } + public function getCommonType() : ?string + { + $aliases = $this->getAliases(); + $mainType = null; + foreach ($this->getTypes() as $type) { + if ('null' === $type) { + continue; + } + if (\strncmp($type, '?', \strlen('?')) === 0) { + $type = \substr($type, 1); + } + if (Preg::match('/\\[\\h*\\]$/', $type)) { + $type = 'array'; + } elseif (Preg::match('/^(.+?)\\h*[<{(]/', $type, $matches)) { + $type = $matches[1]; + } + if (isset($aliases[$type])) { + $type = $aliases[$type]; + } + if (null === $mainType || $type === $mainType) { + $mainType = $type; + continue; + } + $mainType = $this->getParentType($type, $mainType); + if (null === $mainType) { + return null; + } + } + return $mainType; + } + public function allowsNull() : bool + { + foreach ($this->getTypes() as $type) { + if (\in_array($type, ['null', 'mixed'], \true) || \strncmp($type, '?', \strlen('?')) === 0) { + return \true; + } + } + return \false; + } + private function parse() : void + { + $index = 0; + while (\true) { + Preg::match('{\\G' . self::REGEX_TYPE . '(?:\\h*(?[|&])\\h*|$)}', $this->value, $matches, \PREG_OFFSET_CAPTURE, $index); + if ([] === $matches) { + throw new \Exception('Unable to parse phpdoc type ' . \var_export($this->value, \true)); + } + if (!$this->isUnionType) { + if (($matches['glue'][0] ?? '') === '') { + break; + } + $this->isUnionType = \true; + $this->typesGlue = $matches['glue'][0]; + } + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['type'][0])]; + $consumedValueLength = \strlen($matches[0][0]); + $index += $consumedValueLength; + if (\strlen($this->value) === $index) { + return; + } + } + $nullableLength = \strlen($matches['nullable'][0]); + $index = $nullableLength; + if ('' !== ($matches['generic'][0] ?? '') && $matches['generic'][1] === $nullableLength) { + $this->parseCommaSeparatedInnerTypes($index + \strlen($matches['generic_start'][0]), $matches['generic_types'][0]); + } elseif ('' !== ($matches['callable'][0] ?? '') && $matches['callable'][1] === $nullableLength) { + $this->parseCallableArgumentTypes($index + \strlen($matches['callable_start'][0]), $matches['callable_arguments'][0]); + if ('' !== ($matches['callable_return'][0] ?? '')) { + $this->innerTypeExpressions[] = ['start_index' => \strlen($this->value) - \strlen($matches['callable_return'][0]), 'expression' => $this->inner($matches['callable_return'][0])]; + } + } elseif ('' !== ($matches['array_shape'][0] ?? '') && $matches['array_shape'][1] === $nullableLength) { + $this->parseArrayShapeInnerTypes($index + \strlen($matches['array_shape_start'][0]), $matches['array_shape_inners'][0]); + } elseif ('' !== ($matches['parenthesized'][0] ?? '') && $matches['parenthesized'][1] === $nullableLength) { + $index += \strlen($matches['parenthesized_start'][0]); + if ('' !== ($matches['conditional'][0] ?? '')) { + if ('' !== ($matches['conditional_cond_left_types'][0] ?? '')) { + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['conditional_cond_left_types'][0])]; + } + $index += \strlen($matches['conditional_cond_left'][0]) + \strlen($matches['conditional_cond_middle'][0]); + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['conditional_cond_right_types'][0])]; + $index += \strlen($matches['conditional_cond_right_types'][0]) + \strlen($matches['conditional_true_start'][0]); + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['conditional_true_types'][0])]; + $index += \strlen($matches['conditional_true_types'][0]) + \strlen($matches['conditional_false_start'][0]); + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['conditional_false_types'][0])]; + } else { + $this->innerTypeExpressions[] = ['start_index' => $index, 'expression' => $this->inner($matches['parenthesized_types'][0])]; + } + } + } + private function parseCommaSeparatedInnerTypes(int $startIndex, string $value) : void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match('{\\G' . self::REGEX_TYPES . '(?:\\h*,\\h*|$)}', $value, $matches, 0, $index); + $this->innerTypeExpressions[] = ['start_index' => $startIndex + $index, 'expression' => $this->inner($matches['types'])]; + $index += \strlen($matches[0]); + } + } + private function parseCallableArgumentTypes(int $startIndex, string $value) : void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match('{\\G(?:(?=1)0' . self::REGEX_TYPES . '|(?<_callable_argument>(?&callable_argument))(?:\\h*,\\h*|$))}', $value, $prematches, 0, $index); + $consumedValue = $prematches['_callable_argument']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + $addedPrefix = 'Closure('; + Preg::match('{^' . self::REGEX_TYPES . '$}', $addedPrefix . $consumedValue . '): void', $matches, \PREG_OFFSET_CAPTURE); + $this->innerTypeExpressions[] = ['start_index' => $startIndex + $index, 'expression' => $this->inner($matches['callable_argument_type'][0])]; + $index += $consumedValueLength + $consumedCommaLength; + } + } + private function parseArrayShapeInnerTypes(int $startIndex, string $value) : void + { + $index = 0; + while (\strlen($value) !== $index) { + Preg::match('{\\G(?:(?=1)0' . self::REGEX_TYPES . '|(?<_array_shape_inner>(?&array_shape_inner))(?:\\h*,\\h*|$))}', $value, $prematches, 0, $index); + $consumedValue = $prematches['_array_shape_inner']; + $consumedValueLength = \strlen($consumedValue); + $consumedCommaLength = \strlen($prematches[0]) - $consumedValueLength; + $addedPrefix = 'array{'; + Preg::match('{^' . self::REGEX_TYPES . '$}', $addedPrefix . $consumedValue . '}', $matches, \PREG_OFFSET_CAPTURE); + $this->innerTypeExpressions[] = ['start_index' => $startIndex + $index + $matches['array_shape_inner_value'][1] - \strlen($addedPrefix), 'expression' => $this->inner($matches['array_shape_inner_value'][0])]; + $index += $consumedValueLength + $consumedCommaLength; + } + } + private function inner(string $value) : self + { + return new self($value, $this->namespace, $this->namespaceUses); + } + private function getParentType(string $type1, string $type2) : ?string + { + $types = [$this->normalize($type1), $this->normalize($type2)]; + \natcasesort($types); + $types = \implode('|', $types); + $parents = ['array|Traversable' => 'iterable', 'array|iterable' => 'iterable', 'iterable|Traversable' => 'iterable', 'self|static' => 'self']; + return $parents[$types] ?? null; + } + private function normalize(string $type) : string + { + $aliases = $this->getAliases(); + if (isset($aliases[$type])) { + return $aliases[$type]; + } + if (\in_array($type, ['array', 'bool', 'callable', 'float', 'int', 'iterable', 'mixed', 'never', 'null', 'object', 'resource', 'string', 'void'], \true)) { + return $type; + } + if (Preg::match('/\\[\\]$/', $type)) { + return 'array'; + } + if (Preg::match('/^(.+?)namespaceUses as $namespaceUse) { + if ($namespaceUse->getShortName() === $type) { + return $namespaceUse->getFullName(); + } + } + if (null === $this->namespace || $this->namespace->isGlobalNamespace()) { + return $type; + } + return "{$this->namespace->getFullName()}\\{$type}"; + } + /** + * @return array + */ + private function getAliases() : array + { + return ['boolean' => 'bool', 'callback' => 'callable', 'double' => 'float', 'false' => 'bool', 'integer' => 'int', 'list' => 'array', 'real' => 'float', 'true' => 'bool']; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php b/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php new file mode 100644 index 00000000000..62ab6b58a9a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Token.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Doctrine\Annotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +/** + * A Doctrine annotation token. + * + * @internal + */ +final class Token +{ + /** + * @var int + */ + private $type; + /** + * @var string + */ + private $content; + /** + * @param int $type The type + * @param string $content The content + */ + public function __construct(int $type = DocLexer::T_NONE, string $content = '') + { + $this->type = $type; + $this->content = $content; + } + public function getType() : int + { + return $this->type; + } + public function setType(int $type) : void + { + $this->type = $type; + } + public function getContent() : string + { + return $this->content; + } + public function setContent(string $content) : void + { + $this->content = $content; + } + /** + * Returns whether the token type is one of the given types. + * + * @param int|int[] $types + */ + public function isType($types) : bool + { + if (!\is_array($types)) { + $types = [$types]; + } + return \in_array($this->getType(), $types, \true); + } + /** + * Overrides the content with an empty string. + */ + public function clear() : void + { + $this->setContent(''); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php b/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php new file mode 100644 index 00000000000..ab44ee01a52 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Doctrine/Annotation/Tokens.php @@ -0,0 +1,239 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Doctrine\Annotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +use ECSPrefix202307\Doctrine\Common\Lexer\Token as LexerToken; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token as PhpToken; +/** + * A list of Doctrine annotation tokens. + * + * @internal + * + * @extends \SplFixedArray + */ +final class Tokens extends \SplFixedArray +{ + /** + * @param string[] $ignoredTags + * + * @throws \InvalidArgumentException + */ + public static function createFromDocComment(PhpToken $input, array $ignoredTags = []) : self + { + if (!$input->isGivenKind(\T_DOC_COMMENT)) { + throw new \InvalidArgumentException('Input must be a T_DOC_COMMENT token.'); + } + $tokens = []; + $content = $input->getContent(); + $ignoredTextPosition = 0; + $currentPosition = 0; + $token = null; + 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 && !$token->isA(DocLexer::T_AT)) { + break; + } + if (1 === $index) { + if (!$token->isA(DocLexer::T_IDENTIFIER) || \in_array($token->value, $ignoredTags, \true)) { + break; + } + $nbScannedTokensToUse = 2; + } + if ($index >= 2 && 0 === $nbScopes && !$token->isA(DocLexer::T_NONE, DocLexer::T_OPEN_PARENTHESIS)) { + break; + } + $scannedTokens[] = $token; + if ($token->isA(DocLexer::T_OPEN_PARENTHESIS)) { + ++$nbScopes; + } elseif ($token->isA(DocLexer::T_CLOSE_PARENTHESIS)) { + if (0 === --$nbScopes) { + $nbScannedTokensToUse = \count($scannedTokens); + break; + } + } + ++$index; + } + if (0 !== $nbScopes) { + break; + } + if (0 !== $nbScannedTokensToUse) { + $ignoredTextLength = $nextAtPosition - $ignoredTextPosition; + if (0 !== $ignoredTextLength) { + $tokens[] = new \PhpCsFixer\Doctrine\Annotation\Token(DocLexer::T_NONE, \substr($content, $ignoredTextPosition, $ignoredTextLength)); + } + $lastTokenEndIndex = 0; + foreach (\array_slice($scannedTokens, 0, $nbScannedTokensToUse) as $token) { + if ($token->isA(DocLexer::T_STRING)) { + $token = new LexerToken('"' . \str_replace('"', '""', $token->value) . '"', $token->type, $token->position); + } + $missingTextLength = $token->position - $lastTokenEndIndex; + if ($missingTextLength > 0) { + $tokens[] = new \PhpCsFixer\Doctrine\Annotation\Token(DocLexer::T_NONE, \substr($content, $nextAtPosition + $lastTokenEndIndex, $missingTextLength)); + } + $tokens[] = new \PhpCsFixer\Doctrine\Annotation\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 \PhpCsFixer\Doctrine\Annotation\Token(DocLexer::T_NONE, \substr($content, $ignoredTextPosition)); + } + return self::fromArray($tokens); + } + /** + * Create token collection from array. + * + * @param Token[] $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null) : self + { + $tokens = new self(\count($array)); + if (null === $saveIndices || $saveIndices) { + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + return $tokens; + } + /** + * Returns the index of the closest next token that is neither a comment nor a whitespace token. + */ + public function getNextMeaningfulToken(int $index) : ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + /** + * Returns the index of the closest previous token that is neither a comment nor a whitespace token. + */ + public function getPreviousMeaningfulToken(int $index) : ?int + { + return $this->getMeaningfulTokenSibling($index, -1); + } + /** + * Returns the index of the last token that is part of the annotation at the given index. + */ + public function getAnnotationEnd(int $index) : ?int + { + $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; + } + /** + * Returns the code from the tokens. + */ + public function getCode() : string + { + $code = ''; + foreach ($this as $token) { + $code .= $token->getContent(); + } + return $code; + } + /** + * Inserts a token at the given index. + */ + public function insertAt(int $index, \PhpCsFixer\Doctrine\Annotation\Token $token) : void + { + $this->setSize($this->getSize() + 1); + for ($i = $this->getSize() - 1; $i > $index; --$i) { + $this[$i] = $this[$i - 1] ?? new \PhpCsFixer\Doctrine\Annotation\Token(); + } + $this[$index] = $token; + } + public function offsetSet($index, $token) : void + { + if (null === $token) { + throw new \InvalidArgumentException('Token must be an instance of PhpCsFixer\\Doctrine\\Annotation\\Token, "null" given.'); + } + if (!$token instanceof \PhpCsFixer\Doctrine\Annotation\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)); + } + parent::offsetSet($index, $token); + } + /** + * @param mixed $index + * + * @throws \OutOfBoundsException + */ + public function offsetUnset($index) : void + { + 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(int $index, int $direction) : ?int + { + while (\true) { + $index += $direction; + if (!$this->offsetExists($index)) { + break; + } + if (!$this[$index]->isType(DocLexer::T_NONE)) { + return $index; + } + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php b/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php new file mode 100644 index 00000000000..84b2a567bcd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Documentation/DocumentationLocator.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Utils; +/** + * @internal + */ +final class DocumentationLocator +{ + /** + * @var string + */ + private $path; + public function __construct() + { + $this->path = \dirname(__DIR__, 2) . '/doc'; + } + public function getFixersDocumentationDirectoryPath() : string + { + return $this->path . '/rules'; + } + public function getFixersDocumentationIndexFilePath() : string + { + return $this->getFixersDocumentationDirectoryPath() . '/index.rst'; + } + public function getFixerDocumentationFilePath(FixerInterface $fixer) : string + { + return $this->getFixersDocumentationDirectoryPath() . '/' . Preg::replaceCallback('/^.*\\\\(.+)\\\\(.+)Fixer$/', static function (array $matches) : string { + return Utils::camelCaseToUnderscore($matches[1]) . '/' . Utils::camelCaseToUnderscore($matches[2]); + }, \get_class($fixer)) . '.rst'; + } + public function getFixerDocumentationFileRelativePath(FixerInterface $fixer) : string + { + return Preg::replace('#^' . \preg_quote($this->getFixersDocumentationDirectoryPath(), '#') . '/#', '', $this->getFixerDocumentationFilePath($fixer)); + } + public function getRuleSetsDocumentationDirectoryPath() : string + { + return $this->path . '/ruleSets'; + } + public function getRuleSetsDocumentationIndexFilePath() : string + { + return $this->getRuleSetsDocumentationDirectoryPath() . '/index.rst'; + } + public function getRuleSetsDocumentationFilePath(string $name) : string + { + return $this->getRuleSetsDocumentationDirectoryPath() . '/' . \str_replace(':risky', 'Risky', \ucfirst(\substr($name, 1))) . '.rst'; + } + public function getListingFilePath() : string + { + return $this->path . '/list.rst'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php b/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php new file mode 100644 index 00000000000..1bd600d2064 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Documentation/FixerDocumentGenerator.php @@ -0,0 +1,283 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Differ\FullDiffer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +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\RuleSets; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +/** + * @internal + */ +final class FixerDocumentGenerator +{ + /** + * @var \PhpCsFixer\Documentation\DocumentationLocator + */ + private $locator; + /** + * @var \PhpCsFixer\Differ\FullDiffer + */ + private $differ; + public function __construct(\PhpCsFixer\Documentation\DocumentationLocator $locator) + { + $this->locator = $locator; + $this->differ = new FullDiffer(); + } + public function generateFixerDocumentation(FixerInterface $fixer) : string + { + $name = $fixer->getName(); + $title = "Rule ``{$name}``"; + $titleLine = \str_repeat('=', \strlen($title)); + $doc = "{$titleLine}\n{$title}\n{$titleLine}"; + $definition = $fixer->getDefinition(); + $doc .= "\n\n" . \PhpCsFixer\Documentation\RstUtils::toRst($definition->getSummary()); + $description = $definition->getDescription(); + if (null !== $description) { + $description = \PhpCsFixer\Documentation\RstUtils::toRst($description); + $doc .= <<getSuccessorsNames(); + if (0 !== \count($alternatives)) { + $deprecationDescription .= \PhpCsFixer\Documentation\RstUtils::toRst(\sprintf("\n\nYou should use %s instead.", Utils::naturalLanguageJoinWithBackticks($alternatives)), 0); + } + } + $riskyDescription = ''; + $riskyDescriptionRaw = $definition->getRiskyDescription(); + if (null !== $riskyDescriptionRaw) { + $riskyDescriptionRaw = \PhpCsFixer\Documentation\RstUtils::toRst($riskyDescriptionRaw, 0); + $riskyDescription = <<getConfigurationDefinition(); + foreach ($configurationDefinition->getOptions() as $option) { + $optionInfo = "``{$option->getName()}``"; + $optionInfo .= "\n" . \str_repeat('~', \strlen($optionInfo)); + if ($option instanceof DeprecatedFixerOptionInterface) { + $deprecationMessage = \PhpCsFixer\Documentation\RstUtils::toRst($option->getDeprecationMessage()); + $optionInfo .= "\n\n.. warning:: This option is deprecated and will be removed on next major version. {$deprecationMessage}"; + } + $optionInfo .= "\n\n" . \PhpCsFixer\Documentation\RstUtils::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); + if (null === $allowed) { + $allowedKind = 'Allowed types'; + $allowed = \array_map(static function ($value) : string { + return '``' . $value . '``'; + }, $option->getAllowedTypes()); + } else { + $allowedKind = 'Allowed values'; + $allowed = \array_map(static function ($value) : string { + return $value instanceof AllowedValueSubset ? 'a subset of ``' . Utils::toString($value->getAllowedValues()) . '``' : '``' . Utils::toString($value) . '``'; + }, $allowed); + } + $allowed = Utils::naturalLanguageJoin($allowed, ''); + $optionInfo .= "\n\n{$allowedKind}: {$allowed}"; + if ($option->hasDefault()) { + $default = Utils::toString($option->getDefault()); + $optionInfo .= "\n\nDefault value: ``{$default}``"; + } else { + $optionInfo .= "\n\nThis option is required."; + } + $doc .= "\n\n{$optionInfo}"; + } + } + $samples = $definition->getCodeSamples(); + 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``.", Utils::toString($sample->getConfiguration())); + } + } + $doc .= "\n" . $this->generateSampleDiff($fixer, $sample, $index + 1, $name); + } + } + $ruleSetConfigs = []; + foreach (RuleSets::getSetDefinitionNames() as $set) { + $ruleSet = new RuleSet([$set => \true]); + if ($ruleSet->hasRule($name)) { + $ruleSetConfigs[$set] = $ruleSet->getRuleConfiguration($name); + } + } + if ([] !== $ruleSetConfigs) { + $plural = 1 !== \count($ruleSetConfigs) ? 's' : ''; + $doc .= << $config) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($set); + $ruleSetPath = \substr($ruleSetPath, \strrpos($ruleSetPath, '/')); + $doc .= <<`_ rule set will enable the ``{$name}`` rule +RST; + if (null !== $config) { + $doc .= " with the config below:\n\n ``" . Utils::toString($config) . '``'; + } elseif ($fixer instanceof ConfigurableFixerInterface) { + $doc .= ' with the default config.'; + } else { + $doc .= '.'; + } + } + } + return "{$doc}\n"; + } + /** + * @param FixerInterface[] $fixers + */ + public function generateFixersDocumentationIndex(array $fixers) : string + { + $overrideGroups = ['PhpUnit' => 'PHPUnit', 'PhpTag' => 'PHP Tag', 'Phpdoc' => 'PHPDoc']; + \usort($fixers, static function (FixerInterface $a, FixerInterface $b) : int { + 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)); + $group = $overrideGroups[$namespace] ?? Preg::replace('/(?<=[[:lower:]])(?=[[:upper:]])/', ' ', $namespace); + if ($group !== $currentGroup) { + $underline = \str_repeat('-', \strlen($group)); + $documentation .= "\n\n{$group}\n{$underline}\n"; + $currentGroup = $group; + } + $path = './' . $this->locator->getFixerDocumentationFileRelativePath($fixer); + $attributes = []; + if ($fixer instanceof DeprecatedFixerInterface) { + $attributes[] = 'deprecated'; + } + if ($fixer->isRisky()) { + $attributes[] = 'risky'; + } + $attributes = 0 === \count($attributes) ? '' : ' *(' . \implode(', ', $attributes) . ')*'; + $summary = \str_replace('`', '``', $fixer->getDefinition()->getSummary()); + $documentation .= <<getName()} <{$path}>`_{$attributes} + + {$summary} +RST; + } + return "{$documentation}\n"; + } + private function generateSampleDiff(FixerInterface $fixer, CodeSampleInterface $sample, int $sampleNumber, string $ruleName) : string + { + if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) { + $existingFile = @\file_get_contents($this->locator->getFixerDocumentationFilePath($fixer)); + if (\false !== $existingFile) { + Preg::match("/\\RExample #{$sampleNumber}\\R.+?(?\\R\\.\\. code-block:: diff\\R\\R.*?)\\R(?:\\R\\S|\$)/s", $existingFile, $matches); + if (isset($matches['diff'])) { + return $matches['diff']; + } + } + $error = <<getCode(); + $tokens = Tokens::fromCode($old); + $file = $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : new StdinFileInfo(); + if ($fixer instanceof ConfigurableFixerInterface) { + $fixer->configure($sample->getConfiguration() ?? []); + } + $fixer->fix($file, $tokens); + $diff = $this->differ->diff($old, $tokens->generateCode()); + $diff = Preg::replace('/@@[ \\+\\-\\d,]+@@\\n/', '', $diff); + $diff = Preg::replace('/\\r/', '^M', $diff); + $diff = Preg::replace('/^ $/m', '', $diff); + $diff = Preg::replace('/\\n$/', '', $diff); + $diff = \PhpCsFixer\Documentation\RstUtils::indent($diff, 3); + return << + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Console\Command\HelpCommand; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\FixerConfiguration\AliasedFixerOption; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface; +use PhpCsFixer\RuleSet\RuleSet; +use PhpCsFixer\RuleSet\RuleSets; +use PhpCsFixer\Utils; +/** + * @internal + */ +final class ListDocumentGenerator +{ + /** + * @var \PhpCsFixer\Documentation\DocumentationLocator + */ + private $locator; + public function __construct(\PhpCsFixer\Documentation\DocumentationLocator $locator) + { + $this->locator = $locator; + } + /** + * @param FixerInterface[] $fixers + */ + public function generateListingDocumentation(array $fixers) : string + { + \usort($fixers, static function (FixerInterface $fixer1, FixerInterface $fixer2) : int { + return \strnatcasecmp($fixer1->getName(), $fixer2->getName()); + }); + $documentation = <<<'RST' +======================= +List of Available Rules +======================= + +RST; + foreach ($fixers as $fixer) { + $name = $fixer->getName(); + $definition = $fixer->getDefinition(); + $path = './rules/' . $this->locator->getFixerDocumentationFileRelativePath($fixer); + $documentation .= "\n- `{$name} <{$path}>`_\n"; + $documentation .= "\n " . \str_replace('`', '``', $definition->getSummary()) . "\n"; + $description = $definition->getDescription(); + if (null !== $description) { + $documentation .= "\n " . \PhpCsFixer\Documentation\RstUtils::toRst($description, 3) . "\n"; + } + if ($fixer instanceof DeprecatedFixerInterface) { + $documentation .= "\n *warning deprecated*"; + $alternatives = $fixer->getSuccessorsNames(); + if (0 !== \count($alternatives)) { + $documentation .= \PhpCsFixer\Documentation\RstUtils::toRst(\sprintf(' Use %s instead.', Utils::naturalLanguageJoinWithBackticks($alternatives)), 3); + } + $documentation .= "\n"; + } + if ($fixer->isRisky()) { + $documentation .= "\n *warning risky* " . \PhpCsFixer\Documentation\RstUtils::toRst($definition->getRiskyDescription(), 3) . "\n"; + } + if ($fixer instanceof ConfigurableFixerInterface) { + $documentation .= "\n Configuration options:\n"; + $configurationDefinition = $fixer->getConfigurationDefinition(); + foreach ($configurationDefinition->getOptions() as $option) { + $documentation .= "\n - | ``{$option->getName()}``"; + $documentation .= "\n | {$option->getDescription()}"; + if ($option instanceof DeprecatedFixerOptionInterface) { + $deprecationMessage = \PhpCsFixer\Documentation\RstUtils::toRst($option->getDeprecationMessage(), 3); + $documentation .= "\n | warning:: This option is deprecated and will be removed on next major version. {$deprecationMessage}"; + } + if ($option instanceof AliasedFixerOption) { + $documentation .= "\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); + if (null === $allowed) { + $allowedKind = 'Allowed types'; + $allowed = \array_map(static function ($value) : string { + return '``' . $value . '``'; + }, $option->getAllowedTypes()); + } else { + $allowedKind = 'Allowed values'; + $allowed = \array_map(static function ($value) : string { + return $value instanceof AllowedValueSubset ? 'a subset of ``' . Utils::toString($value->getAllowedValues()) . '``' : '``' . Utils::toString($value) . '``'; + }, $allowed); + } + $allowed = Utils::naturalLanguageJoin($allowed, ''); + $documentation .= "\n | {$allowedKind}: {$allowed}"; + if ($option->hasDefault()) { + $default = Utils::toString($option->getDefault()); + $documentation .= "\n | Default value: ``{$default}``"; + } else { + $documentation .= "\n | This option is required."; + } + } + $documentation .= "\n\n"; + } + $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' : ''; + $documentation .= "\n Part of rule set{$plural} "; + foreach ($ruleSetConfigs as $set => $config) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($set); + $ruleSetPath = \substr($ruleSetPath, \strrpos($ruleSetPath, '/')); + $documentation .= "`{$set} <./ruleSets{$ruleSetPath}>`_ "; + } + $documentation = \rtrim($documentation) . "\n"; + } + $reflectionObject = new \ReflectionObject($fixer); + $className = \str_replace('\\', '\\\\', $reflectionObject->getName()); + $fileName = $reflectionObject->getFileName(); + $fileName = \str_replace('\\', '/', $fileName); + $fileName = \substr($fileName, \strrpos($fileName, '/src/Fixer/') + 1); + $fileName = "`Source {$className} <./../{$fileName}>`_"; + $documentation .= "\n " . $fileName; + } + return $documentation . "\n"; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php b/vendor/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php new file mode 100644 index 00000000000..3785c3d1a34 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Documentation/RstUtils.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Preg; +/** + * @internal + */ +final class RstUtils +{ + private function __construct() + { + // cannot create instance of util. class + } + public static function toRst(string $string, int $indent = 0) : string + { + $string = \wordwrap(Preg::replace('/(? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Documentation; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\RuleSet\RuleSetDescriptionInterface; +use PhpCsFixer\Utils; +/** + * @internal + */ +final class RuleSetDocumentationGenerator +{ + /** + * @var \PhpCsFixer\Documentation\DocumentationLocator + */ + private $locator; + public function __construct(\PhpCsFixer\Documentation\DocumentationLocator $locator) + { + $this->locator = $locator; + } + /** + * @param FixerInterface[] $fixers + */ + public function generateRuleSetsDocumentation(RuleSetDescriptionInterface $definition, array $fixers) : string + { + $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.'; + } + $rules = $definition->getRules(); + if ([] === $rules) { + $doc .= "\n\nThis is an empty set."; + } else { + $enabledRules = \array_filter($rules, static function ($config) { + return \false !== $config; + }); + $disabledRules = \array_filter($rules, static function ($config) { + return \false === $config; + }); + $listRules = function (array $rules) use(&$doc, $fixerNames) : void { + foreach ($rules as $rule => $config) { + if (\strncmp($rule, '@', \strlen('@')) === 0) { + $ruleSetPath = $this->locator->getRuleSetsDocumentationFilePath($rule); + $ruleSetPath = \substr($ruleSetPath, \strrpos($ruleSetPath, '/')); + $doc .= "\n- `{$rule} <.{$ruleSetPath}>`_"; + } else { + $path = Preg::replace('#^' . \preg_quote($this->locator->getFixersDocumentationDirectoryPath(), '#') . '/#', './../rules/', $this->locator->getFixerDocumentationFilePath($fixerNames[$rule])); + $doc .= "\n- `{$rule} <{$path}>`_"; + } + if (!\is_bool($config)) { + $doc .= "\n config:\n ``" . Utils::toString($config) . '``'; + } + } + }; + if ([] !== $enabledRules) { + $doc .= "\n\nRules\n-----\n"; + $listRules($enabledRules); + } + if ([] !== $disabledRules) { + $doc .= "\n\nDisabled rules\n--------------\n"; + $listRules($disabledRules); + } + } + return $doc . "\n"; + } + /** + * @param array $setDefinitions + */ + public function generateRuleSetsDocumentationIndex(array $setDefinitions) : string + { + $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"; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php b/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php new file mode 100644 index 00000000000..472df4463c2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Error/Error.php @@ -0,0 +1,90 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Error; + +/** + * An abstraction for errors that can occur before and during fixing. + * + * @author Andreas Möller + * + * @internal + */ +final class Error +{ + /** + * Error which has occurred in linting phase, before applying any fixers. + */ + public const TYPE_INVALID = 1; + /** + * Error which has occurred during fixing phase. + */ + public const TYPE_EXCEPTION = 2; + /** + * Error which has occurred in linting phase, after applying any fixers. + */ + public const TYPE_LINT = 3; + /** + * @var int + */ + private $type; + /** + * @var string + */ + private $filePath; + /** + * @var \Throwable|null + */ + private $source; + /** + * @var list + */ + private $appliedFixers; + /** + * @var string|null + */ + private $diff; + /** + * @param list $appliedFixers + */ + public function __construct(int $type, string $filePath, ?\Throwable $source = null, array $appliedFixers = [], ?string $diff = null) + { + $this->type = $type; + $this->filePath = $filePath; + $this->source = $source; + $this->appliedFixers = $appliedFixers; + $this->diff = $diff; + } + public function getFilePath() : string + { + return $this->filePath; + } + public function getSource() : ?\Throwable + { + return $this->source; + } + public function getType() : int + { + return $this->type; + } + /** + * @return list + */ + public function getAppliedFixers() : array + { + return $this->appliedFixers; + } + public function getDiff() : ?string + { + return $this->diff; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php b/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php new file mode 100644 index 00000000000..30f5f9d5ec3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Error/ErrorsManager.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Error; + +/** + * Manager of errors that occur during fixing. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ErrorsManager +{ + /** + * @var Error[] + */ + private $errors = []; + /** + * Returns errors reported during linting before fixing. + * + * @return Error[] + */ + public function getInvalidErrors() : array + { + return \array_filter($this->errors, static function (\PhpCsFixer\Error\Error $error) : bool { + return \PhpCsFixer\Error\Error::TYPE_INVALID === $error->getType(); + }); + } + /** + * Returns errors reported during fixing. + * + * @return Error[] + */ + public function getExceptionErrors() : array + { + return \array_filter($this->errors, static function (\PhpCsFixer\Error\Error $error) : bool { + return \PhpCsFixer\Error\Error::TYPE_EXCEPTION === $error->getType(); + }); + } + /** + * Returns errors reported during linting after fixing. + * + * @return Error[] + */ + public function getLintErrors() : array + { + return \array_filter($this->errors, static function (\PhpCsFixer\Error\Error $error) : bool { + return \PhpCsFixer\Error\Error::TYPE_LINT === $error->getType(); + }); + } + /** + * Returns true if no errors were reported. + */ + public function isEmpty() : bool + { + return [] === $this->errors; + } + public function report(\PhpCsFixer\Error\Error $error) : void + { + $this->errors[] = $error; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FileReader.php b/vendor/friendsofphp/php-cs-fixer/src/FileReader.php new file mode 100644 index 00000000000..1b7bfd3c5e6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FileReader.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * File reader that unify access to regular file and stdin-alike file. + * + * Regular file could be read multiple times with `file_get_contents`, but file provided on stdin cannot. + * Consecutive try will provide empty content for stdin-alike file. + * This reader unifies access to them. + * + * @internal + */ +final class FileReader +{ + /** + * @var null|string + */ + private $stdinContent; + public static function createSingleton() : self + { + static $instance = null; + if (!$instance) { + $instance = new self(); + } + return $instance; + } + public function read(string $filePath) : string + { + if ('php://stdin' === $filePath) { + if (null === $this->stdinContent) { + $this->stdinContent = $this->readRaw($filePath); + } + return $this->stdinContent; + } + return $this->readRaw($filePath); + } + private function readRaw(string $realPath) : string + { + $content = @\file_get_contents($realPath); + if (\false === $content) { + $error = \error_get_last(); + throw new \RuntimeException(\sprintf('Failed to read content from "%s".%s', $realPath, null !== $error ? ' ' . $error['message'] : '')); + } + return $content; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php b/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php new file mode 100644 index 00000000000..01ff9f8978a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FileRemoval.php @@ -0,0 +1,88 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * Handles files removal with possibility to remove them on shutdown. + * + * @author Adam Klvač + * @author Dariusz Rumiński + * + * @internal + */ +final class FileRemoval +{ + /** + * List of observed files to be removed. + * + * @var array + */ + private $files = []; + public function __construct() + { + \register_shutdown_function([$this, 'clean']); + } + public function __destruct() + { + $this->clean(); + } + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep() : array + { + throw new \BadMethodCallException('Cannot serialize ' . __CLASS__); + } + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup() : void + { + throw new \BadMethodCallException('Cannot unserialize ' . __CLASS__); + } + /** + * Adds a file to be removed. + */ + public function observe(string $path) : void + { + $this->files[$path] = \true; + } + /** + * Removes a file from shutdown removal. + */ + public function delete(string $path) : void + { + if (isset($this->files[$path])) { + unset($this->files[$path]); + } + $this->unlink($path); + } + /** + * Removes attached files. + */ + public function clean() : void + { + foreach ($this->files as $file => $value) { + $this->unlink($file); + } + $this->files = []; + } + private function unlink(string $path) : void + { + @\unlink($path); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Finder.php b/vendor/friendsofphp/php-cs-fixer/src/Finder.php new file mode 100644 index 00000000000..439847d0ba7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Finder.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use ECSPrefix202307\Symfony\Component\Finder\Finder as BaseFinder; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +class Finder extends BaseFinder +{ + public function __construct() + { + parent::__construct(); + $this->files()->name('/\\.php$/')->exclude('vendor'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php new file mode 100644 index 00000000000..8d6a7bba61c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractIncrementOperatorFixer.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Tokenizer\Tokens; +abstract class AbstractIncrementOperatorFixer extends AbstractFixer +{ + protected final function findStart(Tokens $tokens, int $index) : int + { + 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->isObjectOperator()) { + 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php new file mode 100644 index 00000000000..72d67dd69a0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/AbstractPhpUnitFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Indicator\PhpUnitTestCaseIndicator; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +abstract class AbstractPhpUnitFixer extends AbstractFixer +{ + public final function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_STRING]); + } + protected final function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $phpUnitTestCaseIndicator = new PhpUnitTestCaseIndicator(); + foreach ($phpUnitTestCaseIndicator->findPhpUnitClasses($tokens) as $indices) { + $this->applyPhpUnitClassFix($tokens, $indices[0], $indices[1]); + } + } + protected abstract function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void; + protected final function getDocBlockIndex(Tokens $tokens, int $index) : int + { + $modifiers = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_COMMENT]; + if (\defined('T_ATTRIBUTE')) { + // @TODO: drop condition when PHP 8.0+ is required + $modifiers[] = \T_ATTRIBUTE; + } + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.2+ is required + $modifiers[] = \T_READONLY; + } + do { + $index = $tokens->getPrevNonWhitespace($index); + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($modifiers)); + return $index; + } + /** + * @param array $preventingAnnotations + */ + protected final function ensureIsDockBlockWithAnnotation(Tokens $tokens, int $index, string $annotation, array $preventingAnnotations) : void + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + if ($this->isPHPDoc($tokens, $docBlockIndex)) { + $this->updateDocBlockIfNeeded($tokens, $docBlockIndex, $annotation, $preventingAnnotations); + } else { + $this->createDocBlock($tokens, $docBlockIndex, $annotation); + } + } + protected final function isPHPDoc(Tokens $tokens, int $index) : bool + { + return $tokens[$index]->isGivenKind(\T_DOC_COMMENT); + } + private function createDocBlock(Tokens $tokens, int $docBlockIndex, string $annotation) : void + { + $lineEnd = $this->whitespacesConfig->getLineEnding(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $toInsert = [new Token([\T_DOC_COMMENT, "/**{$lineEnd}{$originalIndent} * @{$annotation}{$lineEnd}{$originalIndent} */"]), new Token([\T_WHITESPACE, $lineEnd . $originalIndent])]; + $index = $tokens->getNextMeaningfulToken($docBlockIndex); + $tokens->insertAt($index, $toInsert); + if (!$tokens[$index - 1]->isGivenKind(\T_WHITESPACE)) { + $extraNewLines = $this->whitespacesConfig->getLineEnding(); + if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) { + $extraNewLines .= $this->whitespacesConfig->getLineEnding(); + } + $tokens->insertAt($index, [new Token([\T_WHITESPACE, $extraNewLines . WhitespacesAnalyzer::detectIndent($tokens, $index)])]); + } + } + /** + * @param array $preventingAnnotations + */ + private function updateDocBlockIfNeeded(Tokens $tokens, int $docBlockIndex, string $annotation, array $preventingAnnotations) : void + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + foreach ($preventingAnnotations as $preventingAnnotation) { + if ([] !== $doc->getAnnotationsOfType($preventingAnnotation)) { + return; + } + } + $doc = $this->makeDocBlockMultiLineIfNeeded($doc, $tokens, $docBlockIndex, $annotation); + $lines = $this->addInternalAnnotation($doc, $tokens, $docBlockIndex, $annotation); + $lines = \implode('', $lines); + $tokens[$docBlockIndex] = new Token([\T_DOC_COMMENT, $lines]); + } + /** + * @return array + */ + private function addInternalAnnotation(DocBlock $docBlock, Tokens $tokens, int $docBlockIndex, string $annotation) : array + { + $lines = $docBlock->getLines(); + $originalIndent = WhitespacesAnalyzer::detectIndent($tokens, $docBlockIndex); + $lineEnd = $this->whitespacesConfig->getLineEnding(); + \array_splice($lines, -1, 0, $originalIndent . ' * @' . $annotation . $lineEnd); + return $lines; + } + private function makeDocBlockMultiLineIfNeeded(DocBlock $doc, Tokens $tokens, int $docBlockIndex, string $annotation) : DocBlock + { + $lines = $doc->getLines(); + if (1 === \count($lines) && [] === $doc->getAnnotationsOfType($annotation)) { + $indent = WhitespacesAnalyzer::detectIndent($tokens, $tokens->getNextNonWhitespace($docBlockIndex)); + $doc->makeMultiLine($indent, $this->whitespacesConfig->getLineEnding()); + return $doc; + } + return $doc; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php new file mode 100644 index 00000000000..83ce80522ee --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ArrayPushFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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() : FixerDefinitionInterface + { + return new FixerDefinition('Converts simple usages of `array_push($x, $y);` to `$x[] = $y;`.', [new CodeSample("isTokenKindFound(\T_STRING) && $tokens->count() > 7; + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // redeclare/override + } + // meaningful before must be `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; + } + // figure out where the arguments list opens + $openBraceIndex = $tokens->getNextMeaningfulToken($callIndex); + $blockType = Tokens::detectBlockType($tokens[$openBraceIndex]); + if (null === $blockType || Tokens::BLOCK_TYPE_PARENTHESIS_BRACE !== $blockType['type']) { + continue; + } + // figure out where the arguments list closes + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openBraceIndex); + // meaningful after `)` must be `;`, `? >` or nothing + $afterCloseBraceIndex = $tokens->getNextMeaningfulToken($closeBraceIndex); + if (null !== $afterCloseBraceIndex && !$tokens[$afterCloseBraceIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + continue; + } + // must have 2 arguments + // first argument must be a variable (with possibly array indexing etc.), + // after that nothing meaningful should be there till the next `,` or `)` + // if `)` than we cannot fix it (it is a single argument call) + $firstArgumentStop = $this->getFirstArgumentEnd($tokens, $openBraceIndex); + $firstArgumentStop = $tokens->getNextMeaningfulToken($firstArgumentStop); + if (!$tokens[$firstArgumentStop]->equals(',')) { + return; + } + // second argument can be about anything but ellipsis, we must make sure there is not + // a third argument (or more) passed to `array_push` + $secondArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStop); + $secondArgumentStop = $this->getSecondArgumentEnd($tokens, $secondArgumentStart, $closeBraceIndex); + if (null === $secondArgumentStop) { + continue; + } + // candidate is valid, replace tokens + $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, int $index) : int + { + $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; + } + /** + * @param int $endIndex boundary, i.e. tokens index of `)` + */ + private function getSecondArgumentEnd(Tokens $tokens, int $index, int $endIndex) : ?int + { + if ($tokens[$index]->isGivenKind(\T_ELLIPSIS)) { + return null; + } + 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php new file mode 100644 index 00000000000..3620e368b08 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/BacktickToShellExecFixer.php @@ -0,0 +1,118 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class BacktickToShellExecFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('`'); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts backtick operators to `shell_exec` calls.', [new CodeSample(<<<'EOT' +call()}`; + +EOT +)], 'Conversion is done only when it is non risky, so when special chars like single-quotes, double-quotes and backticks are not used inside the command.'); + } + /** + * {@inheritdoc} + * + * Must run before EscapeImplicitBackslashesFixer, ExplicitStringVariableFixer, NativeFunctionInvocationFixer, SingleQuoteFixer. + */ + public function getPriority() : int + { + return 17; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + } + } + /** + * Override backtick code with corresponding double-quoted string. + * + * @param array $backtickTokens + */ + private function fixBackticks(Tokens $tokens, array $backtickTokens) : void + { + // Track indices for final override + \ksort($backtickTokens); + $openingBacktickIndex = \key($backtickTokens); + \end($backtickTokens); + $closingBacktickIndex = \key($backtickTokens); + // Strip enclosing backticks + \array_shift($backtickTokens); + \array_pop($backtickTokens); + // Double-quoted strings are parsed differently if they contain + // variables or not, so we need to build the new token array accordingly + $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(); + // Escaping special chars depends on the context: too tricky + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php new file mode 100644 index 00000000000..60d212f1f8f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/EregToPregFixer.php @@ -0,0 +1,151 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\PregException; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Matteo Beccati + */ +final class EregToPregFixer extends AbstractFixer +{ + /** + * @var list> the list of the ext/ereg function names, their preg equivalent and the preg modifier(s), if any + * all condensed in an array of arrays + */ + 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']]; + /** + * @var list the list of preg delimiters, in order of preference + */ + private static $delimiters = ['/', '#', '!']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace deprecated `ereg` regular expression functions with `preg`.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $end = $tokens->count() - 1; + $functionsAnalyzer = new FunctionsAnalyzer(); + foreach (self::$functions as $map) { + // the sequence is the function name, followed by "(" and a quoted string + $seq = [[\T_STRING, $map[0]], '(', [\T_CONSTANT_ENCAPSED_STRING]]; + $currIndex = 0; + while (\true) { + $match = $tokens->findSequence($seq, $currIndex, $end, \false); + // did we find a match? + if (null === $match) { + break; + } + // findSequence also returns the tokens, but we're only interested in the indices, i.e.: + // 0 => function name, + // 1 => bracket "(" + // 2 => quoted string passed as 1st parameter + $match = \array_keys($match); + // advance tokenizer cursor + $currIndex = $match[2]; + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $match[0])) { + continue; + } + // ensure the first parameter is just a string (e.g. has nothing appended) + $next = $tokens->getNextMeaningfulToken($match[2]); + if (null === $next || !$tokens[$next]->equalsAny([',', ')'])) { + continue; + } + // convert to PCRE + $regexTokenContent = $tokens[$match[2]]->getContent(); + if ('b' === $regexTokenContent[0] || 'B' === $regexTokenContent[0]) { + $quote = $regexTokenContent[1]; + $prefix = $regexTokenContent[0]; + $string = \substr($regexTokenContent, 2, -1); + } else { + $quote = $regexTokenContent[0]; + $prefix = ''; + $string = \substr($regexTokenContent, 1, -1); + } + $delim = $this->getBestDelimiter($string); + $preg = $delim . \addcslashes($string, $delim) . $delim . 'D' . $map[2]; + // check if the preg is valid + if (!$this->checkPreg($preg)) { + continue; + } + // modify function and argument + $tokens[$match[0]] = new Token([\T_STRING, $map[1]]); + $tokens[$match[2]] = new Token([\T_CONSTANT_ENCAPSED_STRING, $prefix . $quote . $preg . $quote]); + } + } + } + /** + * Check the validity of a PCRE. + * + * @param string $pattern the regular expression + */ + private function checkPreg(string $pattern) : bool + { + try { + Preg::match($pattern, ''); + return \true; + } catch (PregException $e) { + return \false; + } + } + /** + * Get the delimiter that would require the least escaping in a regular expression. + * + * @param string $pattern the regular expression + * + * @return string the preg delimiter + */ + private function getBestDelimiter(string $pattern) : string + { + // try to find something that's not used + $delimiters = []; + foreach (self::$delimiters as $k => $d) { + if (\strpos($pattern, $d) === \false) { + return $d; + } + $delimiters[$d] = [\substr_count($pattern, $d), $k]; + } + // return the least used delimiter, using the position in the list as a tiebreaker + \uasort($delimiters, static function (array $a, array $b) : int { + if ($a[0] === $b[0]) { + return $a[1] <=> $b[1]; + } + return $a[0] <=> $b[0]; + }); + return \key($delimiters); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php new file mode 100644 index 00000000000..7a27d099461 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/MbStrFunctionsFixer.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class MbStrFunctionsFixer extends AbstractFunctionReferenceFixer +{ + /** + * list of the string-related function names and their mb_ equivalent. + * + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + 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]]]; + /** + * @var array< + * string, + * array{ + * alternativeName: string, + * argumentCount: list, + * }, + * > + */ + private $functions; + public function __construct() + { + parent::__construct(); + $this->functions = \array_filter(self::$functionsMap, static function (array $mapping) : bool { + return (new \ReflectionFunction($mapping['alternativeName']))->isInternal(); + }); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace non multibyte-safe functions with corresponding mb function.', [new CodeSample('functions as $functionIdentity => $functionReplacement) { + $currIndex = 0; + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + if (!\in_array($count, $functionReplacement['argumentCount'], \true)) { + continue 2; + } + // analysing cursor shift, so nested calls could be processed + $currIndex = $openParenthesis; + $tokens[$functionName] = new Token([\T_STRING, $functionReplacement['alternativeName']]); + } while (null !== $currIndex); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php new file mode 100644 index 00000000000..07244860a68 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/ModernizeStrposFixer.php @@ -0,0 +1,162 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Alexander M. Turek + */ +final class ModernizeStrposFixer extends AbstractFixer +{ + private const REPLACEMENTS = [['operator' => [\T_IS_IDENTICAL, '==='], 'operand' => [\T_LNUMBER, '0'], 'replacement' => [\T_STRING, 'str_starts_with'], 'negate' => \false], ['operator' => [\T_IS_NOT_IDENTICAL, '!=='], 'operand' => [\T_LNUMBER, '0'], 'replacement' => [\T_STRING, 'str_starts_with'], 'negate' => \true], ['operator' => [\T_IS_NOT_IDENTICAL, '!=='], 'operand' => [\T_STRING, 'false'], 'replacement' => [\T_STRING, 'str_contains'], 'negate' => \false], ['operator' => [\T_IS_IDENTICAL, '==='], 'operand' => [\T_STRING, 'false'], 'replacement' => [\T_STRING, 'str_contains'], 'negate' => \true]]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace `strpos()` calls with `str_starts_with()` or `str_contains()` if possible.', [new CodeSample('isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + for ($index = \count($tokens) - 1; $index > 0; --$index) { + // find candidate function call + if (!$tokens[$index]->equals([\T_STRING, 'strpos'], \false) || !$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + // assert called with 2 arguments + $openIndex = $tokens->getNextMeaningfulToken($index); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex); + if (2 !== \count($arguments)) { + continue; + } + // check if part condition and fix if needed + $compareTokens = $this->getCompareTokens($tokens, $index, -1); + // look behind + if (null === $compareTokens) { + $compareTokens = $this->getCompareTokens($tokens, $closeIndex, 1); + // look ahead + } + if (null !== $compareTokens) { + $this->fixCall($tokens, $index, $compareTokens); + } + } + } + /** + * @param array{operator_index: int, operand_index: int} $operatorIndices + */ + private function fixCall(Tokens $tokens, int $functionIndex, array $operatorIndices) : void + { + foreach (self::REPLACEMENTS as $replacement) { + if (!$tokens[$operatorIndices['operator_index']]->equals($replacement['operator'])) { + continue; + } + if (!$tokens[$operatorIndices['operand_index']]->equals($replacement['operand'], \false)) { + continue; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operator_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($operatorIndices['operand_index']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionIndex); + if ($replacement['negate']) { + $negateInsertIndex = $functionIndex; + $prevFunctionIndex = $tokens->getPrevMeaningfulToken($functionIndex); + if ($tokens[$prevFunctionIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $negateInsertIndex = $prevFunctionIndex; + } + $tokens->insertAt($negateInsertIndex, new Token('!')); + ++$functionIndex; + } + $tokens->insertAt($functionIndex, new Token($replacement['replacement'])); + break; + } + } + /** + * @param -1|1 $direction + * + * @return null|array{operator_index: int, operand_index: int} + */ + private function getCompareTokens(Tokens $tokens, int $offsetIndex, int $direction) : ?array + { + $operatorIndex = $tokens->getMeaningfulTokenSibling($offsetIndex, $direction); + if (null !== $operatorIndex && $tokens[$operatorIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $operatorIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + } + if (null === $operatorIndex || !$tokens[$operatorIndex]->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL])) { + return null; + } + $operandIndex = $tokens->getMeaningfulTokenSibling($operatorIndex, $direction); + if (null === $operandIndex) { + return null; + } + $operand = $tokens[$operandIndex]; + if (!$operand->equals([\T_LNUMBER, '0']) && !$operand->equals([\T_STRING, 'false'], \false)) { + return null; + } + $precedenceTokenIndex = $tokens->getMeaningfulTokenSibling($operandIndex, $direction); + if (null !== $precedenceTokenIndex && $this->isOfHigherPrecedence($tokens[$precedenceTokenIndex])) { + return null; + } + return ['operator_index' => $operatorIndex, 'operand_index' => $operandIndex]; + } + private function isOfHigherPrecedence(Token $token) : bool + { + static $operatorsKinds = [ + \T_DEC, + // -- + \T_INC, + // ++ + \T_INSTANCEOF, + // instanceof + \T_IS_GREATER_OR_EQUAL, + // >= + \T_IS_SMALLER_OR_EQUAL, + // <= + \T_POW, + // ** + \T_SL, + // << + \T_SR, + ]; + static $operatorsPerContent = ['!', '%', '*', '+', '-', '.', '/', '<', '>', '~']; + return $token->isGivenKind($operatorsKinds) || $token->equalsAny($operatorsPerContent); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php new file mode 100644 index 00000000000..5dc90f16dab --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasFunctionsFixer.php @@ -0,0 +1,157 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Vladimir Reznichenko + * @author Dariusz Rumiński + */ +final class NoAliasFunctionsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const SETS = ['@internal' => ['diskfreespace' => 'disk_free_space', 'dns_check_record' => 'checkdnsrr', 'dns_get_mx' => 'getmxrr', 'session_commit' => 'session_write_close', 'stream_register_wrapper' => 'stream_wrapper_register', 'set_file_buffer' => 'stream_set_write_buffer', 'socket_set_blocking' => 'stream_set_blocking', 'socket_get_status' => 'stream_get_meta_data', 'socket_set_timeout' => 'stream_set_timeout', 'socket_getopt' => 'socket_get_option', 'socket_setopt' => 'socket_set_option', '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'], '@IMAP' => ['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'], '@ldap' => ['ldap_close' => 'ldap_unbind', 'ldap_modify' => 'ldap_mod_replace'], '@mysqli' => ['mysqli_execute' => 'mysqli_stmt_execute', 'mysqli_set_opt' => 'mysqli_options', 'mysqli_escape_string' => 'mysqli_real_escape_string'], '@pg' => ['pg_exec' => 'pg_query'], '@oci' => ['oci_free_cursor' => 'oci_free_statement'], '@odbc' => ['odbc_do' => 'odbc_exec', 'odbc_field_precision' => 'odbc_field_len'], '@mbreg' => ['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'], '@openssl' => ['openssl_get_publickey' => 'openssl_pkey_get_public', 'openssl_get_privatekey' => 'openssl_pkey_get_private'], '@sodium' => ['sodium_crypto_scalarmult_base' => 'sodium_crypto_box_publickey_from_secretkey'], '@exif' => ['read_exif_data' => 'exif_read_data'], '@ftp' => ['ftp_quit' => 'ftp_close'], '@posix' => ['posix_errno' => 'posix_get_last_error'], '@pcntl' => ['pcntl_errno' => 'pcntl_get_last_error'], '@time' => ['mktime' => ['time', 0], 'gmmktime' => ['time', 0]]]; + /** + * @var array|string> stores alias (key) - master (value) functions mapping + */ + private $aliases = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->aliases = []; + foreach ($this->configuration['sets'] as $set) { + if ('@all' === $set) { + $this->aliases = \array_merge(...\array_values(self::SETS)); + break; + } + $this->aliases = \array_merge($this->aliases, self::SETS[$set]); + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Master functions shall be used instead of aliases.', [new CodeSample(' ['@mbreg']])], null, 'Risky when any of the alias functions are overridden.'); + } + /** + * {@inheritdoc} + * + * Must run before ImplodeCallFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority() : int + { + return 40; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + /** @var Token $token */ + foreach ($tokens->findGivenKind(\T_STRING) as $index => $token) { + // check mapping hit + $tokenContent = \strtolower($token->getContent()); + if (!isset($this->aliases[$tokenContent])) { + continue; + } + // skip expressions without parameters list + $openParenthesis = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$openParenthesis]->equals('(')) { + continue; + } + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + if (\is_array($this->aliases[$tokenContent])) { + [$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() : FixerConfigurationResolverInterface + { + $sets = [ + '@all' => 'all listed sets', + '@internal' => 'native functions', + '@exif' => 'EXIF functions', + '@ftp' => 'FTP functions', + '@IMAP' => 'IMAP functions', + '@ldap' => 'LDAP functions', + '@mbreg' => 'from `ext-mbstring`', + '@mysqli' => 'mysqli functions', + '@oci' => 'oci functions', + '@odbc' => 'odbc functions', + '@openssl' => 'openssl functions', + '@pcntl' => 'PCNTL functions', + '@pg' => 'pg functions', + '@posix' => 'POSIX functions', + '@snmp' => 'SNMP functions', + // @TODO Remove on next major 4.0 as this set is now empty + '@sodium' => 'libsodium functions', + '@time' => 'time functions', + ]; + $list = "List of sets to fix. Defined sets are:\n\n"; + foreach ($sets as $set => $description) { + $list .= \sprintf("* `%s` (%s);\n", $set, $description); + } + $list = \rtrim($list, ";\n") . '.'; + return new FixerConfigurationResolver([(new FixerOptionBuilder('sets', $list))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(\array_keys($sets))])->setDefault(['@internal', '@IMAP', '@pg'])->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php new file mode 100644 index 00000000000..fbbc4efeade --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoAliasLanguageConstructCallFixer.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoAliasLanguageConstructCallFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Master language constructs shall be used instead of aliases.', [new CodeSample('isTokenKindFound(\T_EXIT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_EXIT)) { + continue; + } + if ('exit' === \strtolower($token->getContent())) { + continue; + } + $tokens[$index] = new Token([\T_EXIT, 'exit']); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php new file mode 100644 index 00000000000..49c080ed054 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/NoMixedEchoPrintFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Sullivan Senechal + */ +final class NoMixedEchoPrintFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $callBack; + /** + * @var int T_ECHO or T_PRINT + */ + private $candidateTokenType; + public function configure(array $configuration) : void + { + 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() : FixerDefinitionInterface + { + return new FixerDefinition('Either language construct `print` or `echo` should be used.', [new CodeSample(" 'print'])]); + } + /** + * {@inheritdoc} + * + * Must run after EchoTagSyntaxFixer. + */ + public function getPriority() : int + { + return -10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound($this->candidateTokenType); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $callBack = $this->callBack; + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($this->candidateTokenType)) { + $this->{$callBack}($tokens, $index); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('use', 'The desired language construct.'))->setAllowedValues(['print', 'echo'])->setDefault('echo')->getOption()]); + } + private function fixEchoToPrint(Tokens $tokens, int $index) : void + { + $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, int $index) : void + { + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + if (!$prevToken->equalsAny([';', '{', '}', ')', [\T_OPEN_TAG], [\T_ELSE]])) { + return; + } + $tokens[$index] = new Token([\T_ECHO, 'echo']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php new file mode 100644 index 00000000000..479f57556a2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/PowToExponentiationFixer.php @@ -0,0 +1,172 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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) : bool + { + // minimal candidate to fix is seven tokens: pow(x,y); + return $tokens->count() > 7 && $tokens->isTokenKindFound(\T_STRING); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts `pow` to the `**` operator.', [new CodeSample("findPowCalls($tokens); + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $numberOfTokensAdded = 0; + $previousCloseParenthesisIndex = \count($tokens); + foreach (\array_reverse($candidates) as $candidate) { + // if in the previous iteration(s) tokens were added to the collection and this is done within the tokens + // indices of the current candidate than the index of the close ')' of the candidate has moved and so + // the index needs to be updated + 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], + // functionNameIndex, + $candidate[1], + // openParenthesisIndex, + $candidate[2], + // closeParenthesisIndex, + $arguments + ); + } + } + /** + * @return array + */ + private function findPowCalls(Tokens $tokens) : array + { + $candidates = []; + // Minimal candidate to fix is seven tokens: pow(x,y); + $end = \count($tokens) - 6; + // First possible location is after the open token: 1 + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('pow', $tokens, $i, $end); + if (null === $candidate) { + break; + } + $i = $candidate[1]; + // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + return $candidates; + } + /** + * @param array $arguments + * + * @return int number of tokens added to the collection + */ + private function fixPowToExponentiation(Tokens $tokens, int $functionNameIndex, int $openParenthesisIndex, int $closeParenthesisIndex, array $arguments) : int + { + // find the argument separator ',' directly after the last token of the first argument; + // replace it with T_POW '**' + $tokens[$tokens->getNextTokenOfKind(\reset($arguments), [','])] = new Token([\T_POW, '**']); + // clean up the function call tokens prt. I + $tokens->clearAt($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($closeParenthesisIndex); + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearAt($previousIndex); + // trailing ',' in function call (PHP 7.3) + } + $added = 0; + // check if the arguments need to be wrapped in parentheses + 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; + } + } + // clean up the function call tokens prt. II + $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, int $argumentStartIndex, int $argumentEndIndex) : bool + { + static $allowedKinds = null; + if (null === $allowedKinds) { + $allowedKinds = $this->getAllowedKinds(); + } + 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; + } + /** + * @return int[] + */ + private function getAllowedKinds() : array + { + return \array_merge([\T_DNUMBER, \T_LNUMBER, \T_VARIABLE, \T_STRING, \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], Token::getObjectOperatorKinds()); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php new file mode 100644 index 00000000000..6c5221eef34 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/RandomApiMigrationFixer.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Vladimir Reznichenko + */ +final class RandomApiMigrationFixer extends AbstractFunctionReferenceFixer implements ConfigurableFixerInterface +{ + /** + * @var array> + */ + private static $argumentCounts = ['getrandmax' => [0], 'mt_rand' => [1, 2], 'rand' => [0, 2], 'srand' => [0, 1], 'random_int' => [0, 2]]; + public function configure(array $configuration) : void + { + parent::configure($configuration); + foreach ($this->configuration['replacements'] as $functionName => $replacement) { + $this->configuration['replacements'][$functionName] = ['alternativeName' => $replacement, 'argumentCount' => self::$argumentCounts[$functionName]]; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replaces `rand`, `srand`, `getrandmax` functions calls with their `mt_*` analogs or `random_int`.', [new CodeSample(" ['getrandmax' => 'mt_getrandmax']]), new CodeSample(" ['rand' => 'random_int']])], null, 'Risky when the configured functions are overridden. Or when relying on the seed based generating of the numbers.'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + foreach ($this->configuration['replacements'] as $functionIdentity => $functionReplacement) { + if ($functionIdentity === $functionReplacement['alternativeName']) { + continue; + } + $currIndex = 0; + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + $count = $argumentsAnalyzer->countArguments($tokens, $openParenthesis, $closeParenthesis); + if (!\in_array($count, $functionReplacement['argumentCount'], \true)) { + continue 2; + } + // analysing cursor shift, so nested calls could be processed + $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; + } + } while (null !== $currIndex); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('replacements', 'Mapping between replaced functions with the new ones.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $value) : bool { + 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, \get_debug_type($replacement))); + } + } + return \true; + }])->setDefault([ + 'getrandmax' => 'mt_getrandmax', + 'rand' => 'mt_rand', + // @TODO change to `random_int` as default on 4.0 + 'srand' => 'mt_srand', + ])->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php new file mode 100644 index 00000000000..dddfb0111dd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Alias/SetTypeToCastFixer.php @@ -0,0 +1,148 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Alias; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SetTypeToCastFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Cast shall be used, not `settype`.', [new CodeSample('isAllTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_STRING, \T_VARIABLE]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // function must be overridden or used incorrectly + } + $prev = $tokens->getPrevMeaningfulToken($functionNameIndex); + if (!$tokens[$prev]->equalsAny([';', '{', '}', [\T_OPEN_TAG]])) { + continue; + // return value of the function is used + } + \reset($arguments); + // --- Test first argument -------------------- + $firstArgumentStart = \key($arguments); + if ($tokens[$firstArgumentStart]->isComment() || $tokens[$firstArgumentStart]->isWhitespace()) { + $firstArgumentStart = $tokens->getNextMeaningfulToken($firstArgumentStart); + } + if (!$tokens[$firstArgumentStart]->isGivenKind(\T_VARIABLE)) { + continue; + // settype only works with variables pass by reference, function must be overridden + } + $commaIndex = $tokens->getNextMeaningfulToken($firstArgumentStart); + if (null === $commaIndex || !$tokens[$commaIndex]->equals(',')) { + continue; + // first argument is complex statement; function must be overridden + } + // --- Test second argument ------------------- + \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; + // second argument is of the wrong type or is a (complex) statement of some sort (function is overridden) + } + // --- Test type ------------------------------ + $type = \strtolower(\trim($tokens[$secondArgumentStart]->getContent(), '"\'"')); + if ('null' !== $type && !isset($map[$type])) { + continue; + // we don't know how to map + } + // --- Fixing --------------------------------- + $argumentToken = $tokens[$firstArgumentStart]; + $this->removeSettypeCall($tokens, $functionNameIndex, $candidate[1], $firstArgumentStart, $commaIndex, $secondArgumentStart, $candidate[2]); + if ('null' === $type) { + $this->fixSettypeNullCall($tokens, $functionNameIndex, $argumentToken); + } else { + $this->fixSettypeCall($tokens, $functionNameIndex, $argumentToken, new Token($map[$type])); + } + } + } + /** + * @return list> + */ + private function findSettypeCalls(Tokens $tokens) : array + { + $candidates = []; + $end = \count($tokens); + for ($i = 1; $i < $end; ++$i) { + $candidate = $this->find('settype', $tokens, $i, $end); + if (null === $candidate) { + break; + } + $i = $candidate[1]; + // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + return $candidates; + } + private function removeSettypeCall(Tokens $tokens, int $functionNameIndex, int $openParenthesisIndex, int $firstArgumentStart, int $commaIndex, int $secondArgumentStart, int $closeParenthesisIndex) : void + { + $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); + // we'll be inserting here so no need to merge the space tokens + $tokens->clearEmptyTokens(); + } + private function fixSettypeCall(Tokens $tokens, int $functionNameIndex, Token $argumentToken, Token $castToken) : void + { + $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); + // 6 = number of inserted tokens -1 for offset correction + } + private function fixSettypeNullCall(Tokens $tokens, int $functionNameIndex, Token $argumentToken) : void + { + $tokens->insertAt($functionNameIndex, [clone $argumentToken, new Token([\T_WHITESPACE, ' ']), new Token('='), new Token([\T_WHITESPACE, ' ']), new Token([\T_STRING, 'null'])]); + $tokens->removeTrailingWhitespace($functionNameIndex + 4); + // 4 = number of inserted tokens -1 for offset correction + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php new file mode 100644 index 00000000000..5935b907c8a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/ArraySyntaxFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + * @author Sebastiaan Stok + * @author Dariusz Rumiński + */ +final class ArraySyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|int + */ + private $candidateTokenKind; + /** + * @var null|string + */ + private $fixCallback; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->resolveCandidateTokenKind(); + $this->resolveFixCallback(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHP arrays should be declared using the configured syntax.', [new CodeSample(" 'long'])]); + } + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $callback = $this->fixCallback; + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if ($tokens[$index]->isGivenKind($this->candidateTokenKind)) { + $this->{$callback}($tokens, $index); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` array syntax.'))->setAllowedValues(['long', 'short'])->setDefault('short')->getOption()]); + } + private function fixToLongArraySyntax(Tokens $tokens, int $index) : void + { + $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, int $index) : void + { + $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() : void + { + $this->fixCallback = \sprintf('fixTo%sArraySyntax', \ucfirst($this->configuration['syntax'])); + } + private function resolveCandidateTokenKind() : void + { + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_ARRAY_SQUARE_BRACE_OPEN : \T_ARRAY; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php new file mode 100644 index 00000000000..9de3f7bd9df --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoMultilineWhitespaceAroundDoubleArrowFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Carlos Cirello + * @author Dariusz Rumiński + * @author Graham Campbell + */ +final class NoMultilineWhitespaceAroundDoubleArrowFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Operator `=>` should not be surrounded by multi-line whitespaces.', [new CodeSample(" 2);\n")]); + } + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, MethodArgumentSpaceFixer. + */ + public function getPriority() : int + { + return 31; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOUBLE_ARROW); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOUBLE_ARROW)) { + continue; + } + if (!$tokens[$index - 2]->isComment() || \strncmp($tokens[$index - 2]->getContent(), '/*', \strlen('/*')) === 0) { + $this->fixWhitespace($tokens, $index - 1); + } + // do not move anything about if there is a comment following the whitespace + if (!$tokens[$index + 2]->isComment()) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + private function fixWhitespace(Tokens $tokens, int $index) : void + { + $token = $tokens[$index]; + if ($token->isWhitespace() && !$token->isWhitespace(" \t")) { + $tokens[$index] = new Token([\T_WHITESPACE, \rtrim($token->getContent()) . ' ']); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php new file mode 100644 index 00000000000..beb388559eb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoTrailingCommaInSinglelineArrayFixer.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @deprecated + * + * @author Dariusz Rumiński + * @author Sebastiaan Stok + */ +final class NoTrailingCommaInSinglelineArrayFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHP single-line arrays should not have trailing comma.', [new CodeSample("proxyFixers); + } + protected function createProxyFixers() : array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php new file mode 100644 index 00000000000..434013fc898 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NoWhitespaceBeforeCommaInArrayFixer.php @@ -0,0 +1,112 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Adam Marczuk + */ +final class NoWhitespaceBeforeCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('In array declaration, there MUST NOT be a whitespace before each comma.', [new CodeSample(" \true])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * Method to fix spacing in array declaration. + */ + private function fixSpacing(int $index, Tokens $tokens) : void + { + 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() && (\true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC))) { + $tokens->removeLeadingWhitespace($i); + } + } + } + /** + * Method to move index over the non-array elements like function calls or function declarations. + */ + private function skipNonArrayElements(int $index, Tokens $tokens) : int + { + 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; + } + } + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + return $index; + } + private function commaIsPartOfImplementsList(int $index, Tokens $tokens) : bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + $current = $tokens[$index]; + } while ($current->isGivenKind(\T_STRING) || $current->equals(',')); + return $current->isGivenKind(\T_IMPLEMENTS); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php new file mode 100644 index 00000000000..ee33859d586 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/NormalizeIndexBraceFixer.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class NormalizeIndexBraceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Array index should always be written by using square braces.', [new CodeSample("isTokenKindFound(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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(']'); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php new file mode 100644 index 00000000000..1dfa48ccf64 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/TrimArraySpacesFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jared Henderson + */ +final class TrimArraySpacesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Arrays should be formatted like function/method arguments, without leading or trailing single line space.', [new CodeSample("isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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); + } + } + } + /** + * Method to trim leading/trailing whitespace within single line arrays. + */ + private static function fixArray(Tokens $tokens, int $index) : void + { + $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") || \strncmp($nextNonWhitespaceToken->getContent(), '/*', \strlen('/*')) === 0)) { + $tokens->clearAt($nextIndex); + } + if ($prevToken->isWhitespace(" \t") && !$prevNonWhitespaceToken->equals(',')) { + $tokens->clearAt($prevIndex); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php new file mode 100644 index 00000000000..946608213d2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/WhitespaceAfterCommaInArrayFixer.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Adam Marczuk + */ +final class WhitespaceAfterCommaInArrayFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('In array declaration, there MUST be a whitespace after each comma.', [new CodeSample(" \true])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('ensure_single_space', 'If there are only horizontal whitespaces after the comma then ensure it is a single space.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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(',')) { + continue; + } + if (!$tokens[$i + 1]->isWhitespace()) { + $tokensToInsert[$i + 1] = new Token([\T_WHITESPACE, ' ']); + } elseif ($this->configuration['ensure_single_space'] && ' ' !== $tokens[$i + 1]->getContent() && Preg::match('/^\\h+$/', $tokens[$i + 1]->getContent()) && (!$tokens[$i + 2]->isComment() || Preg::match('/^\\h+$/', $tokens[$i + 3]->getContent()))) { + $tokens[$i + 1] = new Token([\T_WHITESPACE, ' ']); + } + } + } + if ([] !== $tokensToInsert) { + $tokens->insertSlices($tokensToInsert); + } + } + /** + * Method to move index over the non-array elements like function calls or function declarations. + * + * @return int New index + */ + private function skipNonArrayElements(int $index, Tokens $tokens) : int + { + 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; + } + } + if ($tokens[$index]->equals(',') && $this->commaIsPartOfImplementsList($index, $tokens)) { + --$index; + } + return $index; + } + private function commaIsPartOfImplementsList(int $index, Tokens $tokens) : bool + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + $current = $tokens[$index]; + } while ($current->isGivenKind(\T_STRING) || $current->equals(',')); + return $current->isGivenKind(\T_IMPLEMENTS); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php new file mode 100644 index 00000000000..c3f0dc6fbe2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ArrayNotation/YieldFromArrayToYieldsFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ArrayNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class YieldFromArrayToYieldsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Yield from array must be unpacked to series of yields.', [new CodeSample('isTokenKindFound(\T_YIELD_FROM); + } + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer, NoExtraBlankLinesFixer, NoMultipleStatementsPerLineFixer, NoWhitespaceInBlankLineFixer, StatementIndentationFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + /** + * @var array $inserts + */ + $inserts = []; + foreach ($this->getYieldsFromToUnpack($tokens) as $index => [$startIndex, $endIndex]) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + if ($tokens[$startIndex]->equals('(')) { + $prevStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($prevStartIndex); + // clear `array` from `array(` + } + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($endIndex); + $arrayHasTrailingComma = \false; + $inserts[$startIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])]; + foreach ($this->findArrayItemCommaIndex($tokens, $tokens->getNextMeaningfulToken($startIndex), $tokens->getPrevMeaningfulToken($endIndex)) as $commaIndex) { + $nextItemIndex = $tokens->getNextMeaningfulToken($commaIndex); + if ($nextItemIndex < $endIndex) { + $inserts[$nextItemIndex] = [new Token([\T_YIELD, 'yield']), new Token([\T_WHITESPACE, ' '])]; + $tokens[$commaIndex] = new Token(';'); + } else { + $arrayHasTrailingComma = \true; + // array has trailing comma - we replace it with `;` (as it's best fit to put it) + $tokens[$commaIndex] = new Token(';'); + } + } + // there was a trailing comma, so we do not need original `;` after initial array structure + if (\true === $arrayHasTrailingComma) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($endIndex)); + } + } + $tokens->insertSlices($inserts); + } + /** + * @return array> + */ + private function getYieldsFromToUnpack(Tokens $tokens) : array + { + $yieldsFromToUnpack = []; + $tokensCount = $tokens->count(); + $index = 0; + while (++$index < $tokensCount) { + if (!$tokens[$index]->isGivenKind(\T_YIELD_FROM)) { + continue; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->equalsAny([';', '{', [\T_OPEN_TAG]])) { + continue; + } + $arrayStartIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$arrayStartIndex]->isGivenKind([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN])) { + continue; + } + if ($tokens[$arrayStartIndex]->isGivenKind(\T_ARRAY)) { + $startIndex = $tokens->getNextTokenOfKind($arrayStartIndex, ['(']); + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + } else { + $startIndex = $arrayStartIndex; + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $startIndex); + } + // is there any nested "yield from"? + if ([] !== $tokens->findGivenKind(\T_YIELD_FROM, $startIndex, $endIndex)) { + continue; + } + $yieldsFromToUnpack[$index] = [$startIndex, $endIndex]; + } + return $yieldsFromToUnpack; + } + /** + * @return iterable + */ + private function findArrayItemCommaIndex(Tokens $tokens, int $startIndex, int $endIndex) : iterable + { + for ($index = $startIndex; $index <= $endIndex; ++$index) { + $token = $tokens[$index]; + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + if (null !== $blockDefinitionProbe && \true === $blockDefinitionProbe['isStart']) { + $index = $tokens->findBlockEnd($blockDefinitionProbe['type'], $index); + continue; + } + if (!$tokens[$index]->equals(',')) { + continue; + } + (yield $index); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php new file mode 100644 index 00000000000..70bdf562e1f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/BracesFixer.php @@ -0,0 +1,166 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureBracesFixer; +use PhpCsFixer\Fixer\ControlStructure\ControlStructureContinuationPositionFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\LanguageConstruct\DeclareParenthesesFixer; +use PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer; +use PhpCsFixer\Fixer\Whitespace\NoExtraBlankLinesFixer; +use PhpCsFixer\Fixer\Whitespace\StatementIndentationFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * Fixer for rules defined in PSR2 ¶4.1, ¶4.4, ¶5. + * + * @author Dariusz Rumiński + * + * @deprecated + */ +final class BracesFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + /** + * @internal + */ + public const LINE_NEXT = 'next'; + /** + * @internal + */ + public const LINE_SAME = 'same'; + /** + * @var null|CurlyBracesPositionFixer + */ + private $curlyBracesPositionFixer; + /** + * @var null|ControlStructureContinuationPositionFixer + */ + private $controlStructureContinuationPositionFixer; + public function getDefinition() : FixerDefinitionInterface + { + 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('= 0; }; +$negative = function ($item) { + return $item < 0; }; +', ['allow_single_line_closure' => \true]), new CodeSample(' self::LINE_SAME])]); + } + /** + * {@inheritdoc} + * + * Must run before HeredocIndentationFixer. + * Must run after ClassAttributesSeparationFixer, ClassDefinitionFixer, EmptyLoopBodyFixer, NoAlternativeSyntaxFixer, NoEmptyStatementFixer, NoUselessElseFixer, SingleLineThrowFixer, SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority() : int + { + return 35; + } + public function getSuccessorsNames() : array + { + return \array_keys($this->proxyFixers); + } + public function configure(array $configuration = null) : void + { + parent::configure($configuration); + $this->getCurlyBracesPositionFixer()->configure(['control_structures_opening_brace' => $this->translatePositionOption($this->configuration['position_after_control_structures']), 'functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), 'anonymous_functions_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), 'classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_functions_and_oop_constructs']), 'anonymous_classes_opening_brace' => $this->translatePositionOption($this->configuration['position_after_anonymous_constructs']), 'allow_single_line_empty_anonymous_classes' => $this->configuration['allow_single_line_anonymous_class_with_empty_body'], 'allow_single_line_anonymous_functions' => $this->configuration['allow_single_line_closure']]); + $this->getControlStructureContinuationPositionFixer()->configure(['position' => self::LINE_NEXT === $this->configuration['position_after_control_structures'] ? ControlStructureContinuationPositionFixer::NEXT_LINE : ControlStructureContinuationPositionFixer::SAME_LINE]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + protected function createProxyFixers() : array + { + $singleSpaceAroundConstructFixer = new SingleSpaceAroundConstructFixer(); + $singleSpaceAroundConstructFixer->configure(['constructs_contain_a_single_space' => [], 'constructs_followed_by_a_single_space' => ['elseif', 'for', 'foreach', 'if', 'match', 'while', 'use_lambda'], 'constructs_preceded_by_a_single_space' => ['use_lambda']]); + $noExtraBlankLinesFixer = new NoExtraBlankLinesFixer(); + $noExtraBlankLinesFixer->configure(['tokens' => ['curly_brace_block']]); + return [$singleSpaceAroundConstructFixer, new ControlStructureBracesFixer(), $noExtraBlankLinesFixer, $this->getCurlyBracesPositionFixer(), $this->getControlStructureContinuationPositionFixer(), new DeclareParenthesesFixer(), new \PhpCsFixer\Fixer\Basic\NoMultipleStatementsPerLineFixer(), new StatementIndentationFixer(\true)]; + } + private function getCurlyBracesPositionFixer() : \PhpCsFixer\Fixer\Basic\CurlyBracesPositionFixer + { + if (null === $this->curlyBracesPositionFixer) { + $this->curlyBracesPositionFixer = new \PhpCsFixer\Fixer\Basic\CurlyBracesPositionFixer(); + } + return $this->curlyBracesPositionFixer; + } + private function getControlStructureContinuationPositionFixer() : ControlStructureContinuationPositionFixer + { + if (null === $this->controlStructureContinuationPositionFixer) { + $this->controlStructureContinuationPositionFixer = new ControlStructureContinuationPositionFixer(); + } + return $this->controlStructureContinuationPositionFixer; + } + private function translatePositionOption(string $option) : string + { + return self::LINE_NEXT === $option ? \PhpCsFixer\Fixer\Basic\CurlyBracesPositionFixer::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END : \PhpCsFixer\Fixer\Basic\CurlyBracesPositionFixer::SAME_LINE; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php new file mode 100644 index 00000000000..8d8518917b2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/CurlyBracesPositionFixer.php @@ -0,0 +1,283 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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; +final class CurlyBracesPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + use Indentation; + /** + * @internal + */ + public const NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END = 'next_line_unless_newline_at_signature_end'; + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Curly braces must be placed as configured.', [new CodeSample(' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END]), new CodeSample(' self::SAME_LINE]), new CodeSample(' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END]), new CodeSample(' self::SAME_LINE]), new VersionSpecificCodeSample(' self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END]), new VersionSpecificCodeSample(' \true]), new CodeSample(' \true])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('{'); + } + /** + * {@inheritdoc} + * + * Must run before SingleLineEmptyBodyFixer, StatementIndentationFixer. + * Must run after ControlStructureBracesFixer, NoMultipleStatementsPerLineFixer. + */ + public function getPriority() : int + { + return -2; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $classyTokens = Token::getClassyTokenKinds(); + $controlStructureTokens = [\T_DECLARE, \T_DO, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_FOR, \T_FOREACH, \T_IF, \T_WHILE, \T_TRY, \T_CATCH, \T_SWITCH]; + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_MATCH')) { + $controlStructureTokens[] = \T_MATCH; + } + $tokensAnalyzer = new TokensAnalyzer($tokens); + $allowSingleLineUntil = null; + foreach ($tokens as $index => $token) { + $allowSingleLine = \false; + $allowSingleLineIfEmpty = \false; + if ($token->isGivenKind($classyTokens)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + if ($tokensAnalyzer->isAnonymousClass($index)) { + $allowSingleLineIfEmpty = $this->configuration['allow_single_line_empty_anonymous_classes']; + $positionOption = 'anonymous_classes_opening_brace'; + } else { + $positionOption = 'classes_opening_brace'; + } + } elseif ($token->isGivenKind(\T_FUNCTION)) { + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$openBraceIndex]->equals(';')) { + continue; + } + if ($tokensAnalyzer->isLambda($index)) { + $allowSingleLine = $this->configuration['allow_single_line_anonymous_functions']; + $positionOption = 'anonymous_functions_opening_brace'; + } else { + $positionOption = 'functions_opening_brace'; + } + } elseif ($token->isGivenKind($controlStructureTokens)) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $openBraceIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + $positionOption = 'control_structures_opening_brace'; + } else { + continue; + } + $closeBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openBraceIndex); + $addNewlinesInsideBraces = \true; + if ($allowSingleLine || $allowSingleLineIfEmpty || $index < $allowSingleLineUntil) { + $addNewlinesInsideBraces = \false; + for ($indexInsideBraces = $openBraceIndex + 1; $indexInsideBraces < $closeBraceIndex; ++$indexInsideBraces) { + $tokenInsideBraces = $tokens[$indexInsideBraces]; + if ($allowSingleLineIfEmpty && !$tokenInsideBraces->isWhitespace() && !$tokenInsideBraces->isComment() || $tokenInsideBraces->isWhitespace() && Preg::match('/\\R/', $tokenInsideBraces->getContent())) { + $addNewlinesInsideBraces = \true; + break; + } + } + if (!$addNewlinesInsideBraces && null === $allowSingleLineUntil) { + $allowSingleLineUntil = $closeBraceIndex; + } + } + if ($addNewlinesInsideBraces && !$this->isFollowedByNewLine($tokens, $openBraceIndex) && !$this->hasCommentOnSameLine($tokens, $openBraceIndex) && !$tokens[$tokens->getNextMeaningfulToken($openBraceIndex)]->isGivenKind(\T_CLOSE_TAG)) { + $whitespace = $this->whitespacesConfig->getLineEnding() . $this->getLineIndentation($tokens, $openBraceIndex); + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, $whitespace)) { + ++$closeBraceIndex; + } + } + $whitespace = ' '; + if (self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END === $this->configuration[$positionOption]) { + $whitespace = $this->whitespacesConfig->getLineEnding() . $this->getLineIndentation($tokens, $index); + $previousTokenIndex = $openBraceIndex; + do { + $previousTokenIndex = $tokens->getPrevMeaningfulToken($previousTokenIndex); + } while ($tokens[$previousTokenIndex]->isGivenKind([CT::T_TYPE_COLON, CT::T_NULLABLE_TYPE, \T_STRING, \T_NS_SEPARATOR, CT::T_ARRAY_TYPEHINT, \T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_CALLABLE, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE])); + if ($tokens[$previousTokenIndex]->equals(')')) { + if ($tokens[--$previousTokenIndex]->isComment()) { + --$previousTokenIndex; + } + if ($tokens[$previousTokenIndex]->isWhitespace() && Preg::match('/\\R/', $tokens[$previousTokenIndex]->getContent())) { + $whitespace = ' '; + } + } + } + $moveBraceToIndex = null; + if (' ' === $whitespace) { + $previousMeaningfulIndex = $tokens->getPrevMeaningfulToken($openBraceIndex); + for ($indexBeforeOpenBrace = $openBraceIndex - 1; $indexBeforeOpenBrace > $previousMeaningfulIndex; --$indexBeforeOpenBrace) { + if (!$tokens[$indexBeforeOpenBrace]->isComment()) { + continue; + } + $tokenBeforeOpenBrace = $tokens[--$indexBeforeOpenBrace]; + if ($tokenBeforeOpenBrace->isWhitespace()) { + $moveBraceToIndex = $indexBeforeOpenBrace; + } elseif ($indexBeforeOpenBrace === $previousMeaningfulIndex) { + $moveBraceToIndex = $previousMeaningfulIndex + 1; + } + } + } elseif (!$tokens[$openBraceIndex - 1]->isWhitespace() || !Preg::match('/\\R/', $tokens[$openBraceIndex - 1]->getContent())) { + for ($indexAfterOpenBrace = $openBraceIndex + 1; $indexAfterOpenBrace < $closeBraceIndex; ++$indexAfterOpenBrace) { + if ($tokens[$indexAfterOpenBrace]->isWhitespace() && Preg::match('/\\R/', $tokens[$indexAfterOpenBrace]->getContent())) { + break; + } + if ($tokens[$indexAfterOpenBrace]->isComment() && \strncmp($tokens[$indexAfterOpenBrace]->getContent(), '/*', \strlen('/*')) !== 0) { + $moveBraceToIndex = $indexAfterOpenBrace + 1; + } + } + } + if (null !== $moveBraceToIndex) { + /** @var Token $movedToken */ + $movedToken = clone $tokens[$openBraceIndex]; + $delta = $openBraceIndex < $moveBraceToIndex ? 1 : -1; + if ($tokens[$openBraceIndex + $delta]->isWhitespace()) { + if (-1 === $delta && Preg::match('/\\R/', $tokens[$openBraceIndex - 1]->getContent())) { + $content = Preg::replace('/^(\\h*?\\R)?\\h*/', '', $tokens[$openBraceIndex + 1]->getContent()); + if ('' !== $content) { + $tokens[$openBraceIndex + 1] = new Token([\T_WHITESPACE, $content]); + } else { + $tokens->clearAt($openBraceIndex + 1); + } + } elseif ($tokens[$openBraceIndex - 1]->isWhitespace()) { + $tokens->clearAt($openBraceIndex - 1); + } + } + for (; $openBraceIndex !== $moveBraceToIndex; $openBraceIndex += $delta) { + /** @var Token $siblingToken */ + $siblingToken = $tokens[$openBraceIndex + $delta]; + $tokens[$openBraceIndex] = $siblingToken; + } + $tokens[$openBraceIndex] = $movedToken; + $openBraceIndex = $moveBraceToIndex; + } + if ($tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, $whitespace)) { + ++$closeBraceIndex; + if (null !== $allowSingleLineUntil) { + ++$allowSingleLineUntil; + } + } + if (!$addNewlinesInsideBraces || $tokens[$tokens->getPrevMeaningfulToken($closeBraceIndex)]->isGivenKind(\T_OPEN_TAG)) { + continue; + } + for ($prevIndex = $closeBraceIndex - 1; $tokens->isEmptyAt($prevIndex); --$prevIndex) { + } + $prevToken = $tokens[$prevIndex]; + if ($prevToken->isWhitespace() && Preg::match('/\\R/', $prevToken->getContent())) { + continue; + } + $whitespace = $this->whitespacesConfig->getLineEnding() . $this->getLineIndentation($tokens, $openBraceIndex); + $tokens->ensureWhitespaceAtIndex($prevIndex, 1, $whitespace); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('control_structures_opening_brace', 'The position of the opening brace of control structures‘ body.'))->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE])->setDefault(self::SAME_LINE)->getOption(), (new FixerOptionBuilder('functions_opening_brace', 'The position of the opening brace of functions‘ body.'))->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE])->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END)->getOption(), (new FixerOptionBuilder('anonymous_functions_opening_brace', 'The position of the opening brace of anonymous functions‘ body.'))->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE])->setDefault(self::SAME_LINE)->getOption(), (new FixerOptionBuilder('classes_opening_brace', 'The position of the opening brace of classes‘ body.'))->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE])->setDefault(self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END)->getOption(), (new FixerOptionBuilder('anonymous_classes_opening_brace', 'The position of the opening brace of anonymous classes‘ body.'))->setAllowedValues([self::NEXT_LINE_UNLESS_NEWLINE_AT_SIGNATURE_END, self::SAME_LINE])->setDefault(self::SAME_LINE)->getOption(), (new FixerOptionBuilder('allow_single_line_empty_anonymous_classes', 'Allow anonymous classes to have opening and closing braces on the same line.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption(), (new FixerOptionBuilder('allow_single_line_anonymous_functions', 'Allow anonymous functions to have opening and closing braces on the same line.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex) : int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + // return if next token is not opening parenthesis + if (!$nextToken->equals('(')) { + return $structureTokenIndex; + } + return $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex); + } + private function isFollowedByNewLine(Tokens $tokens, int $index) : bool + { + for (++$index, $max = \count($tokens) - 1; $index < $max; ++$index) { + $token = $tokens[$index]; + if (!$token->isComment()) { + return $token->isWhitespace() && Preg::match('/\\R/', $token->getContent()); + } + } + return \false; + } + private function hasCommentOnSameLine(Tokens $tokens, int $index) : bool + { + $token = $tokens[$index + 1]; + if ($token->isWhitespace() && !Preg::match('/\\R/', $token->getContent())) { + $token = $tokens[$index + 2]; + } + return $token->isComment(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php new file mode 100644 index 00000000000..eb953bbdc68 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/EncodingFixer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR1 ¶2.2. + * + * @author Dariusz Rumiński + */ +final class EncodingFixer extends AbstractFixer +{ + /** + * @var string + */ + private $bom; + public function __construct() + { + parent::__construct(); + $this->bom = \pack('CCC', 0xef, 0xbb, 0xbf); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHP code MUST use only UTF-8 without BOM (remove BOM).', [new CodeSample($this->bom . 'getContent(); + if (\strncmp($content, $this->bom, \strlen($this->bom)) === 0) { + $newContent = \substr($content, 3); + if ('' === $newContent) { + $tokens->clearAt(0); + } else { + $tokens[0] = new Token([$tokens[0]->getId(), $newContent]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php new file mode 100644 index 00000000000..592ad93bb25 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoMultipleStatementsPerLineFixer.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.3 Lines: There must not be more than one statement per line. + */ +final class NoMultipleStatementsPerLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must not be more than one statement per line.', [new CodeSample("isTokenKindFound(';'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = 1, $max = \count($tokens) - 1; $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FOR)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextTokenOfKind($index, ['('])); + continue; + } + if (!$tokens[$index]->equals(';')) { + continue; + } + for ($nextIndex = $index + 1; $nextIndex < $max; ++$nextIndex) { + $token = $tokens[$nextIndex]; + if ($token->isWhitespace() || $token->isComment()) { + if (Preg::match('/\\R/', $token->getContent())) { + break; + } + continue; + } + if (!$token->equalsAny(['}', [\T_CLOSE_TAG], [\T_ENDIF], [\T_ENDFOR], [\T_ENDSWITCH], [\T_ENDWHILE], [\T_ENDFOREACH]])) { + $whitespaceIndex = $index; + do { + $token = $tokens[++$whitespaceIndex]; + } while ($token->isComment()); + $newline = $this->whitespacesConfig->getLineEnding() . $this->getLineIndentation($tokens, $index); + if ($tokens->ensureWhitespaceAtIndex($whitespaceIndex, 0, $newline)) { + ++$max; + } + } + break; + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php new file mode 100644 index 00000000000..c9989dcb3c6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NoTrailingCommaInSinglelineFixer.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +final class NoTrailingCommaInSinglelineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('If a list of values separated by a comma is contained on a single line, then the last item MUST NOT have a trailing comma.', [new CodeSample(" ['array_destructuring']])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(',') && $tokens->isAnyTokenKindsFound([')', CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $elements = ['arguments', 'array_destructuring', 'array', 'group_import']; + return new FixerConfigurationResolver([(new FixerOptionBuilder('elements', 'Which elements to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($elements)])->setDefault($elements)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->equals(')') && !$tokens[$index]->isGivenKind([CT::T_ARRAY_SQUARE_BRACE_CLOSE, CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, CT::T_GROUP_IMPORT_BRACE_CLOSE])) { + continue; + } + $commaIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$commaIndex]->equals(',')) { + continue; + } + $block = Tokens::detectBlockType($tokens[$index]); + $blockOpenIndex = $tokens->findBlockStart($block['type'], $index); + if ($tokens->isPartialCodeMultiline($blockOpenIndex, $index)) { + continue; + } + if (!$this->shouldBeCleared($tokens, $blockOpenIndex)) { + continue; + } + do { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($commaIndex); + } while ($tokens[$commaIndex]->equals(',')); + $tokens->removeTrailingWhitespace($commaIndex); + } + } + private function shouldBeCleared(Tokens $tokens, int $openIndex) : bool + { + /** @var string[] $elements */ + $elements = $this->configuration['elements']; + if ($tokens[$openIndex]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + return \in_array('array', $elements, \true); + } + if ($tokens[$openIndex]->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { + return \in_array('array_destructuring', $elements, \true); + } + if ($tokens[$openIndex]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + return \in_array('group_import', $elements, \true); + } + if (!$tokens[$openIndex]->equals('(')) { + return \false; + } + $beforeOpen = $tokens->getPrevMeaningfulToken($openIndex); + if ($tokens[$beforeOpen]->isGivenKind(\T_ARRAY)) { + return \in_array('array', $elements, \true); + } + if ($tokens[$beforeOpen]->isGivenKind(\T_LIST)) { + return \in_array('array_destructuring', $elements, \true); + } + if ($tokens[$beforeOpen]->isGivenKind([\T_UNSET, \T_ISSET, \T_VARIABLE, \T_CLASS])) { + return \in_array('arguments', $elements, \true); + } + if ($tokens[$beforeOpen]->isGivenKind(\T_STRING)) { + return !AttributeAnalyzer::isAttribute($tokens, $beforeOpen) && \in_array('arguments', $elements, \true); + } + if ($tokens[$beforeOpen]->equalsAny([')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]])) { + $block = Tokens::detectBlockType($tokens[$beforeOpen]); + return (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']) && \in_array('arguments', $elements, \true); + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php new file mode 100644 index 00000000000..9a7bdd3f92f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/NonPrintableCharacterFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Removes Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols. + * + * @author Ivan Boprzenkov + */ +final class NonPrintableCharacterFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private $symbolsReplace; + /** + * @var int[] + */ + 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'], + // ZWSP U+200B + \pack('H*', 'e28087') => [' ', '2007'], + // FIGURE SPACE U+2007 + \pack('H*', 'e280af') => [' ', '202f'], + // NBSP U+202F + \pack('H*', 'e281a0') => ['', '2060'], + // WORD JOINER U+2060 + \pack('H*', 'c2a0') => [' ', 'a0'], + ]; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove Zero-width space (ZWSP), Non-breaking space (NBSP) and other invisible unicode symbols.', [new CodeSample(' \false])], null, 'Risky when strings contain intended invisible characters.'); + } + public function isRisky() : bool + { + return \true; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(self::$tokens); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('use_escape_sequences_in_strings', 'Whether characters should be replaced with escape sequences in strings.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $replacements = []; + $escapeSequences = []; + foreach ($this->symbolsReplace as $character => [$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 (\strpos($previousTokenContent, '\'') !== \false) { + $tokens[$index - 1] = new Token([\T_START_HEREDOC, \str_replace('\'', '', $previousTokenContent)]); + $stringTypeChanged = \true; + } + } elseif (\strncmp($content, "'", \strlen("'")) === 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('/^\'(.*)\'$/s', '"$1"', $content); + } + $tokens[$index] = new Token([$token->getId(), \strtr($content, $escapeSequences)]); + continue; + } + if ($token->isGivenKind(self::$tokens)) { + $newContent = \strtr($content, $replacements); + // variable name cannot contain space + if ($token->isGivenKind([\T_STRING_VARNAME, \T_VARIABLE]) && \strpos($newContent, ' ') !== \false) { + continue; + } + // multiline comment must have "*/" only at the end + if ($token->isGivenKind([\T_COMMENT, \T_DOC_COMMENT]) && \strncmp($newContent, '/*', \strlen('/*')) === 0 && \strpos($newContent, '*/') !== \strlen($newContent) - 2) { + continue; + } + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php new file mode 100644 index 00000000000..1ed9ce6e542 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/OctalNotationFixer.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class OctalNotationFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Literal octal must be in `0o` notation.', [new VersionSpecificCodeSample("= 80100 && $tokens->isTokenKindFound(\T_LNUMBER); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_LNUMBER)) { + continue; + } + $content = $token->getContent(); + if (!Preg::match('#^0[\\d_]+$#', $content)) { + continue; + } + $tokens[$index] = Preg::match('#^0+$#', $content) ? new Token([\T_LNUMBER, '0']) : new Token([\T_LNUMBER, '0o' . ('_' === $content[1] ? '0' : '') . \substr($content, 1)]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php new file mode 100644 index 00000000000..8ddf4ad9878 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/PsrAutoloadingFixer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FileSpecificCodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\StdinFileInfo; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Jordi Boggiano + * @author Dariusz Rumiński + * @author Bram Gotink + * @author Graham Campbell + * @author Kuba Werłos + */ +final class PsrAutoloadingFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + 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(' './src'])], null, 'This fixer may change your class name, which will break the code that depends on the old name.'); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + if (null !== $this->configuration['dir']) { + $realpath = \realpath($this->configuration['dir']); + if (\false === $realpath) { + throw new \InvalidArgumentException(\sprintf('Failed to resolve configured directory "%s".', $this->configuration['dir'])); + } + $this->configuration['dir'] = $realpath; + } + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before SelfAccessorFixer. + */ + public function getPriority() : int + { + return -10; + } + public function supports(\SplFileInfo $file) : bool + { + if ($file instanceof StdinFileInfo) { + return \false; + } + if ('php' !== $file->getExtension() || !Preg::match('/^' . TypeExpression::REGEX_IDENTIFIER . '$/', $file->getBasename('.php'))) { + return \false; + } + try { + $tokens = Tokens::fromCode(\sprintf('getBasename('.php'))); + if ($tokens[3]->isKeyword() || $tokens[3]->isMagicConstant()) { + // name cannot be a class name - detected by PHP 5.x + return \false; + } + } catch (\ParseError $e) { + // name cannot be a class name - detected by PHP 7.x + return \false; + } + // ignore stubs/fixtures, since they typically contain invalid files for various reasons + return !Preg::match('{[/\\\\](stub|fixture)s?[/\\\\]}i', $file->getRealPath()); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + if (null !== $this->configuration['dir'] && \strncmp($file->getRealPath(), $this->configuration['dir'], \strlen($this->configuration['dir'])) !== 0) { + return; + } + $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 ($tokenAnalyzer->isAnonymousClass($index)) { + 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('clearRange(0, 2); + $newNamespace->clearEmptyTokens(); + $tokens->insertAt($namespaceStartIndex, $newNamespace); + } + } + private function calculateClassyName(\SplFileInfo $file, ?string $namespace, string $currentName) : string + { + $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, ?string $namespace) : string + { + 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)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php new file mode 100644 index 00000000000..065b2bc09a3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Basic/SingleLineEmptyBodyFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Basic; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SingleLineEmptyBodyFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Empty body of class, interface, trait, enum or function must be abbreviated as `{}` and placed on the same line as the previous symbol, separated by a single space.', [new CodeSample('isTokenKindFound(\T_ENUM)) { + // @TODO: drop condition when PHP 8.1+ is required + return \true; + } + return $tokens->isAnyTokenKindsFound([\T_INTERFACE, \T_CLASS, \T_FUNCTION, \T_TRAIT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\array_merge(Token::getClassyTokenKinds(), [\T_FUNCTION]))) { + continue; + } + $openBraceIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if (!$tokens[$openBraceIndex]->equals('{')) { + continue; + } + $closeBraceIndex = $tokens->getNextNonWhitespace($openBraceIndex); + if (!$tokens[$closeBraceIndex]->equals('}')) { + continue; + } + $tokens->ensureWhitespaceAtIndex($openBraceIndex + 1, 0, ''); + $beforeOpenBraceIndex = $tokens->getPrevNonWhitespace($openBraceIndex); + if (!$tokens[$beforeOpenBraceIndex]->isGivenKind([\T_COMMENT, \T_DOC_COMMENT])) { + $tokens->ensureWhitespaceAtIndex($openBraceIndex - 1, 1, ' '); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php new file mode 100644 index 00000000000..5b9cb95285e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ClassReferenceNameCasingFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class ClassReferenceNameCasingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('When referencing an internal class it must be written using the correct casing.', [new CodeSample("isTokenKindFound(\T_STRING); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $classNames = $this->getClassNames(); + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $uses = []; + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) { + $uses[\strtolower($use->getShortName())] = \true; + } + foreach ($this->getClassReference($tokens, $namespace) as $reference) { + $currentContent = $tokens[$reference]->getContent(); + $lowerCurrentContent = \strtolower($currentContent); + if (isset($classNames[$lowerCurrentContent]) && $currentContent !== $classNames[$lowerCurrentContent] && !isset($uses[$lowerCurrentContent])) { + $tokens[$reference] = new Token([\T_STRING, $classNames[$lowerCurrentContent]]); + } + } + } + } + private function getClassReference(Tokens $tokens, NamespaceAnalysis $namespace) : \Generator + { + static $notBeforeKinds; + static $blockKinds; + if (null === $notBeforeKinds) { + $notBeforeKinds = [ + CT::T_USE_TRAIT, + \T_AS, + \T_CASE, + // PHP 8.1 trait enum-case + \T_CLASS, + \T_CONST, + \T_DOUBLE_ARROW, + \T_DOUBLE_COLON, + \T_FUNCTION, + \T_INTERFACE, + \T_OBJECT_OPERATOR, + \T_TRAIT, + ]; + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + $notBeforeKinds[] = \T_ENUM; + } + } + if (null === $blockKinds) { + $blockKinds = ['before' => [','], 'after' => [',']]; + foreach (Tokens::getBlockEdgeDefinitions() as $definition) { + $blockKinds['before'][] = $definition['start']; + $blockKinds['after'][] = $definition['end']; + } + } + $namespaceIsGlobal = $namespace->isGlobalNamespace(); + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + } + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $nextIndex = $tokens->getNextMeaningfulToken($index); + $isNamespaceSeparator = $tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR); + if (!$isNamespaceSeparator && !$namespaceIsGlobal) { + continue; + } + if ($isNamespaceSeparator) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if ($tokens[$prevIndex]->isGivenKind(\T_STRING)) { + continue; + } + } elseif ($tokens[$prevIndex]->isGivenKind($notBeforeKinds)) { + continue; + } + if ($tokens[$prevIndex]->equalsAny($blockKinds['before']) && $tokens[$nextIndex]->equalsAny($blockKinds['after'])) { + continue; + } + if (!$tokens[$prevIndex]->isGivenKind(\T_NEW) && $tokens[$nextIndex]->equalsAny(['(', ';', [\T_CLOSE_TAG]])) { + continue; + } + (yield $index); + } + } + /** + * @return array + */ + private function getClassNames() : array + { + static $classes = null; + if (null === $classes) { + $classes = []; + foreach (\get_declared_classes() as $class) { + if ((new \ReflectionClass($class))->isInternal()) { + $classes[\strtolower($class)] = $class; + } + } + } + return $classes; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php new file mode 100644 index 00000000000..caf50e2434c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/ConstantCaseFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for constants case. + * + * @author Pol Dellaiera + */ +final class ConstantCaseFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * Hold the function that will be used to convert the constants. + * + * @var callable + */ + private $fixFunction; + public function configure(array $configuration) : void + { + parent::configure($configuration); + if ('lower' === $this->configuration['case']) { + $this->fixFunction = static function (string $content) : string { + return \strtolower($content); + }; + } + if ('upper' === $this->configuration['case']) { + $this->fixFunction = static function (string $content) : string { + return \strtoupper($content); + }; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The PHP constants `true`, `false`, and `null` MUST be written using the correct casing.', [new CodeSample(" 'upper'])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $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)) && !$this->isEnumCaseName($tokens, $index)) { + $tokens[$index] = new Token([$token->getId(), $fixFunction($token->getContent())]); + } + } + } + private function isNeighbourAccepted(Tokens $tokens, int $index) : bool + { + static $forbiddenTokens = null; + if (null === $forbiddenTokens) { + $forbiddenTokens = \array_merge([\T_AS, \T_CLASS, \T_CONST, \T_EXTENDS, \T_IMPLEMENTS, \T_INSTANCEOF, \T_INSTEADOF, \T_INTERFACE, \T_NEW, \T_NS_SEPARATOR, \T_PAAMAYIM_NEKUDOTAYIM, \T_TRAIT, \T_USE, CT::T_USE_TRAIT, CT::T_USE_LAMBDA], Token::getObjectOperatorKinds()); + } + $token = $tokens[$index]; + if ($token->equalsAny(['{', '}'])) { + return \false; + } + return !$token->isGivenKind($forbiddenTokens); + } + private function isEnumCaseName(Tokens $tokens, int $index) : bool + { + if (!\defined('T_ENUM') || !$tokens->isTokenKindFound(\T_ENUM)) { + // @TODO: drop condition when PHP 8.1+ is required + return \false; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (null === $prevIndex || !$tokens[$prevIndex]->isGivenKind(\T_CASE)) { + return \false; + } + if (!$tokens->isTokenKindFound(\T_SWITCH)) { + return \true; + } + $prevIndex = $tokens->getPrevTokenOfKind($prevIndex, [[\T_ENUM], [\T_SWITCH]]); + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_ENUM); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php new file mode 100644 index 00000000000..f7e8013d490 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/IntegerLiteralCaseFixer.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class IntegerLiteralCaseFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Integer literals must be in correct case.', [new CodeSample("isTokenKindFound(\T_LNUMBER); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_LNUMBER)) { + continue; + } + $content = $token->getContent(); + if (!Preg::match('#^0[bxoBXO][0-9a-fA-F]+$#', $content)) { + continue; + } + $newContent = '0' . \strtolower($content[1]) . \strtoupper(\substr($content, 2)); + if ($content === $newContent) { + continue; + } + $tokens[$index] = new Token([\T_LNUMBER, $newContent]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php new file mode 100644 index 00000000000..26f91ceee01 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseKeywordsFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.5. + * + * @author Dariusz Rumiński + */ +final class LowercaseKeywordsFixer extends AbstractFixer +{ + /** + * @var int[] + */ + private static $excludedTokens = [\T_HALT_COMPILER]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHP keywords MUST be in lower case.', [new CodeSample('isAnyTokenKindsFound(Token::getKeywords()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if ($token->isKeyword() && !$token->isGivenKind(self::$excludedTokens)) { + $tokens[$index] = new Token([$token->getId(), \strtolower($token->getContent())]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php new file mode 100644 index 00000000000..aa95729b725 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/LowercaseStaticReferenceFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class LowercaseStaticReferenceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Class static references `self`, `static` and `parent` MUST be in lower case.', [new CodeSample('isAnyTokenKindsFound([\T_STATIC, \T_STRING]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + // case is already correct + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind([\T_CONST, \T_DOUBLE_COLON, \T_FUNCTION, \T_NAMESPACE, \T_NS_SEPARATOR]) || $tokens[$prevIndex]->isObjectOperator()) { + continue; + } + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind([\T_FUNCTION, \T_NS_SEPARATOR, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STRING, CT::T_NULLABLE_TYPE])) { + continue; + } + if ('static' === $newContent && $tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + continue; + } + if ($tokens[$prevIndex]->isGivenKind(\T_CASE) && !$tokens[$nextIndex]->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + continue; + } + $tokens[$index] = new Token([$token->getId(), $newContent]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php new file mode 100644 index 00000000000..9f3ecae6ba3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicConstantCasingFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author ntzm + */ +final class MagicConstantCasingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Magic constants should be referred to using the correct casing.', [new CodeSample("isAnyTokenKindsFound($this->getMagicConstantTokens()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $magicConstants = $this->getMagicConstants(); + $magicConstantTokens = $this->getMagicConstantTokens(); + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($magicConstantTokens)) { + $tokens[$index] = new Token([$token->getId(), $magicConstants[$token->getId()]]); + } + } + } + /** + * @return array + */ + private function getMagicConstants() : array + { + 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; + } + /** + * @return array + */ + private function getMagicConstantTokens() : array + { + static $magicConstantTokens = null; + if (null === $magicConstantTokens) { + $magicConstantTokens = \array_keys($this->getMagicConstants()); + } + return $magicConstantTokens; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php new file mode 100644 index 00000000000..5fe17bc0ef2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/MagicMethodCasingFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class MagicMethodCasingFixer extends AbstractFixer +{ + /** + * @var array + */ + 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() : FixerDefinitionInterface + { + return new FixerDefinition('Magic method definitions and calls must be using the correct casing.', [new CodeSample('__INVOKE(1); +')]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING) && $tokens->isAnyTokenKindsFound(\array_merge([\T_FUNCTION, \T_DOUBLE_COLON], Token::getObjectOperatorKinds())); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // wrong type + } + $content = $tokens[$index]->getContent(); + if (\strncmp($content, '__', \strlen('__')) !== 0) { + continue; + // cheap look ahead + } + $name = \strtolower($content); + if (!$this->isMagicMethodName($name)) { + continue; + // method name is not one of the magic ones we can fix + } + $nameInCorrectCasing = $this->getMagicMethodNameInCorrectCasing($name); + if ($nameInCorrectCasing === $content) { + continue; + // method name is already in the correct casing, no fix needed + } + if ($this->isFunctionSignature($tokens, $index)) { + if (0 !== $inClass) { + // this is a method definition we want to fix + $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, int $index) : bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) { + return \false; + // not a method signature + } + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + private function isMethodCall(Tokens $tokens, int $index) : bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isObjectOperator()) { + return \false; + // not a "simple" method call + } + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + private function isStaticMethodCall(Tokens $tokens, int $index) : bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(\T_DOUBLE_COLON)) { + return \false; + // not a "simple" static method call + } + return $tokens[$tokens->getNextMeaningfulToken($index)]->equals('('); + } + private function isMagicMethodName(string $name) : bool + { + return isset(self::$magicNames[$name]); + } + /** + * @param string $name name of a magic method + */ + private function getMagicMethodNameInCorrectCasing(string $name) : string + { + return self::$magicNames[$name]; + } + private function setTokenToCorrectCasing(Tokens $tokens, int $index, string $nameInCorrectCasing) : void + { + $tokens[$index] = new Token([\T_STRING, $nameInCorrectCasing]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php new file mode 100644 index 00000000000..5ab8f970a40 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionCasingFixer.php @@ -0,0 +1,73 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NativeFunctionCasingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Function defined by PHP should be called using the correct casing.', [new CodeSample("isTokenKindFound(\T_STRING); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + static $nativeFunctionNames = null; + if (null === $nativeFunctionNames) { + $nativeFunctionNames = $this->getNativeFunctionNames(); + } + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + // test if we are at a function all + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + // test if the function call is to a native PHP function + $lower = \strtolower($tokens[$index]->getContent()); + if (!\array_key_exists($lower, $nativeFunctionNames)) { + continue; + } + $tokens[$index] = new Token([\T_STRING, $nativeFunctionNames[$lower]]); + } + } + /** + * @return array + */ + private function getNativeFunctionNames() : array + { + $allFunctions = \get_defined_functions(); + $functions = []; + foreach ($allFunctions['internal'] as $function) { + $functions[\strtolower($function)] = $function; + } + return $functions; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php new file mode 100644 index 00000000000..b933e022dae --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Casing/NativeFunctionTypeDeclarationCasingFixer.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Casing; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 +{ + /** + * https://secure.php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration. + * + * self PHP 5.0 + * array PHP 5.1 + * callable PHP 5.4 + * bool PHP 7.0 + * float PHP 7.0 + * int PHP 7.0 + * string PHP 7.0 + * iterable PHP 7.1 + * void PHP 7.1 + * object PHP 7.2 + * static PHP 8.0 (return type only) + * mixed PHP 8.0 + * false PHP 8.0 (union return type only) + * null PHP 8.0 (union return type only) + * never PHP 8.1 (return type only) + * true PHP 8.2 (standalone type: https://wiki.php.net/rfc/true-type) + * false PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * null PHP 8.2 (standalone type: https://wiki.php.net/rfc/null-false-standalone-types) + * + * @var array + */ + private $hints; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer + */ + private $functionsAnalyzer; + public function __construct() + { + parent::__construct(); + $this->hints = ['array' => \true, 'bool' => \true, 'callable' => \true, 'float' => \true, 'int' => \true, 'iterable' => \true, 'object' => \true, 'self' => \true, 'string' => \true, 'void' => \true]; + if (\PHP_VERSION_ID >= 80000) { + $this->hints['false'] = \true; + $this->hints['mixed'] = \true; + $this->hints['null'] = \true; + $this->hints['static'] = \true; + } + if (\PHP_VERSION_ID >= 80100) { + $this->hints['never'] = \true; + } + if (\PHP_VERSION_ID >= 80200) { + $this->hints['true'] = \true; + } + $this->functionsAnalyzer = new FunctionsAnalyzer(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Native type hints for functions should use the correct case.', [new CodeSample("isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { + $this->fixFunctionReturnType($tokens, $index); + $this->fixFunctionArgumentTypes($tokens, $index); + } + } + } + private function fixFunctionArgumentTypes(Tokens $tokens, int $index) : void + { + foreach ($this->functionsAnalyzer->getFunctionArguments($tokens, $index) as $argument) { + $this->fixArgumentType($tokens, $argument->getTypeAnalysis()); + } + } + private function fixFunctionReturnType(Tokens $tokens, int $index) : void + { + $this->fixArgumentType($tokens, $this->functionsAnalyzer->getFunctionReturnType($tokens, $index)); + } + private function fixArgumentType(Tokens $tokens, ?TypeAnalysis $type = null) : void + { + if (null === $type) { + return; + } + for ($index = $type->getStartIndex(); $index <= $type->getEndIndex(); ++$index) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + } + $lowerCasedName = \strtolower($tokens[$index]->getContent()); + if (!isset($this->hints[$lowerCasedName])) { + continue; + } + $tokens[$index] = new Token([$tokens[$index]->getId(), $lowerCasedName]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php new file mode 100644 index 00000000000..0f10410c0fc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/CastSpacesFixer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class CastSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const INSIDE_CAST_SPACE_REPLACE_MAP = [' ' => '', "\t" => '', "\n" => '', "\r" => '', "\x00" => '', "\v" => '']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('A single space or none should be between cast and variable.', [new CodeSample(" 'single']), new CodeSample(" 'none'])]); + } + /** + * {@inheritdoc} + * + * Must run after NoShortBoolCastFixer. + */ + public function getPriority() : int + { + return -10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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']) { + // force single whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace(" \t")) { + // - if next token is whitespaces that contains only spaces and tabs - override next token with single space + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } elseif (!$tokens[$index + 1]->isWhitespace()) { + // - if next token is not whitespaces that contains spaces, tabs and new lines - append single space to current token + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + continue; + } + // force no whitespace after cast token: + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('space', 'Spacing to apply between cast and variable.'))->setAllowedValues(['none', 'single'])->setDefault('single')->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php new file mode 100644 index 00000000000..04d32890bb5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/LowercaseCastFixer.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class LowercaseCastFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Cast should be written in lower case.', [new VersionSpecificCodeSample('isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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())]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php new file mode 100644 index 00000000000..4965712a0c3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ModernizeTypesCastingFixer.php @@ -0,0 +1,119 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Vladimir Reznichenko + */ +final class ModernizeTypesCastingFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replaces `intval`, `floatval`, `doubleval`, `strval` and `boolval` function calls with according type casting operator.', [new CodeSample(' [\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; + do { + // try getting function reference and translate boundaries for humans + $boundaries = $this->find($functionIdentity, $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + // next function search, as current one not found + continue 2; + } + [$functionName, $openParenthesis, $closeParenthesis] = $boundaries; + // analysing cursor shift + $currIndex = $openParenthesis; + // indicator that the function is overridden + 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; + } + // check if something complex passed as an argument and preserve parentheses then + $countParamTokens = 0; + for ($paramContentIndex = $openParenthesis + 1; $paramContentIndex < $paramContentEnd; ++$paramContentIndex) { + // not a space, means some sensible token + if (!$tokens[$paramContentIndex]->isGivenKind(\T_WHITESPACE)) { + ++$countParamTokens; + } + } + $preserveParentheses = $countParamTokens > 1; + $afterCloseParenthesisIndex = $tokens->getNextMeaningfulToken($closeParenthesis); + $afterCloseParenthesisToken = $tokens[$afterCloseParenthesisIndex]; + $wrapInParentheses = $afterCloseParenthesisToken->equalsAny(['[', '{']) || $afterCloseParenthesisToken->isGivenKind(\T_POW); + // analyse namespace specification (root one or none) and decide what to do + $prevTokenIndex = $tokens->getPrevMeaningfulToken($functionName); + if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + // get rid of root namespace when it used + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + // perform transformation + $replacementSequence = [new Token($newToken), new Token([\T_WHITESPACE, ' '])]; + if ($wrapInParentheses) { + \array_unshift($replacementSequence, new Token('(')); + } + if (!$preserveParentheses) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($closeParenthesis); + $tokens->clearAt($closeParenthesis); + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($openParenthesis); + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearAt($openParenthesis); + } else { + // we'll need to provide a space after a casting operator + $tokens->removeTrailingWhitespace($functionName); + } + if ($wrapInParentheses) { + $tokens->insertAt($closeParenthesis, new Token(')')); + } + $tokens->overrideRange($functionName, $functionName, $replacementSequence); + // nested transformations support + $currIndex = $functionName; + } while (null !== $currIndex); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php new file mode 100644 index 00000000000..5a330329ab1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoShortBoolCastFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoShortBoolCastFixer extends AbstractFixer +{ + /** + * {@inheritdoc} + * + * Must run before CastSpacesFixer. + */ + public function getPriority() : int + { + return -9; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Short cast `bool` using double exclamation mark should not be used.', [new CodeSample("isTokenKindFound('!'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; $index > 1; --$index) { + if ($tokens[$index]->equals('!')) { + $index = $this->fixShortCast($tokens, $index); + } + } + } + private function fixShortCast(Tokens $tokens, int $index) : int + { + 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, int $start, int $end) : void + { + 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)'])); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php new file mode 100644 index 00000000000..105a39b71ba --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/NoUnsetCastFixer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUnsetCastFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Variables must be set `null` instead of using `(unset)` casting.', [new CodeSample("isTokenKindFound(\T_UNSET_CAST); + } + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_UNSET_CAST)) { + $this->fixUnsetCast($tokens, $index); + } + } + } + private function fixUnsetCast(Tokens $tokens, int $index) : void + { + $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'])); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php new file mode 100644 index 00000000000..c3d33dc8b26 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/CastNotation/ShortScalarCastFixer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\CastNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class ShortScalarCastFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Cast `(boolean)` and `(integer)` should be written as `(bool)` and `(int)`, `(double)` and `(real)` as `(float)`, `(binary)` as `(string)`.', [new VersionSpecificCodeSample("isAnyTokenKindsFound(Token::getCastTokenKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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())]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php new file mode 100644 index 00000000000..d3d74c2111f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassAttributesSeparationFixer.php @@ -0,0 +1,430 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * Make sure there is one blank line above and below class elements. + * + * The exception is when an element is the first or last item in a 'classy'. + */ +final class ClassAttributesSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const SPACING_NONE = 'none'; + /** + * @internal + */ + public const SPACING_ONE = 'one'; + private const SPACING_ONLY_IF_META = 'only_if_meta'; + /** + * @var array + */ + private $classElementTypes = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->classElementTypes = []; + // reset previous configuration + foreach ($this->configuration['elements'] as $elementType => $spacing) { + $this->classElementTypes[$elementType] = $spacing; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Class, trait and interface elements must be separated with one or none blank line.', [new CodeSample(' ['property' => self::SPACING_ONE]]), new CodeSample(' ['const' => self::SPACING_ONE]]), new CodeSample(' ['const' => self::SPACING_ONLY_IF_META]]), new VersionSpecificCodeSample(' ['property' => self::SPACING_ONLY_IF_META]])]); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, IndentationTypeFixer, NoExtraBlankLinesFixer, StatementIndentationFixer. + * Must run after OrderedClassElementsFixer, SingleClassElementPerStatementFixer, VisibilityRequiredFixer. + */ + public function getPriority() : int + { + return 55; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($this->getElementsByClass($tokens) as $class) { + $elements = $class['elements']; + $elementCount = \count($elements); + if (0 === $elementCount) { + continue; + } + if (isset($this->classElementTypes[$elements[0]['type']])) { + $this->fixSpaceBelowClassElement($tokens, $class); + $this->fixSpaceAboveClassElement($tokens, $class, 0); + } + for ($index = 1; $index < $elementCount; ++$index) { + if (isset($this->classElementTypes[$elements[$index]['type']])) { + $this->fixSpaceAboveClassElement($tokens, $class, $index); + } + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('elements', 'Dictionary of `const|method|property|trait_import|case` => `none|one|only_if_meta` values.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $option) : bool { + foreach ($option as $type => $spacing) { + $supportedTypes = ['const', 'method', 'property', 'trait_import', 'case']; + if (!\in_array($type, $supportedTypes, \true)) { + throw new InvalidOptionsException(\sprintf('Unexpected element type, expected any of %s, got "%s".', Utils::naturalLanguageJoin($supportedTypes), \gettype($type) . '#' . $type)); + } + $supportedSpacings = [self::SPACING_NONE, self::SPACING_ONE, self::SPACING_ONLY_IF_META]; + if (!\in_array($spacing, $supportedSpacings, \true)) { + throw new InvalidOptionsException(\sprintf('Unexpected spacing for element type "%s", expected any of %s, got "%s".', $spacing, Utils::naturalLanguageJoin($supportedSpacings), \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, 'trait_import' => self::SPACING_NONE, 'case' => self::SPACING_NONE])->getOption()]); + } + /** + * Fix spacing above an element of a class, interface or trait. + * + * Deals with comments, PHPDocs and spaces above the element with respect to the position of the + * element within the class, interface or trait. + * + * @param array{ + * index: int, + * open: int, + * close: int, + * elements: non-empty-list + * } $class + */ + private function fixSpaceAboveClassElement(Tokens $tokens, array $class, int $elementIndex) : void + { + $element = $class['elements'][$elementIndex]; + $elementAboveEnd = isset($class['elements'][$elementIndex + 1]) ? $class['elements'][$elementIndex + 1]['end'] : 0; + $nonWhiteAbove = $tokens->getPrevNonWhitespace($element['start']); + // element is directly after class open brace + if ($nonWhiteAbove === $class['open']) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + return; + } + // deal with comments above an element + if ($tokens[$nonWhiteAbove]->isGivenKind(\T_COMMENT)) { + // check if the comment belongs to the previous element + if ($elementAboveEnd === $nonWhiteAbove) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + return; + } + // more than one line break, always bring it back to 2 line breaks between the element start and what is above it + if ($tokens[$nonWhiteAbove + 1]->isWhitespace() && \substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 1) { + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + return; + } + // there are 2 cases: + if (1 === $element['start'] - $nonWhiteAbove || $tokens[$nonWhiteAbove - 1]->isWhitespace() && \substr_count($tokens[$nonWhiteAbove - 1]->getContent(), "\n") > 0 || $tokens[$nonWhiteAbove + 1]->isWhitespace() && \substr_count($tokens[$nonWhiteAbove + 1]->getContent(), "\n") > 0) { + // 1. The comment is meant for the element (although not a PHPDoc), + // make sure there is one line break between the element and the comment... + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + // ... and make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2); + } else { + // 2. The comment belongs to the code above the element, + // make sure there is a blank line above the element (i.e. 2 line breaks) + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 2); + } + return; + } + // deal with element with a PHPDoc/attribute above it + if ($tokens[$nonWhiteAbove]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE])) { + // there should be one linebreak between the element and the attribute above it + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], 1); + // make sure there is blank line above the comment (with the exception when it is directly after a class opening) + $nonWhiteAbove = $this->findCommentBlockStart($tokens, $nonWhiteAbove, $elementAboveEnd); + $nonWhiteAboveComment = $tokens->getPrevNonWhitespace($nonWhiteAbove); + $this->correctLineBreaks($tokens, $nonWhiteAboveComment, $nonWhiteAbove, $nonWhiteAboveComment === $class['open'] ? 1 : 2); + return; + } + $this->correctLineBreaks($tokens, $nonWhiteAbove, $element['start'], $this->determineRequiredLineCount($tokens, $class, $elementIndex)); + } + private function determineRequiredLineCount(Tokens $tokens, array $class, int $elementIndex) : int + { + $type = $class['elements'][$elementIndex]['type']; + $spacing = $this->classElementTypes[$type]; + if (self::SPACING_ONE === $spacing) { + return 2; + } + if (self::SPACING_NONE === $spacing) { + if (!isset($class['elements'][$elementIndex + 1])) { + return 1; + } + $aboveElement = $class['elements'][$elementIndex + 1]; + if ($aboveElement['type'] !== $type) { + return 2; + } + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($aboveElement['start']); + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + if (self::SPACING_ONLY_IF_META === $spacing) { + $aboveElementDocCandidateIndex = $tokens->getPrevNonWhitespace($class['elements'][$elementIndex]['start']); + return $tokens[$aboveElementDocCandidateIndex]->isGivenKind([\T_DOC_COMMENT, CT::T_ATTRIBUTE_CLOSE]) ? 2 : 1; + } + throw new \RuntimeException(\sprintf('Unknown spacing "%s".', $spacing)); + } + /** + * @param array{ + * index: int, + * open: int, + * close: int, + * elements: non-empty-list + * } $class + */ + private function fixSpaceBelowClassElement(Tokens $tokens, array $class) : void + { + $element = $class['elements'][0]; + // if this is last element fix; fix to the class end `}` here if appropriate + if ($class['close'] === $tokens->getNextNonWhitespace($element['end'])) { + $this->correctLineBreaks($tokens, $element['end'], $class['close'], 1); + } + } + private function correctLineBreaks(Tokens $tokens, int $startIndex, int $endIndex, int $reqLineCount) : void + { + $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; + } + // $lineCount = > $reqLineCount : check the one Token case first since this one will be true most of the time + if (1 === $numbOfWhiteTokens) { + $tokens[$startIndex] = new Token([\T_WHITESPACE, Preg::replace('/\\r\\n|\\n/', '', $tokens[$startIndex]->getContent(), $lineBreakCount - $reqLineCount)]); + return; + } + // $numbOfWhiteTokens = > 1 + $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, int $startIndex, int $endIndex) : int + { + $lineCount = 0; + for ($i = $startIndex; $i < $endIndex; ++$i) { + $lineCount += \substr_count($tokens[$i]->getContent(), "\n"); + } + return $lineCount; + } + private function findCommentBlockStart(Tokens $tokens, int $start, int $elementAboveEnd) : int + { + for ($i = $start; $i > $elementAboveEnd; --$i) { + if ($tokens[$i]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $start = $i = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $i); + continue; + } + if ($tokens[$i]->isComment()) { + $start = $i; + continue; + } + if (!$tokens[$i]->isWhitespace() || $this->getLineBreakCount($tokens, $i, $i + 1) > 1) { + break; + } + } + return $start; + } + /** + * @TODO Introduce proper DTO instead of an array + * + * @return \Generator + * }> + */ + private function getElementsByClass(Tokens $tokens) : \Generator + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $class = $classIndex = \false; + $elements = $tokensAnalyzer->getClassyElements(); + for (\end($elements);; \prev($elements)) { + $index = \key($elements); + if (null === $index) { + break; + } + $element = \current($elements); + $element['index'] = $index; + if ($element['classIndex'] !== $classIndex) { + if (\false !== $class) { + (yield $class); + } + $classIndex = $element['classIndex']; + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); + $class = ['index' => $classIndex, 'open' => $classOpen, 'close' => $classEnd, 'elements' => []]; + } + unset($element['classIndex']); + $element['start'] = $this->getFirstTokenIndexOfClassElement($tokens, $class, $element); + $element['end'] = $this->getLastTokenIndexOfClassElement($tokens, $class, $element, $tokensAnalyzer); + $class['elements'][] = $element; + // reset the key by design + } + if (\false !== $class) { + (yield $class); + } + } + private function getFirstTokenIndexOfClassElement(Tokens $tokens, array $class, array $element) : int + { + $modifierTypes = [\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, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $modifierTypes[] = \T_READONLY; + } + $firstElementAttributeIndex = $element['index']; + do { + $nonWhiteAbove = $tokens->getPrevMeaningfulToken($firstElementAttributeIndex); + if (null !== $nonWhiteAbove && $tokens[$nonWhiteAbove]->isGivenKind($modifierTypes)) { + $firstElementAttributeIndex = $nonWhiteAbove; + } else { + break; + } + } while ($firstElementAttributeIndex > $class['open']); + return $firstElementAttributeIndex; + } + // including trailing single line comments if belonging to the class element + private function getLastTokenIndexOfClassElement(Tokens $tokens, array $class, array $element, TokensAnalyzer $tokensAnalyzer) : int + { + // find last token of the element + if ('method' === $element['type'] && !$tokens[$class['index']]->isGivenKind(\T_INTERFACE)) { + $attributes = $tokensAnalyzer->getMethodAttributes($element['index']); + if (\true === $attributes['abstract']) { + $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']); + } else { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{'])); + } + } elseif ('trait_import' === $element['type']) { + $elementEndIndex = $element['index']; + do { + $elementEndIndex = $tokens->getNextMeaningfulToken($elementEndIndex); + } while ($tokens[$elementEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR]) || $tokens[$elementEndIndex]->equals(',')); + if (!$tokens[$elementEndIndex]->equals(';')) { + $elementEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($element['index'], ['{'])); + } + } else { + // 'const', 'property', enum-'case', or 'method' of an interface + $elementEndIndex = $tokens->getNextTokenOfKind($element['index'], [';']); + } + $singleLineElement = \true; + for ($i = $element['index'] + 1; $i < $elementEndIndex; ++$i) { + if (\strpos($tokens[$i]->getContent(), "\n") !== \false) { + $singleLineElement = \false; + break; + } + } + if ($singleLineElement) { + while (\true) { + $nextToken = $tokens[$elementEndIndex + 1]; + if (($nextToken->isComment() || $nextToken->isWhitespace()) && \strpos($nextToken->getContent(), "\n") === \false) { + ++$elementEndIndex; + } else { + break; + } + } + if ($tokens[$elementEndIndex]->isWhitespace()) { + $elementEndIndex = $tokens->getPrevNonWhitespace($elementEndIndex); + } + } + return $elementEndIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php new file mode 100644 index 00000000000..bad1f0fa13b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ClassDefinitionFixer.php @@ -0,0 +1,355 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * Fixer for part of the rules defined in PSR2 ¶4.1 Extends and Implements and PSR12 ¶8. Anonymous Classes. + */ +final class ClassDefinitionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Whitespace around the keywords of a class, trait, enum or interfaces definition should be one space.', [new CodeSample(' \true]), new CodeSample(' \true]), new CodeSample(' \true]), new CodeSample(' \true]), new CodeSample(" \true])]); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, SingleLineEmptyBodyFixer. + * Must run after NewWithBracesFixer. + */ + public function getPriority() : int + { + return 36; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // -4, one for count to index, 3 because min. of tokens for a classy location. + for ($index = $tokens->getSize() - 4; $index > 0; --$index) { + if ($tokens[$index]->isClassy()) { + $this->fixClassyDefinition($tokens, $index); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('multi_line_extends_each_single_line', 'Whether definitions should be multiline.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('single_item_single_line', 'Whether definitions should be single line when including a single item.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('single_line', 'Whether definitions should be single line.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('space_before_parenthesis', 'Whether there should be a single space after the parenthesis of anonymous class (PSR12) or not.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('inline_constructor_arguments', 'Whether constructor argument list in anonymous classes should be single line.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + /** + * @param int $classyIndex Class definition token start index + */ + private function fixClassyDefinition(Tokens $tokens, int $classyIndex) : void + { + $classDefInfo = $this->getClassyDefinitionInfo($tokens, $classyIndex); + // PSR2 4.1 Lists of implements 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 interface per line. + 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']); + } + // PSR2: class definition open curly brace must go on a new line. + // PSR12: anonymous class curly brace on same line if not multi line implements. + $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']); + } + if ($classDefInfo['anonymousClass'] && !$this->configuration['inline_constructor_arguments']) { + if (!$tokens[$end]->equals(')')) { + // anonymous class with `extends` and/or `implements` + $start = $tokens->getPrevMeaningfulToken($end); + $this->makeClassyDefinitionSingleLine($tokens, $start, $end); + $end = $start; + } + if ($tokens[$end]->equals(')')) { + // skip constructor arguments of anonymous class + $end = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end); + } + } + // 4.1 The extends and implements keywords MUST be declared on the same line as the class name. + $this->makeClassyDefinitionSingleLine($tokens, $classDefInfo['start'], $end); + $this->sortClassModifiers($tokens, $classDefInfo); + } + private function fixClassyDefinitionExtends(Tokens $tokens, int $classOpenIndex, array $classExtendsInfo) : array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + if (\true === $this->configuration['single_line'] || \false === $classExtendsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = \false; + } elseif (\true === $this->configuration['single_item_single_line'] && 1 === $classExtendsInfo['numberOfExtends']) { + $this->makeClassyDefinitionSingleLine($tokens, $classExtendsInfo['start'], $endIndex); + $classExtendsInfo['multiLine'] = \false; + } elseif (\true === $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, int $classOpenIndex, array $classImplementsInfo) : array + { + $endIndex = $tokens->getPrevNonWhitespace($classOpenIndex); + if (\true === $this->configuration['single_line'] || \false === $classImplementsInfo['multiLine']) { + $this->makeClassyDefinitionSingleLine($tokens, $classImplementsInfo['start'], $endIndex); + $classImplementsInfo['multiLine'] = \false; + } elseif (\true === $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) : int + { + 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 && \strpos($tokens[$openIndex - 1]->getContent(), "\n") !== \false) { + 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; + } + /** + * @return array{ + * start: int, + * classy: int, + * open: int, + * extends: false|array{start: int, numberOfExtends: int, multiLine: bool}, + * implements: false|array{start: int, numberOfImplements: int, multiLine: bool}, + * anonymousClass: bool, + * final: false|int, + * abstract: false|int, + * readonly: false|int, + * } + */ + private function getClassyDefinitionInfo(Tokens $tokens, int $classyIndex) : array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $openIndex = $tokens->getNextTokenOfKind($classyIndex, ['{']); + $def = ['classy' => $classyIndex, 'open' => $openIndex, 'extends' => \false, 'implements' => \false, 'anonymousClass' => \false, 'final' => \false, 'abstract' => \false, 'readonly' => \false]; + if (!$tokens[$classyIndex]->isGivenKind(\T_TRAIT)) { + $extends = $tokens->findGivenKind(\T_EXTENDS, $classyIndex, $openIndex); + $def['extends'] = [] !== $extends ? $this->getClassyInheritanceInfo($tokens, \key($extends), 'numberOfExtends') : \false; + if (!$tokens[$classyIndex]->isGivenKind(\T_INTERFACE)) { + $implements = $tokens->findGivenKind(\T_IMPLEMENTS, $classyIndex, $openIndex); + $def['implements'] = [] !== $implements ? $this->getClassyInheritanceInfo($tokens, \key($implements), 'numberOfImplements') : \false; + $def['anonymousClass'] = $tokensAnalyzer->isAnonymousClass($classyIndex); + } + } + if ($def['anonymousClass']) { + $startIndex = $tokens->getPrevTokenOfKind($classyIndex, [[\T_NEW]]); + // go to "new" for anonymous class + } else { + $modifiers = $tokensAnalyzer->getClassyModifiers($classyIndex); + $startIndex = $classyIndex; + foreach (['final', 'abstract', 'readonly'] as $modifier) { + if (isset($modifiers[$modifier])) { + $def[$modifier] = $modifiers[$modifier]; + $startIndex = \min($startIndex, $modifiers[$modifier]); + } else { + $def[$modifier] = \false; + } + } + } + $def['start'] = $startIndex; + return $def; + } + private function getClassyInheritanceInfo(Tokens $tokens, int $startIndex, string $label) : array + { + $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'] && \strpos($tokens[$i]->getContent(), "\n") !== \false) { + $implementsInfo['multiLine'] = \true; + } + } + return $implementsInfo; + } + private function makeClassyDefinitionSingleLine(Tokens $tokens, int $startIndex, int $endIndex) : void + { + for ($i = $endIndex; $i >= $startIndex; --$i) { + if ($tokens[$i]->isWhitespace()) { + if ($tokens[$i - 1]->isComment() || $tokens[$i + 1]->isComment()) { + $content = $tokens[$i - 1]->getContent(); + if (!('#' === $content || \strncmp($content, '//', \strlen('//')) === 0)) { + $content = $tokens[$i + 1]->getContent(); + if (!('#' === $content || \strncmp($content, '//', \strlen('//')) === 0)) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } + } + continue; + } + if ($tokens[$i - 1]->isGivenKind(\T_CLASS) && $tokens[$i + 1]->equals('(')) { + if (\true === $this->configuration['space_before_parenthesis']) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } else { + $tokens->clearAt($i); + } + continue; + } + if (!$tokens[$i - 1]->equals(',') && $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 (\true === $this->configuration['space_before_parenthesis'] && $tokens[$i]->isGivenKind(\T_CLASS) && !$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() && \strpos($tokens[$i]->getContent(), "\n") === \false) { + $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, int $startIndex, int $endIndex) : void + { + for ($i = $endIndex; $i > $startIndex; --$i) { + $previousInterfaceImplementingIndex = $tokens->getPrevTokenOfKind($i, [',', [\T_IMPLEMENTS], [\T_EXTENDS]]); + $breakAtIndex = $tokens->getNextMeaningfulToken($previousInterfaceImplementingIndex); + // make the part of a ',' or 'implements' single line + $this->makeClassyDefinitionSingleLine($tokens, $breakAtIndex, $i); + // make sure the part is on its own line + $isOnOwnLine = \false; + for ($j = $breakAtIndex; $j > $previousInterfaceImplementingIndex; --$j) { + if (\strpos($tokens[$j]->getContent(), "\n") !== \false) { + $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; + } + } + /** + * @param array{ + * final: false|int, + * abstract: false|int, + * readonly: false|int, + * } $classDefInfo + */ + private function sortClassModifiers(Tokens $tokens, array $classDefInfo) : void + { + if (\false === $classDefInfo['readonly']) { + return; + } + $readonlyIndex = $classDefInfo['readonly']; + foreach (['final', 'abstract'] as $accessModifier) { + if (\false === $classDefInfo[$accessModifier] || $classDefInfo[$accessModifier] < $readonlyIndex) { + continue; + } + $accessModifierIndex = $classDefInfo[$accessModifier]; + /** @var Token $readonlyToken */ + $readonlyToken = clone $tokens[$readonlyIndex]; + /** @var Token $accessToken */ + $accessToken = clone $tokens[$accessModifierIndex]; + $tokens[$readonlyIndex] = $accessToken; + $tokens[$accessModifierIndex] = $readonlyToken; + break; + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php new file mode 100644 index 00000000000..04b15d27c00 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalClassFixer.php @@ -0,0 +1,45 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @author Filippo Tessarotto + */ +final class FinalClassFixer extends AbstractProxyFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All classes must be final, except abstract ones and Doctrine entities.', [new CodeSample('configure(['include' => [], 'consider_absent_docblock_as_internal_class' => \true]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php new file mode 100644 index 00000000000..97c092a5f05 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalInternalClassFixer.php @@ -0,0 +1,229 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * @author Dariusz Rumiński + */ +final class FinalInternalClassFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const DEFAULTS = ['include' => ['internal'], 'exclude' => ['final', 'Entity', 'ORM\Entity', 'ORM\Mapping\Entity', 'Mapping\Entity', 'Document', 'ODM\Document']]; + /** + * @var bool + */ + private $checkAttributes; + public function __construct() + { + parent::__construct(); + $this->checkAttributes = \PHP_VERSION_ID >= 80000; + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->assertConfigHasNoConflicts(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Internal classes should be `final`.', [new CodeSample(" ['@Custom'], 'exclude' => ['@not-fix']])], null, 'Changing classes to `final` might cause code execution to break.'); + } + /** + * {@inheritdoc} + * + * Must run before ProtectedToPrivateFixer, SelfStaticAccessorFixer. + * Must run after PhpUnitInternalClassFixer. + */ + public function getPriority() : int + { + return 67; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_CLASS); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->isClassCandidate($tokensAnalyzer, $tokens, $index)) { + continue; + } + // make class 'final' + $tokens->insertSlices([$index => [new Token([\T_FINAL, 'final']), new Token([\T_WHITESPACE, ' '])]]); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $annotationsAsserts = [static function (array $values) : bool { + foreach ($values as $value) { + if (!\is_string($value) || '' === $value) { + return \false; + } + } + return \true; + }]; + $annotationsNormalizer = static function (Options $options, array $value) : array { + $newValue = []; + foreach ($value as $key) { + if (\strncmp($key, '@', \strlen('@')) === 0) { + $key = \substr($key, 1); + } + $newValue[\strtolower($key)] = \true; + } + return $newValue; + }; + return new FixerConfigurationResolver([(new FixerOptionBuilder('annotation_include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).'))->setAllowedTypes(['array'])->setAllowedValues($annotationsAsserts)->setDefault(\array_map(static function (string $string) { + return '@' . $string; + }, self::DEFAULTS['include']))->setNormalizer($annotationsNormalizer)->setDeprecationMessage('Use `include` to configure PHPDoc annotations tags and attributes.')->getOption(), (new FixerOptionBuilder('annotation_exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).'))->setAllowedTypes(['array'])->setAllowedValues($annotationsAsserts)->setDefault(\array_map(static function (string $string) { + return '@' . $string; + }, self::DEFAULTS['exclude']))->setNormalizer($annotationsNormalizer)->setDeprecationMessage('Use `exclude` to configure PHPDoc annotations tags and attributes.')->getOption(), (new FixerOptionBuilder('include', 'Class level attribute or annotation tags that must be set in order to fix the class (case insensitive).'))->setAllowedTypes(['array'])->setAllowedValues($annotationsAsserts)->setDefault(self::DEFAULTS['include'])->setNormalizer($annotationsNormalizer)->getOption(), (new FixerOptionBuilder('exclude', 'Class level attribute or annotation tags that must be omitted to fix the class, even if all of the white list ones are used as well (case insensitive).'))->setAllowedTypes(['array'])->setAllowedValues($annotationsAsserts)->setDefault(self::DEFAULTS['exclude'])->setNormalizer($annotationsNormalizer)->getOption(), (new FixerOptionBuilder('consider_absent_docblock_as_internal_class', 'Whether classes without any DocBlock should be fixed to final.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * @param int $index T_CLASS index + */ + private function isClassCandidate(TokensAnalyzer $tokensAnalyzer, Tokens $tokens, int $index) : bool + { + if ($tokensAnalyzer->isAnonymousClass($index)) { + return \false; + } + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + if (isset($modifiers['final']) || isset($modifiers['abstract'])) { + return \false; + // ignore class; it is abstract or already final + } + $decisions = []; + $currentIndex = $index; + $acceptTypes = [CT::T_ATTRIBUTE_CLOSE, \T_DOC_COMMENT, \T_COMMENT]; + if (\defined('T_READONLY')) { + // Skip readonly classes for PHP 8.2+ + $acceptTypes[] = \T_READONLY; + } + while ($currentIndex) { + $currentIndex = $tokens->getPrevNonWhitespace($currentIndex); + if (!$tokens[$currentIndex]->isGivenKind($acceptTypes)) { + break; + } + if ($this->checkAttributes && $tokens[$currentIndex]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $attributeStartIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $currentIndex); + $decisions[] = $this->isClassCandidateBasedOnAttribute($tokens, $attributeStartIndex, $currentIndex); + $currentIndex = $attributeStartIndex; + } + if ($tokens[$currentIndex]->isGivenKind([\T_DOC_COMMENT])) { + $decisions[] = $this->isClassCandidateBasedOnPhpDoc($tokens, $currentIndex); + } + } + if (\in_array(\false, $decisions, \true)) { + return \false; + } + return \in_array(\true, $decisions, \true) || [] === $decisions && $this->configuration['consider_absent_docblock_as_internal_class']; + } + private function isClassCandidateBasedOnPhpDoc(Tokens $tokens, int $index) : ?bool + { + $doc = new DocBlock($tokens[$index]->getContent()); + $tags = []; + foreach ($doc->getAnnotations() as $annotation) { + if (!Preg::match('/@\\S+(?=\\s|$)/', $annotation->getContent(), $matches)) { + continue; + } + $tag = \strtolower(\substr(\array_shift($matches), 1)); + $tags[$tag] = \true; + } + if (\count(\array_intersect_key($this->configuration['exclude'], $tags)) > 0) { + return \false; + } + if ($this->isConfiguredAsInclude($tags)) { + return \true; + } + return null; + } + private function isClassCandidateBasedOnAttribute(Tokens $tokens, int $startIndex, int $endIndex) : ?bool + { + $attributeCandidates = []; + $attributeString = ''; + $currentIndex = $startIndex; + while ($currentIndex < $endIndex && ($currentIndex = $tokens->getNextMeaningfulToken($currentIndex))) { + if (!$tokens[$currentIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + if ('' !== $attributeString) { + $attributeCandidates[$attributeString] = \true; + $attributeString = ''; + } + continue; + } + $attributeString .= \strtolower($tokens[$currentIndex]->getContent()); + } + if (\count(\array_intersect_key($this->configuration['exclude'], $attributeCandidates)) > 0) { + return \false; + } + if ($this->isConfiguredAsInclude($attributeCandidates)) { + return \true; + } + return null; + } + /** + * @param array $attributes + */ + private function isConfiguredAsInclude(array $attributes) : bool + { + if (0 === \count($this->configuration['include'])) { + return \true; + } + return \count(\array_intersect_key($this->configuration['include'], $attributes)) > 0; + } + private function assertConfigHasNoConflicts() : void + { + foreach (['include', 'exclude'] as $newConfigKey) { + $oldConfigKey = 'annotation_' . $newConfigKey; + $defaults = []; + foreach (self::DEFAULTS[$newConfigKey] as $foo) { + $defaults[\strtolower($foo)] = \true; + } + $newConfigIsSet = $this->configuration[$newConfigKey] !== $defaults; + $oldConfigIsSet = $this->configuration[$oldConfigKey] !== $defaults; + if ($newConfigIsSet && $oldConfigIsSet) { + throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Configuration cannot contain deprecated option "%s" and new option "%s".', $oldConfigKey, $newConfigKey)); + } + if ($oldConfigIsSet) { + $this->configuration[$newConfigKey] = $this->configuration[$oldConfigKey]; + $this->checkAttributes = \false; + // run in old mode + } + // if ($newConfigIsSet) - only new config is set, all good + // if (!$newConfigIsSet && !$oldConfigIsSet) - both are set as to default values, all good + unset($this->configuration[$oldConfigKey]); + } + $intersect = \array_intersect_assoc($this->configuration['include'], $this->configuration['exclude']); + if (\count($intersect) > 0) { + throw new InvalidFixerConfigurationException($this->getName(), \sprintf('Annotation cannot be used in both "include" and "exclude" list, got duplicates: %s.', Utils::naturalLanguageJoin(\array_keys($intersect)))); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php new file mode 100644 index 00000000000..7c943a79dd4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/FinalPublicMethodForAbstractClassFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class FinalPublicMethodForAbstractClassFixer extends AbstractFixer +{ + /** + * @var array + */ + 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() : FixerDefinitionInterface + { + return new FixerDefinition('All `public` methods of `abstract` classes should be `final`.', [new CodeSample('isAllTokenKindsFound([\T_ABSTRACT, \T_PUBLIC, \T_FUNCTION]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $abstracts = \array_keys($tokens->findGivenKind(\T_ABSTRACT)); + while ($abstractIndex = \array_pop($abstracts)) { + $classIndex = $tokens->getNextTokenOfKind($abstractIndex, [[\T_CLASS], [\T_FUNCTION]]); + if (!$tokens[$classIndex]->isGivenKind(\T_CLASS)) { + continue; + } + $classOpen = $tokens->getNextTokenOfKind($classIndex, ['{']); + $classClose = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpen); + $this->fixClass($tokens, $classOpen, $classClose); + } + } + private function fixClass(Tokens $tokens, int $classOpenIndex, int $classCloseIndex) : void + { + for ($index = $classCloseIndex - 1; $index > $classOpenIndex; --$index) { + // skip method contents + if ($tokens[$index]->equals('}')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + continue; + } + // skip non public methods + 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]; + } + // skip uses, attributes, constants etc + if (!$nextToken->isGivenKind(\T_FUNCTION)) { + continue; + } + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + $nextToken = $tokens[$nextIndex]; + // skip magic methods + 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]; + } + // skip abstract or already final methods + if ($prevToken->isGivenKind([\T_ABSTRACT, \T_FINAL])) { + $index = $prevIndex; + continue; + } + $tokens->insertAt($index, [new Token([\T_FINAL, 'final']), new Token([\T_WHITESPACE, ' '])]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php new file mode 100644 index 00000000000..db4c69e79e3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoBlankLinesAfterClassOpeningFixer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Ceeram + */ +final class NoBlankLinesAfterClassOpeningFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should be no empty lines after class opening brace.', [new CodeSample(' $token) { + if (!$token->isClassy()) { + continue; + } + $startBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + if (!$tokens[$startBraceIndex + 1]->isWhitespace()) { + continue; + } + $this->fixWhitespace($tokens, $startBraceIndex + 1); + } + } + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index) : void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (\substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + $tokens[$index] = new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding() . \substr($content, \strrpos($content, "\n") + 1)]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php new file mode 100644 index 00000000000..6e16c179f60 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoNullPropertyInitializationFixer.php @@ -0,0 +1,104 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author ntzm + */ +final class NoNullPropertyInitializationFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Properties MUST not be explicitly initialized with `null` except when they have a type declaration (PHP 7.4).', [new CodeSample('isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]) && $tokens->isAnyTokenKindsFound([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $inClass = []; + $classLevel = 0; + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { + // Enums and interfaces do not have properties + ++$classLevel; + $inClass[$classLevel] = 1; + $index = $tokens->getNextTokenOfKind($index, ['{']); + continue; + } + if (0 === $classLevel) { + continue; + } + if ($tokens[$index]->equals('{')) { + ++$inClass[$classLevel]; + continue; + } + if ($tokens[$index]->equals('}')) { + --$inClass[$classLevel]; + if (0 === $inClass[$classLevel]) { + unset($inClass[$classLevel]); + --$classLevel; + } + continue; + } + // Ensure we are in a class but not in a method in case there are static variables defined + if (1 !== $inClass[$classLevel]) { + continue; + } + if (!$tokens[$index]->isGivenKind([\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_VAR, \T_STATIC])) { + continue; + } + while (\true) { + $varTokenIndex = $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->isGivenKind(\T_STATIC)) { + $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() && \strpos($tokens[$i]->getContent(), "\n") !== \false) && !$tokens[$i]->isComment()) { + $tokens->clearAt($i); + } + } + } + ++$index; + } + if (!$tokens[$index]->equals(',')) { + break; + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php new file mode 100644 index 00000000000..75773be7c85 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoPhp4ConstructorFixer.php @@ -0,0 +1,305 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Matteo Beccati + */ +final class NoPhp4ConstructorFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Convert PHP4-style constructors to `__construct`.', [new CodeSample('isTokenKindFound(\T_CLASS); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $classes = \array_keys($tokens->findGivenKind(\T_CLASS)); + $numClasses = \count($classes); + for ($i = 0; $i < $numClasses; ++$i) { + $index = $classes[$i]; + // is it an anonymous class definition? + if ($tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + // is it inside a namespace? + $nspIndex = $tokens->getPrevTokenOfKind($index, [[\T_NAMESPACE, 'namespace']]); + if (null !== $nspIndex) { + $nspIndex = $tokens->getNextMeaningfulToken($nspIndex); + // make sure it's not the global namespace, as PHP4 constructors are allowed in there + if (!$tokens[$nspIndex]->equals('{')) { + // unless it's the global namespace, the index currently points to the name + $nspIndex = $tokens->getNextTokenOfKind($nspIndex, [';', '{']); + if ($tokens[$nspIndex]->equals(';')) { + // the class is inside a (non-block) namespace, no PHP4-code should be in there + break; + } + // the index points to the { of a block-namespace + $nspEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nspIndex); + if ($index < $nspEnd) { + // the class is inside a block namespace, skip other classes that might be in it + for ($j = $i + 1; $j < $numClasses; ++$j) { + if ($classes[$j] < $nspEnd) { + ++$i; + } + } + // and continue checking the classes that might follow + 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); + } + } + /** + * Fix constructor within a class, if possible. + * + * @param Tokens $tokens the Tokens instance + * @param string $className the class name + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixConstructor(Tokens $tokens, string $className, int $classStart, int $classEnd) : void + { + $php4 = $this->findFunction($tokens, $className, $classStart, $classEnd); + if (null === $php4) { + return; + // no PHP4-constructor! + } + if (isset($php4['modifiers'][\T_ABSTRACT]) || isset($php4['modifiers'][\T_STATIC])) { + return; + // PHP4 constructor can't be abstract or static + } + $php5 = $this->findFunction($tokens, '__construct', $classStart, $classEnd); + if (null === $php5) { + // no PHP5-constructor, we can rename the old one to __construct + $tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']); + // in some (rare) cases we might have just created an infinite recursion issue + $this->fixInfiniteRecursion($tokens, $php4['bodyIndex'], $php4['endIndex']); + return; + } + // does the PHP4-constructor only call $this->__construct($args, ...)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, '__construct', $php4['startIndex'], $php4['bodyIndex']); + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php4['bodyIndex'] - 1, $php4['endIndex'], $case)) { + // good, delete it! + for ($i = $php4['startIndex']; $i <= $php4['endIndex']; ++$i) { + $tokens->clearAt($i); + } + return; + } + } + // does __construct only call the PHP4-constructor (with the same args)? + [$sequences, $case] = $this->getWrapperMethodSequence($tokens, $className, $php4['startIndex'], $php4['bodyIndex']); + foreach ($sequences as $seq) { + if (null !== $tokens->findSequence($seq, $php5['bodyIndex'] - 1, $php5['endIndex'], $case)) { + // that was a weird choice, but we can safely delete it and... + for ($i = $php5['startIndex']; $i <= $php5['endIndex']; ++$i) { + $tokens->clearAt($i); + } + // rename the PHP4 one to __construct + $tokens[$php4['nameIndex']] = new Token([\T_STRING, '__construct']); + return; + } + } + } + /** + * Fix calls to the parent constructor within a class. + * + * @param Tokens $tokens the Tokens instance + * @param int $classStart the class start index + * @param int $classEnd the class end index + */ + private function fixParent(Tokens $tokens, int $classStart, int $classEnd) : void + { + // check calls to the parent constructor + foreach ($tokens->findGivenKind(\T_EXTENDS) as $index => $token) { + $parentIndex = $tokens->getNextMeaningfulToken($index); + $parentClass = $tokens[$parentIndex]->getContent(); + // using parent::ParentClassName() or ParentClassName::ParentClassName() + $parentSeq = $tokens->findSequence([[\T_STRING], [\T_DOUBLE_COLON], [\T_STRING, $parentClass], '('], $classStart, $classEnd, [2 => \false]); + if (null !== $parentSeq) { + // we only need indices + $parentSeq = \array_keys($parentSeq); + // match either of the possibilities + if ($tokens[$parentSeq[0]]->equalsAny([[\T_STRING, 'parent'], [\T_STRING, $parentClass]], \false)) { + // replace with parent::__construct + $tokens[$parentSeq[0]] = new Token([\T_STRING, 'parent']); + $tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']); + } + } + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // using $this->ParentClassName() + $parentSeq = $tokens->findSequence([[\T_VARIABLE, '$this'], [$objectOperatorKind], [\T_STRING, $parentClass], '('], $classStart, $classEnd, [2 => \false]); + if (null !== $parentSeq) { + // we only need indices + $parentSeq = \array_keys($parentSeq); + // replace call with parent::__construct() + $tokens[$parentSeq[0]] = new Token([\T_STRING, 'parent']); + $tokens[$parentSeq[1]] = new Token([\T_DOUBLE_COLON, '::']); + $tokens[$parentSeq[2]] = new Token([\T_STRING, '__construct']); + } + } + } + } + /** + * Fix a particular infinite recursion issue happening when the parent class has __construct and the child has only + * a PHP4 constructor that calls the parent constructor as $this->__construct(). + * + * @param Tokens $tokens the Tokens instance + * @param int $start the PHP4 constructor body start + * @param int $end the PHP4 constructor body end + */ + private function fixInfiniteRecursion(Tokens $tokens, int $start, int $end) : void + { + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + $seq = [[\T_VARIABLE, '$this'], [$objectOperatorKind], [\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, '::']); + } + } + } + /** + * Generate the sequence of tokens necessary for the body of a wrapper method that simply + * calls $this->{$method}( [args...] ) with the same arguments as its own signature. + * + * @param Tokens $tokens the Tokens instance + * @param string $method the wrapped method name + * @param int $startIndex function/method start index + * @param int $bodyIndex function/method body index + * + * @return array an array containing the sequence and case sensitiveness [ 0 => $seq, 1 => $case ] + */ + private function getWrapperMethodSequence(Tokens $tokens, string $method, int $startIndex, int $bodyIndex) : array + { + $sequences = []; + foreach (Token::getObjectOperatorKinds() as $objectOperatorKind) { + // initialise sequence as { $this->{$method}( + $seq = ['{', [\T_VARIABLE, '$this'], [$objectOperatorKind], [\T_STRING, $method], '(']; + // parse method parameters, if any + $index = $startIndex; + while (\true) { + // find the next variable name + $index = $tokens->getNextTokenOfKind($index, [[\T_VARIABLE]]); + if (null === $index || $index >= $bodyIndex) { + // we've reached the body already + break; + } + // append a comma if it's not the first variable + if (\count($seq) > 5) { + $seq[] = ','; + } + // append variable name to the sequence + $seq[] = [\T_VARIABLE, $tokens[$index]->getContent()]; + } + // almost done, close the sequence with ); } + $seq[] = ')'; + $seq[] = ';'; + $seq[] = '}'; + $sequences[] = $seq; + } + return [$sequences, [3 => \false]]; + } + /** + * Find a function or method matching a given name within certain bounds. + * + * Returns: + * - nameIndex (int): The index of the function/method name. + * - startIndex (int): The index of the function/method start. + * - endIndex (int): The index of the function/method end. + * - bodyIndex (int): The index of the function/method body. + * - modifiers (array): The modifiers as array keys and their index as the values, e.g. array(T_PUBLIC => 10) + * + * @param Tokens $tokens the Tokens instance + * @param string $name the function/Method name + * @param int $startIndex the search start index + * @param int $endIndex the search end index + * + * @return null|array{ + * nameIndex: int, + * startIndex: int, + * endIndex: int, + * bodyIndex: int, + * modifiers: list, + * } + */ + private function findFunction(Tokens $tokens, string $name, int $startIndex, int $endIndex) : ?array + { + $function = $tokens->findSequence([[\T_FUNCTION], [\T_STRING, $name], '('], $startIndex, $endIndex, \false); + if (null === $function) { + return null; + } + // keep only the indices + $function = \array_keys($function); + // find previous block, saving method modifiers for later use + $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])) { + // abstract methods have no body + $bodyStart = null; + $funcEnd = $tokens->getNextTokenOfKind($function[2], [';']); + } else { + // find method body start and the end of the function definition + $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]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php new file mode 100644 index 00000000000..52ec231b3a9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/NoUnneededFinalMethodFixer.php @@ -0,0 +1,148 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Filippo Tessarotto + */ +final class NoUnneededFinalMethodFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes `final` from methods where possible.', [new CodeSample(' \false])], null, 'Risky when child class overrides a `private` method.'); + } + public function isCandidate(Tokens $tokens) : bool + { + if (!$tokens->isAllTokenKindsFound([\T_FINAL, \T_FUNCTION])) { + return \false; + } + if (\defined('T_ENUM') && $tokens->isTokenKindFound(\T_ENUM)) { + // @TODO: drop condition when PHP 8.1+ is required + return \true; + } + return $tokens->isTokenKindFound(\T_CLASS); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($this->getMethods($tokens) as $element) { + $index = $element['method_final_index']; + if ($element['method_of_enum'] || $element['class_is_final']) { + $this->clearFinal($tokens, $index); + continue; + } + if (!$element['method_is_private'] || \false === $this->configuration['private_methods'] || $element['method_is_constructor']) { + continue; + } + $this->clearFinal($tokens, $index); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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 getMethods(Tokens $tokens) : \Generator + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifierKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_STATIC]; + $enums = []; + $classesAreFinal = []; + $elements = $tokensAnalyzer->getClassyElements(); + for (\end($elements);; \prev($elements)) { + $index = \key($elements); + if (null === $index) { + break; + } + $element = \current($elements); + if ('method' !== $element['type']) { + continue; + // not a method + } + $classIndex = $element['classIndex']; + if (!\array_key_exists($classIndex, $enums)) { + $enums[$classIndex] = \defined('T_ENUM') && $tokens[$classIndex]->isGivenKind(\T_ENUM); + // @TODO: drop condition when PHP 8.1+ is required + } + $element['method_final_index'] = null; + $element['method_is_private'] = \false; + $previous = $index; + do { + $previous = $tokens->getPrevMeaningfulToken($previous); + if ($tokens[$previous]->isGivenKind(\T_PRIVATE)) { + $element['method_is_private'] = \true; + } elseif ($tokens[$previous]->isGivenKind(\T_FINAL)) { + $element['method_final_index'] = $previous; + } + } while ($tokens[$previous]->isGivenKind($modifierKinds)); + if ($enums[$classIndex]) { + $element['method_of_enum'] = \true; + (yield $element); + continue; + } + if (!\array_key_exists($classIndex, $classesAreFinal)) { + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + $classesAreFinal[$classIndex] = isset($modifiers['final']); + } + $element['method_of_enum'] = \false; + $element['class_is_final'] = $classesAreFinal[$classIndex]; + $element['method_is_constructor'] = '__construct' === \strtolower($tokens[$tokens->getNextMeaningfulToken($index)]->getContent()); + (yield $element); + } + } + private function clearFinal(Tokens $tokens, ?int $index) : void + { + if (null === $index) { + return; + } + $tokens->clearAt($index); + ++$index; + if ($tokens[$index]->isWhitespace()) { + $tokens->clearAt($index); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php new file mode 100644 index 00000000000..ef7a907d742 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedClassElementsFixer.php @@ -0,0 +1,407 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class OrderedClassElementsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const SORT_ALPHA = 'alpha'; + /** @internal */ + public const SORT_NONE = 'none'; + private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_NONE, self::SORT_ALPHA]; + /** + * @var array> Array containing all class element base types (keys) and their parent types (values) + */ + private static $typeHierarchy = ['use_trait' => null, 'public' => null, 'protected' => null, 'private' => null, 'case' => ['public'], '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_readonly' => ['property_readonly', 'property_public'], 'property_protected_readonly' => ['property_readonly', 'property_protected'], 'property_private_readonly' => ['property_readonly', '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_private_abstract' => ['method_abstract', 'method_private'], 'method_public_abstract_static' => ['method_abstract', 'method_static', 'method_public'], 'method_protected_abstract_static' => ['method_abstract', 'method_static', 'method_protected'], 'method_private_abstract_static' => ['method_abstract', 'method_static', 'method_private'], 'method_public_static' => ['method_static', 'method_public'], 'method_protected_static' => ['method_static', 'method_protected'], 'method_private_static' => ['method_static', 'method_private']]; + /** + * @var array Array containing special method types + */ + private static $specialTypes = ['construct' => null, 'destruct' => null, 'magic' => null, 'phpunit' => null]; + /** + * @var array Resolved configuration array (type => position) + */ + private $typePosition; + public function configure(array $configuration) : void + { + 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; + // last digit is used by phpunit method ordering + } + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Orders the elements of classes/interfaces/traits/enums.', [new CodeSample(' ['method_private', 'method_public']]), new CodeSample(' ['method_public'], 'sort_algorithm' => self::SORT_ALPHA]), new CodeSample(' ['method_public'], 'sort_algorithm' => self::SORT_ALPHA, 'case_sensitive' => \true])], 'Accepts a subset of pre-defined element types, special element groups, and custom patterns. + +Element types: `[\'' . \implode('\', \'', \array_keys(self::$typeHierarchy)) . '\']` + +Special element types: `[\'' . \implode('\', \'', \array_keys(self::$specialTypes)) . '\']` + +Custom values: + +- `method:*`: specify a single method name (e.g. `method:__invoke`) to set the order of that specific method.'); + } + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer, NoBlankLinesAfterClassOpeningFixer, SpaceAfterSemicolonFixer. + * Must run after NoPhp4ConstructorFixer, ProtectedToPrivateFixer. + */ + public function getPriority() : int + { + return 65; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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() : FixerConfigurationResolverInterface + { + $builtIns = \array_keys(\array_merge(self::$typeHierarchy, self::$specialTypes)); + return new FixerConfigurationResolver([(new FixerOptionBuilder('order', 'List of strings defining order of elements.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $values) use($builtIns) : bool { + foreach ($values as $value) { + if (\in_array($value, $builtIns, \true)) { + return \true; + } + if (\is_string($value) && 'method:' === \substr($value, 0, 7)) { + return \true; + } + } + return \false; + }])->setDefault(['use_trait', 'case', 'constant_public', 'constant_protected', 'constant_private', 'property_public', 'property_protected', 'property_private', 'construct', 'destruct', 'magic', 'phpunit', 'method_public', 'method_protected', 'method_private'])->getOption(), (new FixerOptionBuilder('sort_algorithm', 'How multiple occurrences of same type statements should be sorted.'))->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)->setDefault(self::SORT_NONE)->getOption(), (new FixerOptionBuilder('case_sensitive', 'Whether the sorting should be case sensitive.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * @return list + */ + private function getElements(Tokens $tokens, int $startIndex) : array + { + static $elementTokenKinds = [CT::T_USE_TRAIT, \T_CASE, \T_CONST, \T_VARIABLE, \T_FUNCTION]; + ++$startIndex; + $elements = []; + while (\true) { + $element = ['start' => $startIndex, 'visibility' => 'public', 'abstract' => \false, 'static' => \false, 'readonly' => \false]; + for ($i = $startIndex;; ++$i) { + $token = $tokens[$i]; + // class end + if ($token->equals('}')) { + return $elements; + } + if ($token->isGivenKind(\T_ABSTRACT)) { + $element['abstract'] = \true; + continue; + } + if ($token->isGivenKind(\T_STATIC)) { + $element['static'] = \true; + continue; + } + if (\defined('T_READONLY') && $token->isGivenKind(\T_READONLY)) { + // @TODO: drop condition when PHP 8.1+ is required + $element['readonly'] = \true; + } + 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', 'case', '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; + } + } + /** + * @return array|string type or array of type and name + */ + private function detectElementType(Tokens $tokens, int $index) + { + $token = $tokens[$index]; + if ($token->isGivenKind(CT::T_USE_TRAIT)) { + return 'use_trait'; + } + if ($token->isGivenKind(\T_CASE)) { + return 'case'; + } + 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, 'assertPreConditions'], [\T_STRING, 'assertPostConditions'], [\T_STRING, 'tearDown'], [\T_STRING, 'doTearDown']], \false)) { + return ['phpunit', \strtolower($nameToken->getContent())]; + } + return \strncmp($nameToken->getContent(), '__', \strlen('__')) === 0 ? 'magic' : 'method'; + } + private function findElementEnd(Tokens $tokens, int $index) : int + { + $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; + } + /** + * @return list + */ + private function sortElements(array $elements) : array + { + static $phpunitPositions = ['setupbeforeclass' => 1, 'dosetupbeforeclass' => 2, 'teardownafterclass' => 3, 'doteardownafterclass' => 4, 'setup' => 5, 'dosetup' => 6, 'assertpreconditions' => 7, 'assertpostconditions' => 8, 'teardown' => 9, 'doteardown' => 10]; + foreach ($elements as &$element) { + $type = $element['type']; + if (\in_array($type, ['method', 'magic', 'phpunit'], \true) && isset($this->typePosition["method:{$element['name']}"])) { + $element['position'] = $this->typePosition["method:{$element['name']}"]; + continue; + } + 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'; + } + if ($element['readonly']) { + $type .= '_readonly'; + } + } + $element['position'] = $this->typePosition[$type]; + } + unset($element); + \usort($elements, function (array $a, array $b) : int { + if ($a['position'] === $b['position']) { + return $this->sortGroupElements($a, $b); + } + return $a['position'] <=> $b['position']; + }); + return $elements; + } + /** + * @param array{ + * start: int, + * visibility: string, + * abstract: bool, + * static: bool, + * readonly: bool, + * type: string, + * name: string, + * end: int, + * position: int, + * } $a + * @param array{ + * start: int, + * visibility: string, + * abstract: bool, + * static: bool, + * readonly: bool, + * type: string, + * name: string, + * end: int, + * position: int, + * } $b + */ + private function sortGroupElements(array $a, array $b) : int + { + $selectedSortAlgorithm = $this->configuration['sort_algorithm']; + if (self::SORT_ALPHA === $selectedSortAlgorithm) { + return $this->configuration['case_sensitive'] ? \strcmp($a['name'], $b['name']) : \strcasecmp($a['name'], $b['name']); + } + return $a['start'] <=> $b['start']; + } + /** + * @param list $elements + */ + private function sortTokens(Tokens $tokens, int $startIndex, int $endIndex, array $elements) : void + { + $replaceTokens = []; + foreach ($elements as $element) { + for ($i = $element['start']; $i <= $element['end']; ++$i) { + $replaceTokens[] = clone $tokens[$i]; + } + } + $tokens->overrideRange($startIndex + 1, $endIndex, $replaceTokens); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php new file mode 100644 index 00000000000..86c54c06e0d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedInterfacesFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dave van der Brugge + */ +final class OrderedInterfacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const OPTION_DIRECTION = 'direction'; + /** @internal */ + public const OPTION_ORDER = 'order'; + /** @internal */ + public const DIRECTION_ASCEND = 'ascend'; + /** @internal */ + public const DIRECTION_DESCEND = 'descend'; + /** @internal */ + public const ORDER_ALPHA = 'alpha'; + /** @internal */ + public const ORDER_LENGTH = 'length'; + /** + * Array of supported directions in configuration. + * + * @var string[] + */ + private const SUPPORTED_DIRECTION_OPTIONS = [self::DIRECTION_ASCEND, self::DIRECTION_DESCEND]; + /** + * Array of supported orders in configuration. + * + * @var string[] + */ + private const SUPPORTED_ORDER_OPTIONS = [self::ORDER_ALPHA, self::ORDER_LENGTH]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Orders the interfaces in an `implements` or `interface extends` clause.', [new CodeSample(" self::DIRECTION_DESCEND]), new CodeSample(" self::ORDER_LENGTH]), new CodeSample(" self::ORDER_LENGTH, self::OPTION_DIRECTION => self::DIRECTION_DESCEND])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_IMPLEMENTS) || $tokens->isAllTokenKindsFound([\T_INTERFACE, \T_EXTENDS]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + } + } + $implementsStart = $index + 1; + $implementsEnd = $tokens->getPrevNonWhitespace($tokens->getNextTokenOfKind($implementsStart, ['{'])); + $interfaces = $this->getInterfaces($tokens, $implementsStart, $implementsEnd); + if (1 === \count($interfaces)) { + continue; + } + foreach ($interfaces as $interfaceIndex => $interface) { + $interfaceTokens = Tokens::fromArray($interface, \false); + $normalized = ''; + $actualInterfaceIndex = $interfaceTokens->getNextMeaningfulToken(-1); + while ($interfaceTokens->offsetExists($actualInterfaceIndex)) { + $token = $interfaceTokens[$actualInterfaceIndex]; + if ($token->isComment() || $token->isWhitespace()) { + break; + } + $normalized .= \str_replace('\\', ' ', $token->getContent()); + ++$actualInterfaceIndex; + } + $interfaces[$interfaceIndex] = ['tokens' => $interface, 'normalized' => $normalized, 'originalIndex' => $interfaceIndex]; + } + \usort($interfaces, function (array $first, array $second) : int { + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder(self::OPTION_ORDER, 'How the interfaces should be ordered.'))->setAllowedValues(self::SUPPORTED_ORDER_OPTIONS)->setDefault(self::ORDER_ALPHA)->getOption(), (new FixerOptionBuilder(self::OPTION_DIRECTION, 'Which direction the interfaces should be ordered.'))->setAllowedValues(self::SUPPORTED_DIRECTION_OPTIONS)->setDefault(self::DIRECTION_ASCEND)->getOption()]); + } + /** + * @return array> + */ + private function getInterfaces(Tokens $tokens, int $implementsStart, int $implementsEnd) : array + { + $interfaces = []; + $interfaceIndex = 0; + for ($i = $implementsStart; $i <= $implementsEnd; ++$i) { + if ($tokens[$i]->equals(',')) { + ++$interfaceIndex; + $interfaces[$interfaceIndex] = []; + continue; + } + $interfaces[$interfaceIndex][] = $tokens[$i]; + } + return $interfaces; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php new file mode 100644 index 00000000000..93e298e4480 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTraitsFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +final class OrderedTraitsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Trait `use` statements must be sorted alphabetically.', [new CodeSample("isTokenKindFound(CT::T_USE_TRAIT); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($this->findUseStatementsGroups($tokens) as $uses) { + $this->sortUseStatements($tokens, $uses); + } + } + /** + * @return iterable> + */ + private function findUseStatementsGroups(Tokens $tokens) : iterable + { + $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; + } + $startIndex = $tokens->getNextNonWhitespace($tokens->getPrevMeaningfulToken($index)); + $endIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + if ($tokens[$endIndex]->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + } + $use = []; + for ($i = $startIndex; $i <= $endIndex; ++$i) { + $use[] = $tokens[$i]; + } + $uses[$startIndex] = Tokens::fromArray($use); + $index = $endIndex; + } + } + /** + * @param array $uses + */ + private function sortUseStatements(Tokens $tokens, array $uses) : void + { + foreach ($uses as $use) { + $this->sortMultipleTraitsInStatement($use); + } + $this->sort($tokens, $uses); + } + private function sortMultipleTraitsInStatement(Tokens $use) : void + { + $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); + } + /** + * @param array $elements + */ + private function sort(Tokens $tokens, array $elements) : void + { + $toTraitName = static function (Tokens $use) : string { + $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) : int { + 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); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php new file mode 100644 index 00000000000..aa80041bb8f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/OrderedTypesFixer.php @@ -0,0 +1,309 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author John Paul E. Balandan, CPA + */ +final class OrderedTypesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Sort union types and intersection types using configured order.', [new CodeSample('save($foo); +} catch (\\RuntimeException|CacheException $e) { + logger($e); + + throw $e; +} +'), new VersionSpecificCodeSample(' 'always_last']), new VersionSpecificCodeSample(' 'none', 'null_adjustment' => 'always_last'])]); + } + /** + * {@inheritdoc} + * + * Must run before TypesSpacesFixer. + * Must run after NullableTypeDeclarationFixer, NullableTypeDeclarationForDefaultNullValueFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('sort_algorithm', 'Whether the types should be sorted alphabetically, or not sorted.'))->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) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + foreach ($this->getElements($tokens) as $index => $type) { + if ('catch' === $type) { + $this->fixCatchArgumentType($tokens, $index); + continue; + } + if ('property' === $type) { + $this->fixPropertyType($tokens, $index); + continue; + } + $this->fixMethodArgumentType($functionsAnalyzer, $tokens, $index); + $this->fixMethodReturnType($functionsAnalyzer, $tokens, $index); + } + } + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens) : array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $elements = \array_map(static function (array $element) : string { + return $element['type']; + }, \array_filter($tokensAnalyzer->getClassyElements(), static function (array $element) : bool { + return \in_array($element['type'], ['method', 'property'], \true); + })); + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_CATCH)) { + $elements[$index] = 'catch'; + continue; + } + if ($token->isGivenKind(\T_FN) || $token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) { + $elements[$index] = 'method'; + } + } + return $elements; + } + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex) : ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + private function fixCatchArgumentType(Tokens $tokens, int $index) : void + { + $catchStart = $tokens->getNextTokenOfKind($index, ['(']); + $catchEnd = $tokens->getNextTokenOfKind($catchStart, [')', [\T_VARIABLE]]); + $catchArgumentType = $this->collectTypeAnalysis($tokens, $catchStart, $catchEnd); + if (null === $catchArgumentType || !$this->isTypeSortable($catchArgumentType)) { + return; + // nothing to fix + } + $this->sortTypes($catchArgumentType, $tokens); + } + private function fixPropertyType(Tokens $tokens, int $index) : void + { + $propertyIndex = $index; + $propertyModifiers = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR]; + if (\defined('T_READONLY')) { + $propertyModifiers[] = \T_READONLY; + // @TODO drop condition when PHP 8.1 is supported + } + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + if (null === $propertyType || !$this->isTypeSortable($propertyType)) { + return; + // nothing to fix + } + $this->sortTypes($propertyType, $tokens); + } + private function fixMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index) : void + { + foreach ($functionsAnalyzer->getFunctionArguments($tokens, $index) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + if (null === $argumentType || !$this->isTypeSortable($argumentType)) { + continue; + // nothing to fix + } + $this->sortTypes($argumentType, $tokens); + } + } + private function fixMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index) : void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + if (null === $returnType || !$this->isTypeSortable($returnType)) { + return; + // nothing to fix + } + $this->sortTypes($returnType, $tokens); + } + private function sortTypes(TypeAnalysis $typeAnalysis, Tokens $tokens) : void + { + $type = $typeAnalysis->getName(); + if (\strpos($type, '|') !== \false && \strpos($type, '&') !== \false) { + // a DNF type of the form (A&B)|C, available as of PHP 8.2 + [$originalTypes, $glue] = $this->collectDisjunctiveNormalFormTypes($type); + } else { + [$originalTypes, $glue] = $this->collectUnionOrIntersectionTypes($type); + } + // If the $types array is coming from a DNF type, then we have parts + // which are also array. If so, we sort those sub-types first before + // running the sorting algorithm to the entire $types array. + $sortedTypes = \array_map(function ($subType) { + if (\is_array($subType)) { + return $this->runTypesThroughSortingAlgorithm($subType); + } + return $subType; + }, $originalTypes); + $sortedTypes = $this->runTypesThroughSortingAlgorithm($sortedTypes); + if ($sortedTypes === $originalTypes) { + return; + } + $tokens->overrideRange($typeAnalysis->getStartIndex(), $typeAnalysis->getEndIndex(), $this->createTypeDeclarationTokens($sortedTypes, $glue)); + } + private function isTypeSortable(TypeAnalysis $type) : bool + { + return \strpos($type->getName(), '|') !== \false || \strpos($type->getName(), '&') !== \false; + } + /** + * @return array{0: array, 1: string} + */ + private function collectDisjunctiveNormalFormTypes(string $type) : array + { + $types = \array_map(static function ($subType) { + if (\strncmp($subType, '(', \strlen('(')) === 0) { + return \explode('&', \trim($subType, '()')); + } + return $subType; + }, \explode('|', $type)); + return [$types, '|']; + } + /** + * @return array{0: string[], 1: string} + */ + private function collectUnionOrIntersectionTypes(string $type) : array + { + $types = \explode('|', $type); + $glue = '|'; + if (1 === \count($types)) { + $types = \explode('&', $type); + $glue = '&'; + } + return [$types, $glue]; + } + /** + * @param array $types + * + * @return array + */ + private function runTypesThroughSortingAlgorithm(array $types) : array + { + $normalizeType = static function (string $type) : string { + return Preg::replace('/^\\\\?/', '', $type); + }; + \usort($types, function ($a, $b) use($normalizeType) : int { + if (\is_array($a)) { + $a = \implode('&', $a); + } + if (\is_array($b)) { + $b = \implode('&', $b); + } + $a = $normalizeType($a); + $b = $normalizeType($b); + $lowerCaseA = \strtolower($a); + $lowerCaseB = \strtolower($b); + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + if ('alpha' === $this->configuration['sort_algorithm']) { + return \strcasecmp($a, $b); + } + return 0; + }); + return $types; + } + /** + * @param array $types + * + * @return array + */ + private function createTypeDeclarationTokens(array $types, string $glue, bool $isDisjunctive = \false) : array + { + static $specialTypes = ['array' => [CT::T_ARRAY_TYPEHINT, 'array'], 'callable' => [\T_CALLABLE, 'callable'], 'static' => [\T_STATIC, 'static']]; + static $glues = ['|' => [CT::T_TYPE_ALTERNATION, '|'], '&' => [CT::T_TYPE_INTERSECTION, '&']]; + $count = \count($types); + $newTokens = []; + foreach ($types as $i => $type) { + if (\is_array($type)) { + $newTokens = \array_merge($newTokens, $this->createTypeDeclarationTokens($type, '&', \true)); + } elseif (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + foreach (\explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + if ($nsIndex > 0) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + $newTokens[] = new Token([\T_STRING, $value]); + } + } + if ($i <= $count - 2) { + $newTokens[] = new Token($glues[$glue]); + } + } + if ($isDisjunctive) { + \array_unshift($newTokens, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $newTokens[] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + return $newTokens; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php new file mode 100644 index 00000000000..57fcb7e6efc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/ProtectedToPrivateFixer.php @@ -0,0 +1,144 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Filippo Tessarotto + */ +final class ProtectedToPrivateFixer extends AbstractFixer +{ + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts `protected` variables and methods to `private` where possible.', [new CodeSample('isAllTokenKindsFound([\T_ENUM, \T_PROTECTED])) { + // @TODO: drop condition when PHP 8.1+ is required + return \true; + } + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_FINAL, \T_PROTECTED]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + $modifierKinds = [\T_PUBLIC, \T_PROTECTED, \T_PRIVATE, \T_FINAL, \T_ABSTRACT, \T_NS_SEPARATOR, \T_STRING, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, \T_STATIC, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = \T_READONLY; + } + $classesCandidate = []; + $classElementTypes = ['method' => \true, 'property' => \true, 'const' => \true]; + foreach ($this->tokensAnalyzer->getClassyElements() as $index => $element) { + $classIndex = $element['classIndex']; + if (!\array_key_exists($classIndex, $classesCandidate)) { + $classesCandidate[$classIndex] = $this->isClassCandidate($tokens, $classIndex); + } + if (\false === $classesCandidate[$classIndex]) { + continue; + } + if (!isset($classElementTypes[$element['type']])) { + continue; + } + $previous = $index; + $isProtected = \false; + $isFinal = \false; + do { + $previous = $tokens->getPrevMeaningfulToken($previous); + if ($tokens[$previous]->isGivenKind(\T_PROTECTED)) { + $isProtected = $previous; + } elseif ($tokens[$previous]->isGivenKind(\T_FINAL)) { + $isFinal = $previous; + } + } while ($tokens[$previous]->isGivenKind($modifierKinds)); + if (\false === $isProtected) { + continue; + } + if ($isFinal && 'const' === $element['type']) { + continue; + // Final constants cannot be private + } + $element['protected_index'] = $isProtected; + $tokens[$element['protected_index']] = new Token([\T_PRIVATE, 'private']); + } + } + /** + * Consider symbol as candidate for fixing if it's: + * - an Enum (PHP8.1+) + * - a class, which: + * - is not anonymous + * - is not final + * - does not use traits + * - does not extend other class. + */ + private function isClassCandidate(Tokens $tokens, int $classIndex) : bool + { + if (\defined('T_ENUM') && $tokens[$classIndex]->isGivenKind(\T_ENUM)) { + // @TODO: drop condition when PHP 8.1+ is required + return \true; + } + if (!$tokens[$classIndex]->isGivenKind(\T_CLASS) || $this->tokensAnalyzer->isAnonymousClass($classIndex)) { + return \false; + } + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classIndex); + if (!isset($modifiers['final'])) { + return \false; + } + $classNameIndex = $tokens->getNextMeaningfulToken($classIndex); + // move to class name as anonymous class is never "final" + $classExtendsIndex = $tokens->getNextMeaningfulToken($classNameIndex); + // move to possible "extends" + if ($tokens[$classExtendsIndex]->isGivenKind(\T_EXTENDS)) { + return \false; + } + if (!$tokens->isTokenKindFound(CT::T_USE_TRAIT)) { + return \true; + // cheap test + } + $classOpenIndex = $tokens->getNextTokenOfKind($classNameIndex, ['{']); + $classCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + return null === $useIndex || $useIndex > $classCloseIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php new file mode 100644 index 00000000000..8b55d2a5d96 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfAccessorFixer.php @@ -0,0 +1,143 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gregor Harlan + */ +final class SelfAccessorFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Inside class or interface element `self` should be preferred to the class name itself.', [new CodeSample('isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]); + } + /** + * {@inheritdoc} + * + * Must run after PsrAutoloadingFixer. + */ + public function getPriority() : int + { + return -11; + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + foreach ($tokens->getNamespaceDeclarations() 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; + } + } + } + /** + * Replace occurrences of the name of the classy element by "self" (if possible). + */ + private function replaceNameOccurrences(Tokens $tokens, string $namespace, string $name, int $startIndex, int $endIndex) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $insideMethodSignatureUntil = null; + for ($i = $startIndex; $i < $endIndex; ++$i) { + if ($i === $insideMethodSignatureUntil) { + $insideMethodSignatureUntil = null; + } + $token = $tokens[$i]; + // skip anonymous classes + 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_STRING) || $prevToken->isObjectOperator()) { + continue; + } + if ($prevToken->isGivenKind([\T_INSTANCEOF, \T_NEW]) || $nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM) || null !== $insideMethodSignatureUntil && $i < $insideMethodSignatureUntil && $prevToken->equalsAny(['(', ',', [CT::T_NULLABLE_TYPE], [CT::T_TYPE_ALTERNATION], [CT::T_TYPE_COLON]])) { + for ($j = $classStartIndex; $j < $i; ++$j) { + $tokens->clearTokenAndMergeSurroundingWhitespace($j); + } + $tokens[$i] = new Token([\T_STRING, 'self']); + } + } + } + private function getClassStart(Tokens $tokens, int $index, string $namespace) : ?int + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php new file mode 100644 index 00000000000..a3d0587084b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SelfStaticAccessorFixer.php @@ -0,0 +1,173 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 +{ + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Inside an enum or `final`/anonymous class, `self` should be preferred over `static`.', [new CodeSample('isTokenKindFound(\T_STATIC) && $tokens->isAnyTokenKindsFound($classyTypes) && $tokens->isAnyTokenKindsFound([\T_DOUBLE_COLON, \T_NEW, \T_INSTANCEOF]); + } + /** + * {@inheritdoc} + * + * Must run after FinalClassFixer, FinalInternalClassFixer, FunctionToConstantFixer, PhpUnitTestCaseStaticMethodCallsFixer. + */ + public function getPriority() : int + { + return -10; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $classyTokensOfInterest = [[\T_CLASS]]; + if (\defined('T_ENUM')) { + $classyTokensOfInterest[] = [\T_ENUM]; + // @TODO drop condition when PHP 8.1+ is required + } + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + $classyIndex = $tokens->getNextTokenOfKind(0, $classyTokensOfInterest); + while (null !== $classyIndex) { + if ($tokens[$classyIndex]->isGivenKind(\T_CLASS)) { + $modifiers = $this->tokensAnalyzer->getClassyModifiers($classyIndex); + if (isset($modifiers['final']) || $this->tokensAnalyzer->isAnonymousClass($classyIndex)) { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + } else { + $classyIndex = $this->fixClassy($tokens, $classyIndex); + } + $classyIndex = $tokens->getNextTokenOfKind($classyIndex, $classyTokensOfInterest); + } + } + private function fixClassy(Tokens $tokens, int $index) : int + { + $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)) { + // do not fix inside lambda + if ($this->tokensAnalyzer->isLambda($index)) { + // figure out where the lambda starts + $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->fixClassy($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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php new file mode 100644 index 00000000000..b2edfabbbbc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleClassElementPerStatementFixer.php @@ -0,0 +1,172 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * Fixer for rules defined in PSR2 ¶4.2. + * + * @author Javier Spagnoletti + * @author Dariusz Rumiński + */ +final class SingleClassElementPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority() : int + { + return 56; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST NOT be more than one property or constant declared per statement.', [new CodeSample(' ['property']])]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // not in configuration + } + $this->fixElement($tokens, $element['type'], $index); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $values = ['const', 'property']; + return new FixerConfigurationResolver([(new FixerOptionBuilder('elements', 'List of strings which element should be modified.'))->setDefault($values)->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($values)])->getOption()]); + } + private function fixElement(Tokens $tokens, string $type, int $index) : void + { + $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; + // no repeating found, no fixing needed + } + if ($repeatToken->equals(',')) { + break; + } + } + $start = $tokens->getPrevTokenOfKind($index, [';', '{', '}']); + $this->expandElement($tokens, $type, $tokens->getNextMeaningfulToken($start), $tokens->getNextTokenOfKind($index, [';'])); + } + private function expandElement(Tokens $tokens, string $type, int $startIndex, int $endIndex) : void + { + $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"); + } + } + // iterate variables to split up + 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])); + } + // collect modifiers + $sequence = $this->getModifiersSequences($tokens, $type, $startIndex, $endIndex); + $tokens->insertAt($i + 2, $sequence); + } + } + /** + * @return Token[] + */ + private function getModifiersSequences(Tokens $tokens, string $type, int $startIndex, int $endIndex) : array + { + 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, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $tokenKinds[] = \T_READONLY; + } + } 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php new file mode 100644 index 00000000000..36cb8893f6c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/SingleTraitInsertPerStatementFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SingleTraitInsertPerStatementFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Each trait `use` must be done as single statement.', [new CodeSample('isTokenKindFound(CT::T_USE_TRAIT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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); + } + } + } + } + /** + * @param int[] $candidates ',' indices to fix + */ + private function fixTraitUse(Tokens $tokens, int $useTraitIndex, array $candidates) : void + { + 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 (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); + } + } + /** + * @return int[] + */ + private function getCandidates(Tokens $tokens, int $index) : array + { + $indices = []; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->equals('{')) { + return []; + // do not fix use cases with grouping + } + $indices[] = $index; + $index = $tokens->getNextTokenOfKind($index, [',', ';', '{']); + } + return \array_reverse($indices); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php new file mode 100644 index 00000000000..3d8c4c5702c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassNotation/VisibilityRequiredFixer.php @@ -0,0 +1,157 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.5. + * + * @author Dariusz Rumiński + */ +final class VisibilityRequiredFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + 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(' ['const']])]); + } + /** + * {@inheritdoc} + * + * Must run before ClassAttributesSeparationFixer. + */ + public function getPriority() : int + { + return 56; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(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', 'const'])->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $propertyTypeDeclarationKinds = [\T_STRING, \T_NS_SEPARATOR, CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $propertyReadOnlyType = \T_READONLY; + $propertyTypeDeclarationKinds[] = \T_READONLY; + } else { + $propertyReadOnlyType = -999; + } + $expectedKindsGeneric = [\T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR]; + $expectedKindsPropertyKinds = \array_merge($expectedKindsGeneric, $propertyTypeDeclarationKinds); + foreach (\array_reverse($tokensAnalyzer->getClassyElements(), \true) as $index => $element) { + if (!\in_array($element['type'], $this->configuration['elements'], \true)) { + continue; + } + $abstractFinalIndex = null; + $visibilityIndex = null; + $staticIndex = null; + $typeIndex = null; + $readOnlyIndex = null; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $expectedKinds = 'property' === $element['type'] ? $expectedKindsPropertyKinds : $expectedKindsGeneric; + 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($propertyReadOnlyType)) { + $readOnlyIndex = $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; + } + $swapIndex = $staticIndex ?? $readOnlyIndex; + // "static" property cannot be "readonly", so there can always be at most one swap + if (null !== $swapIndex) { + if ($this->isKeywordPlacedProperly($tokens, $swapIndex, $index)) { + $index = $swapIndex; + } else { + $this->moveTokenAndEnsureSingleSpaceFollows($tokens, $swapIndex, $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, int $keywordIndex, int $comparedIndex) : bool + { + return $keywordIndex + 2 === $comparedIndex && ' ' === $tokens[$keywordIndex + 1]->getContent(); + } + private function moveTokenAndEnsureSingleSpaceFollows(Tokens $tokens, int $fromIndex, int $toIndex) : void + { + $tokens->insertAt($toIndex, [$tokens[$fromIndex], new Token([\T_WHITESPACE, ' '])]); + $tokens->clearAt($fromIndex); + if ($tokens[$fromIndex + 1]->isWhitespace()) { + $tokens->clearAt($fromIndex + 1); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php new file mode 100644 index 00000000000..b3a765a9d49 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ClassUsage/DateTimeImmutableFixer.php @@ -0,0 +1,115 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ClassUsage; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class DateTimeImmutableFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Class `DateTimeImmutable` should be used instead of `DateTime`.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $functionMap = ['date_create' => 'date_create_immutable', 'date_create_from_format' => 'date_create_immutable_from_format']; + $isInNamespace = \false; + $isImported = \false; + // e.g. use DateTime; + for ($index = 0, $limit = $tokens->count(); $index < $limit; ++$index) { + $token = $tokens[$index]; + if ($token->isGivenKind(\T_NAMESPACE)) { + $isInNamespace = \true; + continue; + } + if ($isInNamespace && $token->isGivenKind(\T_USE)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ('datetime' !== \strtolower($tokens[$nextIndex]->getContent())) { + continue; + } + $nextNextIndex = $tokens->getNextMeaningfulToken($nextIndex); + if ($tokens[$nextNextIndex]->equals(';')) { + $isImported = \true; + } + $index = $nextNextIndex; + continue; + } + if (!$token->isGivenKind(\T_STRING)) { + continue; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) { + continue; + } + $lowercaseContent = \strtolower($token->getContent()); + if ('datetime' === $lowercaseContent) { + $this->fixClassUsage($tokens, $index, $isInNamespace, $isImported); + $limit = $tokens->count(); + // update limit, as fixing class usage may insert new token + continue; + } + if (isset($functionMap[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $tokens[$index] = new Token([\T_STRING, $functionMap[$lowercaseContent]]); + } + } + } + private function fixClassUsage(Tokens $tokens, int $index, bool $isInNamespace, bool $isImported) : void + { + $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; + // e.g. new DateTime(); + $isUsedWithLeadingBackslash = \false; + // e.g. new \DateTime(); + $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) && !$tokens[$prevIndex]->isObjectOperator()) { + $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, '\\'])); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php new file mode 100644 index 00000000000..58c2c447440 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/CommentToPhpdocFixer.php @@ -0,0 +1,168 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +/** + * @author Kuba Werłos + */ +final class CommentToPhpdocFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var string[] + */ + private $ignoredTags = []; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_COMMENT); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after AlignMultilineCommentFixer. + */ + public function getPriority() : int + { + // Should be run before all other PHPDoc fixers + return 26; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Comments with annotation should be docblock when used on structural elements.', [new CodeSample(" ['todo']])], null, 'Risky as new docblocks might mean more, e.g. a Doctrine entity might have a new column in database.'); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->ignoredTags = \array_map(static function (string $tag) : string { + return \strtolower($tag); + }, $this->configuration['ignored_tags']); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('ignored_tags', 'List of ignored tags.'))->setAllowedTypes(['array'])->setDefault([])->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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); + } + } + /** + * @param int[] $indices + */ + private function isCommentCandidate(Tokens $tokens, array $indices) : bool + { + return \array_reduce($indices, function (bool $carry, int $index) use($tokens) : bool { + if ($carry) { + return \true; + } + if (!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); + } + /** + * @param int[] $indices + */ + private function fixComment(Tokens $tokens, array $indices) : void + { + if (1 === \count($indices)) { + $this->fixCommentSingleLine($tokens, \reset($indices)); + } else { + $this->fixCommentMultiLine($tokens, $indices); + } + } + private function fixCommentSingleLine(Tokens $tokens, int $index) : void + { + $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 . '*/']); + } + /** + * @param int[] $indices + */ + private function fixCommentMultiLine(Tokens $tokens, array $indices) : void + { + $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 (\strpos($tokens[$index]->getContent(), '*/') !== \false) { + return; + } + $message = $this->getMessage($tokens[$index]->getContent()); + if ('' !== \trim(\substr($message, 0, 1))) { + $message = ' ' . $message; + } + $newContent .= $indent . ' *' . $message . $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(string $content) : string + { + if (\strncmp($content, '#', \strlen('#')) === 0) { + return \substr($content, 1); + } + if (\strncmp($content, '//', \strlen('//')) === 0) { + return \substr($content, 2); + } + return \rtrim(\ltrim($content, '/*'), '*/'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php new file mode 100644 index 00000000000..5bf9b3e23db --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/HeaderCommentFixer.php @@ -0,0 +1,306 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * @author Antonio J. García Lagar + */ +final class HeaderCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const HEADER_PHPDOC = 'PHPDoc'; + /** + * @internal + */ + public const HEADER_COMMENT = 'comment'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Add, replace or remove header comment.', [new CodeSample(' 'Made with love.']), new CodeSample(' 'Made with love.', 'comment_type' => 'PHPDoc', 'location' => 'after_open', 'separate' => 'bottom']), new CodeSample(' 'Made with love.', 'comment_type' => 'comment', 'location' => 'after_declare_strict']), new CodeSample(' ''])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isMonolithicPhp(); + } + /** + * {@inheritdoc} + * + * Must run before SingleLineCommentStyleFixer. + * Must run after DeclareStrictTypesFixer, NoBlankLinesAfterPhpdocFixer. + */ + public function getPriority() : int + { + // When this fixer is configured with ["separate" => "bottom", "comment_type" => "PHPDoc"] + // and the target file has no namespace or declare() construct, + // the fixed header comment gets trimmed by NoBlankLinesAfterPhpdocFixer if we run before it. + return -30; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $location = $this->configuration['location']; + $locationIndices = []; + foreach (['after_open', 'after_declare_strict'] as $possibleLocation) { + $locationIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + if (!isset($locationIndices[$locationIndex]) || $possibleLocation === $location) { + $locationIndices[$locationIndex] = $possibleLocation; + } + } + foreach ($locationIndices as $possibleLocation) { + // figure out where the comment should be placed + $headerNewIndex = $this->findHeaderCommentInsertionIndex($tokens, $possibleLocation); + // check if there is already a comment + $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 xor $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() : FixerConfigurationResolverInterface + { + $fixerName = $this->getName(); + return new FixerConfigurationResolver([(new FixerOptionBuilder('header', 'Proper header content.'))->setAllowedTypes(['string'])->setNormalizer(static function (Options $options, string $value) use($fixerName) : string { + if ('' === \trim($value)) { + return ''; + } + if (\strpos($value, '*/') !== \false) { + throw new InvalidFixerConfigurationException($fixerName, 'Cannot use \'*/\' in header.'); + } + return $value; + })->getOption(), (new FixerOptionBuilder('comment_type', 'Comment syntax type.'))->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()]); + } + /** + * Enclose the given text in a comment block. + */ + private function getHeaderAsComment() : string + { + $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, int $headerNewIndex) : ?int + { + $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; + } + /** + * Find the index where the header comment must be inserted. + */ + private function findHeaderCommentInsertionIndex(Tokens $tokens, string $location) : int + { + $openTagIndex = $tokens[0]->isGivenKind(\T_OPEN_TAG) ? 0 : $tokens->getNextTokenOfKind(0, [[\T_OPEN_TAG]]); + if (null === $openTagIndex) { + return 1; + } + if ('after_open' === $location) { + return $openTagIndex + 1; + } + $index = $tokens->getNextMeaningfulToken($openTagIndex); + if (null === $index) { + return $openTagIndex + 1; + // file without meaningful tokens but an open tag, comment should always be placed directly after the open tag + } + if (!$tokens[$index]->isGivenKind(\T_DECLARE)) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($index); + if (null === $next || !$tokens[$next]->equals('(')) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($next); + if (null === $next || !$tokens[$next]->equals([\T_STRING, 'strict_types'], \false)) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($next); + if (null === $next || !$tokens[$next]->equals('=')) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($next); + if (null === $next || !$tokens[$next]->isGivenKind(\T_LNUMBER)) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($next); + if (null === $next || !$tokens[$next]->equals(')')) { + return $openTagIndex + 1; + } + $next = $tokens->getNextMeaningfulToken($next); + if (null === $next || !$tokens[$next]->equals(';')) { + // don't insert after close tag + return $openTagIndex + 1; + } + return $next + 1; + } + private function fixWhiteSpaceAroundHeader(Tokens $tokens, int $headerIndex) : void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + // fix lines after header comment + 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())]); + } + } + // fix lines before header comment + $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) { + // because of the way the insert index was determined for header comment there cannot be an empty token here + $tokens->insertAt($headerIndex, new Token([\T_WHITESPACE, \str_repeat($lineEnding, $expectedLineCount - $lineBreakCount)])); + } + } + private function getLineBreakCount(Tokens $tokens, int $index, int $direction) : int + { + $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, int $index) : void + { + $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); + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $content); + } + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex] ?? null; + if (!$newlineRemoved && null !== $nextToken && $nextToken->isWhitespace()) { + $content = Preg::replace('/^\\R/', '', $nextToken->getContent()); + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + private function insertHeader(Tokens $tokens, int $index) : void + { + $tokens->insertAt($index, new Token([self::HEADER_COMMENT === $this->configuration['comment_type'] ? \T_COMMENT : \T_DOC_COMMENT, $this->getHeaderAsComment()])); + $this->fixWhiteSpaceAroundHeader($tokens, $index); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php new file mode 100644 index 00000000000..952f8e87674 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/MultilineCommentOpeningClosingFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class MultilineCommentOpeningClosingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + 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' +isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + $originalContent = $token->getContent(); + if (!$token->isGivenKind(\T_DOC_COMMENT) && !($token->isGivenKind(\T_COMMENT) && \strncmp($originalContent, '/*', \strlen('/*')) === 0)) { + continue; + } + $newContent = $originalContent; + // Fix opening + if ($token->isGivenKind(\T_COMMENT)) { + $newContent = Preg::replace('/^\\/\\*{2,}(?!\\/)/', '/*', $newContent); + } + // Fix closing + $newContent = Preg::replace('/(?getId(), $newContent]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php new file mode 100644 index 00000000000..f08f02a1560 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoEmptyCommentFixer.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +final class NoEmptyCommentFixer extends AbstractFixer +{ + private const TYPE_HASH = 1; + private const TYPE_DOUBLE_SLASH = 2; + private const TYPE_SLASH_ASTERISK = 3; + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer. + * Must run after PhpdocToCommentFixer. + */ + public function getPriority() : int + { + return 2; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be any empty comments.', [new CodeSample("isTokenKindFound(\T_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_COMMENT)) { + continue; + } + [$blockStart, $index, $isEmpty] = $this->getCommentBlock($tokens, $index); + if (\false === $isEmpty) { + continue; + } + for ($i = $blockStart; $i <= $index; ++$i) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + /** + * Return the start index, end index and a flag stating if the comment block is empty. + * + * @param int $index T_COMMENT index + */ + private function getCommentBlock(Tokens $tokens, int $index) : array + { + $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) { + // don't retest if already known the block not being 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(string $content) : int + { + if (\strncmp($content, '#', \strlen('#')) === 0) { + return self::TYPE_HASH; + } + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + return self::TYPE_DOUBLE_SLASH; + } + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd) : int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\\R/u', $tokens[$i]->getContent(), $matches); + } + return $lineCount; + } + private function isEmptyComment(string $content) : bool + { + static $mapper = [ + self::TYPE_HASH => '|^#\\s*$|', + // single line comment starting with '#' + self::TYPE_SLASH_ASTERISK => '|^/\\*[\\s\\*]*\\*+/$|', + // comment starting with '/*' and ending with '*/' (but not a PHPDoc) + self::TYPE_DOUBLE_SLASH => '|^//\\s*$|', + ]; + $type = $this->getCommentType($content); + return Preg::match($mapper[$type], $content); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php new file mode 100644 index 00000000000..7c68ed79667 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/NoTrailingWhitespaceInCommentFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class NoTrailingWhitespaceInCommentFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST be no trailing spaces inside comment or PHPDoc.', [new CodeSample('isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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 (\strncmp($token->getContent(), '/*', \strlen('/*')) === 0) { + $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"); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $trimmedContent); + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php new file mode 100644 index 00000000000..99105796790 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentSpacingFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SingleLineCommentSpacingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Single-line comments must have proper spacing.', [new CodeSample('isTokenKindFound(\T_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind(\T_COMMENT)) { + continue; + } + $content = $token->getContent(); + $contentLength = \strlen($content); + if ('/' === $content[0]) { + if ($contentLength < 3) { + continue; + // cheap check for "//" + } + if ('*' === $content[1]) { + // slash asterisk comment + if ($contentLength < 5 || '*' === $content[2] || \strpos($content, "\n") !== \false) { + continue; + // cheap check for "/**/", comment that looks like a PHPDoc, or multi line comment + } + $newContent = \rtrim(\substr($content, 0, -2)) . ' ' . \substr($content, -2); + $newContent = $this->fixCommentLeadingSpace($newContent, '/*'); + } else { + // double slash comment + $newContent = $this->fixCommentLeadingSpace($content, '//'); + } + } else { + // hash comment + if ($contentLength < 2 || '[' === $content[1]) { + // cheap check for "#" or annotation (like) comment + continue; + } + $newContent = $this->fixCommentLeadingSpace($content, '#'); + } + if ($newContent !== $content) { + $tokens[$index] = new Token([\T_COMMENT, $newContent]); + } + } + } + // fix space between comment open and leading text + private function fixCommentLeadingSpace(string $content, string $prefix) : string + { + if (Preg::match(\sprintf('@^%s\\h+.*$@', \preg_quote($prefix, '@')), $content)) { + return $content; + } + $position = \strlen($prefix); + return \substr($content, 0, $position) . ' ' . \substr($content, $position); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php new file mode 100644 index 00000000000..4c0c0c26665 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Comment/SingleLineCommentStyleFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Comment; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class SingleLineCommentStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var bool + */ + private $asteriskEnabled; + /** + * @var bool + */ + private $hashEnabled; + public function configure(array $configuration) : void + { + 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() : FixerDefinitionInterface + { + return new FixerDefinition('Single-line comments and multi-line comments with only one line of actual content should use the `//` syntax.', [new CodeSample(' ['asterisk']]), new CodeSample(" ['hash']])]); + } + /** + * {@inheritdoc} + * + * Must run after HeaderCommentFixer, NoUselessReturnFixer, PhpdocToCommentFixer. + */ + public function getPriority() : int + { + return -31; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_COMMENT)) { + continue; + } + $content = $token->getContent(); + $commentContent = \substr($content, 2, -2) ?: ''; + if ($this->hashEnabled && \strncmp($content, '#', \strlen('#')) === 0) { + if (isset($content[1]) && '[' === $content[1]) { + continue; + // This might be an attribute on PHP8, do not change + } + $tokens[$index] = new Token([$token->getId(), '//' . \substr($content, 1)]); + continue; + } + if (!$this->asteriskEnabled || \strpos($commentContent, '?>') !== \false || \strncmp($content, '/*', \strlen('/*')) !== 0 || Preg::match('/[^\\s\\*].*\\R.*[^\\s\\*]/s', $commentContent)) { + continue; + } + $nextTokenIndex = $index + 1; + if (isset($tokens[$nextTokenIndex])) { + $nextToken = $tokens[$nextTokenIndex]; + if (!$nextToken->isWhitespace() || !Preg::match('/\\R/', $nextToken->getContent())) { + continue; + } + $tokens[$nextTokenIndex] = new Token([$nextToken->getId(), \ltrim($nextToken->getContent(), " \t")]); + } + $content = '//'; + if (Preg::match('/[^\\s\\*]/', $commentContent)) { + $content = '// ' . Preg::replace('/[\\s\\*]*([^\\s\\*](?:.+[^\\s\\*])?)[\\s\\*]*/', '\\1', $commentContent); + } + $tokens[$index] = new Token([$token->getId(), $content]); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('comment_types', 'List of comment types to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(['asterisk', 'hash'])])->setDefault(['asterisk', 'hash'])->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php new file mode 100644 index 00000000000..d46119806ac --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConfigurableFixerInterface.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +/** + * @author Dariusz Rumiński + */ +interface ConfigurableFixerInterface extends \PhpCsFixer\Fixer\FixerInterface +{ + /** + * Set configuration. + * + * New configuration must override current one, not patch it. + * Using empty array makes fixer to use default configuration + * (or reset configuration from previously configured back to default one). + * + * Some fixers may have no configuration, then - simply don't implement this interface. + * Other ones may have configuration that will change behavior of fixer, + * eg `php_unit_strict` fixer allows to configure which methods should be fixed. + * Finally, some fixers need configuration to work, eg `header_comment`. + * + * @param array $configuration configuration depends on Fixer + * + * @throws InvalidFixerConfigurationException + */ + public function configure(array $configuration) : void; + /** + * Defines the available configuration options of the fixer. + */ + public function getConfigurationDefinition() : FixerConfigurationResolverInterface; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php new file mode 100644 index 00000000000..ed63aca3120 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ConstantNotation/NativeConstantInvocationFixer.php @@ -0,0 +1,175 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ConstantNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Filippo Tessarotto + */ +final class NativeConstantInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private $constantsToEscape = []; + /** + * @var array + */ + private $caseInsensitiveConstantsToEscape = []; + public function getDefinition() : FixerDefinitionInterface + { + 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(" 'namespaced']), new CodeSample(" ['MY_CUSTOM_PI']]), new CodeSample(" \false, 'include' => ['MY_CUSTOM_PI']]), new CodeSample(" ['M_PI']])], null, 'Risky when any of the constants are namespaced or overridden.'); + } + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + */ + public function getPriority() : int + { + return 10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $uniqueConfiguredExclude = \array_unique($this->configuration['exclude']); + // Case-sensitive constants handling + $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); + // Case-insensitive constants handling + 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 (string $function) : string { + return \strtolower($function); + }, $uniqueConfiguredExclude)); + // Store the cache + $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) : void + { + if ('all' === $this->configuration['scope']) { + $this->fixConstantInvocations($tokens, 0, \count($tokens) - 1); + return; + } + $namespaces = $tokens->getNamespaceDeclarations(); + // 'scope' is 'namespaced' here + /** @var NamespaceAnalysis $namespace */ + foreach (\array_reverse($namespaces) as $namespace) { + if ($namespace->isGlobalNamespace()) { + continue; + } + $this->fixConstantInvocations($tokens, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex()); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $constantChecker = static function (array $value) : bool { + 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.', \get_debug_type($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(\true)->getOption()]); + } + private function fixConstantInvocations(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $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]; + // test if we are at a constant call + 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 (\false === $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, '\\'])); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php new file mode 100644 index 00000000000..7714d9fe4d1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureBracesFixer.php @@ -0,0 +1,178 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class ControlStructureBracesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The body of each control structure MUST be enclosed within braces.', [new CodeSample("getControlTokens(); + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind($controlTokens)) { + continue; + } + if ($token->isGivenKind(\T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF)) { + continue; + } + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $index); + $nextAfterParenthesisEndIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + $tokenAfterParenthesis = $tokens[$nextAfterParenthesisEndIndex]; + if ($tokenAfterParenthesis->equalsAny([';', '{', ':', [\T_CLOSE_TAG]])) { + continue; + } + $statementEndIndex = null; + if ($tokenAfterParenthesis->isGivenKind([\T_IF, \T_FOR, \T_FOREACH, \T_SWITCH, \T_WHILE])) { + $tokenAfterParenthesisBlockEnd = $tokens->findBlockEnd( + // go to ')' + Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, + $tokens->getNextMeaningfulToken($nextAfterParenthesisEndIndex) + ); + if ($tokens[$tokens->getNextMeaningfulToken($tokenAfterParenthesisBlockEnd)]->equals(':')) { + $statementEndIndex = $alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $nextAfterParenthesisEndIndex); + $tokenAfterStatementEndIndex = $tokens->getNextMeaningfulToken($statementEndIndex); + if ($tokens[$tokenAfterStatementEndIndex]->equals(';')) { + $statementEndIndex = $tokenAfterStatementEndIndex; + } + } + } + if (null === $statementEndIndex) { + $statementEndIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + } + $tokensToInsertAfterStatement = [new Token([\T_WHITESPACE, ' ']), new Token('}')]; + if (!$tokens[$statementEndIndex]->equalsAny([';', '}'])) { + \array_unshift($tokensToInsertAfterStatement, new Token(';')); + } + $tokens->insertSlices([$statementEndIndex + 1 => $tokensToInsertAfterStatement]); + // insert opening brace + $tokens->insertSlices([$parenthesisEndIndex + 1 => [new Token([\T_WHITESPACE, ' ']), new Token('{')]]); + } + } + private function findParenthesisEnd(Tokens $tokens, int $structureTokenIndex) : int + { + $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, int $parenthesisEndIndex) : int + { + $nextIndex = $tokens->getNextMeaningfulToken($parenthesisEndIndex); + if (null === $nextIndex) { + return $parenthesisEndIndex; + } + $nextToken = $tokens[$nextIndex]; + 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); + if (null !== $nextIndex && $tokens[$nextIndex]->isGivenKind($this->getControlContinuationTokensForOpeningToken($openingTokenKind))) { + $parenthesisEndIndex = $this->findParenthesisEnd($tokens, $nextIndex); + $endIndex = $this->findStatementEnd($tokens, $parenthesisEndIndex); + if ($tokens[$nextIndex]->isGivenKind($this->getFinalControlContinuationTokensForOpeningToken($openingTokenKind))) { + return $endIndex; + } + } else { + break; + } + } + } + return $endIndex; + } + $index = $parenthesisEndIndex; + while (\true) { + $token = $tokens[++$index]; + // if there is some block in statement (eg lambda function) we need to skip it + 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); + } + } + } + /** + * @return list + */ + private function getControlTokens() : array + { + 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; + } + /** + * @return list + */ + private function getControlContinuationTokensForOpeningToken(int $openingTokenKind) : array + { + 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 []; + } + /** + * @return list + */ + private function getFinalControlContinuationTokensForOpeningToken(int $openingTokenKind) : array + { + if (\T_IF === $openingTokenKind) { + return [\T_ELSE]; + } + if (\T_TRY === $openingTokenKind) { + return [\T_FINALLY]; + } + return []; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php new file mode 100644 index 00000000000..a8a3af92e9d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ControlStructureContinuationPositionFixer.php @@ -0,0 +1,96 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +final class ControlStructureContinuationPositionFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const NEXT_LINE = 'next_line'; + /** + * @internal + */ + public const SAME_LINE = 'same_line'; + private const CONTROL_CONTINUATION_TOKENS = [\T_CATCH, \T_ELSE, \T_ELSEIF, \T_FINALLY, \T_WHILE]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Control structure continuation keyword must be on the configured line.', [new CodeSample(' self::NEXT_LINE])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(self::CONTROL_CONTINUATION_TOKENS); + } + /** + * {@inheritdoc} + * + * Must run after ControlStructureBracesFixer. + */ + public function getPriority() : int + { + return parent::getPriority(); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('position', 'The position of the keyword that continues the control structure.'))->setAllowedValues([self::NEXT_LINE, self::SAME_LINE])->setDefault(self::SAME_LINE)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->fixControlContinuationBraces($tokens); + } + private function fixControlContinuationBraces(Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; 0 < $index; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind(self::CONTROL_CONTINUATION_TOKENS)) { + continue; + } + $prevIndex = $tokens->getPrevNonWhitespace($index); + $prevToken = $tokens[$prevIndex]; + if (!$prevToken->equals('}')) { + continue; + } + if ($token->isGivenKind(\T_WHILE)) { + $prevIndex = $tokens->getPrevMeaningfulToken($tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevIndex)); + if (!$tokens[$prevIndex]->isGivenKind(\T_DO)) { + continue; + } + } + $tokens->ensureWhitespaceAtIndex($index - 1, 1, self::NEXT_LINE === $this->configuration['position'] ? $this->whitespacesConfig->getLineEnding() . WhitespacesAnalyzer::detectIndent($tokens, $index) : ' '); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php new file mode 100644 index 00000000000..ac2823891fd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/ElseifFixer.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶5.1. + * + * @author Dariusz Rumiński + */ +final class ElseifFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The keyword `elseif` should be used instead of `else if` so that all control keywords look like single words.', [new CodeSample("isAllTokenKindsFound([\T_IF, \T_ELSE]); + } + /** + * Replace all `else if` (T_ELSE T_IF) with `elseif` (T_ELSEIF). + * + * {@inheritdoc} + */ + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_ELSE)) { + continue; + } + $ifTokenIndex = $tokens->getNextMeaningfulToken($index); + // if next meaningful token is not T_IF - continue searching, this is not the case for fixing + if (!$tokens[$ifTokenIndex]->isGivenKind(\T_IF)) { + continue; + } + // if next meaningful token is T_IF, but uses an alternative syntax - this is not the case for fixing neither + $conditionEndBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($ifTokenIndex)); + $afterConditionIndex = $tokens->getNextMeaningfulToken($conditionEndBraceIndex); + if ($tokens[$afterConditionIndex]->equals(':')) { + continue; + } + // now we have T_ELSE following by T_IF with no alternative syntax so we could fix this + // 1. clear whitespaces between T_ELSE and T_IF + $tokens->clearAt($index + 1); + // 2. change token from T_ELSE into T_ELSEIF + $tokens[$index] = new Token([\T_ELSEIF, 'elseif']); + // 3. clear succeeding T_IF + $tokens->clearAt($ifTokenIndex); + $beforeIfTokenIndex = $tokens->getPrevNonWhitespace($ifTokenIndex); + // 4. clear extra whitespace after T_IF in T_COMMENT,T_WHITESPACE?,T_IF,T_WHITESPACE sequence + if ($tokens[$beforeIfTokenIndex]->isComment() && $tokens[$ifTokenIndex + 1]->isWhitespace()) { + $tokens->clearAt($ifTokenIndex + 1); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php new file mode 100644 index 00000000000..6d2ddf21bff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopBodyFixer.php @@ -0,0 +1,93 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +final class EmptyLoopBodyFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STYLE_BRACES = 'braces'; + private const STYLE_SEMICOLON = 'semicolon'; + private const TOKEN_LOOP_KINDS = [\T_FOR, \T_FOREACH, \T_WHILE]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Empty loop-body must be in configured style.', [new CodeSample(" 'braces'])]); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + * Must run after NoEmptyStatementFixer. + */ + public function getPriority() : int + { + return 39; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (self::STYLE_BRACES === $this->configuration['style']) { + $analyzer = new TokensAnalyzer($tokens); + $fixLoop = static function (int $index, int $endIndex) use($tokens, $analyzer) : void { + if ($tokens[$index]->isGivenKind(\T_WHILE) && $analyzer->isWhilePartOfDoWhile($index)) { + return; + } + $semiColonIndex = $tokens->getNextMeaningfulToken($endIndex); + if (!$tokens[$semiColonIndex]->equals(';')) { + return; + } + $tokens[$semiColonIndex] = new Token('{'); + $tokens->insertAt($semiColonIndex + 1, new Token('}')); + }; + } else { + $fixLoop = static function (int $index, int $endIndex) use($tokens) : void { + $braceOpenIndex = $tokens->getNextMeaningfulToken($endIndex); + if (!$tokens[$braceOpenIndex]->equals('{')) { + return; + } + $braceCloseIndex = $tokens->getNextNonWhitespace($braceOpenIndex); + if (!$tokens[$braceCloseIndex]->equals('}')) { + return; + } + $tokens[$braceOpenIndex] = new Token(';'); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceCloseIndex); + }; + } + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(self::TOKEN_LOOP_KINDS)) { + $endIndex = $tokens->getNextTokenOfKind($index, ['(']); + // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + // proceed to close ')' + $fixLoop($index, $endIndex); + // fix loop if needs fixing + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('style', 'Style of empty loop-bodies.'))->setAllowedTypes(['string'])->setAllowedValues([self::STYLE_BRACES, self::STYLE_SEMICOLON])->setDefault(self::STYLE_SEMICOLON)->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php new file mode 100644 index 00000000000..610cbd823f9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/EmptyLoopConditionFixer.php @@ -0,0 +1,150 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class EmptyLoopConditionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STYLE_FOR = 'for'; + private const STYLE_WHILE = 'while'; + private const TOKEN_LOOP_KINDS = [\T_FOR, \T_WHILE]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Empty loop-condition must be in configured style.', [new CodeSample(" 'for'])]); + } + /** + * {@inheritdoc} + * + * Must run before NoExtraBlankLinesFixer, NoTrailingWhitespaceFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(self::TOKEN_LOOP_KINDS); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (self::STYLE_WHILE === $this->configuration['style']) { + $candidateLoopKinds = [\T_FOR, \T_WHILE]; + $replacement = [new Token([\T_WHILE, 'while']), new Token([\T_WHITESPACE, ' ']), new Token('('), new Token([\T_STRING, 'true']), new Token(')')]; + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use($tokens, $replacement) : void { + if (self::isForLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } elseif (self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + $doIndex = self::getDoIndex($tokens, $index); + if (null !== $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); + // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + } + }; + } else { + // self::STYLE_FOR + $candidateLoopKinds = [\T_WHILE]; + $replacement = [new Token([\T_FOR, 'for']), new Token('('), new Token(';'), new Token(';'), new Token(')')]; + $fixLoop = static function (int $index, int $openIndex, int $endIndex) use($tokens, $replacement) : void { + if (!self::isWhileLoopWithEmptyCondition($tokens, $index, $openIndex, $endIndex)) { + return; + } + $doIndex = self::getDoIndex($tokens, $index); + if (null === $doIndex) { + self::clearNotCommentsInRange($tokens, $index, $endIndex); + self::cloneAndInsert($tokens, $index, $replacement); + } else { + self::clearNotCommentsInRange($tokens, $index, $tokens->getNextMeaningfulToken($endIndex)); + // clear including `;` + $tokens->clearAt($doIndex); + self::cloneAndInsert($tokens, $doIndex, $replacement); + } + }; + } + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($candidateLoopKinds)) { + $openIndex = $tokens->getNextTokenOfKind($index, ['(']); + // proceed to open '(' + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + // proceed to close ')' + $fixLoop($index, $openIndex, $endIndex); + // fix loop if needed + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('style', 'Style of empty loop-condition.'))->setAllowedTypes(['string'])->setAllowedValues([self::STYLE_WHILE, self::STYLE_FOR])->setDefault(self::STYLE_WHILE)->getOption()]); + } + private static function clearNotCommentsInRange(Tokens $tokens, int $indexStart, int $indexEnd) : void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + } + /** + * @param Token[] $replacement + */ + private static function cloneAndInsert(Tokens $tokens, int $index, array $replacement) : void + { + $replacementClones = []; + foreach ($replacement as $token) { + $replacementClones[] = clone $token; + } + $tokens->insertAt($index, $replacementClones); + } + private static function getDoIndex(Tokens $tokens, int $index) : ?int + { + $endIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$endIndex]->equals('}')) { + return null; + } + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + $index = $tokens->getPrevMeaningfulToken($startIndex); + return null === $index || !$tokens[$index]->isGivenKind(\T_DO) ? null : $index; + } + private static function isForLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex) : bool + { + if (!$tokens[$index]->isGivenKind(\T_FOR)) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($openIndex); + if (null === $index || !$tokens[$index]->equals(';')) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($index); + return null !== $index && $tokens[$index]->equals(';') && $endIndex === $tokens->getNextMeaningfulToken($index); + } + private static function isWhileLoopWithEmptyCondition(Tokens $tokens, int $index, int $openIndex, int $endIndex) : bool + { + if (!$tokens[$index]->isGivenKind(\T_WHILE)) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($openIndex); + return null !== $index && $tokens[$index]->equals([\T_STRING, 'true']) && $endIndex === $tokens->getNextMeaningfulToken($index); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php new file mode 100644 index 00000000000..64a18e4dc12 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/IncludeFixer.php @@ -0,0 +1,112 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\BlocksAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + */ +final class IncludeFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + 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('isAnyTokenKindsFound([\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->clearIncludies($tokens, $this->findIncludies($tokens)); + } + /** + * @param array $includies + */ + private function clearIncludies(Tokens $tokens, array $includies) : void + { + $blocksAnalyzer = new BlocksAnalyzer(); + foreach ($includies as $includy) { + if (!$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']); + // Include is also legal as function parameter or condition statement but requires being wrapped then. + 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, ' '])); + } + } + } + /** + * @return array + */ + private function findIncludies(Tokens $tokens) : array + { + 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, int $index) : void + { + $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); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php new file mode 100644 index 00000000000..86238496615 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoAlternativeSyntaxFixer.php @@ -0,0 +1,170 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Eddilbert Macharia + */ +final class NoAlternativeSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace control structure alternative syntax to use braces.', [new CodeSample("\nLorem ipsum.\n\n", ['fix_non_monolithic_code' => \true])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->hasAlternativeSyntax() && (\true === $this->configuration['fix_non_monolithic_code'] || $tokens->isMonolithicPhp()); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ElseifFixer, NoSuperfluousElseifFixer, NoUnneededControlParenthesesFixer, NoUselessElseFixer, SwitchContinueToBreakFixer. + */ + public function getPriority() : int + { + return 42; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('fix_non_monolithic_code', 'Whether to also fix code with inline HTML.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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, int $structureTokenIndex) : int + { + $nextIndex = $tokens->getNextMeaningfulToken($structureTokenIndex); + $nextToken = $tokens[$nextIndex]; + return $nextToken->equals('(') ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $nextIndex) : $structureTokenIndex; + // return if next token is not opening parenthesis + } + /** + * Handle both extremes of the control structures. + * e.g. if(): or endif;. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixOpenCloseControls(int $index, Token $token, Tokens $tokens) : void + { + 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); + } + } + /** + * Handle the else: cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElse(int $index, Token $token, Tokens $tokens) : void + { + 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); + } + /** + * Handle the elsif(): cases. + * + * @param int $index the index of the token being processed + * @param Token $token the token being processed + * @param Tokens $tokens the collection of tokens + */ + private function fixElseif(int $index, Token $token, Tokens $tokens) : void + { + 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); + } + /** + * Add opening and closing braces to the else: and elseif: cases. + * + * @param Tokens $tokens the tokens collection + * @param Token $token the current token + * @param int $index the current token index + * @param int $colonIndex the index of the colon + */ + private function addBraces(Tokens $tokens, Token $token, int $index, int $colonIndex) : void + { + $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); + // increment the position of the colon by number of items inserted + $colonIndex += \count($items); + $items = [new Token('{')]; + if (!$tokens[$colonIndex + 1]->isWhitespace()) { + $items[] = new Token([\T_WHITESPACE, ' ']); + } + $tokens->clearAt($colonIndex); + $tokens->insertAt($colonIndex, $items); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php new file mode 100644 index 00000000000..f227aeb7568 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoBreakCommentFixer.php @@ -0,0 +1,263 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * Fixer for rule defined in PSR2 ¶5.2. + */ +final class NoBreakCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must be a comment when fall-through is intentional in a non-empty case body.', [new CodeSample(' '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) : bool + { + return $tokens->isTokenKindFound(\T_SWITCH); + } + /** + * {@inheritdoc} + * + * Must run after NoUselessElseFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('comment_text', 'The text to use in the added comment and to detect it.'))->setAllowedTypes(['string'])->setAllowedValues([static function (string $value) : bool { + if (Preg::match('/\\R/', $value)) { + throw new InvalidOptionsException('The comment text must not contain new lines.'); + } + return \true; + }])->setNormalizer(static function (Options $options, string $value) : string { + return \rtrim($value); + })->setDefault('no break')->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; $index >= 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_DEFAULT)) { + if ($tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_ARROW)) { + continue; + // this is "default" from "match" + } + } elseif (!$tokens[$index]->isGivenKind(\T_CASE)) { + continue; + } + $this->fixCase($tokens, $tokens->getNextTokenOfKind($index, [':', ';'])); + } + } + private function fixCase(Tokens $tokens, int $casePosition) : void + { + $empty = \true; + $fallThrough = \true; + $commentPosition = null; + for ($i = $casePosition + 1, $max = \count($tokens); $i < $max; ++$i) { + if ($tokens[$i]->isGivenKind(\array_merge(self::getParenthesisedStructureKinds(), [\T_ELSE, \T_DO, \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 === $casePosition || $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) : bool + { + if (!$token->isComment()) { + return \false; + } + $text = \preg_quote($this->configuration['comment_text'], '~'); + return Preg::match("~^((//|#)\\s*{$text}\\s*)|(/\\*\\*?\\s*{$text}(\\s+.*)*\\*/)\$~i", $token->getContent()); + } + private function insertCommentAt(Tokens $tokens, int $casePosition) : void + { + $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); + } + /** + * @return int The newline token position + */ + private function ensureNewLineAt(Tokens $tokens, int $position) : int + { + $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, int $commentPosition) : void + { + 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()); + $tokens->ensureWhitespaceAtIndex($whitespacePosition, 0, $content); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($commentPosition); + } + private function getStructureEnd(Tokens $tokens, int $position) : int + { + $initialToken = $tokens[$position]; + if ($initialToken->isGivenKind(self::getParenthesisedStructureKinds())) { + $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; + } + /** + * @return array + */ + private static function getParenthesisedStructureKinds() : array + { + static $structureKinds = null; + if (null === $structureKinds) { + $structureKinds = [\T_FOR, \T_FOREACH, \T_WHILE, \T_IF, \T_ELSEIF, \T_SWITCH, \T_FUNCTION]; + if (\defined('T_MATCH')) { + // @TODO: drop condition when PHP 8.0+ is required + $structureKinds[] = \T_MATCH; + } + } + return $structureKinds; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php new file mode 100644 index 00000000000..9069e9ac7e9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoSuperfluousElseifFixer.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoSuperfluousElseifFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ELSE, \T_ELSEIF]); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replaces superfluous `elseif` with `if`.', [new CodeSample(" $token) { + if ($this->isElseif($tokens, $index) && $this->isSuperfluousElse($tokens, $index)) { + $this->convertElseifToIf($tokens, $index); + } + } + } + private function isElseif(Tokens $tokens, int $index) : bool + { + return $tokens[$index]->isGivenKind(\T_ELSEIF) || $tokens[$index]->isGivenKind(\T_ELSE) && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_IF); + } + private function convertElseifToIf(Tokens $tokens, int $index) : void + { + 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]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php new file mode 100644 index 00000000000..4ee3f0d8ede --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoTrailingCommaInListCallFixer.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @deprecated + * + * @author Dariusz Rumiński + */ +final class NoTrailingCommaInListCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove trailing commas in list function calls.', [new CodeSample("proxyFixers); + } + protected function createProxyFixers() : array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['array_destructuring']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php new file mode 100644 index 00000000000..b99f9f10086 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededControlParenthesesFixer.php @@ -0,0 +1,523 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Sullivan Senechal + * @author Dariusz Rumiński + * @author Gregor Harlan + */ +final class NoUnneededControlParenthesesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var int[] + */ + private const BLOCK_TYPES = [Tokens::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE, Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, Tokens::BLOCK_TYPE_CURLY_BRACE, Tokens::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE, Tokens::BLOCK_TYPE_DYNAMIC_PROP_BRACE, Tokens::BLOCK_TYPE_DYNAMIC_VAR_BRACE, Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, Tokens::BLOCK_TYPE_PARENTHESIS_BRACE]; + private const BEFORE_TYPES = [ + ';', + '{', + [\T_OPEN_TAG], + [\T_OPEN_TAG_WITH_ECHO], + [\T_ECHO], + [\T_PRINT], + [\T_RETURN], + [\T_THROW], + [\T_YIELD], + [\T_YIELD_FROM], + [\T_BREAK], + [\T_CONTINUE], + // won't be fixed, but true in concept, helpful for fast check + [\T_REQUIRE], + [\T_REQUIRE_ONCE], + [\T_INCLUDE], + [\T_INCLUDE_ONCE], + ]; + private const CONFIG_OPTIONS = ['break', 'clone', 'continue', 'echo_print', 'negative_instanceof', 'others', 'return', 'switch_case', 'yield', 'yield_from']; + private const TOKEN_TYPE_CONFIG_MAP = [\T_BREAK => 'break', \T_CASE => 'switch_case', \T_CONTINUE => 'continue', \T_ECHO => 'echo_print', \T_PRINT => 'echo_print', \T_RETURN => 'return', \T_YIELD => 'yield', \T_YIELD_FROM => 'yield_from']; + // handled by the `include` rule + private const TOKEN_TYPE_NO_CONFIG = [\T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE]; + /** + * @var list|string> + */ + private $noopTypes; + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + public function __construct() + { + parent::__construct(); + $this->noopTypes = [ + '$', + [\T_CONSTANT_ENCAPSED_STRING], + [\T_DNUMBER], + [\T_DOUBLE_COLON], + [\T_LNUMBER], + [\T_NS_SEPARATOR], + [\T_STRING], + [\T_VARIABLE], + [\T_STATIC], + // magic constants + [\T_CLASS_C], + [\T_DIR], + [\T_FILE], + [\T_FUNC_C], + [\T_LINE], + [\T_METHOD_C], + [\T_NS_C], + [\T_TRAIT_C], + ]; + foreach (Token::getObjectOperatorKinds() as $kind) { + $this->noopTypes[] = [$kind]; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes unneeded parentheses around control statements.', [new CodeSample(' ['break', 'continue']])]); + } + /** + * {@inheritdoc} + * + * Must run before ConcatSpaceFixer, NoTrailingWhitespaceFixer. + * Must run after ModernizeTypesCastingFixer, NoAlternativeSyntaxFixer. + */ + public function getPriority() : int + { + return 30; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(['(', CT::T_BRACE_CLASS_INSTANTIATION_OPEN]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + foreach ($tokens as $openIndex => $token) { + if ($token->equals('(')) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + } elseif ($token->isGivenKind(CT::T_BRACE_CLASS_INSTANTIATION_OPEN)) { + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION, $openIndex); + } else { + continue; + } + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($openIndex); + $afterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + // do a cheap check for negative case: `X()` + if ($tokens->getNextMeaningfulToken($openIndex) === $closeIndex) { + if ($this->isExitStatement($tokens, $beforeOpenIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'others'); + } + continue; + } + // do a cheap check for negative case: `foo(1,2)` + if ($this->isKnownNegativePre($tokens[$beforeOpenIndex])) { + continue; + } + // check for the simple useless wrapped cases + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + continue; + } + // handle `clone` statements + if ($this->isCloneStatement($tokens, $beforeOpenIndex)) { + if ($this->isWrappedCloneArgument($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, 'clone'); + } + continue; + } + // handle `instance of` statements + $instanceOfIndex = $this->getIndexOfInstanceOfStatement($tokens, $openIndex, $closeIndex); + if (null !== $instanceOfIndex) { + if ($this->isWrappedInstanceOf($tokens, $instanceOfIndex, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $tokens[$beforeOpenIndex]->equals('!') ? 'negative_instanceof' : 'others'); + } + continue; + } + // last checks deal with operators, do not swap around + if ($this->isWrappedPartOfOperation($tokens, $beforeOpenIndex, $openIndex, $closeIndex, $afterCloseIndex)) { + $this->removeUselessParenthesisPair($tokens, $beforeOpenIndex, $afterCloseIndex, $openIndex, $closeIndex, $this->getConfigType($tokens, $beforeOpenIndex)); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $defaults = \array_filter(self::CONFIG_OPTIONS, static function (string $option) : bool { + return 'negative_instanceof' !== $option && 'others' !== $option && 'yield_from' !== $option; + }); + return new FixerConfigurationResolver([(new FixerOptionBuilder('statements', 'List of control statements to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(self::CONFIG_OPTIONS)])->setDefault(\array_values($defaults))->getOption()]); + } + private function isUselessWrapped(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex) : bool + { + return $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedLanguageConstructArgument($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + private function isExitStatement(Tokens $tokens, int $beforeOpenIndex) : bool + { + return $tokens[$beforeOpenIndex]->isGivenKind(\T_EXIT); + } + private function isCloneStatement(Tokens $tokens, int $beforeOpenIndex) : bool + { + return $tokens[$beforeOpenIndex]->isGivenKind(\T_CLONE); + } + private function isWrappedCloneArgument(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex) : bool + { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + if (!($tokens[$beforeOpenIndex]->equals('?') || $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex))) { + return \false; + } + $newCandidateIndex = $tokens->getNextMeaningfulToken($openIndex); + if ($tokens[$newCandidateIndex]->isGivenKind(\T_NEW)) { + $openIndex = $newCandidateIndex; + // `clone (new X)`, `clone (new X())`, clone (new X(Y))` + } + return !$this->containsOperation($tokens, $openIndex, $closeIndex); + } + private function getIndexOfInstanceOfStatement(Tokens $tokens, int $openIndex, int $closeIndex) : ?int + { + $instanceOfIndex = $tokens->findGivenKind(\T_INSTANCEOF, $openIndex, $closeIndex); + \reset($instanceOfIndex); + return 1 === \count($instanceOfIndex) ? \key($instanceOfIndex) : null; + } + private function isWrappedInstanceOf(Tokens $tokens, int $instanceOfIndex, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex) : bool + { + if ($this->containsOperation($tokens, $openIndex, $instanceOfIndex) || $this->containsOperation($tokens, $instanceOfIndex, $closeIndex)) { + return \false; + } + if ($tokens[$beforeOpenIndex]->equals('!')) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + return $this->isSimpleAssignment($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isSingleStatement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedFnBody($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedForElement($tokens, $beforeOpenIndex, $afterCloseIndex) || $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + private function isWrappedPartOfOperation(Tokens $tokens, int $beforeOpenIndex, int $openIndex, int $closeIndex, int $afterCloseIndex) : bool + { + if ($this->containsOperation($tokens, $openIndex, $closeIndex)) { + return \false; + } + $boundariesMoved = \false; + if ($this->isPreUnaryOperation($tokens, $beforeOpenIndex)) { + $beforeOpenIndex = $this->getBeforePreUnaryOperation($tokens, $beforeOpenIndex); + $boundariesMoved = \true; + } + if ($this->isAccess($tokens, $afterCloseIndex)) { + $afterCloseIndex = $this->getAfterAccess($tokens, $afterCloseIndex); + $boundariesMoved = \true; + if ($this->tokensAnalyzer->isUnarySuccessorOperator($afterCloseIndex)) { + // post unary operation are only valid here + $afterCloseIndex = $tokens->getNextMeaningfulToken($afterCloseIndex); + } + } + if ($boundariesMoved) { + if ($this->isKnownNegativePre($tokens[$beforeOpenIndex])) { + return \false; + } + if ($this->isUselessWrapped($tokens, $beforeOpenIndex, $afterCloseIndex)) { + return \true; + } + } + // check if part of some operation sequence + $beforeIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($beforeOpenIndex); + $afterIsBinaryOperation = $this->tokensAnalyzer->isBinaryOperator($afterCloseIndex); + if ($beforeIsBinaryOperation && $afterIsBinaryOperation) { + return \true; + // `+ (x) +` + } + $beforeToken = $tokens[$beforeOpenIndex]; + $afterToken = $tokens[$afterCloseIndex]; + $beforeIsBlockOpenOrComma = $beforeToken->equals(',') || null !== $this->getBlock($tokens, $beforeOpenIndex, \true); + $afterIsBlockEndOrComma = $afterToken->equals(',') || null !== $this->getBlock($tokens, $afterCloseIndex, \false); + if ($beforeIsBlockOpenOrComma && $afterIsBinaryOperation || $beforeIsBinaryOperation && $afterIsBlockEndOrComma) { + // $beforeIsBlockOpenOrComma && $afterIsBlockEndOrComma is covered by `isWrappedSequenceElement` + // `[ (x) +` or `+ (X) ]` or `, (X) +` or `+ (X) ,` + return \true; + } + if ($tokens[$beforeOpenIndex]->equals('}')) { + $beforeIsStatementOpen = !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } else { + $beforeIsStatementOpen = $beforeToken->equalsAny(self::BEFORE_TYPES) || $beforeToken->isGivenKind(\T_CASE); + } + $afterIsStatementEnd = $afterToken->equalsAny([';', [\T_CLOSE_TAG]]); + return $beforeIsStatementOpen && $afterIsBinaryOperation || $beforeIsBinaryOperation && $afterIsStatementEnd; + // `+ (X);` + } + // bounded `print|yield|yield from|require|require_once|include|include_once (X)` + private function isWrappedLanguageConstructArgument(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex) : bool + { + if (!$tokens[$beforeOpenIndex]->isGivenKind([\T_PRINT, \T_YIELD, \T_YIELD_FROM, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE])) { + return \false; + } + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + return $this->isWrappedSequenceElement($tokens, $beforeOpenIndex, $afterCloseIndex); + } + // any of `isGivenKind(\T_CASE)) { + return $tokens[$afterCloseIndex]->equalsAny([':', ';']); + // `switch case` + } + if (!$tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + return \false; + } + if ($tokens[$beforeOpenIndex]->equals('}')) { + return !$this->closeCurlyBelongsToDynamicElement($tokens, $beforeOpenIndex); + } + return $tokens[$beforeOpenIndex]->equalsAny(self::BEFORE_TYPES); + } + private function isSimpleAssignment(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex) : bool + { + return $tokens[$beforeOpenIndex]->equals('=') && $tokens[$afterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG]]); + // `= (X) ;` + } + private function isWrappedSequenceElement(Tokens $tokens, int $startIndex, int $endIndex) : bool + { + $startIsComma = $tokens[$startIndex]->equals(','); + $endIsComma = $tokens[$endIndex]->equals(','); + if ($startIsComma && $endIsComma) { + return \true; + // `,(X),` + } + $blockTypeStart = $this->getBlock($tokens, $startIndex, \true); + $blockTypeEnd = $this->getBlock($tokens, $endIndex, \false); + return $startIsComma && null !== $blockTypeEnd || $endIsComma && null !== $blockTypeStart || null !== $blockTypeEnd && null !== $blockTypeStart; + // any type of `{(X)}`, `[(X)]` and `((X))` + } + // any of `for( (X); ;(X)) ;` note that the middle element is covered as 'single statement' as it is `; (X) ;` + private function isWrappedForElement(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex) : bool + { + $forCandidateIndex = null; + if ($tokens[$beforeOpenIndex]->equals('(') && $tokens[$afterCloseIndex]->equals(';')) { + $forCandidateIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } elseif ($tokens[$afterCloseIndex]->equals(')') && $tokens[$beforeOpenIndex]->equals(';')) { + $forCandidateIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $afterCloseIndex); + $forCandidateIndex = $tokens->getPrevMeaningfulToken($forCandidateIndex); + } + return null !== $forCandidateIndex && $tokens[$forCandidateIndex]->isGivenKind(\T_FOR); + } + // `fn() => (X);` + private function isWrappedFnBody(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex) : bool + { + if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_DOUBLE_ARROW)) { + return \false; + } + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + if ($tokens[$beforeOpenIndex]->isGivenKind(\T_STRING)) { + while (\true) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + if (!$tokens[$beforeOpenIndex]->isGivenKind([\T_STRING, CT::T_TYPE_INTERSECTION, CT::T_TYPE_ALTERNATION])) { + break; + } + } + if (!$tokens[$beforeOpenIndex]->isGivenKind(CT::T_TYPE_COLON)) { + return \false; + } + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + if (!$tokens[$beforeOpenIndex]->equals(')')) { + return \false; + } + $beforeOpenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $beforeOpenIndex); + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + if ($tokens[$beforeOpenIndex]->isGivenKind(CT::T_RETURN_REF)) { + $beforeOpenIndex = $tokens->getPrevMeaningfulToken($beforeOpenIndex); + } + if (!$tokens[$beforeOpenIndex]->isGivenKind(\T_FN)) { + return \false; + } + return $tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]); + } + private function isPreUnaryOperation(Tokens $tokens, int $index) : bool + { + return $this->tokensAnalyzer->isUnaryPredecessorOperator($index) || $tokens[$index]->isCast(); + } + private function getBeforePreUnaryOperation(Tokens $tokens, int $index) : int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($this->isPreUnaryOperation($tokens, $index)); + return $index; + } + // array access `(X)[` or `(X){` or object access `(X)->` or `(X)?->` + private function isAccess(Tokens $tokens, int $index) : bool + { + $token = $tokens[$index]; + return $token->isObjectOperator() || $token->equals('[') || $token->isGivenKind([CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]); + } + private function getAfterAccess(Tokens $tokens, int $index) : int + { + while (\true) { + $block = $this->getBlock($tokens, $index, \true); + if (null !== $block) { + $index = $tokens->findBlockEnd($block['type'], $index); + $index = $tokens->getNextMeaningfulToken($index); + continue; + } + if ($tokens[$index]->isObjectOperator() || $tokens[$index]->equalsAny(['$', [\T_PAAMAYIM_NEKUDOTAYIM], [\T_STRING], [\T_VARIABLE]])) { + $index = $tokens->getNextMeaningfulToken($index); + continue; + } + break; + } + return $index; + } + /** + * @return null|array{type: Tokens::BLOCK_TYPE_*, isStart: bool} + */ + private function getBlock(Tokens $tokens, int $index, bool $isStart) : ?array + { + $block = Tokens::detectBlockType($tokens[$index]); + return null !== $block && $isStart === $block['isStart'] && \in_array($block['type'], self::BLOCK_TYPES, \true) ? $block : null; + } + // cheap check on a tokens type before `(` of which we know the `(` will never be superfluous + private function isKnownNegativePre(Token $token) : bool + { + static $knownNegativeTypes; + if (null === $knownNegativeTypes) { + $knownNegativeTypes = [ + [CT::T_CLASS_CONSTANT], + [CT::T_DYNAMIC_VAR_BRACE_CLOSE], + [CT::T_RETURN_REF], + [CT::T_USE_LAMBDA], + [\T_ARRAY], + [\T_CATCH], + [\T_CLASS], + [\T_DECLARE], + [\T_ELSEIF], + [\T_EMPTY], + [\T_EXIT], + [\T_EVAL], + [\T_FN], + [\T_FOREACH], + [\T_FOR], + [\T_FUNCTION], + [\T_HALT_COMPILER], + [\T_IF], + [\T_ISSET], + [\T_LIST], + [\T_STRING], + [\T_SWITCH], + [\T_STATIC], + [\T_UNSET], + [\T_VARIABLE], + [\T_WHILE], + // handled by the `include` rule + [\T_REQUIRE], + [\T_REQUIRE_ONCE], + [\T_INCLUDE], + [\T_INCLUDE_ONCE], + ]; + if (\defined('T_MATCH')) { + // @TODO: drop condition and add directly in `$knownNegativeTypes` above when PHP 8.0+ is required + $knownNegativeTypes[] = \T_MATCH; + } + } + return $token->equalsAny($knownNegativeTypes); + } + private function containsOperation(Tokens $tokens, int $startIndex, int $endIndex) : bool + { + while (\true) { + $startIndex = $tokens->getNextMeaningfulToken($startIndex); + if ($startIndex === $endIndex) { + break; + } + $block = Tokens::detectBlockType($tokens[$startIndex]); + if (null !== $block && $block['isStart']) { + $startIndex = $tokens->findBlockEnd($block['type'], $startIndex); + continue; + } + if (!$tokens[$startIndex]->equalsAny($this->noopTypes)) { + return \true; + } + } + return \false; + } + private function getConfigType(Tokens $tokens, int $beforeOpenIndex) : ?string + { + if ($tokens[$beforeOpenIndex]->isGivenKind(self::TOKEN_TYPE_NO_CONFIG)) { + return null; + } + foreach (self::TOKEN_TYPE_CONFIG_MAP as $type => $configItem) { + if ($tokens[$beforeOpenIndex]->isGivenKind($type)) { + return $configItem; + } + } + return 'others'; + } + private function removeUselessParenthesisPair(Tokens $tokens, int $beforeOpenIndex, int $afterCloseIndex, int $openIndex, int $closeIndex, ?string $configType) : void + { + $statements = $this->configuration['statements']; + if (null === $configType || !\in_array($configType, $statements, \true)) { + return; + } + $needsSpaceAfter = !$this->isAccess($tokens, $afterCloseIndex) && !$tokens[$afterCloseIndex]->equalsAny([';', ',', [\T_CLOSE_TAG]]) && null === $this->getBlock($tokens, $afterCloseIndex, \false) && !($tokens[$afterCloseIndex]->equalsAny([':', ';']) && $tokens[$beforeOpenIndex]->isGivenKind(\T_CASE)); + $needsSpaceBefore = !$this->isPreUnaryOperation($tokens, $beforeOpenIndex) && !$tokens[$beforeOpenIndex]->equalsAny(['}', [\T_EXIT], [\T_OPEN_TAG]]) && null === $this->getBlock($tokens, $beforeOpenIndex, \true); + $this->removeBrace($tokens, $closeIndex, $needsSpaceAfter); + $this->removeBrace($tokens, $openIndex, $needsSpaceBefore); + } + private function removeBrace(Tokens $tokens, int $index, bool $needsSpace) : void + { + if ($needsSpace) { + foreach ([-1, 1] as $direction) { + $siblingIndex = $tokens->getNonEmptySibling($index, $direction); + if ($tokens[$siblingIndex]->isWhitespace() || $tokens[$siblingIndex]->isComment()) { + $needsSpace = \false; + break; + } + } + } + if ($needsSpace) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + private function closeCurlyBelongsToDynamicElement(Tokens $tokens, int $beforeOpenIndex) : bool + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $beforeOpenIndex); + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + return \true; + } + if ($tokens[$index]->equals(':')) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_CASE], '?']); + return !$tokens[$index]->isGivenKind(\T_CASE); + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php new file mode 100644 index 00000000000..604ca0bedef --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUnneededCurlyBracesFixer.php @@ -0,0 +1,126 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUnneededCurlyBracesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes unneeded curly braces that are superfluous and aren\'t part of a control structure\'s body.', [new CodeSample(' \true])]); + } + /** + * {@inheritdoc} + * + * Must run before NoUselessElseFixer, NoUselessReturnFixer, ReturnAssignmentFixer, SimplifiedIfReturnFixer. + */ + public function getPriority() : int + { + return 40; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('}'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($this->findCurlyBraceOpen($tokens) as $index) { + if ($this->isOverComplete($tokens, $index)) { + $this->clearOverCompleteBraces($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); + } + } + if (\true === $this->configuration['namespaces']) { + $this->clearIfIsOverCompleteNamespaceBlock($tokens); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('namespaces', 'Remove unneeded curly braces from bracketed namespaces.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * @param int $openIndex index of `{` token + * @param int $closeIndex index of `}` token + */ + private function clearOverCompleteBraces(Tokens $tokens, int $openIndex, int $closeIndex) : void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + } + /** + * @return iterable + */ + private function findCurlyBraceOpen(Tokens $tokens) : iterable + { + for ($i = \count($tokens) - 1; $i > 0; --$i) { + if ($tokens[$i]->equals('{')) { + (yield $i); + } + } + } + /** + * @param int $index index of `{` token + */ + private function isOverComplete(Tokens $tokens, int $index) : bool + { + static $include = ['{', '}', [\T_OPEN_TAG], ':', ';']; + return $tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny($include); + } + private function clearIfIsOverCompleteNamespaceBlock(Tokens $tokens) : void + { + if (1 !== $tokens->countTokenKind(\T_NAMESPACE)) { + return; + // fast check, we never fix if multiple namespaces are defined + } + $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; + } + // clear up + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + $tokens[$index] = new Token(';'); + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index - 1); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php new file mode 100644 index 00000000000..2b2be22922c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/NoUselessElseFixer.php @@ -0,0 +1,100 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractNoUselessElseFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUselessElseFixer extends AbstractNoUselessElseFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_ELSE); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be useless `else` cases.', [new CodeSample(" $token) { + if (!$token->isGivenKind(\T_ELSE)) { + continue; + } + // `else if` vs. `else` and alternative syntax `else:` checks + if ($tokens[$tokens->getNextMeaningfulToken($index)]->equalsAny([':', [\T_IF]])) { + continue; + } + // clean up `else` if it is an empty statement + $this->fixEmptyElse($tokens, $index); + if ($tokens->isEmptyAt($index)) { + continue; + } + // clean up `else` if possible + if ($this->isSuperfluousElse($tokens, $index)) { + $this->clearElse($tokens, $index); + } + } + } + /** + * Remove tokens part of an `else` statement if not empty (i.e. no meaningful tokens inside). + * + * @param int $index T_ELSE index + */ + private function fixEmptyElse(Tokens $tokens, int $index) : void + { + $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; + } + // short `else` + $end = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + if ($next === $end) { + $this->clearElse($tokens, $index); + } + } + /** + * @param int $index index of T_ELSE + */ + private function clearElse(Tokens $tokens, int $index) : void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + // clear T_ELSE and the '{' '}' if there are any + $next = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$next]->equals('{')) { + return; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $next)); + $tokens->clearTokenAndMergeSurroundingWhitespace($next); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php new file mode 100644 index 00000000000..eee31f39541 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SimplifiedIfReturnFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class SimplifiedIfReturnFixer extends AbstractFixer +{ + /** + * @var list|string>}> + */ + 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() : FixerDefinitionInterface + { + return new FixerDefinition('Simplify `if` control structures that return the boolean result of their condition.', [new CodeSample("isAllTokenKindsFound([\T_IF, \T_RETURN, \T_STRING]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($ifIndex = $tokens->count() - 1; 0 <= $ifIndex; --$ifIndex) { + if (!$tokens[$ifIndex]->isGivenKind([\T_IF, \T_ELSEIF])) { + continue; + } + if ($tokens[$tokens->getPrevMeaningfulToken($ifIndex)]->equals(')')) { + continue; + // in a loop without braces + } + $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; + } + $indicesToClear = \array_keys($sequenceFound); + \array_pop($indicesToClear); + // Preserve last semicolon + \rsort($indicesToClear); + foreach ($indicesToClear 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); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php new file mode 100644 index 00000000000..3e3901e08c7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSemicolonToColonFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶5.2. + */ +final class SwitchCaseSemicolonToColonFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('A case should be followed by a colon and not a semicolon.', [new CodeSample('isTokenKindFound(\T_SWITCH); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + if (null !== $default) { + $this->fixTokenIfNeeded($tokens, $default->getColonIndex()); + } + foreach ($analysis->getCases() as $caseAnalysis) { + $this->fixTokenIfNeeded($tokens, $caseAnalysis->getColonIndex()); + } + } + } + private function fixTokenIfNeeded(Tokens $tokens, int $index) : void + { + if ($tokens[$index]->equals(';')) { + $tokens[$index] = new Token(':'); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php new file mode 100644 index 00000000000..d03d8396aa9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchCaseSpaceFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶5.2. + * + * @author Sullivan Senechal + */ +final class SwitchCaseSpaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes extra spaces between colon and case value.', [new CodeSample('isTokenKindFound(\T_SWITCH); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + $default = $analysis->getDefaultAnalysis(); + if (null !== $default) { + $index = $default->getIndex(); + if (!$tokens[$index + 1]->isWhitespace() || !$tokens[$index + 2]->equalsAny([':', ';'])) { + continue; + } + $tokens->clearAt($index + 1); + } + foreach ($analysis->getCases() as $caseAnalysis) { + $colonIndex = $caseAnalysis->getColonIndex(); + $valueIndex = $tokens->getPrevNonWhitespace($colonIndex); + // skip if there is no space between the colon and previous token or is space after comment + if ($valueIndex === $colonIndex - 1 || $tokens[$valueIndex]->isComment()) { + continue; + } + $tokens->clearAt($valueIndex + 1); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php new file mode 100644 index 00000000000..166125a87b6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/SwitchContinueToBreakFixer.php @@ -0,0 +1,192 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SwitchContinueToBreakFixer extends AbstractFixer +{ + /** + * @var int[] + */ + private $switchLevels = []; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Switch case must not be ended with `continue` but with `break`.', [new CodeSample(' 3) { + continue; + } + + continue 2; + } +} +')]); + } + /** + * {@inheritdoc} + * + * Must run after NoAlternativeSyntaxFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAllTokenKindsFound([\T_SWITCH, \T_CONTINUE]) && !$tokens->hasAlternativeSyntax(); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $count = \count($tokens); + for ($index = 1; $index < $count - 1; ++$index) { + $index = $this->doFix($tokens, $index, 0, \false); + } + } + /** + * @param int $depth >= 0 + */ + private function doFix(Tokens $tokens, int $index, int $depth, bool $isInSwitch) : int + { + $token = $tokens[$index]; + if ($token->isGivenKind([\T_FOREACH, \T_FOR, \T_WHILE])) { + // go to first `(`, go to its close ')', go to first of '{', ';', '? >' + $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, int $switchIndex, int $depth) : int + { + $this->switchLevels[] = $depth; + // figure out where the switch starts + $openIndex = $tokens->getNextTokenOfKind($switchIndex, ['{']); + // figure out where the switch ends + $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, int $openIndex, int $depth) : int + { + $openCount = 1; + while (\true) { + ++$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); + } + return $openIndex; + } + private function fixContinueWhenActsAsBreak(Tokens $tokens, int $continueIndex, bool $isInSwitch, int $depth) : int + { + $followingContinueIndex = $tokens->getNextMeaningfulToken($continueIndex); + $followingContinueToken = $tokens[$followingContinueIndex]; + if ($isInSwitch && $followingContinueToken->equals(';')) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); + // short continue 1 notation + return $followingContinueIndex; + } + if (!$followingContinueToken->isGivenKind(\T_LNUMBER)) { + return $followingContinueIndex; + } + $afterFollowingContinueIndex = $tokens->getNextMeaningfulToken($followingContinueIndex); + if (!$tokens[$afterFollowingContinueIndex]->equals(';')) { + return $afterFollowingContinueIndex; + // if next not is `;` return without fixing, for example `continue 1 ? >getContent(); + $jump = \str_replace('_', '', $jump); + // support for numeric_literal_separator + if (\strlen($jump) > 2 && 'x' === $jump[1]) { + $jump = \hexdec($jump); + // hexadecimal - 0x1 + } elseif (\strlen($jump) > 2 && 'b' === $jump[1]) { + $jump = \bindec($jump); + // binary - 0b1 + } elseif (\strlen($jump) > 1 && '0' === $jump[0]) { + $jump = \octdec($jump); + // octal 01 + } elseif (Preg::match('#^\\d+$#', $jump)) { + // positive int + $jump = (float) $jump; + // cast to float, might be a number bigger than PHP max. int value + } else { + return $afterFollowingContinueIndex; + // cannot process value, ignore + } + if ($jump > \PHP_INT_MAX) { + return $afterFollowingContinueIndex; + // cannot process value, ignore + } + $jump = (int) $jump; + if ($isInSwitch && (1 === $jump || 0 === $jump)) { + $this->replaceContinueWithBreakToken($tokens, $continueIndex); + // long continue 0/1 notation + 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, int $index) : void + { + $tokens[$index] = new Token([\T_BREAK, 'break']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php new file mode 100644 index 00000000000..26cc05a38a2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/TrailingCommaInMultilineFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Kuba Werłos + */ +final class TrailingCommaInMultilineFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const ELEMENTS_ARRAYS = 'arrays'; + /** + * @internal + */ + public const ELEMENTS_ARGUMENTS = 'arguments'; + /** + * @internal + */ + public const ELEMENTS_PARAMETERS = 'parameters'; + private const MATCH_EXPRESSIONS = 'match'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Multi-line arrays, arguments list, parameters list and `match` expressions must have a trailing comma.', [new CodeSample(" \true]), new VersionSpecificCodeSample(" [self::ELEMENTS_ARGUMENTS]]), new VersionSpecificCodeSample(" [self::ELEMENTS_PARAMETERS]])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN, '(']); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('after_heredoc', 'Whether a trailing comma should also be placed after heredoc end.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('elements', \sprintf('Where to fix multiline trailing comma (PHP >= 8.0 for `%s` and `%s`).', self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS)))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset([self::ELEMENTS_ARRAYS, self::ELEMENTS_ARGUMENTS, self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS])])->setDefault([self::ELEMENTS_ARRAYS])->setNormalizer(static function (Options $options, $value) { + if (\PHP_VERSION_ID < 80000) { + // @TODO: drop condition when PHP 8.0+ is required + foreach ([self::ELEMENTS_PARAMETERS, self::MATCH_EXPRESSIONS] as $option) { + if (\in_array($option, $value, \true)) { + throw new InvalidOptionsForEnvException(\sprintf('"%s" option can only be enabled with PHP 8.0+.', $option)); + } + } + } + return $value; + })->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $fixArrays = \in_array(self::ELEMENTS_ARRAYS, $this->configuration['elements'], \true); + $fixArguments = \in_array(self::ELEMENTS_ARGUMENTS, $this->configuration['elements'], \true); + $fixParameters = \PHP_VERSION_ID >= 80000 && \in_array(self::ELEMENTS_PARAMETERS, $this->configuration['elements'], \true); + // @TODO: drop condition when PHP 8.0+ is required + $fixMatch = \PHP_VERSION_ID >= 80000 && \in_array(self::MATCH_EXPRESSIONS, $this->configuration['elements'], \true); + // @TODO: drop condition when PHP 8.0+ is required + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($fixArrays && ($tokens[$index]->equals('(') && $tokens[$prevIndex]->isGivenKind(\T_ARRAY) || $tokens[$index]->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN))) { + $this->fixBlock($tokens, $index); + continue; + } + if (!$tokens[$index]->equals('(')) { + continue; + } + $prevPrevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if ($fixArguments && $tokens[$prevIndex]->equalsAny([']', [\T_CLASS], [\T_STRING], [\T_VARIABLE], [\T_STATIC]]) && !$tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION)) { + $this->fixBlock($tokens, $index); + continue; + } + if ($fixParameters && ($tokens[$prevIndex]->isGivenKind(\T_STRING) && $tokens[$prevPrevIndex]->isGivenKind(\T_FUNCTION) || $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]))) { + $this->fixBlock($tokens, $index); + } + if ($fixMatch && $tokens[$prevIndex]->isGivenKind(\T_MATCH)) { + $this->fixMatch($tokens, $index); + } + } + } + private function fixBlock(Tokens $tokens, int $startIndex) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + if (!$tokensAnalyzer->isBlockMultiline($tokens, $startIndex)) { + return; + } + $blockType = Tokens::detectBlockType($tokens[$startIndex]); + $endIndex = $tokens->findBlockEnd($blockType['type'], $startIndex); + $beforeEndIndex = $tokens->getPrevMeaningfulToken($endIndex); + if (!$tokens->isPartialCodeMultiline($beforeEndIndex, $endIndex)) { + return; + } + $beforeEndToken = $tokens[$beforeEndIndex]; + // if there is some item between braces then add `,` after it + if ($startIndex !== $beforeEndIndex && !$beforeEndToken->equals(',') && (\true === $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, ' '); + } + } + } + private function fixMatch(Tokens $tokens, int $index) : void + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $closeIndex = $index; + $isMultiline = \false; + $depth = 1; + do { + ++$closeIndex; + if ($tokens[$closeIndex]->equals('{')) { + ++$depth; + } elseif ($tokens[$closeIndex]->equals('}')) { + --$depth; + } elseif (!$isMultiline && \strpos($tokens[$closeIndex]->getContent(), "\n") !== \false) { + $isMultiline = \true; + } + } while ($depth > 0); + if (!$isMultiline) { + return; + } + $previousIndex = $tokens->getPrevMeaningfulToken($closeIndex); + if (!$tokens->isPartialCodeMultiline($previousIndex, $closeIndex)) { + return; + } + if (!$tokens[$previousIndex]->equals(',')) { + $tokens->insertAt($previousIndex + 1, new Token(',')); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php new file mode 100644 index 00000000000..a4a6be70b42 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ControlStructure/YodaStyleFixer.php @@ -0,0 +1,549 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ControlStructure; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Bram Gotink + * @author Dariusz Rumiński + */ +final class YodaStyleFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private $candidatesMap; + /** + * @var array + */ + private $candidateTypesConfiguration; + /** + * @var array + */ + private $candidateTypes; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->resolveConfiguration(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Write conditions in Yoda style (`true`), non-Yoda style (`[\'equal\' => false, \'identical\' => false, \'less_and_greater\' => false]`) or ignore those conditions (`null`) based on configuration.', [new CodeSample(' 3; // less than +', ['equal' => \true, 'identical' => \false, 'less_and_greater' => null]), new CodeSample(' \true]), new CodeSample(' \false, 'identical' => \false, 'less_and_greater' => \false])]); + } + /** + * {@inheritdoc} + * + * Must run after IsNullFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound($this->candidateTypes); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->fixTokens($tokens); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + /** + * Finds the end of the right-hand side of the comparison at the given + * index. + * + * The right-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The last index of the right-hand side of the comparison + */ + private function findComparisonEnd(Tokens $tokens, int $index) : int + { + ++$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; + } + /** + * Finds the start of the left-hand side of the comparison at the given + * index. + * + * The left-hand side ends when an operator with a lower precedence is + * encountered or when the block level for `()`, `{}` or `[]` goes below + * zero. + * + * @param Tokens $tokens The token list + * @param int $index The index of the comparison + * + * @return int The first index of the left-hand side of the comparison + */ + private function findComparisonStart(Tokens $tokens, int $index) : int + { + --$index; + $nonBlockFound = \false; + while (0 <= $index) { + $token = $tokens[$index]; + if ($token->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + --$index; + continue; + } + if ($token->isGivenKind([CT::T_NAMED_ARGUMENT_COLON])) { + break; + } + 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) : 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; + } + /** + * Fixes the comparison at the given index. + * + * A comparison is considered fixed when + * - both sides are a variable (e.g. $a === $b) + * - neither side is a variable (e.g. self::CONST === 3) + * - only the right-hand side is a variable (e.g. 3 === self::$var) + * + * If the left-hand side and right-hand side of the given comparison are + * swapped, this function runs recursively on the previous left-hand-side. + * + * @return int an upper bound for all non-fixed comparisons + */ + private function fixTokensCompare(Tokens $tokens, int $startLeft, int $endLeft, int $compareOperatorIndex, int $startRight, int $endRight) : int + { + $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, int $start, int $end) : Tokens + { + $newTokens = $tokens->generatePartialCode($start, $end); + $newTokens = $this->fixTokens(Tokens::fromCode(\sprintf('clearAt(\count($newTokens) - 1); + $newTokens->clearAt(0); + $newTokens->clearEmptyTokens(); + return $newTokens; + } + private function getCompareFixableInfo(Tokens $tokens, int $index, bool $yoda) : ?array + { + $left = $this->getLeftSideCompareFixableInfo($tokens, $index); + $right = $this->getRightSideCompareFixableInfo($tokens, $index); + if (!$yoda && $this->isOfLowerPrecedenceAssignment($tokens[$tokens->getNextMeaningfulToken($right['end'])])) { + return null; + } + if ($this->isListStatement($tokens, $left['start'], $left['end']) || $this->isListStatement($tokens, $right['start'], $right['end'])) { + return null; + // do not fix lists assignment inside statements + } + /** @var bool $strict */ + $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 xor $rightSideIsVariable)) { + return null; + // both are (not) variables, do not touch + } + if (!$strict) { + // special handling for braces with not "always_move_variable" + $leftSideIsVariable = $leftSideIsVariable && !$tokens[$left['start']]->equals('('); + $rightSideIsVariable = $rightSideIsVariable && !$tokens[$right['start']]->equals('('); + } + return $yoda && !$leftSideIsVariable || !$yoda && !$rightSideIsVariable ? null : ['left' => $left, 'right' => $right]; + } + /** + * @return array{start: int, end: int} + */ + private function getLeftSideCompareFixableInfo(Tokens $tokens, int $index) : array + { + return ['start' => $this->findComparisonStart($tokens, $index), 'end' => $tokens->getPrevMeaningfulToken($index)]; + } + /** + * @return array{start: int, end: int} + */ + private function getRightSideCompareFixableInfo(Tokens $tokens, int $index) : array + { + return ['start' => $tokens->getNextMeaningfulToken($index), 'end' => $this->findComparisonEnd($tokens, $index)]; + } + private function isListStatement(Tokens $tokens, int $index, int $end) : bool + { + 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; + } + /** + * Checks whether the given token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + * + * @param Token $token The token to check + * + * @return bool Whether the token has a lower precedence + */ + private function isOfLowerPrecedence(Token $token) : bool + { + static $tokens; + if (null === $tokens) { + $tokens = [ + \T_BOOLEAN_AND, + // && + \T_BOOLEAN_OR, + // || + \T_CASE, + // case + \T_DOUBLE_ARROW, + // => + \T_ECHO, + // echo + \T_GOTO, + // goto + \T_LOGICAL_AND, + // and + \T_LOGICAL_OR, + // or + \T_LOGICAL_XOR, + // xor + \T_OPEN_TAG, + // isOfLowerPrecedenceAssignment($token) || $token->isGivenKind($tokens) || $token->equalsAny($otherTokens); + } + /** + * Checks whether the given assignment token has a lower precedence than `T_IS_EQUAL` + * or `T_IS_IDENTICAL`. + */ + private function isOfLowerPrecedenceAssignment(Token $token) : bool + { + static $tokens; + if (null === $tokens) { + $tokens = [ + \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, + // ^= + \T_COALESCE_EQUAL, + ]; + } + return $token->equals('=') || $token->isGivenKind($tokens); + } + /** + * Checks whether the tokens between the given start and end describe a + * variable. + * + * @param Tokens $tokens The token list + * @param int $start The first index of the possible variable + * @param int $end The last index of the possible variable + * @param bool $strict Enable strict variable detection + * + * @return bool Whether the tokens describe a variable + */ + private function isVariable(Tokens $tokens, int $start, int $end, bool $strict) : bool + { + $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; + // handle multiple braces around statement ((($a === 1))) + 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; + } + // check if this is the last token + 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]; + // self:: or ClassName:: + if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_DOUBLE_COLON)) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + continue; + } + // \ClassName + if ($current->isGivenKind(\T_NS_SEPARATOR) && $next->isGivenKind(\T_STRING)) { + $index = $nextIndex; + continue; + } + // ClassName\ + if ($current->isGivenKind(\T_STRING) && $next->isGivenKind(\T_NS_SEPARATOR)) { + $index = $nextIndex; + continue; + } + // $a-> or a-> (as in $b->a->c) + if ($current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->isObjectOperator()) { + $index = $tokens->getNextMeaningfulToken($nextIndex); + $expectString = \true; + continue; + } + // $a[...], a[...] (as in $c->a[$b]), $a{...} or a{...} (as in $c->a{$b}) + 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(['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{']]) && !$tokens[$index]->isObjectOperator()) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($index); + $expectString = \true; + continue; + } + // $a(...) or $a->b(...) + if ($strict && $current->isGivenKind([\T_STRING, \T_VARIABLE]) && $next->equals('(')) { + return \false; + } + // {...} (as in $a->{$b}) + 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]->isObjectOperator()) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($index); + $expectString = \true; + continue; + } + break; + } + return !$this->isConstant($tokens, $start, $end); + } + private function isConstant(Tokens $tokens, int $index, int $end) : bool + { + $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() : void + { + $candidateTypes = []; + $this->candidatesMap = []; + if (null !== $this->configuration['equal']) { + // `==`, `!=` and `<>` + $candidateTypes[\T_IS_EQUAL] = $this->configuration['equal']; + $candidateTypes[\T_IS_NOT_EQUAL] = $this->configuration['equal']; + } + if (null !== $this->configuration['identical']) { + // `===` and `!==` + $candidateTypes[\T_IS_IDENTICAL] = $this->configuration['identical']; + $candidateTypes[\T_IS_NOT_IDENTICAL] = $this->configuration['identical']; + } + if (null !== $this->configuration['less_and_greater']) { + // `<`, `<=`, `>` and `>=` + $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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php new file mode 100644 index 00000000000..e029b2fb503 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DeprecatedFixerInterface.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +/** + * @author Kuba Werłos + */ +interface DeprecatedFixerInterface extends \PhpCsFixer\Fixer\FixerInterface +{ + /** + * Returns names of fixers to use instead, if any. + * + * @return string[] + */ + public function getSuccessorsNames() : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php new file mode 100644 index 00000000000..525e7831442 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationArrayAssignmentFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * Forces the configured operator for assignment in arrays in Doctrine Annotations. + */ +final class DoctrineAnnotationArrayAssignmentFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Doctrine annotations must use configured operator for assignment in arrays.', [new CodeSample(" ':'])]); + } + /** + * {@inheritdoc} + * + * Must run before DoctrineAnnotationSpacesFixer. + */ + public function getPriority() : int + { + return 1; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $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 $doctrineAnnotationTokens) : void + { + $scopes = []; + foreach ($doctrineAnnotationTokens 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']); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php new file mode 100644 index 00000000000..0bf4e1d4b3e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationBracesFixer.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * Adds braces to Doctrine annotations when missing. + */ +final class DoctrineAnnotationBracesFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Doctrine annotations without arguments must use the configured syntax.', [new CodeSample(" 'with_braces'])]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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 $doctrineAnnotationTokens) : void + { + if ('without_braces' === $this->configuration['syntax']) { + $this->removesBracesFromAnnotations($doctrineAnnotationTokens); + } else { + $this->addBracesToAnnotations($doctrineAnnotationTokens); + } + } + private function addBracesToAnnotations(Tokens $tokens) : void + { + 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) : void + { + 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(); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php new file mode 100644 index 00000000000..73b0ebef473 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationIndentationFixer.php @@ -0,0 +1,133 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +final class DoctrineAnnotationIndentationFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Doctrine annotations must be indented with four spaces.', [new CodeSample(" \true])]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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 $doctrineAnnotationTokens) : void + { + $annotationPositions = []; + for ($index = 0, $max = \count($doctrineAnnotationTokens); $index < $max; ++$index) { + if (!$doctrineAnnotationTokens[$index]->isType(DocLexer::T_AT)) { + continue; + } + $annotationEndIndex = $doctrineAnnotationTokens->getAnnotationEnd($index); + if (null === $annotationEndIndex) { + return; + } + $annotationPositions[] = [$index, $annotationEndIndex]; + $index = $annotationEndIndex; + } + $indentLevel = 0; + foreach ($doctrineAnnotationTokens as $index => $token) { + if (!$token->isType(DocLexer::T_NONE) || \strpos($token->getContent(), "\n") === \false) { + continue; + } + if (!$this->indentationCanBeFixed($doctrineAnnotationTokens, $index, $annotationPositions)) { + continue; + } + $braces = $this->getLineBracesCount($doctrineAnnotationTokens, $index); + $delta = $braces[0] - $braces[1]; + $mixedBraces = 0 === $delta && $braces[0] > 0; + $extraIndentLevel = 0; + if ($indentLevel > 0 && ($delta < 0 || $mixedBraces)) { + --$indentLevel; + if (\true === $this->configuration['indent_mixed_lines'] && $this->isClosingLineWithMeaningfulContent($doctrineAnnotationTokens, $index)) { + $extraIndentLevel = 1; + } + } + $token->setContent(Preg::replace('/(\\n( +\\*)?) *$/', '$1' . \str_repeat(' ', 4 * ($indentLevel + $extraIndentLevel) + 1), $token->getContent())); + if ($delta > 0 || $mixedBraces) { + ++$indentLevel; + } + } + } + /** + * @return int[] + */ + private function getLineBracesCount(Tokens $tokens, int $index) : array + { + $opening = 0; + $closing = 0; + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE) && \strpos($token->getContent(), "\n") !== \false) { + 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, int $index) : bool + { + while (isset($tokens[++$index])) { + $token = $tokens[$index]; + if ($token->isType(DocLexer::T_NONE)) { + if (\strpos($token->getContent(), "\n") !== \false) { + return \false; + } + continue; + } + return !$token->isType([DocLexer::T_CLOSE_PARENTHESIS, DocLexer::T_CLOSE_CURLY_BRACES]); + } + return \false; + } + /** + * @param array> $annotationPositions Pairs of begin and end indices of main annotations + */ + private function indentationCanBeFixed(Tokens $tokens, int $newLineTokenIndex, array $annotationPositions) : bool + { + 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 (\strpos($token->getContent(), "\n") !== \false) { + return \false; + } + return $tokens[$index]->isType(DocLexer::T_AT); + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php new file mode 100644 index 00000000000..5fcb9150947 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/DoctrineAnnotation/DoctrineAnnotationSpacesFixer.php @@ -0,0 +1,194 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\DoctrineAnnotation; + +use ECSPrefix202307\Doctrine\Common\Annotations\DocLexer; +use PhpCsFixer\AbstractDoctrineAnnotationFixer; +use PhpCsFixer\Doctrine\Annotation\Token; +use PhpCsFixer\Doctrine\Annotation\Tokens; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +/** + * Fixes spaces around commas and assignment operators in Doctrine annotations. + */ +final class DoctrineAnnotationSpacesFixer extends AbstractDoctrineAnnotationFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Fixes spaces in Doctrine annotations.', [new CodeSample(" \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.'); + } + /** + * {@inheritdoc} + * + * Must run after DoctrineAnnotationArrayAssignmentFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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('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('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 $doctrineAnnotationTokens) : void + { + if (\true === $this->configuration['around_parentheses']) { + $this->fixSpacesAroundParentheses($doctrineAnnotationTokens); + } + if (\true === $this->configuration['around_commas']) { + $this->fixSpacesAroundCommas($doctrineAnnotationTokens); + } + 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($doctrineAnnotationTokens); + } + } + private function fixSpacesAroundParentheses(Tokens $tokens) : void + { + $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 (\strpos($token->getContent(), "\n") !== \false) { + continue; + } + $token->clear(); + } + } + } + private function fixSpacesAroundCommas(Tokens $tokens) : void + { + $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) : void + { + $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, int $index, ?bool $insert) : void + { + $this->updateSpacesAt($tokens, $index + 1, $index + 1, $insert); + } + private function updateSpacesBefore(Tokens $tokens, int $index, ?bool $insert) : void + { + $this->updateSpacesAt($tokens, $index - 1, $index, $insert); + } + private function updateSpacesAt(Tokens $tokens, int $index, int $insertIndex, ?bool $insert) : void + { + 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(); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php new file mode 100644 index 00000000000..15c491f5b97 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FixerInterface.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + * @author Fabien Potencier + */ +interface FixerInterface +{ + /** + * Check if the fixer is a candidate for given Tokens collection. + * + * Fixer is a candidate when the collection contains tokens that may be fixed + * during fixer work. This could be considered as some kind of bloom filter. + * When this method returns true then to the Tokens collection may or may not + * need a fixing, but when this method returns false then the Tokens collection + * need no fixing for sure. + */ + public function isCandidate(Tokens $tokens) : bool; + /** + * Check if fixer is risky or not. + * + * Risky fixer could change code behavior! + */ + public function isRisky() : bool; + /** + * Fixes a file. + * + * @param \SplFileInfo $file A \SplFileInfo instance + * @param Tokens $tokens Tokens collection + */ + public function fix(\SplFileInfo $file, Tokens $tokens) : void; + /** + * Returns the definition of the fixer. + */ + public function getDefinition() : FixerDefinitionInterface; + /** + * Returns the name of the fixer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName() : string; + /** + * Returns the priority of the fixer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority() : int; + /** + * Returns true if the file is supported by this fixer. + * + * @return bool true if the file is supported by this fixer, false otherwise + */ + public function supports(\SplFileInfo $file) : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php new file mode 100644 index 00000000000..380deae953a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/CombineNestedDirnameFixer.php @@ -0,0 +1,170 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class CombineNestedDirnameFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace multiple nested calls of `dirname` by only one call with second `$level` parameter. Requires PHP >= 7.0.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NoSpacesInsideParenthesisFixer. + * Must run after DirConstantFixer. + */ + public function getPriority() : int + { + return 35; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + } + } + /** + * @param int $index Index of `dirname` + * @param null|int $firstArgumentEndIndex Index of last token of first argument of `dirname` call + * + * @return array{indexes: list, secondArgument?: int, levels: int, end: int}|bool `false` when it is not a (supported) `dirname` call, an array with info about the dirname call otherwise + */ + private function getDirnameInfo(Tokens $tokens, int $index, ?int $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; + // opening parenthesis "(" + $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 (null !== $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; + } + /** + * @param array, secondArgument?: int, levels: int, end: int}> $dirnameInfoArray + */ + private function combineDirnames(Tokens $tokens, array $dirnameInfoArray) : void + { + $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); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php new file mode 100644 index 00000000000..79274b13b91 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/DateTimeCreateFromFormatCallFixer.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class DateTimeCreateFromFormatCallFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The first argument of `DateTime::createFromFormat` method must start with `!`.', [new CodeSample("isTokenKindFound(\T_DOUBLE_COLON); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $scopeStartIndex = $namespace->getScopeStartIndex(); + $useDeclarations = $namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace); + for ($index = $namespace->getScopeEndIndex(); $index > $scopeStartIndex; --$index) { + if (!$tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + continue; + } + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$functionNameIndex]->equals([\T_STRING, 'createFromFormat'], \false)) { + continue; + } + if (!$tokens[$tokens->getNextMeaningfulToken($functionNameIndex)]->equals('(')) { + continue; + } + $classNameIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$classNameIndex]->equalsAny([[\T_STRING, 'DateTime'], [\T_STRING, 'DateTimeImmutable']], \false)) { + continue; + } + $preClassNameIndex = $tokens->getPrevMeaningfulToken($classNameIndex); + if ($tokens[$preClassNameIndex]->isGivenKind(\T_NS_SEPARATOR)) { + if ($tokens[$tokens->getPrevMeaningfulToken($preClassNameIndex)]->isGivenKind(\T_STRING)) { + continue; + } + } elseif (!$namespace->isGlobalNamespace()) { + continue; + } else { + foreach ($useDeclarations as $useDeclaration) { + foreach (['datetime', 'datetimeimmutable'] as $name) { + if ($name === \strtolower($useDeclaration->getShortName()) && $name !== \strtolower($useDeclaration->getFullName())) { + continue 3; + } + } + } + } + $openIndex = $tokens->getNextTokenOfKind($functionNameIndex, ['(']); + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openIndex); + $argumentIndex = $this->getFirstArgumentTokenIndex($tokens, $argumentsAnalyzer->getArguments($tokens, $openIndex, $closeIndex)); + if (null === $argumentIndex) { + continue; + } + $format = $tokens[$argumentIndex]->getContent(); + if (\strlen($format) < 3) { + continue; + } + $offset = 'b' === $format[0] || 'B' === $format[0] ? 2 : 1; + if ('!' === $format[$offset]) { + continue; + } + $tokens->clearAt($argumentIndex); + $tokens->insertAt($argumentIndex, new Token([\T_CONSTANT_ENCAPSED_STRING, \substr_replace($format, '!', $offset, 0)])); + } + } + } + /** + * @param array $arguments + */ + private function getFirstArgumentTokenIndex(Tokens $tokens, array $arguments) : ?int + { + if (2 !== \count($arguments)) { + return null; + } + \reset($arguments); + $argumentStartIndex = \key($arguments); + $argumentEndIndex = $arguments[$argumentStartIndex]; + $argumentStartIndex = $tokens->getNextMeaningfulToken($argumentStartIndex - 1); + if ($argumentStartIndex !== $argumentEndIndex && $tokens->getNextMeaningfulToken($argumentStartIndex) <= $argumentEndIndex) { + return null; + // argument is not a simple single string + } + return !$tokens[$argumentStartIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING) ? null : $argumentStartIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php new file mode 100644 index 00000000000..7be9a8b7479 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagOrderFixer.php @@ -0,0 +1,98 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class FopenFlagOrderFixer extends AbstractFopenFlagFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Order the flags in `fopen` calls, `b` and `t` must be last.', [new CodeSample("isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + if (null !== $argumentFlagIndex) { + return; + // multiple meaningful tokens found, no candidate for fixing + } + $argumentFlagIndex = $i; + } + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + return; + } + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; + // `'`, `"`, `b` or `B` + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; + // `'` or `"` + $mode = \substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = \substr($content, 1, -1); + } + $modeLength = \strlen($mode); + if ($modeLength < 2) { + return; + // nothing to sort + } + 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]); + } + } + /** + * @param string[] $flags + * + * @return string[] + */ + private function sortFlags(array $flags) : array + { + \usort($flags, static function (string $flag1, string $flag2) : int { + 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php new file mode 100644 index 00000000000..a92ae88bebc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FopenFlagsFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFopenFlagFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class FopenFlagsFixer extends AbstractFopenFlagFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The flags in `fopen` calls must omit `t`, and `b` must be omitted or included consistently.', [new CodeSample(" \false])], null, 'Risky when the function `fopen` is overridden.'); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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, int $argumentStartIndex, int $argumentEndIndex) : void + { + $argumentFlagIndex = null; + for ($i = $argumentStartIndex; $i <= $argumentEndIndex; ++$i) { + if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + if (null !== $argumentFlagIndex) { + return; + // multiple meaningful tokens found, no candidate for fixing + } + $argumentFlagIndex = $i; + } + // check if second argument is candidate + if (null === $argumentFlagIndex || !$tokens[$argumentFlagIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + return; + } + $content = $tokens[$argumentFlagIndex]->getContent(); + $contentQuote = $content[0]; + // `'`, `"`, `b` or `B` + if ('b' === $contentQuote || 'B' === $contentQuote) { + $binPrefix = $contentQuote; + $contentQuote = $content[1]; + // `'` or `"` + $mode = \substr($content, 2, -1); + } else { + $binPrefix = ''; + $mode = \substr($content, 1, -1); + } + if (\false === $this->isValidModeString($mode)) { + return; + } + $mode = \str_replace('t', '', $mode); + if (\true === $this->configuration['b_mode']) { + if (\strpos($mode, 'b') === \false) { + $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]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php new file mode 100644 index 00000000000..ea8e3702405 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionDeclarationFixer.php @@ -0,0 +1,177 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * Fixer for rules defined in PSR2 generally (¶1 and ¶6). + * + * @author Dariusz Rumiński + */ +final class FunctionDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SPACING_NONE = 'none'; + /** + * @internal + */ + public const SPACING_ONE = 'one'; + private const SUPPORTED_SPACINGS = [self::SPACING_NONE, self::SPACING_ONE]; + /** + * @var string + */ + private $singleLineWhitespaceOptions = " \t"; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Spaces should be properly placed in a function declaration.', [new CodeSample(' self::SPACING_NONE]), new VersionSpecificCodeSample(' null; +', new VersionSpecification(70400), ['closure_fn_spacing' => self::SPACING_NONE])]); + } + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after SingleSpaceAfterConstructFixer, SingleSpaceAroundConstructFixer, UseArrowFunctionsFixer. + */ + public function getPriority() : int + { + return 31; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind([\T_FUNCTION, \T_FN])) { + continue; + } + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', [\T_CLOSE_TAG]]); + if (!$tokens[$startParenthesisIndex]->equals('(')) { + continue; + } + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); + if (\false === $this->configuration['trailing_comma_single_line'] && !$tokens->isPartialCodeMultiline($index, $endParenthesisIndex)) { + $commaIndex = $tokens->getPrevMeaningfulToken($endParenthesisIndex); + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + $startBraceIndex = $tokens->getNextTokenOfKind($endParenthesisIndex, [';', '{', [\T_DOUBLE_ARROW]]); + // fix single-line whitespace before { or => + // eg: `function foo(){}` => `function foo() {}` + // eg: `function foo() {}` => `function foo() {}` + // eg: `fn() =>` => `fn() =>` + 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)) { + // fix whitespace after CT:T_USE_LAMBDA (we might add a token, so do this before determining start and end parenthesis) + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex + 1, 0, ' '); + $useStartParenthesisIndex = $tokens->getNextTokenOfKind($afterParenthesisIndex, ['(']); + $useEndParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $useStartParenthesisIndex); + if (\false === $this->configuration['trailing_comma_single_line'] && !$tokens->isPartialCodeMultiline($index, $useEndParenthesisIndex)) { + $commaIndex = $tokens->getPrevMeaningfulToken($useEndParenthesisIndex); + if ($tokens[$commaIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaIndex); + } + } + // remove single-line edge whitespaces inside use parentheses + $this->fixParenthesisInnerEdge($tokens, $useStartParenthesisIndex, $useEndParenthesisIndex); + // fix whitespace before CT::T_USE_LAMBDA + $tokens->ensureWhitespaceAtIndex($afterParenthesisIndex - 1, 1, ' '); + } + // remove single-line edge whitespaces inside parameters list parentheses + $this->fixParenthesisInnerEdge($tokens, $startParenthesisIndex, $endParenthesisIndex); + $isLambda = $tokensAnalyzer->isLambda($index); + // remove whitespace before ( + // eg: `function foo () {}` => `function foo() {}` + if (!$isLambda && $tokens[$startParenthesisIndex - 1]->isWhitespace() && !$tokens[$tokens->getPrevNonWhitespace($startParenthesisIndex - 1)]->isComment()) { + $tokens->clearAt($startParenthesisIndex - 1); + } + $option = $token->isGivenKind(\T_FN) ? 'closure_fn_spacing' : 'closure_function_spacing'; + if ($isLambda && self::SPACING_NONE === $this->configuration[$option]) { + // optionally remove whitespace after T_FUNCTION of a closure + // eg: `function () {}` => `function() {}` + if ($tokens[$index + 1]->isWhitespace()) { + $tokens->clearAt($index + 1); + } + } else { + // otherwise, enforce whitespace after T_FUNCTION + // eg: `function foo() {}` => `function foo() {}` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + if ($isLambda) { + $prev = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prev]->isGivenKind(\T_STATIC)) { + // fix whitespace after T_STATIC + // eg: `$a = static function(){};` => `$a = static function(){};` + $tokens->ensureWhitespaceAtIndex($prev + 1, 0, ' '); + } + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('closure_function_spacing', 'Spacing to use before open parenthesis for closures.'))->setDefault(self::SPACING_ONE)->setAllowedValues(self::SUPPORTED_SPACINGS)->getOption(), (new FixerOptionBuilder('closure_fn_spacing', 'Spacing to use before open parenthesis for short arrow functions.'))->setDefault(self::SPACING_ONE)->setAllowedValues(self::SUPPORTED_SPACINGS)->getOption(), (new FixerOptionBuilder('trailing_comma_single_line', 'Whether trailing commas are allowed in single line signatures.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + private function fixParenthesisInnerEdge(Tokens $tokens, int $start, int $end) : void + { + do { + --$end; + } while ($tokens->isEmptyAt($end)); + // remove single-line whitespace before `)` + if ($tokens[$end]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($end); + } + // remove single-line whitespace after `(` + if ($tokens[$start + 1]->isWhitespace($this->singleLineWhitespaceOptions)) { + $tokens->clearAt($start + 1); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php new file mode 100644 index 00000000000..b644cbdedf2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/FunctionTypehintSpaceFixer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\Whitespace\TypeDeclarationSpacesFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + * + * @deprecated + */ +final class FunctionTypehintSpaceFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ensure single space between function\'s argument and its typehint.', [new CodeSample("isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + public function getSuccessorsNames() : array + { + return \array_keys($this->proxyFixers); + } + protected function createProxyFixers() : array + { + $fixer = new TypeDeclarationSpacesFixer(); + $fixer->configure(['elements' => ['function']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php new file mode 100644 index 00000000000..b4b7bc07e1e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ImplodeCallFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class ImplodeCallFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Function `implode` must be called with 2 arguments in the documented order.', [new CodeSample("isTokenKindFound(\T_STRING); + } + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer. + * Must run after NoAliasFunctionsFixer. + */ + public function getPriority() : int + { + return 37; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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)) { + [$firstArgumentIndex, $secondArgumentIndex] = \array_keys($argumentsIndices); + // If the first argument is string we have nothing to do + if ($tokens[$firstArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + // If the second argument is not string we cannot make a swap + if (!$tokens[$secondArgumentIndex]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + continue; + } + // collect tokens from first argument + $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]); + // insert above increased the second argument index + ++$secondArgumentIndex; + $tokens->clearAt($secondArgumentIndex); + $tokens->insertAt($secondArgumentIndex, $newSecondArgumentTokens); + } + } + } + /** + * @return array In the format: startIndex => endIndex + */ + private function getArgumentIndices(Tokens $tokens, int $functionNameIndex) : array + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php new file mode 100644 index 00000000000..a77f044c209 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/LambdaNotUsedImportFixer.php @@ -0,0 +1,270 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 +{ + /** + * @var ArgumentsAnalyzer + */ + private $argumentsAnalyzer; + /** + * @var FunctionsAnalyzer + */ + private $functionAnalyzer; + /** + * @var TokensAnalyzer + */ + private $tokensAnalyzer; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Lambda must not import variables it doesn\'t use.', [new CodeSample("isAllTokenKindsFound([\T_FUNCTION, CT::T_USE_LAMBDA]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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, int $lambdaUseIndex) : void + { + $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; + // no imports to remove + } + $notUsedImports = $this->findNotUsedLambdaImports($tokens, $imports, $lambdaUseCloseBraceIndex); + $notUsedImportsCount = \count($notUsedImports); + if (0 === $notUsedImportsCount) { + return; + // no not used imports found + } + if ($notUsedImportsCount === \count($arguments)) { + $this->clearImportsAndUse($tokens, $lambdaUseIndex, $lambdaUseCloseBraceIndex); + // all imports are not used + return; + } + $this->clearImports($tokens, \array_reverse($notUsedImports)); + } + /** + * @return array + */ + private function findNotUsedLambdaImports(Tokens $tokens, array $imports, int $lambdaUseCloseBraceIndex) : array + { + static $riskyKinds = [CT::T_DYNAMIC_VAR_BRACE_OPEN, \T_EVAL, \T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE]; + // figure out where the lambda starts ... + $lambdaOpenIndex = $tokens->getNextTokenOfKind($lambdaUseCloseBraceIndex, ['{']); + $curlyBracesLevel = 0; + for ($index = $lambdaOpenIndex;; ++$index) { + // go through the body of the lambda and keep count of the (possible) usages of the imported variables + $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 []; + // wouldn't touch it with a ten-foot pole + } + if ($token->isGivenKind($riskyKinds)) { + return []; + } + if ($token->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + return []; + // "$$a" case + } + } + 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()) { + // is anonymous class + // check if used as argument in the constructor of the anonymous class + $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, ['{']); + } + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + continue; + } + if ($token->isGivenKind(\T_FUNCTION)) { + // check if used as argument + $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); + // check if used as import + $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, ['{']); + } + // skip body + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + continue; + } + } + return $imports; + } + private function countImportsUsedAsArgument(Tokens $tokens, array $imports, array $arguments) : array + { + 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; + } + /** + * @return false|int + */ + private function getLambdaUseIndex(Tokens $tokens, int $index) + { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$this->tokensAnalyzer->isLambda($index)) { + return \false; + } + $lambdaUseIndex = $tokens->getNextMeaningfulToken($index); + // we are @ '(' or '&' after this + if ($tokens[$lambdaUseIndex]->isGivenKind(CT::T_RETURN_REF)) { + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + } + $lambdaUseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $lambdaUseIndex); + // we are @ ')' after this + $lambdaUseIndex = $tokens->getNextMeaningfulToken($lambdaUseIndex); + if (!$tokens[$lambdaUseIndex]->isGivenKind(CT::T_USE_LAMBDA)) { + return \false; + } + return $lambdaUseIndex; + } + private function filterArguments(Tokens $tokens, array $arguments) : array + { + $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; + } + /** + * @param array $imports + */ + private function clearImports(Tokens $tokens, array $imports) : void + { + foreach ($imports as $removeIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($removeIndex); + $previousRemoveIndex = $tokens->getPrevMeaningfulToken($removeIndex); + if ($tokens[$previousRemoveIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousRemoveIndex); + } elseif ($tokens[$previousRemoveIndex]->equals('(')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($tokens->getNextMeaningfulToken($removeIndex)); + // next is always ',' here + } + } + } + /** + * Remove `use` and all imported variables. + */ + private function clearImportsAndUse(Tokens $tokens, int $lambdaUseIndex, int $lambdaUseCloseBraceIndex) : void + { + 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); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php new file mode 100644 index 00000000000..cdb3442b661 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/MethodArgumentSpaceFixer.php @@ -0,0 +1,295 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶4.4, ¶4.6. + * + * @author Kuanhung Chen + */ +final class MethodArgumentSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('In method arguments and method call, there MUST NOT be a space before each comma and there MUST be one space after each comma. Argument lists MAY be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list MUST be on the next line, and there MUST be only one argument per line.', [new CodeSample(" \false]), new CodeSample(" \true]), new CodeSample(" 'ensure_fully_multiline']), new CodeSample(" 'ensure_single_line']), new CodeSample(" 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => \true]), new CodeSample(" 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => \false]), new VersionSpecificCodeSample(<<<'SAMPLE' + \true])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('('); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + if (isset($configuration['ensure_fully_multiline'])) { + $this->configuration['on_multiline'] = $this->configuration['ensure_fully_multiline'] ? 'ensure_fully_multiline' : 'ignore'; + } + } + /** + * {@inheritdoc} + * + * Must run before ArrayIndentationFixer. + * Must run after CombineNestedDirnameFixer, FunctionDeclarationFixer, ImplodeCallFixer, LambdaNotUsedImportFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUselessSprintfFixer, PowToExponentiationFixer, StrictParamFixer. + */ + public function getPriority() : int + { + return 30; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $expectedTokens = [\T_LIST, \T_FUNCTION, CT::T_USE_LAMBDA, \T_FN, \T_CLASS]; + 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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('keep_multiple_spaces_after_comma', 'Whether keep multiple spaces after comma.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption(), (new FixerOptionBuilder('on_multiline', 'Defines how to handle function arguments lists that contain newlines.'))->setAllowedValues(['ignore', 'ensure_single_line', 'ensure_fully_multiline'])->setDefault('ensure_fully_multiline')->getOption(), (new FixerOptionBuilder('after_heredoc', 'Whether the whitespace between heredoc end and comma should be removed.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * Fix arguments spacing for given function. + * + * @param Tokens $tokens Tokens to handle + * @param int $startFunctionIndex Start parenthesis position + * + * @return bool whether the function is multiline + */ + private function fixFunction(Tokens $tokens, int $startFunctionIndex) : bool + { + $isMultiline = \false; + $endFunctionIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startFunctionIndex); + $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->fixSpace($tokens, $index); + if (!$isMultiline && $this->isNewline($tokens[$index + 1])) { + $isMultiline = \true; + } + } + } + return $isMultiline; + } + private function findWhitespaceIndexAfterParenthesis(Tokens $tokens, int $startParenthesisIndex, int $endParenthesisIndex) : ?int + { + $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; + } + /** + * @return bool Whether newlines were removed from the whitespace token + */ + private function ensureSingleLine(Tokens $tokens, int $index) : bool + { + $previousToken = $tokens[$index - 1]; + if ($previousToken->isComment() && \strncmp($previousToken->getContent(), '/*', \strlen('/*')) !== 0) { + return \false; + } + $content = Preg::replace('/\\R\\h*/', '', $tokens[$index]->getContent()); + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + return \true; + } + private function ensureFunctionFullyMultiline(Tokens $tokens, int $startFunctionIndex) : void + { + // find out what the indentation is + $searchIndex = $startFunctionIndex; + do { + $prevWhitespaceTokenIndex = $tokens->getPrevTokenOfKind($searchIndex, [[\T_WHITESPACE]]); + $searchIndex = $prevWhitespaceTokenIndex; + } while (null !== $prevWhitespaceTokenIndex && \strpos($tokens[$prevWhitespaceTokenIndex]->getContent(), "\n") === \false); + 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]; + // skip nested method calls and arrays + if ($token->equals(')')) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + continue; + } + // skip nested arrays + 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); + } + /** + * Method to insert newline after comma or opening parenthesis. + * + * @param int $index index of a comma + * @param string $indentation the indentation that should be used + * @param bool $override whether to override the existing character or not + */ + private function fixNewline(Tokens $tokens, int $index, string $indentation, bool $override = \true) : void + { + 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); + } + /** + * Method to insert space after comma and remove space before comma. + */ + private function fixSpace(Tokens $tokens, int $index) : void + { + // remove space before comma if exist + if ($tokens[$index - 1]->isWhitespace()) { + $prevIndex = $tokens->getPrevNonWhitespace($index - 1); + if (!$tokens[$prevIndex]->equals(',') && !$tokens[$prevIndex]->isComment() && (\true === $this->configuration['after_heredoc'] || !$tokens[$prevIndex]->isGivenKind(\T_END_HEREDOC))) { + $tokens->clearAt($index - 1); + } + } + $nextIndex = $index + 1; + $nextToken = $tokens[$nextIndex]; + // Two cases for fix space after comma (exclude multiline comments) + // 1) multiple spaces after comma + // 2) no space after comma + if ($nextToken->isWhitespace()) { + $newContent = $nextToken->getContent(); + if ('ensure_single_line' === $this->configuration['on_multiline']) { + $newContent = Preg::replace('/\\R/', '', $newContent); + } + if ((\false === $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, ' '])); + } + } + /** + * Check if last item of current line is a comment. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function isCommentLastLineToken(Tokens $tokens, int $index) : bool + { + if (!$tokens[$index]->isComment() || !$tokens[$index + 1]->isWhitespace()) { + return \false; + } + $content = $tokens[$index + 1]->getContent(); + return $content !== \ltrim($content, "\r\n"); + } + /** + * Checks if token is new line. + */ + private function isNewline(Token $token) : bool + { + return $token->isWhitespace() && \strpos($token->getContent(), "\n") !== \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php new file mode 100644 index 00000000000..cd21c7930e1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NativeFunctionInvocationFixer.php @@ -0,0 +1,299 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Andreas Möller + */ +final class NativeFunctionInvocationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SET_ALL = '@all'; + /** + * Subset of SET_INTERNAL. + * + * Change function call to functions known to be optimized by the Zend engine. + * For details: + * - @see https://github.com/php/php-src/blob/php-7.2.6/Zend/zend_compile.c "zend_try_compile_special_func" + * - @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + * + * @internal + */ + public const SET_COMPILER_OPTIMIZED = '@compiler_optimized'; + /** + * @internal + */ + public const SET_INTERNAL = '@internal'; + /** + * @var callable + */ + private $functionFilter; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->functionFilter = $this->getFunctionFilter(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Add leading `\\` before function invocation to speed up resolving.', [new CodeSample(' ['json_encode']]), new CodeSample(' 'all']), new CodeSample(' 'namespaced']), new CodeSample(' ['myGlobalFunction']]), new CodeSample(' ['@all']]), new CodeSample(' ['@internal']]), new CodeSample(' ['@compiler_optimized']])], null, 'Risky when any of the functions are overridden.'); + } + /** + * {@inheritdoc} + * + * Must run before GlobalNamespaceImportFixer. + * Must run after BacktickToShellExecFixer, RegularCallableCallFixer, StrictParamFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if ('all' === $this->configuration['scope']) { + $this->fixFunctionCalls($tokens, $this->functionFilter, 0, \count($tokens) - 1, \false); + return; + } + $namespaces = $tokens->getNamespaceDeclarations(); + // 'scope' is 'namespaced' here + /** @var NamespaceAnalysis $namespace */ + foreach (\array_reverse($namespaces) as $namespace) { + $this->fixFunctionCalls($tokens, $this->functionFilter, $namespace->getScopeStartIndex(), $namespace->getScopeEndIndex(), $namespace->isGlobalNamespace()); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('exclude', 'List of functions to ignore.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $value) : bool { + 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.', \get_debug_type($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) : bool { + 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.', \get_debug_type($functionName))); + } + $sets = [self::SET_ALL, self::SET_INTERNAL, self::SET_COMPILER_OPTIMIZED]; + if (\strncmp($functionName, '@', \strlen('@')) === 0 && !\in_array($functionName, $sets, \true)) { + throw new InvalidOptionsException(\sprintf('Unknown set "%s", known sets are %s.', $functionName, Utils::naturalLanguageJoin($sets))); + } + } + return \true; + }])->setDefault([self::SET_COMPILER_OPTIMIZED])->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(\true)->getOption()]); + } + private function fixFunctionCalls(Tokens $tokens, callable $functionFilter, int $start, int $end, bool $tryToRemove) : void + { + $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 (\false === $this->configuration['strict']) { + continue; + } + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + continue; + } + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + continue; + // do not bother if previous token is already namespace separator + } + $tokensToInsert[$index] = new Token([\T_NS_SEPARATOR, '\\']); + } + $tokens->insertSlices($tokensToInsert); + } + private function getFunctionFilter() : callable + { + $exclude = $this->normalizeFunctionNames($this->configuration['exclude']); + if (\in_array(self::SET_ALL, $this->configuration['include'], \true)) { + if (\count($exclude) > 0) { + return static function (string $functionName) use($exclude) : bool { + return !isset($exclude[\strtolower($functionName)]); + }; + } + return static function () : bool { + 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(); + // if `@internal` is set all compiler optimized function are already loaded + } + foreach ($this->configuration['include'] as $additional) { + if (\strncmp($additional, '@', \strlen('@')) !== 0) { + $include[\strtolower($additional)] = \true; + } + } + if (\count($exclude) > 0) { + return static function (string $functionName) use($include, $exclude) : bool { + return isset($include[\strtolower($functionName)]) && !isset($exclude[\strtolower($functionName)]); + }; + } + return static function (string $functionName) use($include) : bool { + return isset($include[\strtolower($functionName)]); + }; + } + /** + * @return array normalized function names of which the PHP compiler optimizes + */ + private function getAllCompilerOptimizedFunctionsNormalized() : array + { + return $this->normalizeFunctionNames([ + // @see https://github.com/php/php-src/blob/PHP-7.4/Zend/zend_compile.c "zend_try_compile_special_func" + '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_scalar', + 'is_string', + 'ord', + 'sizeof', + 'strlen', + 'strval', + // @see https://github.com/php/php-src/blob/php-7.2.6/ext/opcache/Optimizer/pass1_5.c + // @see https://github.com/php/php-src/blob/PHP-8.1.2/Zend/Optimizer/block_pass.c + // @see https://github.com/php/php-src/blob/php-8.1.3/Zend/Optimizer/zend_optimizer.c + 'constant', + 'define', + 'dirname', + 'extension_loaded', + 'function_exists', + 'is_callable', + 'ini_get', + ]); + } + /** + * @return array normalized function names of all internal defined functions + */ + private function getAllInternalFunctionsNormalized() : array + { + return $this->normalizeFunctionNames(\get_defined_functions()['internal']); + } + /** + * @param string[] $functionNames + * + * @return array all function names lower cased + */ + private function normalizeFunctionNames(array $functionNames) : array + { + foreach ($functionNames as $index => $functionName) { + $functionNames[\strtolower($functionName)] = \true; + unset($functionNames[$index]); + } + return $functionNames; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php new file mode 100644 index 00000000000..e8ea78ab44e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoSpacesAfterFunctionNameFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶4.6. + * + * @author Varga Bence + * @author Dariusz Rumiński + */ +final class NoSpacesAfterFunctionNameFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + 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("isAnyTokenKindsFound(\array_merge($this->getFunctionyTokenKinds(), [\T_STRING])); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionyTokens = $this->getFunctionyTokenKinds(); + $languageConstructionTokens = $this->getLanguageConstructionTokenKinds(); + $braceTypes = $this->getBraceAfterVariableKinds(); + foreach ($tokens as $index => $token) { + // looking for start brace + if (!$token->equals('(')) { + continue; + } + // last non-whitespace token, can never be `null` always at least PHP open tag before it + $lastTokenIndex = $tokens->getPrevNonWhitespace($index); + // check for ternary operator + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $nextNonWhiteSpace = $tokens->getNextMeaningfulToken($endParenthesisIndex); + if (null !== $nextNonWhiteSpace && $tokens[$nextNonWhiteSpace]->equals('?') && $tokens[$lastTokenIndex]->isGivenKind($languageConstructionTokens)) { + continue; + } + // check if it is a function call + if ($tokens[$lastTokenIndex]->isGivenKind($functionyTokens)) { + $this->fixFunctionCall($tokens, $index); + } elseif ($tokens[$lastTokenIndex]->isGivenKind(\T_STRING)) { + // for real function calls or definitions + $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); + } + } + } + } + /** + * Fixes whitespaces around braces of a function(y) call. + * + * @param Tokens $tokens tokens to handle + * @param int $index index of token + */ + private function fixFunctionCall(Tokens $tokens, int $index) : void + { + // remove space before opening brace + if ($tokens[$index - 1]->isWhitespace()) { + $tokens->clearAt($index - 1); + } + } + /** + * @return array|string> + */ + private function getBraceAfterVariableKinds() : array + { + static $tokens = [')', ']', [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]; + return $tokens; + } + /** + * Gets the token kinds which can work as function calls. + * + * @return int[] Token names + */ + private function getFunctionyTokenKinds() : array + { + 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; + } + /** + * Gets the token kinds of actually language construction. + * + * @return int[] + */ + private function getLanguageConstructionTokenKinds() : array + { + static $languageConstructionTokens = [\T_ECHO, \T_PRINT, \T_INCLUDE, \T_INCLUDE_ONCE, \T_REQUIRE, \T_REQUIRE_ONCE]; + return $languageConstructionTokens; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php new file mode 100644 index 00000000000..fdfef51dcd4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoTrailingCommaInSinglelineFunctionCallFixer.php @@ -0,0 +1,49 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\Basic\NoTrailingCommaInSinglelineFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @deprecated + */ +final class NoTrailingCommaInSinglelineFunctionCallFixer extends AbstractProxyFixer implements DeprecatedFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('When making a method or function call on a single line there MUST NOT be a trailing comma after the last argument.', [new CodeSample("proxyFixers); + } + protected function createProxyFixers() : array + { + $fixer = new NoTrailingCommaInSinglelineFixer(); + $fixer->configure(['elements' => ['arguments', 'array_destructuring']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php new file mode 100644 index 00000000000..f872da72e34 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUnreachableDefaultArgumentValueFixer.php @@ -0,0 +1,146 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Mark Scherer + * @author Lucas Manzke + * @author Gregor Harlan + */ +final class NoUnreachableDefaultArgumentValueFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('In function arguments there must not be arguments with default values before non-default ones.', [new CodeSample('isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionKinds = [\T_FUNCTION, \T_FN]; + for ($i = 0, $l = $tokens->count(); $i < $l; ++$i) { + if (!$tokens[$i]->isGivenKind($functionKinds)) { + continue; + } + $startIndex = $tokens->getNextTokenOfKind($i, ['(']); + $i = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + $this->fixFunctionDefinition($tokens, $startIndex, $i); + } + } + private function fixFunctionDefinition(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $lastArgumentIndex = $this->getLastNonDefaultArgumentIndex($tokens, $startIndex, $endIndex); + if (null === $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; + } + $this->removeDefaultValue($tokens, $i, $this->getDefaultValueEndIndex($tokens, $lastArgumentIndex)); + } + } + private function getLastNonDefaultArgumentIndex(Tokens $tokens, int $startIndex, int $endIndex) : ?int + { + 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, int $variableIndex) : bool + { + return $tokens[$tokens->getPrevMeaningfulToken($variableIndex)]->isGivenKind(\T_ELLIPSIS); + } + private function getDefaultValueEndIndex(Tokens $tokens, int $index) : int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + } while (!$tokens[$index]->equals(',')); + return $tokens->getPrevMeaningfulToken($index); + } + private function removeDefaultValue(Tokens $tokens, int $startIndex, int $endIndex) : void + { + for ($i = $startIndex; $i <= $endIndex;) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $this->clearWhitespacesBeforeIndex($tokens, $i); + $i = $tokens->getNextMeaningfulToken($i); + } + } + /** + * @param int $index Index of "=" + */ + private function isNonNullableTypehintedNullableVariable(Tokens $tokens, int $index) : bool + { + $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, int $index) : void + { + $prevIndex = $tokens->getNonEmptySibling($index, -1); + if (!$tokens[$prevIndex]->isWhitespace()) { + return; + } + $prevNonWhiteIndex = $tokens->getPrevNonWhitespace($prevIndex); + if (null === $prevNonWhiteIndex || !$tokens[$prevNonWhiteIndex]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php new file mode 100644 index 00000000000..de0c783fe85 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NoUselessSprintfFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUselessSprintfFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must be no `sprintf` calls with only the first argument.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionCasingFixer, NoEmptyStatementFixer, NoExtraBlankLinesFixer, NoSpacesInsideParenthesisFixer. + */ + public function getPriority() : int + { + return 42; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php new file mode 100644 index 00000000000..f0713c870ce --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/NullableTypeDeclarationForDefaultNullValueFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author HypeMC + */ +final class NullableTypeDeclarationForDefaultNullValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Adds or removes `?` before single type declarations or `|null` at the end of union types when parameters have a default `null` value.', [new CodeSample(" \false]), new VersionSpecificCodeSample(" \false]), new VersionSpecificCodeSample(" \false])], 'Rule is applied only in a PHP 7.1+ environment.'); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_VARIABLE) && $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + /** + * {@inheritdoc} + * + * Must run before NoUnreachableDefaultArgumentValueFixer, NullableTypeDeclarationFixer, OrderedTypesFixer. + */ + public function getPriority() : int + { + return 3; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('use_nullable_type_declaration', 'Whether to add or remove `?` or `|null` to parameters with a default `null` value.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $tokenKinds = [\T_FUNCTION, \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); + } + } + /** + * @param ArgumentAnalysis[] $arguments + */ + private function fixFunctionParameters(Tokens $tokens, array $arguments) : void + { + $constructorPropertyModifiers = [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $constructorPropertyModifiers[] = \T_READONLY; + } + foreach (\array_reverse($arguments) as $argumentInfo) { + if (!$argumentInfo->hasTypeAnalysis() || \in_array(\strtolower($argumentInfo->getTypeAnalysis()->getName()), ['mixed', 'null'], \true) || !$argumentInfo->hasDefault() || 'null' !== \strtolower($argumentInfo->getDefault())) { + continue; + } + $argumentTypeInfo = $argumentInfo->getTypeAnalysis(); + if (\PHP_VERSION_ID >= 80000 && \false === $this->configuration['use_nullable_type_declaration']) { + $visibility = $tokens[$tokens->getPrevMeaningfulToken($argumentTypeInfo->getStartIndex())]; + if ($visibility->isGivenKind($constructorPropertyModifiers)) { + continue; + } + } + $typeAnalysisName = $argumentTypeInfo->getName(); + if (\strpos($typeAnalysisName, '|') !== \false || \strpos($typeAnalysisName, '&') !== \false) { + $this->fixUnionTypeParameter($tokens, $argumentTypeInfo); + } else { + $this->fixSingleTypeParameter($tokens, $argumentTypeInfo); + } + } + } + private function fixSingleTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo) : void + { + if (\true === $this->configuration['use_nullable_type_declaration']) { + if (!$argumentTypeInfo->isNullable()) { + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_NULLABLE_TYPE, '?'])); + } + } elseif ($argumentTypeInfo->isNullable()) { + $tokens->removeTrailingWhitespace($startIndex = $argumentTypeInfo->getStartIndex()); + $tokens->clearTokenAndMergeSurroundingWhitespace($startIndex); + } + } + private function fixUnionTypeParameter(Tokens $tokens, TypeAnalysis $argumentTypeInfo) : void + { + if (\true === $this->configuration['use_nullable_type_declaration']) { + if ($argumentTypeInfo->isNullable()) { + return; + } + $typeAnalysisName = $argumentTypeInfo->getName(); + $endIndex = $argumentTypeInfo->getEndIndex(); + if (\strpos($typeAnalysisName, '&') !== \false && \strpos($typeAnalysisName, '|') === \false) { + $endIndex += 2; + $tokens->insertAt($argumentTypeInfo->getStartIndex(), new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('])); + $tokens->insertAt($endIndex, new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')'])); + } + $tokens->insertAt($endIndex + 1, [new Token([CT::T_TYPE_ALTERNATION, '|']), new Token([\T_STRING, 'null'])]); + } elseif ($argumentTypeInfo->isNullable()) { + $startIndex = $argumentTypeInfo->getStartIndex(); + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[\T_STRING, 'null']], \false); + if ($index === $startIndex) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } else { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->equals([CT::T_TYPE_ALTERNATION, '|'])) { + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + $typeAnalysisName = $argumentTypeInfo->getName(); + if (\strpos($typeAnalysisName, '&') !== \false && 1 === \substr_count($typeAnalysisName, '|')) { + $index = $tokens->getNextTokenOfKind($startIndex - 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN]]); + $tokens->removeTrailingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $index = $tokens->getPrevTokenOfKind($argumentTypeInfo->getEndIndex() + 1, [[CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]]); + $tokens->removeLeadingWhitespace($index); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php new file mode 100644 index 00000000000..d390b6a5cd9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToParamTypeFixer.php @@ -0,0 +1,134 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jan Gantzert + */ +final class PhpdocToParamTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + /** + * @var array{int, string}[] + */ + private const EXCLUDE_FUNC_NAMES = [[\T_STRING, '__clone'], [\T_STRING, '__destruct']]; + /** + * @var array + */ + private const SKIPPED_TYPES = ['mixed' => \true, 'resource' => \true, 'static' => \true, 'void' => \true]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('EXPERIMENTAL: Takes `@param` annotations of non-mixed types and adjusts accordingly the function signature. Requires PHP >= 7.0.', [new CodeSample(' \false])], 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) : bool + { + return $tokens->isTokenKindFound(\T_FUNCTION); + } + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 8; + } + protected function isSkippedType(string $type) : bool + { + return isset(self::SKIPPED_TYPES[$type]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + $funcName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$funcName]->equalsAny(self::EXCLUDE_FUNC_NAMES, \false)) { + continue; + } + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + if (null === $docCommentIndex) { + continue; + } + foreach ($this->getAnnotationsFromDocComment('param', $tokens, $docCommentIndex) as $paramTypeAnnotation) { + $typeInfo = $this->getCommonTypeFromAnnotation($paramTypeAnnotation, \false); + if (null === $typeInfo) { + continue; + } + [$paramType, $isNullable] = $typeInfo; + $startIndex = $tokens->getNextTokenOfKind($index, ['(']); + $variableIndex = $this->findCorrectVariable($tokens, $startIndex, $paramTypeAnnotation); + if (null === $variableIndex) { + continue; + } + $byRefIndex = $tokens->getPrevMeaningfulToken($variableIndex); + if ($tokens[$byRefIndex]->equals('&')) { + $variableIndex = $byRefIndex; + } + if ($this->hasParamTypeHint($tokens, $variableIndex)) { + continue; + } + if (!$this->isValidSyntax(\sprintf('insertAt($variableIndex, \array_merge($this->createTypeDeclarationTokens($paramType, $isNullable), [new Token([\T_WHITESPACE, ' '])])); + } + } + } + private function findCorrectVariable(Tokens $tokens, int $startIndex, Annotation $paramTypeAnnotation) : ?int + { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startIndex); + for ($index = $startIndex + 1; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + continue; + } + $variableName = $tokens[$index]->getContent(); + if ($paramTypeAnnotation->getVariableName() === $variableName) { + return $index; + } + } + return null; + } + /** + * Determine whether the function already has a param type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasParamTypeHint(Tokens $tokens, int $index) : bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + return !$tokens[$prevIndex]->equalsAny([',', '(']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php new file mode 100644 index 00000000000..e68627abecb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToPropertyTypeFixer.php @@ -0,0 +1,164 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class PhpdocToPropertyTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + /** + * @var array + */ + private $skippedTypes = ['mixed' => \true, 'resource' => \true, 'null' => \true]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('EXPERIMENTAL: Takes `@var` annotation of non-mixed types and adjusts accordingly the property signature. Requires PHP >= 7.4.', [new VersionSpecificCodeSample(' \false])], null, 'This rule is EXPERIMENTAL and [1] is not covered with backward compatibility promise. [2] `@var` annotation is mandatory for the fixer to make changes, signatures of properties without it (no docblock) will not be fixed. [3] Manual actions might be required for newly typed properties that are read before initialization.'); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 7; + } + protected function isSkippedType(string $type) : bool + { + return isset($this->skippedTypes[$type]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if ($tokens[$index]->isGivenKind([\T_CLASS, \T_TRAIT])) { + $this->fixClass($tokens, $index); + } + } + } + private function fixClass(Tokens $tokens, int $index) : void + { + $index = $tokens->getNextTokenOfKind($index, ['{']); + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + for (; $index < $classEndIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } + continue; + } + if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $docCommentIndex = $index; + $propertyIndices = $this->findNextUntypedPropertiesDeclaration($tokens, $docCommentIndex); + if ([] === $propertyIndices) { + continue; + } + $typeInfo = $this->resolveApplicableType($propertyIndices, $this->getAnnotationsFromDocComment('var', $tokens, $docCommentIndex)); + if (null === $typeInfo) { + continue; + } + [$propertyType, $isNullable] = $typeInfo; + if (\in_array($propertyType, ['callable', 'never', 'void'], \true)) { + continue; + } + $newTokens = \array_merge($this->createTypeDeclarationTokens($propertyType, $isNullable), [new Token([\T_WHITESPACE, ' '])]); + $tokens->insertAt(\current($propertyIndices), $newTokens); + $index = \max($propertyIndices) + \count($newTokens) + 1; + $classEndIndex += \count($newTokens); + } + } + /** + * @return array + */ + private function findNextUntypedPropertiesDeclaration(Tokens $tokens, int $index) : array + { + do { + $index = $tokens->getNextMeaningfulToken($index); + } while ($tokens[$index]->isGivenKind([\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR])); + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + return []; + } + $properties = []; + while (!$tokens[$index]->equals(';')) { + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + $properties[$tokens[$index]->getContent()] = $index; + } + $index = $tokens->getNextMeaningfulToken($index); + } + return $properties; + } + /** + * @param array $propertyIndices + * @param Annotation[] $annotations + */ + private function resolveApplicableType(array $propertyIndices, array $annotations) : ?array + { + $propertyTypes = []; + foreach ($annotations as $annotation) { + $propertyName = $annotation->getVariableName(); + if (null === $propertyName) { + if (1 !== \count($propertyIndices)) { + continue; + } + $propertyName = \key($propertyIndices); + } + if (!isset($propertyIndices[$propertyName])) { + continue; + } + $typeInfo = $this->getCommonTypeFromAnnotation($annotation, \false); + if (!isset($propertyTypes[$propertyName])) { + $propertyTypes[$propertyName] = []; + } elseif ($typeInfo !== $propertyTypes[$propertyName]) { + return null; + } + $propertyTypes[$propertyName] = $typeInfo; + } + if (\count($propertyTypes) !== \count($propertyIndices)) { + return null; + } + $type = \array_shift($propertyTypes); + foreach ($propertyTypes as $propertyType) { + if ($propertyType !== $type) { + return null; + } + } + return $type; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php new file mode 100644 index 00000000000..b6972bb27ba --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/PhpdocToReturnTypeFixer.php @@ -0,0 +1,136 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class PhpdocToReturnTypeFixer extends AbstractPhpdocToTypeDeclarationFixer +{ + /** + * @var array> + */ + private $excludeFuncNames = [[\T_STRING, '__construct'], [\T_STRING, '__destruct'], [\T_STRING, '__clone']]; + /** + * @var array + */ + private $skippedTypes = ['mixed' => \true, 'resource' => \true, 'null' => \true]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('EXPERIMENTAL: Takes `@return` annotation of non-mixed types and adjusts accordingly the function signature. Requires PHP >= 7.0.', [new CodeSample(' \false]), new VersionSpecificCodeSample('isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + /** + * {@inheritdoc} + * + * Must run before FullyQualifiedStrictTypesFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, ReturnTypeDeclarationFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 13; + } + protected function isSkippedType(string $type) : bool + { + return isset($this->skippedTypes[$type]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (\PHP_VERSION_ID >= 80000) { + unset($this->skippedTypes['mixed']); + } + for ($index = $tokens->count() - 1; 0 < $index; --$index) { + if (!$tokens[$index]->isGivenKind([\T_FUNCTION, \T_FN])) { + continue; + } + $funcName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$funcName]->equalsAny($this->excludeFuncNames, \false)) { + continue; + } + $docCommentIndex = $this->findFunctionDocComment($tokens, $index); + if (null === $docCommentIndex) { + continue; + } + $returnTypeAnnotation = $this->getAnnotationsFromDocComment('return', $tokens, $docCommentIndex); + if (1 !== \count($returnTypeAnnotation)) { + continue; + } + $typeInfo = $this->getCommonTypeFromAnnotation(\current($returnTypeAnnotation), \true); + if (null === $typeInfo) { + continue; + } + [$returnType, $isNullable] = $typeInfo; + $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($this->hasReturnTypeHint($tokens, $startIndex)) { + continue; + } + if (!$this->isValidSyntax(\sprintf('getPrevTokenOfKind($startIndex, [')']); + $tokens->insertAt($endFuncIndex + 1, \array_merge([new Token([CT::T_TYPE_COLON, ':']), new Token([\T_WHITESPACE, ' '])], $this->createTypeDeclarationTokens($returnType, $isNullable))); + } + } + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index) : bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php new file mode 100644 index 00000000000..2647c039cf7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/RegularCallableCallFixer.php @@ -0,0 +1,189 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class RegularCallableCallFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Callables must be called without using `call_user_func*` when possible.', [new CodeSample(' \'baz\'])` or `call_user_func($foo, $foo = \'bar\')`.'); + } + /** + * {@inheritdoc} + * + * Must run before NativeFunctionInvocationFixer. + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer. + */ + public function getPriority() : int + { + return 2; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // redeclare/override + } + $openParenthesis = $tokens->getNextMeaningfulToken($index); + $closeParenthesis = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesis); + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesis, $closeParenthesis); + if (1 > \count($arguments)) { + return; + // no arguments! + } + $this->processCall($tokens, $index, $arguments); + } + } + /** + * @param array $arguments + */ + private function processCall(Tokens $tokens, int $index, array $arguments) : void + { + $firstArgIndex = $tokens->getNextMeaningfulToken($tokens->getNextMeaningfulToken($index)); + /** @var Token $firstArgToken */ + $firstArgToken = $tokens[$firstArgIndex]; + if ($firstArgToken->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgIndex); + if (!$tokens[$afterFirstArgIndex]->equalsAny([',', ')'])) { + return; + // first argument is an expression like `call_user_func("foo"."bar", ...)`, not supported! + } + $firstArgTokenContent = $firstArgToken->getContent(); + if (!$this->isValidFunctionInvoke($firstArgTokenContent)) { + return; + } + $newCallTokens = Tokens::fromCode('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) || $firstArgToken->isGivenKind(\T_STATIC) && $tokens[$tokens->getNextMeaningfulToken($firstArgIndex)]->isGivenKind(\T_FUNCTION)) { + $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); + // check if the same variable is used multiple times and if so do not fix + foreach ($arguments as $argumentStart => $argumentEnd) { + if ($firstArgEndIndex === $argumentEnd) { + continue; + } + for ($i = $argumentStart; $i <= $argumentEnd; ++$i) { + if ($tokens[$i]->equals($firstArgToken)) { + return; + } + } + } + // check if complex statement and if so wrap the call in () if on PHP 7 or up, else do not fix + $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) { + $newCallTokens->insertAt($newCallTokens->count(), new Token(')')); + $newCallTokens->insertAt(0, new Token('(')); + } + $this->replaceCallUserFuncWithCallback($tokens, $index, $newCallTokens, $firstArgIndex, $firstArgEndIndex); + } + } + private function replaceCallUserFuncWithCallback(Tokens $tokens, int $callIndex, Tokens $newCallTokens, int $firstArgStartIndex, int $firstArgEndIndex) : void + { + $tokens->clearRange($firstArgStartIndex, $firstArgEndIndex); + $afterFirstArgIndex = $tokens->getNextMeaningfulToken($firstArgEndIndex); + $afterFirstArgToken = $tokens[$afterFirstArgIndex]; + if ($afterFirstArgToken->equals(',')) { + $useEllipsis = $tokens[$callIndex]->equals([\T_STRING, 'call_user_func_array'], \false); + 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, int $indexStart, int $indexEnd) : Tokens + { + $size = $indexEnd - $indexStart + 1; + $subCollection = new Tokens($size); + for ($i = 0; $i < $size; ++$i) { + /** @var Token $toClone */ + $toClone = $tokens[$i + $indexStart]; + $subCollection[$i] = clone $toClone; + } + return $subCollection; + } + private function isValidFunctionInvoke(string $name) : bool + { + if (\strlen($name) < 3 || 'b' === $name[0] || 'B' === $name[0]) { + return \false; + } + $name = \substr($name, 1, -1); + if ($name !== \trim($name)) { + return \false; + } + return \true; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php new file mode 100644 index 00000000000..ce1bb36dd5d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/ReturnTypeDeclarationFixer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class ReturnTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Adjust spacing around colon in return type declarations and backed enum types.', [new CodeSample(" 'none']), new CodeSample(" 'one'])], 'Rule is applied only in a PHP 7+ environment.'); + } + /** + * {@inheritdoc} + * + * Must run after PhpUnitDataProviderReturnTypeFixer, PhpdocToReturnTypeFixer, VoidReturnFixer. + */ + public function getPriority() : int + { + return -17; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(CT::T_TYPE_COLON); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('space_before', 'Spacing to apply before colon.'))->setAllowedValues(['one', 'none'])->setDefault('none')->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php new file mode 100644 index 00000000000..8622f8ba73e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/SingleLineThrowFixer.php @@ -0,0 +1,119 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class SingleLineThrowFixer extends AbstractFixer +{ + private const REMOVE_WHITESPACE_AFTER_TOKENS = ['[']; + private const REMOVE_WHITESPACE_AROUND_TOKENS = ['(', [\T_DOUBLE_COLON]]; + private const REMOVE_WHITESPACE_BEFORE_TOKENS = [')', ']', ',', ';']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Throwing exception must be done in single line.', [new CodeSample("isTokenKindFound(\T_THROW); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, ConcatSpaceFixer. + */ + public function getPriority() : int + { + return 36; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = 0, $count = $tokens->count(); $index < $count; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_THROW)) { + continue; + } + $endCandidateIndex = $tokens->getNextMeaningfulToken($index); + while (!$tokens[$endCandidateIndex]->equalsAny([')', ']', ',', ';'])) { + $blockType = Tokens::detectBlockType($tokens[$endCandidateIndex]); + if (null !== $blockType) { + if (Tokens::BLOCK_TYPE_CURLY_BRACE === $blockType['type'] || !$blockType['isStart']) { + break; + } + $endCandidateIndex = $tokens->findBlockEnd($blockType['type'], $endCandidateIndex); + } + $endCandidateIndex = $tokens->getNextMeaningfulToken($endCandidateIndex); + } + $this->trimNewLines($tokens, $index, $tokens->getPrevMeaningfulToken($endCandidateIndex)); + } + } + private function trimNewLines(Tokens $tokens, int $startIndex, int $endIndex) : void + { + for ($index = $startIndex; $index < $endIndex; ++$index) { + $content = $tokens[$index]->getContent(); + if ($tokens[$index]->isGivenKind(\T_COMMENT)) { + if (\strncmp($content, '//', \strlen('//')) === 0) { + $content = '/*' . \substr($content, 2) . ' */'; + $tokens->clearAt($index + 1); + } elseif (\strncmp($content, '#', \strlen('#')) === 0) { + $content = '/*' . \substr($content, 1) . ' */'; + $tokens->clearAt($index + 1); + } elseif (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 (!Preg::match('/\\R/', $content)) { + continue; + } + $prevIndex = $tokens->getNonEmptySibling($index, -1); + if ($this->isPreviousTokenToClear($tokens[$prevIndex])) { + $tokens->clearAt($index); + continue; + } + $nextIndex = $tokens->getNonEmptySibling($index, 1); + if ($this->isNextTokenToClear($tokens[$nextIndex]) && !$tokens[$prevIndex]->isGivenKind(\T_FUNCTION)) { + $tokens->clearAt($index); + continue; + } + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + } + private function isPreviousTokenToClear(Token $token) : bool + { + static $tokens = null; + if (null === $tokens) { + $tokens = \array_merge(self::REMOVE_WHITESPACE_AFTER_TOKENS, self::REMOVE_WHITESPACE_AROUND_TOKENS); + } + return $token->equalsAny($tokens) || $token->isObjectOperator(); + } + private function isNextTokenToClear(Token $token) : bool + { + static $tokens = null; + if (null === $tokens) { + $tokens = \array_merge(self::REMOVE_WHITESPACE_AROUND_TOKENS, self::REMOVE_WHITESPACE_BEFORE_TOKENS); + } + return $token->equalsAny($tokens) || $token->isObjectOperator(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php new file mode 100644 index 00000000000..9380c207755 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/StaticLambdaFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +final class StaticLambdaFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Lambdas not (indirect) referencing `$this` must be declared `static`.', [new CodeSample("bindTo` on lambdas without referencing to `$this`.'); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_FUNCTION, \T_FN]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $analyzer = new TokensAnalyzer($tokens); + $expectedFunctionKinds = [\T_FUNCTION, \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; + // lambda is already 'static' + } + $argumentsStartIndex = $tokens->getNextTokenOfKind($index, ['(']); + $argumentsEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStartIndex); + // figure out where the lambda starts and ends + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, ['{']); + $lambdaEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $lambdaOpenIndex); + } else { + // T_FN + $lambdaOpenIndex = $tokens->getNextTokenOfKind($argumentsEndIndex, [[\T_DOUBLE_ARROW]]); + $lambdaEndIndex = $this->findExpressionEnd($tokens, $lambdaOpenIndex); + } + if ($this->hasPossibleReferenceToThis($tokens, $lambdaOpenIndex, $lambdaEndIndex)) { + continue; + } + // make the lambda static + $tokens->insertAt($index, [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])]); + $index -= 4; + // fixed after a lambda, closes candidate is at least 4 tokens before that + } + } + private function findExpressionEnd(Tokens $tokens, int $index) : int + { + $nextIndex = $tokens->getNextMeaningfulToken($index); + while (null !== $nextIndex) { + /** @var Token $nextToken */ + $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; + } + /** + * Returns 'true' if there is a possible reference to '$this' within the given tokens index range. + */ + private function hasPossibleReferenceToThis(Tokens $tokens, int $startIndex, int $endIndex) : bool + { + for ($i = $startIndex; $i <= $endIndex; ++$i) { + if ($tokens[$i]->isGivenKind(\T_VARIABLE) && '$this' === \strtolower($tokens[$i]->getContent())) { + return \true; + // directly accessing '$this' + } + if ($tokens[$i]->isGivenKind([ + \T_INCLUDE, + // loading additional symbols we cannot analyze here + \T_INCLUDE_ONCE, + // " + \T_REQUIRE, + // " + \T_REQUIRE_ONCE, + // " + CT::T_DYNAMIC_VAR_BRACE_OPEN, + // "$h = ${$g};" case + \T_EVAL, + ])) { + return \true; + } + if ($tokens[$i]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($i); + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + return \true; + // "$$a" case + } + } + if ($tokens[$i]->equals([\T_STRING, 'parent'], \false)) { + return \true; + // parent:: case + } + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php new file mode 100644 index 00000000000..53587cbeb58 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/UseArrowFunctionsFixer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gregor Harlan + */ +final class UseArrowFunctionsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Anonymous functions with one-liner return statement must use arrow functions.', [new VersionSpecificCodeSample(<<<'SAMPLE' +isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before FunctionDeclarationFixer. + */ + public function getPriority() : int + { + return 32; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $analyzer = new TokensAnalyzer($tokens); + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION) || !$analyzer->isLambda($index)) { + continue; + } + // Find parameters end + // Abort if they are multilined + $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; + } + // Find `use ()` start and end + // Abort if it contains reference variables + $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('&')) { + // variables used by reference are not supported by arrow functions + continue 2; + } + $next = $tokens->getNextMeaningfulToken($next); + } + $useEnd = $next; + $next = $tokens->getNextMeaningfulToken($next); + } + // Find opening brace and following `return` + // Abort if there is more than whitespace between them (like comments) + $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; + } + // Find semicolon of `return` statement + $semicolon = $tokens->getNextTokenOfKind($return, ['{', ';']); + if (!$tokens[$semicolon]->equals(';')) { + continue; + } + // Find closing brace + // Abort if there is more than whitespace between semicolon and closing brace + $braceClose = $semicolon + 1; + if ($tokens[$braceClose]->isGivenKind(\T_WHITESPACE)) { + ++$braceClose; + } + if (!$tokens[$braceClose]->equals('}')) { + continue; + } + // Abort if the `return` statement is multilined + if ($this->isMultilined($tokens, $return, $semicolon)) { + continue; + } + // Transform the function to an arrow function + $this->transform($tokens, $index, $useStart, $useEnd, $braceOpen, $return, $semicolon, $braceClose); + } + } + private function isMultilined(Tokens $tokens, int $start, int $end) : bool + { + for ($i = $start; $i < $end; ++$i) { + if (\strpos($tokens[$i]->getContent(), "\n") !== \false) { + return \true; + } + } + return \false; + } + private function transform(Tokens $tokens, int $index, ?int $useStart, ?int $useEnd, int $braceOpen, int $return, int $semicolon, int $braceClose) : void + { + $tokensToInsert = [new Token([\T_DOUBLE_ARROW, '=>'])]; + if ($tokens->getNextMeaningfulToken($return) === $semicolon) { + $tokensToInsert[] = new Token([\T_WHITESPACE, ' ']); + $tokensToInsert[] = new Token([\T_STRING, 'null']); + } + $tokens->clearRange($semicolon, $braceClose); + $tokens->clearRange($braceOpen + 1, $return); + $tokens->overrideRange($braceOpen, $braceOpen, $tokensToInsert); + if (null !== $useStart) { + $tokens->clearRange($useStart, $useEnd); + } + $tokens[$index] = new Token([\T_FN, 'fn']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php new file mode 100644 index 00000000000..eabe79445ab --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/FunctionNotation/VoidReturnFixer.php @@ -0,0 +1,186 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\FunctionNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Mark Nielsen + */ +final class VoidReturnFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + 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 CodeSample("isTokenKindFound(\T_FUNCTION); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // These cause syntax errors. + static $excludedFunctions = [[\T_STRING, '__clone'], [\T_STRING, '__construct'], [\T_STRING, '__debugInfo'], [\T_STRING, '__destruct'], [\T_STRING, '__isset'], [\T_STRING, '__serialize'], [\T_STRING, '__set_state'], [\T_STRING, '__sleep'], [\T_STRING, '__toString']]; + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + $functionName = $tokens->getNextMeaningfulToken($index); + if ($tokens[$functionName]->equalsAny($excludedFunctions, \false)) { + continue; + } + $startIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($this->hasReturnTypeHint($tokens, $startIndex)) { + continue; + } + if ($tokens[$startIndex]->equals(';')) { + // No function body defined, fallback to PHPDoc. + 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); + } + } + } + /** + * Determine whether there is a non-void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasReturnAnnotation(Tokens $tokens, int $index) : bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] !== $return->getTypes()) { + return \true; + } + } + return \false; + } + /** + * Determine whether there is a void return annotation in the function's PHPDoc comment. + * + * @param int $index The index of the function token + */ + private function hasVoidReturnAnnotation(Tokens $tokens, int $index) : bool + { + foreach ($this->findReturnAnnotations($tokens, $index) as $return) { + if (['void'] === $return->getTypes()) { + return \true; + } + } + return \false; + } + /** + * Determine whether the function already has a return type hint. + * + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function hasReturnTypeHint(Tokens $tokens, int $index) : bool + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $nextIndex = $tokens->getNextMeaningfulToken($endFuncIndex); + return $tokens[$nextIndex]->isGivenKind(CT::T_TYPE_COLON); + } + /** + * Determine whether the function has a void return. + * + * @param int $startIndex Start of function body + * @param int $endIndex End of function body + */ + private function hasVoidReturn(Tokens $tokens, int $startIndex, int $endIndex) : bool + { + $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; + // Generators cannot return void. + } + if (!$tokens[$i]->isGivenKind(\T_RETURN)) { + continue; + } + $i = $tokens->getNextMeaningfulToken($i); + if (!$tokens[$i]->equals(';')) { + return \false; + } + } + return \true; + } + /** + * @param int $index The index of the end of the function definition line, EG at { or ; + */ + private function fixFunctionDefinition(Tokens $tokens, int $index) : void + { + $endFuncIndex = $tokens->getPrevTokenOfKind($index, [')']); + $tokens->insertAt($endFuncIndex + 1, [new Token([CT::T_TYPE_COLON, ':']), new Token([\T_WHITESPACE, ' ']), new Token([\T_STRING, 'void'])]); + } + /** + * Find all the return annotations in the function's PHPDoc comment. + * + * @param int $index The index of the function token + * + * @return Annotation[] + */ + private function findReturnAnnotations(Tokens $tokens, int $index) : array + { + $previousTokens = [\T_ABSTRACT, \T_FINAL, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC]; + if (\defined('T_ATTRIBUTE')) { + // @TODO: drop condition when PHP 8.0+ is required + $previousTokens[] = \T_ATTRIBUTE; + } + do { + $index = $tokens->getPrevNonWhitespace($index); + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($previousTokens)); + if (!$tokens[$index]->isGivenKind(\T_DOC_COMMENT)) { + return []; + } + $doc = new DocBlock($tokens[$index]->getContent()); + return $doc->getAnnotationsOfType('return'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php new file mode 100644 index 00000000000..227d72c15c6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/FullyQualifiedStrictTypesFixer.php @@ -0,0 +1,189 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author VeeWee + */ +final class FullyQualifiedStrictTypesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Transforms imported FQCN parameters and return types in function arguments to short version.', [new CodeSample('isTokenKindFound(\T_FUNCTION); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $namespaceUsesAnalyzer = new NamespaceUsesAnalyzer(); + $functionsAnalyzer = new FunctionsAnalyzer(); + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $namespaceName = \strtolower($namespace->getFullName()); + $uses = []; + foreach ($namespaceUsesAnalyzer->getDeclarationsInNamespace($tokens, $namespace) as $use) { + $uses[\strtolower(\ltrim($use->getFullName(), '\\'))] = $use->getShortName(); + } + for ($index = $namespace->getScopeStartIndex(); $index < $namespace->getScopeEndIndex(); ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $this->fixFunction($functionsAnalyzer, $tokens, $index, $uses, $namespaceName); + } + } + } + } + /** + * @param array $uses + */ + private function fixFunction(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index, array $uses, string $namespaceName) : void + { + $arguments = $functionsAnalyzer->getFunctionArguments($tokens, $index); + foreach ($arguments as $argument) { + if ($argument->hasTypeAnalysis()) { + $this->replaceByShortType($tokens, $argument->getTypeAnalysis(), $uses, $namespaceName); + } + } + $returnTypeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + if (null !== $returnTypeAnalysis) { + $this->replaceByShortType($tokens, $returnTypeAnalysis, $uses, $namespaceName); + } + } + /** + * @param array $uses + */ + private function replaceByShortType(Tokens $tokens, TypeAnalysis $type, array $uses, string $namespaceName) : void + { + if ($type->isReservedType()) { + return; + } + $typeStartIndex = $type->getStartIndex(); + if ($tokens[$typeStartIndex]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $typeStartIndex = $tokens->getNextMeaningfulToken($typeStartIndex); + } + $namespaceNameLength = \strlen($namespaceName); + $types = $this->getTypes($tokens, $typeStartIndex, $type->getEndIndex()); + foreach ($types as $typeName => [$startIndex, $endIndex]) { + if (\strncmp($typeName, '\\', \strlen('\\')) !== 0) { + continue; + // Not a FQCN, no shorter type possible + } + $typeName = \substr($typeName, 1); + $typeNameLower = \strtolower($typeName); + if (isset($uses[$typeNameLower])) { + // if the type without leading "\" equals any of the full "uses" long names, it can be replaced with the short one + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($uses[$typeNameLower])); + } elseif ('' === $namespaceName) { + // if we are in the global namespace and the type is not imported the leading '\' can be removed (TODO nice config candidate) + foreach ($uses as $useShortName) { + if (\strtolower($useShortName) === $typeNameLower) { + continue 2; + } + } + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($typeName)); + } elseif (\strpos($typeName, '\\') === \false) { + // If we're NOT in the global namespace, there's no related import, + // AND used type is from global namespace, then it can't be shortened. + continue; + } elseif ($typeNameLower !== $namespaceName && \strncmp($typeNameLower, $namespaceName . '\\', \strlen($namespaceName . '\\')) === 0) { + // if the type starts with namespace and the type is not the same as the namespace it can be shortened + $typeNameShort = \substr($typeName, $namespaceNameLength + 1); + // if short names are the same, but long one are different then it cannot be shortened + foreach ($uses as $useLongName => $useShortName) { + if (\strtolower($typeNameShort) === \strtolower($useShortName) && \strtolower($typeName) !== \strtolower($useLongName)) { + continue 2; + } + } + $tokens->overrideRange($startIndex, $endIndex, $this->namespacedStringToTokens($typeNameShort)); + } + } + } + /** + * @return iterable + */ + private function getTypes(Tokens $tokens, int $index, int $endIndex) : iterable + { + $index = $typeStartIndex = $typeEndIndex = $tokens->getNextMeaningfulToken($index - 1); + $type = $tokens[$index]->getContent(); + while (\true) { + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + (yield $type => [$typeStartIndex, $typeEndIndex]); + $index = $typeStartIndex = $typeEndIndex = $tokens->getNextMeaningfulToken($index); + $type = $tokens[$index]->getContent(); + continue; + } + if ($index > $endIndex || !$tokens[$index]->isGivenKind([\T_STRING, \T_NS_SEPARATOR])) { + (yield $type => [$typeStartIndex, $typeEndIndex]); + break; + } + $typeEndIndex = $index; + $type .= $tokens[$index]->getContent(); + } + } + /** + * @return Token[] + */ + private function namespacedStringToTokens(string $input) : array + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php new file mode 100644 index 00000000000..ccbb51561db --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GlobalNamespaceImportFixer.php @@ -0,0 +1,554 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gregor Harlan + */ +final class GlobalNamespaceImportFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Imports or fully qualifies global classes/functions/constants.', [new CodeSample(' \true, 'import_constants' => \true, 'import_functions' => \true]), new CodeSample(' \false, 'import_constants' => \false, 'import_functions' => \false])]); + } + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, OrderedImportsFixer. + * Must run after NativeConstantInvocationFixer, NativeFunctionInvocationFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_DOC_COMMENT, \T_NS_SEPARATOR, \T_USE]) && $tokens->isTokenKindFound(\T_NAMESPACE) && 1 === $tokens->countTokenKind(\T_NAMESPACE) && $tokens->isMonolithicPhp(); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $namespaceAnalyses = $tokens->getNamespaceDeclarations(); + if (1 !== \count($namespaceAnalyses) || $namespaceAnalyses[0]->isGlobalNamespace()) { + 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 (\count($newImports) > 0) { + $this->insertImports($tokens, $newImports, $useDeclarations); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importConstants(Tokens $tokens, array $useDeclarations) : array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + return $declaration->isConstant(); + }, \true); + // find namespaced const declarations (`const FOO = 1`) + // and add them to the not importable names (already used) + 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); + $indices = []; + 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])) { + // found an unqualified constant invocation + // add it to the not importable names (already used) + $other[$name] = \true; + } + continue; + } + $prevIndex = $tokens->getPrevMeaningfulToken($nsSeparatorIndex); + if ($tokens[$prevIndex]->isGivenKind([CT::T_NAMESPACE_OPERATOR, \T_STRING])) { + continue; + } + $indices[] = $index; + } + return $this->prepareImports($tokens, $indices, $global, $other, \true); + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importFunctions(Tokens $tokens, array $useDeclarations) : array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + return $declaration->isFunction(); + }, \false); + // find function declarations + // and add them to the not importable names (already used) + foreach ($this->findFunctionDeclarations($tokens, 0, $tokens->count() - 1) as $name) { + $other[\strtolower($name)] = \true; + } + $analyzer = new FunctionsAnalyzer(); + $indices = []; + 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; + } + $indices[] = $index; + } + return $this->prepareImports($tokens, $indices, $global, $other, \false); + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + * + * @return array + */ + private function importClasses(Tokens $tokens, array $useDeclarations) : array + { + [$global, $other] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + return $declaration->isClass(); + }, \false); + /** @var DocBlock[] $docBlocks */ + $docBlocks = []; + // find class declarations and class usages in docblocks + // and add them to the not importable names (already used) + 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 (string $type) use($global, &$other) : void { + if (\strpos($type, '\\') !== \false) { + 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(); + $indices = []; + 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; + } + $indices[] = $index; + } + $imports = []; + foreach ($docBlocks as $index => $docBlock) { + $changed = $this->traverseDocBlockTypes($docBlock, static function (string $type) use($global, $other, &$imports) : string { + if ('\\' !== $type[0]) { + return $type; + } + $name = \substr($type, 1); + $checkName = \strtolower($name); + if (\strpos($checkName, '\\') !== \false || 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, $indices, $global, $other, \false); + } + /** + * Removes the leading slash at the given indices (when the name is not already used). + * + * @param int[] $indices + * @param array $other + * + * @return array array keys contain the names that must be imported + */ + private function prepareImports(Tokens $tokens, array $indices, array $global, array $other, bool $caseSensitive) : array + { + $imports = []; + foreach ($indices 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; + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function insertImports(Tokens $tokens, array $imports, array $useDeclarations) : void + { + if (\count($useDeclarations) > 0) { + $useDeclaration = \end($useDeclarations); + $index = $useDeclaration->getEndIndex() + 1; + } else { + $namespace = $tokens->getNamespaceDeclarations()[0]; + $index = $namespace->getEndIndex() + 1; + } + $lineEnding = $this->whitespacesConfig->getLineEnding(); + if (!$tokens[$index]->isWhitespace() || \strpos($tokens[$index]->getContent(), "\n") === \false) { + $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); + } + } + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyConstants(Tokens $tokens, array $useDeclarations) : void + { + if (!$tokens->isTokenKindFound(CT::T_CONST_IMPORT)) { + return; + } + [$global] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + 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, '\\'])); + } + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyFunctions(Tokens $tokens, array $useDeclarations) : void + { + if (!$tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + return; + } + [$global] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + 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, '\\'])); + } + } + /** + * @param NamespaceUseAnalysis[] $useDeclarations + */ + private function fullyQualifyClasses(Tokens $tokens, array $useDeclarations) : void + { + if (!$tokens->isTokenKindFound(\T_USE)) { + return; + } + [$global] = $this->filterUseDeclarations($useDeclarations, static function (NamespaceUseAnalysis $declaration) : bool { + 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 (string $type) use($global) : string { + 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, '\\'])); + } + } + /** + * @param NamespaceUseAnalysis[] $declarations + */ + private function filterUseDeclarations(array $declarations, callable $callback, bool $caseSensitive) : array + { + $global = []; + $other = []; + foreach ($declarations as $declaration) { + if (!$callback($declaration)) { + continue; + } + $fullName = \ltrim($declaration->getFullName(), '\\'); + if (\strpos($fullName, '\\') !== \false) { + $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]; + } + /** + * @return iterable + */ + private function findFunctionDeclarations(Tokens $tokens, int $start, int $end) : iterable + { + 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) : bool + { + $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); + if (0 === \count($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 [$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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php new file mode 100644 index 00000000000..fa0872a85a7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/GroupImportFixer.php @@ -0,0 +1,191 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Volodymyr Kupriienko + */ +final class GroupImportFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST be group use for the same namespaces.', [new CodeSample("isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $useWithSameNamespaces = $this->getSameNamespaces($tokens); + if ([] === $useWithSameNamespaces) { + return; + } + $this->removeSingleUseStatements($useWithSameNamespaces, $tokens); + $this->addGroupUseStatements($useWithSameNamespaces, $tokens); + } + /** + * Gets namespace use analyzers with same namespaces. + * + * @return NamespaceUseAnalysis[] + */ + private function getSameNamespaces(Tokens $tokens) : array + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + if (0 === \count($useDeclarations)) { + return []; + } + $allNamespaceAndType = \array_map(function (NamespaceUseAnalysis $useDeclaration) : string { + return $this->getNamespaceNameWithSlash($useDeclaration) . $useDeclaration->getType(); + }, $useDeclarations); + $sameNamespaces = \array_filter(\array_count_values($allNamespaceAndType), static function (int $count) : bool { + return $count > 1; + }); + $sameNamespaces = \array_keys($sameNamespaces); + $sameNamespaceAnalysis = \array_filter($useDeclarations, function (NamespaceUseAnalysis $useDeclaration) use($sameNamespaces) : bool { + $namespaceNameAndType = $this->getNamespaceNameWithSlash($useDeclaration) . $useDeclaration->getType(); + return \in_array($namespaceNameAndType, $sameNamespaces, \true); + }); + \usort($sameNamespaceAnalysis, function (NamespaceUseAnalysis $a, NamespaceUseAnalysis $b) : int { + $namespaceA = $this->getNamespaceNameWithSlash($a); + $namespaceB = $this->getNamespaceNameWithSlash($b); + return \strlen($namespaceA) - \strlen($namespaceB) ?: \strcmp($a->getFullName(), $b->getFullName()); + }); + return $sameNamespaceAnalysis; + } + /** + * @param NamespaceUseAnalysis[] $statements + */ + private function removeSingleUseStatements(array $statements, Tokens $tokens) : void + { + 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); + } + } + } + /** + * @param NamespaceUseAnalysis[] $statements + */ + private function addGroupUseStatements(array $statements, Tokens $tokens) : void + { + $currentUseDeclaration = null; + $insertIndex = \array_slice($statements, -1)[0]->getEndIndex() + 1; + foreach ($statements as $index => $useDeclaration) { + if ($this->areDeclarationsDifferent($currentUseDeclaration, $useDeclaration)) { + $currentUseDeclaration = $useDeclaration; + $insertIndex += $this->createNewGroup($tokens, $insertIndex, $useDeclaration, $this->getNamespaceNameWithSlash($currentUseDeclaration)); + } else { + $newTokens = [new Token(','), new Token([\T_WHITESPACE, ' '])]; + if ($useDeclaration->isAliased()) { + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + $newTokens = []; + $insertIndex += $this->insertToGroupUseWithAlias($tokens, $insertIndex, $useDeclaration); + } + $newTokens[] = new Token([\T_STRING, $useDeclaration->getShortName()]); + if (!isset($statements[$index + 1]) || $this->areDeclarationsDifferent($currentUseDeclaration, $statements[$index + 1])) { + $newTokens[] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + $newTokens[] = new Token(';'); + $newTokens[] = new Token([\T_WHITESPACE, "\n"]); + } + $tokens->insertAt($insertIndex, $newTokens); + $insertIndex += \count($newTokens); + } + } + } + private function getNamespaceNameWithSlash(NamespaceUseAnalysis $useDeclaration) : string + { + $position = \strrpos($useDeclaration->getFullName(), '\\'); + if (\false === $position || 0 === $position) { + return $useDeclaration->getFullName(); + } + return \substr($useDeclaration->getFullName(), 0, $position + 1); + } + /** + * Insert use with alias to the group. + */ + private function insertToGroupUseWithAlias(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration) : int + { + $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); + } + /** + * Creates new use statement group. + */ + private function createNewGroup(Tokens $tokens, int $insertIndex, NamespaceUseAnalysis $useDeclaration, string $currentNamespace) : int + { + $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) + 1; + $insertedTokens += $inserted; + $insertIndex += $inserted; + } + $tokens->insertAt($insertIndex, new Token([\T_STRING, $useDeclaration->getShortName()])); + return ++$insertedTokens; + } + /** + * Check if namespace use analyses are different. + */ + private function areDeclarationsDifferent(?NamespaceUseAnalysis $analysis1, ?NamespaceUseAnalysis $analysis2) : bool + { + if (null === $analysis1 || null === $analysis2) { + return \true; + } + $namespaceName1 = $this->getNamespaceNameWithSlash($analysis1); + $namespaceName2 = $this->getNamespaceNameWithSlash($analysis2); + return $namespaceName1 !== $namespaceName2 || $analysis1->getType() !== $analysis2->getType(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php new file mode 100644 index 00000000000..5b8f0dbed57 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoLeadingImportSlashFixer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Carlos Cirello + */ +final class NoLeadingImportSlashFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove leading slashes in `use` clauses.', [new CodeSample("isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $usesIndices = $tokensAnalyzer->getImportUseIndexes(); + foreach ($usesIndices 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, int $index) : void + { + $previousIndex = $tokens->getPrevNonWhitespace($index); + if ($previousIndex < $index - 1 || $tokens[$previousIndex]->isComment()) { + $tokens->clearAt($index); + return; + } + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php new file mode 100644 index 00000000000..b564bff04f1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnneededImportAliasFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUnneededImportAliasFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Imports should not be aliased as the same name.', [new CodeSample("isAllTokenKindsFound([\T_USE, \T_AS]); + } + /** + * {@inheritdoc} + * + * Must run before NoSinglelineWhitespaceBeforeSemicolonsFixer. + */ + public function getPriority() : int + { + return 1; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; 0 <= $index; --$index) { + if (!$tokens[$index]->isGivenKind(\T_AS)) { + continue; + } + $aliasIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$aliasIndex]->isGivenKind(\T_STRING)) { + continue; + } + $importIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$importIndex]->isGivenKind(\T_STRING)) { + continue; + } + if ($tokens[$importIndex]->getContent() !== $tokens[$aliasIndex]->getContent()) { + continue; + } + do { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } while ($tokens[$importIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING, \T_AS]) || $tokens[$importIndex]->equals(',')); + if ($tokens[$importIndex]->isGivenKind([CT::T_FUNCTION_IMPORT, CT::T_CONST_IMPORT])) { + $importIndex = $tokens->getPrevMeaningfulToken($importIndex); + } + if (!$tokens[$importIndex]->isGivenKind([\T_USE, CT::T_GROUP_IMPORT_BRACE_OPEN])) { + continue; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($aliasIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php new file mode 100644 index 00000000000..778c092d02c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/NoUnusedImportsFixer.php @@ -0,0 +1,213 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + */ +final class NoUnusedImportsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Unused `use` statements must be removed.', [new CodeSample("isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $useDeclarations = (new NamespaceUsesAnalyzer())->getDeclarationsFromTokens($tokens); + if (0 === \count($useDeclarations)) { + return; + } + foreach ($tokens->getNamespaceDeclarations() as $namespace) { + $currentNamespaceUseDeclarations = []; + $currentNamespaceUseDeclarationIndices = []; + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->getStartIndex() >= $namespace->getScopeStartIndex() && $useDeclaration->getEndIndex() <= $namespace->getScopeEndIndex()) { + $currentNamespaceUseDeclarations[] = $useDeclaration; + $currentNamespaceUseDeclarationIndices[$useDeclaration->getStartIndex()] = $useDeclaration->getEndIndex(); + } + } + foreach ($currentNamespaceUseDeclarations as $useDeclaration) { + if (!$this->isImportUsed($tokens, $namespace, $useDeclaration, $currentNamespaceUseDeclarationIndices)) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + $this->removeUsesInSameNamespace($tokens, $currentNamespaceUseDeclarations, $namespace); + } + } + /** + * @param array $ignoredIndices indices of the use statements themselves that should not be checked as being "used" + */ + private function isImportUsed(Tokens $tokens, NamespaceAnalysis $namespace, NamespaceUseAnalysis $import, array $ignoredIndices) : bool + { + $analyzer = new TokensAnalyzer($tokens); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $tokensNotBeforeFunctionCall = [\T_NEW]; + $attributeIsDefined = \defined('T_ATTRIBUTE'); + if ($attributeIsDefined) { + // @TODO: drop condition when PHP 8.0+ is required + $tokensNotBeforeFunctionCall[] = \T_ATTRIBUTE; + } + $namespaceEndIndex = $namespace->getScopeEndIndex(); + $inAttribute = \false; + for ($index = $namespace->getScopeStartIndex(); $index <= $namespaceEndIndex; ++$index) { + $token = $tokens[$index]; + if ($attributeIsDefined && $token->isGivenKind(\T_ATTRIBUTE)) { + $inAttribute = \true; + continue; + } + if ($attributeIsDefined && $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $inAttribute = \false; + continue; + } + if (isset($ignoredIndices[$index])) { + $index = $ignoredIndices[$index]; + continue; + } + if ($token->isGivenKind(\T_STRING)) { + if (0 !== \strcasecmp($import->getShortName(), $token->getContent())) { + continue; + } + if ($inAttribute) { + return \true; + } + $prevMeaningfulToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + if ($prevMeaningfulToken->isGivenKind(\T_NAMESPACE)) { + $index = $tokens->getNextTokenOfKind($index, [';', '{', [\T_CLOSE_TAG]]); + continue; + } + if ($prevMeaningfulToken->isGivenKind([\T_NS_SEPARATOR, \T_FUNCTION, \T_CONST, \T_DOUBLE_COLON]) || $prevMeaningfulToken->isObjectOperator()) { + continue; + } + $nextMeaningfulIndex = $tokens->getNextMeaningfulToken($index); + if ($gotoLabelAnalyzer->belongsToGoToLabel($tokens, $nextMeaningfulIndex)) { + continue; + } + $nextMeaningfulToken = $tokens[$nextMeaningfulIndex]; + if ($analyzer->isConstantInvocation($index)) { + $type = NamespaceUseAnalysis::TYPE_CONSTANT; + } elseif ($nextMeaningfulToken->equals('(') && !$prevMeaningfulToken->isGivenKind($tokensNotBeforeFunctionCall)) { + $type = NamespaceUseAnalysis::TYPE_FUNCTION; + } else { + $type = NamespaceUseAnalysis::TYPE_CLASS; + } + if ($import->getType() === $type) { + return \true; + } + continue; + } + if ($token->isComment() && Preg::match('/(?getShortName() . '(?![[:alnum:]])/i', $token->getContent())) { + return \true; + } + } + return \false; + } + private function removeUseDeclaration(Tokens $tokens, NamespaceUseAnalysis $useDeclaration) : void + { + for ($index = $useDeclaration->getEndIndex() - 1; $index >= $useDeclaration->getStartIndex(); --$index) { + if ($tokens[$index]->isComment()) { + continue; + } + if (!$tokens[$index]->isWhitespace() || \strpos($tokens[$index]->getContent(), "\n") === \false) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + continue; + } + // when multi line white space keep the line feed if the previous token is a comment + $prevIndex = $tokens->getPrevNonWhitespace($index); + if ($tokens[$prevIndex]->isComment()) { + $content = $tokens[$index]->getContent(); + $tokens[$index] = new Token([\T_WHITESPACE, \substr($content, \strrpos($content, "\n"))]); + // preserve indent only + } else { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + if ($tokens[$useDeclaration->getEndIndex()]->equals(';')) { + // do not remove `? >` + $tokens->clearAt($useDeclaration->getEndIndex()); + } + // remove white space above and below where the `use` statement was + $prevIndex = $useDeclaration->getStartIndex() - 1; + $prevToken = $tokens[$prevIndex]; + if ($prevToken->isWhitespace()) { + $content = \rtrim($prevToken->getContent(), " \t"); + $tokens->ensureWhitespaceAtIndex($prevIndex, 0, $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); + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + $nextToken = $tokens[$nextIndex]; + } + if ($prevToken->isWhitespace() && $nextToken->isWhitespace()) { + $content = $prevToken->getContent() . $nextToken->getContent(); + $tokens->ensureWhitespaceAtIndex($nextIndex, 0, $content); + $tokens->clearAt($prevIndex); + } + } + /** + * @param list $useDeclarations + */ + private function removeUsesInSameNamespace(Tokens $tokens, array $useDeclarations, NamespaceAnalysis $namespaceDeclaration) : void + { + $namespace = $namespaceDeclaration->getFullName(); + $nsLength = \strlen($namespace . '\\'); + foreach ($useDeclarations as $useDeclaration) { + if ($useDeclaration->isAliased()) { + continue; + } + $useDeclarationFullName = \ltrim($useDeclaration->getFullName(), '\\'); + if (\strncmp($useDeclarationFullName, $namespace . '\\', \strlen($namespace . '\\')) !== 0) { + continue; + } + $partName = \substr($useDeclarationFullName, $nsLength); + if (\strpos($partName, '\\') === \false) { + $this->removeUseDeclaration($tokens, $useDeclaration); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php new file mode 100644 index 00000000000..c2c8414e56d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/OrderedImportsFixer.php @@ -0,0 +1,425 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Sebastiaan Stok + * @author Dariusz Rumiński + * @author Darius Matulionis + * @author Adriano Pilger + */ +final class OrderedImportsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const IMPORT_TYPE_CLASS = 'class'; + /** + * @internal + */ + public const IMPORT_TYPE_CONST = 'const'; + /** + * @internal + */ + public const IMPORT_TYPE_FUNCTION = 'function'; + /** + * @internal + */ + public const SORT_ALPHA = 'alpha'; + /** + * @internal + */ + public const SORT_LENGTH = 'length'; + /** + * @internal + */ + public const SORT_NONE = 'none'; + /** + * Array of supported sort types in configuration. + * + * @var string[] + */ + private const SUPPORTED_SORT_TYPES = [self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_FUNCTION]; + /** + * Array of supported sort algorithms in configuration. + * + * @var string[] + */ + private const SUPPORTED_SORT_ALGORITHMS = [self::SORT_ALPHA, self::SORT_LENGTH, self::SORT_NONE]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ordering `use` statements.', [new CodeSample(" self::SORT_LENGTH]), new CodeSample(' self::SORT_LENGTH, 'imports_order' => [self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION]]), new CodeSample(' self::SORT_ALPHA, 'imports_order' => [self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION]]), new CodeSample(' self::SORT_NONE, 'imports_order' => [self::IMPORT_TYPE_CONST, self::IMPORT_TYPE_CLASS, self::IMPORT_TYPE_FUNCTION]])]); + } + /** + * {@inheritdoc} + * + * Must run before BlankLineBetweenImportGroupsFixer. + * Must run after GlobalNamespaceImportFixer, NoLeadingImportSlashFixer. + */ + public function getPriority() : int + { + return -30; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(\true); + foreach (\array_reverse($namespacesImports) as $usesPerNamespaceIndices) { + $count = \count($usesPerNamespaceIndices); + if (0 === $count) { + continue; + // nothing to sort + } + if (1 === $count) { + $this->setNewOrder($tokens, $this->getNewOrder($usesPerNamespaceIndices, $tokens)); + continue; + } + $groupUsesOffset = 0; + $groupUses = [$groupUsesOffset => [$usesPerNamespaceIndices[0]]]; + // if there's some logic between two `use` statements, sort only imports grouped before that logic + for ($index = 0; $index < $count - 1; ++$index) { + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [';', [\T_CLOSE_TAG]]); + if ($tokens[$nextGroupUse]->isGivenKind(\T_CLOSE_TAG)) { + $nextGroupUse = $tokens->getNextTokenOfKind($usesPerNamespaceIndices[$index], [[\T_OPEN_TAG]]); + } + $nextGroupUse = $tokens->getNextMeaningfulToken($nextGroupUse); + if ($nextGroupUse !== $usesPerNamespaceIndices[$index + 1]) { + $groupUses[++$groupUsesOffset] = []; + } + $groupUses[$groupUsesOffset][] = $usesPerNamespaceIndices[$index + 1]; + } + for ($index = $groupUsesOffset; $index >= 0; --$index) { + $this->setNewOrder($tokens, $this->getNewOrder($groupUses[$index], $tokens)); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $supportedSortTypes = self::SUPPORTED_SORT_TYPES; + return new FixerConfigurationResolver([(new FixerOptionBuilder('sort_algorithm', 'Whether the statements should be sorted alphabetically or by length, or not sorted.'))->setAllowedValues(self::SUPPORTED_SORT_ALGORITHMS)->setDefault(self::SORT_ALPHA)->getOption(), (new FixerOptionBuilder('imports_order', 'Defines the order of import types.'))->setAllowedTypes(['array', 'null'])->setAllowedValues([static function (?array $value) use($supportedSortTypes) : bool { + if (null !== $value) { + $missing = \array_diff($supportedSortTypes, $value); + if (\count($missing) > 0) { + throw new InvalidOptionsException(\sprintf('Missing sort %s %s.', 1 === \count($missing) ? 'type' : 'types', Utils::naturalLanguageJoin($missing))); + } + $unknown = \array_diff($value, $supportedSortTypes); + if (\count($unknown) > 0) { + throw new InvalidOptionsException(\sprintf('Unknown sort %s %s.', 1 === \count($unknown) ? 'type' : 'types', Utils::naturalLanguageJoin($unknown))); + } + } + return \true; + }])->setDefault(null)->getOption()]); + } + /** + * This method is used for sorting the uses in a namespace. + * + * @param array $first + * @param array $second + * + * @internal + */ + private function sortAlphabetically(array $first, array $second) : int + { + // Replace backslashes by spaces before sorting for correct sort order + $firstNamespace = \str_replace('\\', ' ', $this->prepareNamespace($first['namespace'])); + $secondNamespace = \str_replace('\\', ' ', $this->prepareNamespace($second['namespace'])); + return \strcasecmp($firstNamespace, $secondNamespace); + } + /** + * This method is used for sorting the uses statements in a namespace by length. + * + * @param array $first + * @param array $second + * + * @internal + */ + private function sortByLength(array $first, array $second) : int + { + $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(string $namespace) : string + { + return \trim(Preg::replace('%/\\*(.*)\\*/%s', '', $namespace)); + } + /** + * @param list $uses + */ + private function getNewOrder(array $uses, Tokens $tokens) : array + { + $indices = []; + $originalIndices = []; + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $usesCount = \count($uses); + for ($i = 0; $i < $usesCount; ++$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']) { + // if group import, sort the items within the group definition + // figure out where the list of namespace parts within the group def. starts + $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(); + } + // fetch all parts, split up in an array of strings, move comments to the end + $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 there is any line ending inside the group import, it should be indented properly + if ('' === $firstIndent && $namespaceTokens[$k2]->isWhitespace() && \strpos($namespaceTokens[$k2]->getContent(), $lineEnding) !== \false) { + $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); + // check if the order needs to be updated, otherwise don't touch as we might change valid CS (to other valid CS). + if ($sortedParts === $parts) { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } else { + $namespace .= $firstIndent . \implode($separator, $parts) . ($hasGroupTrailingComma ? ',' : '') . $lastIndent . '}'; + } + } else { + $namespace = Tokens::fromArray($namespaceTokens)->generateCode(); + } + $indices[$startIndex] = ['namespace' => $namespace, 'startIndex' => $startIndex, 'endIndex' => $index - 1, 'importType' => $type, 'group' => $group]; + $originalIndices[] = $startIndex; + if ($index === $endIndex) { + break; + } + $namespaceTokens = []; + $nextPartIndex = $tokens->getTokenNotOfKindSibling($index, 1, [',', [\T_WHITESPACE]]); + $startIndex = $nextPartIndex; + $index = $nextPartIndex; + continue; + } + $namespaceTokens[] = $token; + ++$index; + } + } + // Is sort types provided, sorting by groups and each group by algorithm + if (null !== $this->configuration['imports_order']) { + // Grouping indices by import type. + $groupedByTypes = []; + foreach ($indices as $startIndex => $item) { + $groupedByTypes[$item['importType']][$startIndex] = $item; + } + // Sorting each group by algorithm. + foreach ($groupedByTypes as $type => $groupIndices) { + $groupedByTypes[$type] = $this->sortByAlgorithm($groupIndices); + } + // Ordering groups + $sortedGroups = []; + foreach ($this->configuration['imports_order'] as $type) { + if (isset($groupedByTypes[$type]) && [] !== $groupedByTypes[$type]) { + foreach ($groupedByTypes[$type] as $startIndex => $item) { + $sortedGroups[$startIndex] = $item; + } + } + } + $indices = $sortedGroups; + } else { + // Sorting only by algorithm + $indices = $this->sortByAlgorithm($indices); + } + $index = -1; + $usesOrder = []; + // Loop through the index but use original index order + foreach ($indices as $v) { + $usesOrder[$originalIndices[++$index]] = $v; + } + return $usesOrder; + } + /** + * @param array< + * int, + * array{ + * namespace: string, + * startIndex: int, + * endIndex: int, + * importType: string, + * group: bool, + * } + * > $indices + * + * @return array< + * int, + * array{ + * namespace: string, + * startIndex: int, + * endIndex: int, + * importType: string, + * group: bool, + * } + * > + */ + private function sortByAlgorithm(array $indices) : array + { + if (self::SORT_ALPHA === $this->configuration['sort_algorithm']) { + \uasort($indices, [$this, 'sortAlphabetically']); + } elseif (self::SORT_LENGTH === $this->configuration['sort_algorithm']) { + \uasort($indices, [$this, 'sortByLength']); + } + return $indices; + } + /** + * @param array $usesOrder + */ + private function setNewOrder(Tokens $tokens, array $usesOrder) : void + { + $mapStartToEnd = []; + foreach ($usesOrder as $use) { + $mapStartToEnd[$use['startIndex']] = $use['endIndex']; + } + // Now insert the new tokens, starting from the end + foreach (\array_reverse($usesOrder, \true) as $index => $use) { + $code = \sprintf('clearRange(0, 2); + // clear `clearAt(\count($declarationTokens) - 1); + // clear `;` + $declarationTokens->clearEmptyTokens(); + $tokens->overrideRange($index, $mapStartToEnd[$index], $declarationTokens); + if ($use['group']) { + // a group import must start with `use` and cannot be part of comma separated import list + $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, ' '])); + } + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php new file mode 100644 index 00000000000..fc5e05b617e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleImportPerStatementFixer.php @@ -0,0 +1,193 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Dariusz Rumiński + */ +final class SingleImportPerStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST be one use keyword per declaration.', [new CodeSample(' \true])]); + } + /** + * {@inheritdoc} + * + * Must run before MultilineWhitespaceBeforeSemicolonsFixer, NoLeadingImportSlashFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoUnusedImportsFixer, SpaceAfterSemicolonFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $fixGroups = $this->configuration['group_to_single_imports']; + foreach (\array_reverse($tokensAnalyzer->getImportUseIndexes()) as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + $groupClose = $tokens->getPrevMeaningfulToken($endIndex); + if ($tokens[$groupClose]->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + if ($fixGroups) { + $this->fixGroupUse($tokens, $index, $endIndex); + } + } else { + $this->fixMultipleUse($tokens, $index, $endIndex); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('group_to_single_imports', 'Whether to change group imports into single imports.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + private function getGroupDeclaration(Tokens $tokens, int $index) : array + { + $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]; + } + /** + * @return string[] + */ + private function getGroupStatements(Tokens $tokens, string $groupPrefix, int $groupOpenIndex, int $groupCloseIndex, string $comment) : array + { + $statements = []; + $statement = $groupPrefix; + for ($i = $groupOpenIndex + 1; $i <= $groupCloseIndex; ++$i) { + $token = $tokens[$i]; + if ($token->equals(',') && $tokens[$tokens->getNextMeaningfulToken($i)]->isGivenKind(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]->isGivenKind(\T_AS)) { + $statement .= ' as '; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $statement = ' function' . $statement; + $i += 2; + } elseif ($tokens[$j]->isGivenKind(CT::T_CONST_IMPORT)) { + $statement = ' const' . $statement; + $i += 2; + } + if ($token->isWhitespace(" \t") || \strncmp($tokens[$i - 1]->getContent(), '//', \strlen('//')) !== 0) { + continue; + } + } + $statement .= $token->getContent(); + } + if ('' !== $comment) { + $statements[0] .= ' ' . $comment; + } + return $statements; + } + private function fixGroupUse(Tokens $tokens, int $index, int $endIndex) : void + { + [$groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment] = $this->getGroupDeclaration($tokens, $index); + $statements = $this->getGroupStatements($tokens, $groupPrefix, $groupOpenIndex, $groupCloseIndex, $comment); + if (\count($statements) < 2) { + return; + } + $tokens->clearRange($index, $groupCloseIndex); + if ($tokens[$endIndex]->equals(';')) { + $tokens->clearAt($endIndex); + } + $ending = $this->whitespacesConfig->getLineEnding(); + $importTokens = Tokens::fromCode('clearAt(0); + $importTokens->clearEmptyTokens(); + $tokens->insertAt($index, $importTokens); + } + private function fixMultipleUse(Tokens $tokens, int $index, int $endIndex) : void + { + $nextTokenIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextTokenIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $leadingTokens = [new Token([CT::T_FUNCTION_IMPORT, 'function']), new Token([\T_WHITESPACE, ' '])]; + } elseif ($tokens[$nextTokenIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $leadingTokens = [new Token([CT::T_CONST_IMPORT, 'const']), new Token([\T_WHITESPACE, ' '])]; + } else { + $leadingTokens = []; + } + $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, ' '])); + foreach ($leadingTokens as $offset => $leadingToken) { + $tokens->insertAt($i + 2 + $offset, clone $leadingTokens[$offset]); + } + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + if ($tokens[$i - 1]->isWhitespace()) { + $tokens[$i - 1] = new Token([\T_WHITESPACE, $ending . $indent]); + } elseif (\strpos($tokens[$i - 1]->getContent(), "\n") === \false) { + $tokens->insertAt($i, new Token([\T_WHITESPACE, $ending . $indent])); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php new file mode 100644 index 00000000000..fb00a9b4c4f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Import/SingleLineAfterImportsFixer.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Import; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Ceeram + * @author Graham Campbell + */ +final class SingleLineAfterImportsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_USE); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Each namespace use MUST go on its own line and there MUST be one blank line after the use statements block.', [new CodeSample('whitespacesConfig->getLineEnding(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + $added = 0; + foreach ($tokensAnalyzer->getImportUseIndexes() as $index) { + $index += $added; + $indent = ''; + // if previous line ends with comment and current line starts with whitespace, use current 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]]); + // Handle insert index for inline T_COMMENT with whitespace after semicolon + $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; + } + // Increment insert index for inline T_COMMENT or T_DOC_COMMENT + 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; + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php new file mode 100644 index 00000000000..e9377df4cca --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Indentation.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +trait Indentation +{ + private function getLineIndentation(Tokens $tokens, int $index) : string + { + $newlineTokenIndex = $this->getPreviousNewlineTokenIndex($tokens, $index); + if (null === $newlineTokenIndex) { + return ''; + } + return $this->extractIndent($this->computeNewLineContent($tokens, $newlineTokenIndex)); + } + private function extractIndent(string $content) : string + { + if (Preg::match('/\\R(\\h*)[^\\r\\n]*$/D', $content, $matches)) { + return $matches[1]; + } + return ''; + } + private function getPreviousNewlineTokenIndex(Tokens $tokens, int $index) : ?int + { + 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 computeNewLineContent(Tokens $tokens, int $index) : string + { + $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; + } + private function isNewLineToken(Tokens $tokens, int $index) : bool + { + $token = $tokens[$index]; + if ($token->isGivenKind(\T_OPEN_TAG) && isset($tokens[$index + 1]) && !$tokens[$index + 1]->isWhitespace() && Preg::match('/\\R/', $token->getContent())) { + return \true; + } + if (!$tokens[$index]->isGivenKind([\T_WHITESPACE, \T_INLINE_HTML])) { + return \false; + } + return Preg::match('/\\R/', $this->computeNewLineContent($tokens, $index)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php new file mode 100644 index 00000000000..263df7b47a7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ClassKeywordRemoveFixer.php @@ -0,0 +1,183 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @deprecated + * + * @author Sullivan Senechal + */ +final class ClassKeywordRemoveFixer extends AbstractFixer implements DeprecatedFixerInterface +{ + /** + * @var string[] + */ + private $imports = []; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts `::class` keywords to FQCN strings.', [new CodeSample('isTokenKindFound(CT::T_CLASS_CONSTANT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $previousNamespaceScopeEndIndex = 0; + foreach ($tokens->getNamespaceDeclarations() 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, int $startIndex, int $endIndex) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $this->imports = []; + /** @var int $index */ + 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(); + } + // Imports group (PHP 7 spec) + 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 (string $import) : string { + return \trim($import); + }, \explode(',', $tokens->generatePartialCode($index + 1, $groupEndIndex - 1))); + foreach ($groupImports as $groupImport) { + $groupImportParts = \array_map(static function (string $import) : string { + 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, string $namespace, int $startIndex, int $endIndex) : void + { + 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, string $namespacePrefix, int $classIndex) : void + { + $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() && \strpos($tokens[$i]->getContent(), "\n") !== \false)) { + $tokens->clearAt($i); + } + } + $tokens->insertAt($classBeginIndex, new Token([\T_CONSTANT_ENCAPSED_STRING, "'" . $this->makeClassFQN($namespacePrefix, $classImport, $classString) . "'"])); + } + /** + * @param false|string $classImport + */ + private function makeClassFQN(string $namespacePrefix, $classImport, string $classString) : string + { + 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)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php new file mode 100644 index 00000000000..5845c5fed9e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveIssetsFixer.php @@ -0,0 +1,131 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class CombineConsecutiveIssetsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Using `isset($var) &&` multiple times should be done in one call.', [new CodeSample("isAllTokenKindsFound([\T_ISSET, \T_BOOLEAN_AND]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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); + // ')' token + $insertLocation = \prev($issetInfo) + 1; + // one index after the previous meaningful of ')' + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + while ($tokens[$booleanAndTokenIndex]->isGivenKind(\T_BOOLEAN_AND)) { + $issetIndex = $tokens->getNextMeaningfulToken($booleanAndTokenIndex); + if (!$tokens[$issetIndex]->isGivenKind(\T_ISSET)) { + $index = $issetIndex; + break; + } + // fetch info about the 'isset' statement that we're merging + $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; + } + // clone what we want to move, do not clone '(' and ')' of the 'isset' statement we're merging + $clones = $this->getTokenClones($tokens, \array_slice($nextIssetInfo, 1, -1)); + // clean up now the tokens of the 'isset' statement we're merging + $this->clearTokens($tokens, \array_merge($nextIssetInfo, [$issetIndex, $booleanAndTokenIndex])); + // insert the tokens to create the new statement + \array_unshift($clones, new Token(','), new Token([\T_WHITESPACE, ' '])); + $tokens->insertAt($insertLocation, $clones); + // correct some counts and offset based on # of tokens inserted + $numberOfTokensInserted = \count($clones); + $tokenCount += $numberOfTokensInserted; + $issetCloseBraceIndex += $numberOfTokensInserted; + $insertLocation += $numberOfTokensInserted; + $booleanAndTokenIndex = $tokens->getNextMeaningfulToken($issetCloseBraceIndex); + } + } + } + /** + * @param int[] $indices + */ + private function clearTokens(Tokens $tokens, array $indices) : void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + /** + * @param int $index of T_ISSET + * + * @return int[] indices of meaningful tokens belonging to the isset statement + */ + private function getIssetInfo(Tokens $tokens, int $index) : array + { + $openIndex = $tokens->getNextMeaningfulToken($index); + $braceOpenCount = 1; + $meaningfulTokenIndices = [$openIndex]; + for ($i = $openIndex + 1;; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + $meaningfulTokenIndices[] = $i; + if ($tokens[$i]->equals(')')) { + --$braceOpenCount; + if (0 === $braceOpenCount) { + break; + } + } elseif ($tokens[$i]->equals('(')) { + ++$braceOpenCount; + } + } + return $meaningfulTokenIndices; + } + /** + * @param int[] $indices + * + * @return Token[] + */ + private function getTokenClones(Tokens $tokens, array $indices) : array + { + $clones = []; + foreach ($indices as $i) { + $clones[] = clone $tokens[$i]; + } + return $clones; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php new file mode 100644 index 00000000000..de96b37ce01 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/CombineConsecutiveUnsetsFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class CombineConsecutiveUnsetsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Calling `unset` on multiple items should be done in one call.', [new CodeSample("isTokenKindFound(\T_UNSET); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + } + [$previousUnset, , $previousUnsetBraceEnd] = $previousUnsetCall; + // Merge the tokens inside the 'unset' call into the previous one 'unset' call. + $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; + // Remove 'unset', '(', ')' and (possibly) ';' from the merged 'unset' call. + $this->clearOffsetTokens($tokens, $tokensAddCount, [$index, $nextUnsetContentStart, $nextUnsetContentEnd]); + $nextUnsetSemicolon = $tokens->getNextMeaningfulToken($nextUnsetContentEnd); + if (null !== $nextUnsetSemicolon && $tokens[$nextUnsetSemicolon]->equals(';')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($nextUnsetSemicolon); + } + $index = $previousUnset + 1; + } + } + /** + * @param int[] $indices + */ + private function clearOffsetTokens(Tokens $tokens, int $offset, array $indices) : void + { + foreach ($indices as $index) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index + $offset); + } + } + /** + * Find a previous call to unset directly before the index. + * + * Returns an array with + * * unset index + * * opening brace index + * * closing brace index + * * end semicolon index + * + * Or the index to where the method looked for a call. + * + * @return int|int[] + */ + private function getPreviousUnsetCall(Tokens $tokens, int $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]; + } + /** + * @param int $start Index previous of the first token to move + * @param int $end Index of the last token to move + * @param int $to Upper boundary index + * + * @return int Number of tokens inserted + */ + private function moveTokens(Tokens $tokens, int $start, int $end, int $to) : int + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php new file mode 100644 index 00000000000..3a0f47dcf1a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareEqualNormalizeFixer.php @@ -0,0 +1,106 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class DeclareEqualNormalizeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $callback; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->callback = 'none' === $this->configuration['space'] ? 'removeWhitespaceAroundToken' : 'ensureWhitespaceAroundToken'; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Equal sign in declare statement should be surrounded by spaces or not following configuration.', [new CodeSample(" 'single'])]); + } + /** + * {@inheritdoc} + * + * Must run after DeclareStrictTypesFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DECLARE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $callback = $this->callback; + for ($index = 0, $count = $tokens->count(); $index < $count - 6; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_DECLARE)) { + continue; + } + $openParenthesisIndex = $tokens->getNextMeaningfulToken($index); + $closeParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openParenthesisIndex); + for ($i = $closeParenthesisIndex; $i > $openParenthesisIndex; --$i) { + if ($tokens[$i]->equals('=')) { + $this->{$callback}($tokens, $i); + } + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('space', 'Spacing to apply around the equal sign.'))->setAllowedValues(['single', 'none'])->setDefault('none')->getOption()]); + } + /** + * @param int $index of `=` token + */ + private function ensureWhitespaceAroundToken(Tokens $tokens, int $index) : void + { + 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, ' '])); + } + } + /** + * @param int $index of `=` token + */ + private function removeWhitespaceAroundToken(Tokens $tokens, int $index) : void + { + if (!$tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + $tokens->removeLeadingWhitespace($index); + } + $tokens->removeTrailingWhitespace($index); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php new file mode 100644 index 00000000000..574da7d50b1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DeclareParenthesesFixer.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +final class DeclareParenthesesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must not be spaces around `declare` statement parentheses.', [new CodeSample("isTokenKindFound(\T_DECLARE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; 0 <= $index; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind(\T_DECLARE)) { + continue; + } + $tokens->removeTrailingWhitespace($index); + $startParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(']); + $tokens->removeTrailingWhitespace($startParenthesisIndex); + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $startParenthesisIndex); + $tokens->removeLeadingWhitespace($endParenthesisIndex); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php new file mode 100644 index 00000000000..925d86339ba --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/DirConstantFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Vladimir Reznichenko + */ +final class DirConstantFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replaces `dirname(__FILE__)` expression with equivalent `__DIR__` constant.', [new CodeSample("isAllTokenKindsFound([\T_STRING, \T_FILE]); + } + /** + * {@inheritdoc} + * + * Must run before CombineNestedDirnameFixer. + */ + public function getPriority() : int + { + return 40; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $currIndex = 0; + do { + $boundaries = $this->find('dirname', $tokens, $currIndex, $tokens->count() - 1); + if (null === $boundaries) { + return; + } + [$functionNameIndex, $openParenthesis, $closeParenthesis] = $boundaries; + // analysing cursor shift, so nested expressions kept processed + $currIndex = $openParenthesis; + // ensure __FILE__ is in between (...) + $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; + } + // get rid of root namespace when it used + $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); + } + // closing parenthesis removed with leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($closeParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($closeParenthesis); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesis); + // opening parenthesis removed with trailing and leading spaces + if (!$tokens[$tokens->getNextNonWhitespace($openParenthesis)]->isComment()) { + $tokens->removeLeadingWhitespace($openParenthesis); + } + $tokens->removeTrailingWhitespace($openParenthesis); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesis); + // replace constant and remove function name + $tokens[$fileCandidateLeftIndex] = new Token([\T_DIR, '__DIR__']); + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + } while (null !== $currIndex); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php new file mode 100644 index 00000000000..c8065722a25 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ErrorSuppressionFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jules Pietri + * @author Kuba Werłos + */ +final class ErrorSuppressionFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const OPTION_MUTE_DEPRECATION_ERROR = 'mute_deprecation_error'; + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES = 'noise_remaining_usages'; + /** + * @internal + */ + public const OPTION_NOISE_REMAINING_USAGES_EXCLUDE = 'noise_remaining_usages_exclude'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Error control operator should be added to deprecation notices and/or removed from other cases.', [new CodeSample(" \true]), new CodeSample(" \true, self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE => ['unlink']])], null, 'Risky because adding/removing `@` might cause changes to code behaviour or if `trigger_error` function is overridden.'); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $excludedFunctions = \array_map(static function (string $function) : string { + return \strtolower($function); + }, $this->configuration[self::OPTION_NOISE_REMAINING_USAGES_EXCLUDE]); + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + if (\true === $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 (\false === $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 (\true === $this->configuration[self::OPTION_NOISE_REMAINING_USAGES] && !\in_array($tokens[$functionIndex]->getContent(), $excludedFunctions, \true)) { + $tokens->clearAt($index); + } + } + } + private function isDeprecationErrorCall(Tokens $tokens, int $index) : bool + { + 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']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php new file mode 100644 index 00000000000..7d032460099 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/ExplicitIndirectVariableFixer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class ExplicitIndirectVariableFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Add curly braces to indirect variables to make them clear to understand. Requires PHP >= 7.0.', [new CodeSample(<<<'EOT' +{$bar}['baz']; +echo $foo->{$callback}($baz); + +EOT +)]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_VARIABLE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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->isObjectOperator()) { + continue; + } + $openingBrace = CT::T_DYNAMIC_VAR_BRACE_OPEN; + $closingBrace = CT::T_DYNAMIC_VAR_BRACE_CLOSE; + if ($prevToken->isObjectOperator()) { + $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, '}'])]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php new file mode 100644 index 00000000000..22e695f24a1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/FunctionToConstantFixer.php @@ -0,0 +1,191 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class FunctionToConstantFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static $availableFunctions; + /** + * @var array + */ + 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) : void + { + parent::configure($configuration); + $this->functionsFixMap = []; + foreach ($this->configuration['functions'] as $key) { + $this->functionsFixMap[$key] = self::$availableFunctions[$key]; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace core functions calls returning constants with the constants.', [new CodeSample(" ['get_called_class', 'get_class_this', 'phpversion']])], null, 'Risky when any of the configured functions to replace are overridden.'); + } + /** + * {@inheritdoc} + * + * Must run before NativeFunctionCasingFixer, NoExtraBlankLinesFixer, NoSinglelineWhitespaceBeforeSemicolonsFixer, NoTrailingWhitespaceFixer, NoWhitespaceInBlankLineFixer, SelfStaticAccessorFixer. + * Must run after NoSpacesAfterFunctionNameFixer, NoSpacesInsideParenthesisFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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], + // brace open + $candidate[1], + // brace close + $candidate[2] + ); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $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_called_class', 'get_class', 'get_class_this', 'php_sapi_name', 'phpversion', 'pi'])->getOption()]); + } + /** + * @param Token[] $replacements + */ + private function fixFunctionCallToConstant(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex, array $replacements) : void + { + 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, int $index) : ?array + { + 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; + } + // test if function call without parameters + $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, int $index) : ?array + { + 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)) { + // no arguments passed + 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(string $lowerContent, int $braceOpenIndex, int $braceCloseIndex) : array + { + $clones = []; + foreach ($this->functionsFixMap[$lowerContent] as $token) { + $clones[] = clone $token; + } + return [$braceOpenIndex, $braceCloseIndex, $clones]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php new file mode 100644 index 00000000000..b3b86f2d1f9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/GetClassToClassKeywordFixer.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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; +/** + * @author John Paul E. Balandan, CPA + */ +final class GetClassToClassKeywordFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace `get_class` calls on object variables with class keyword syntax.', [new VersionSpecificCodeSample("= 80000 && $tokens->isAllTokenKindsFound([\T_STRING, \T_VARIABLE]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $indicesToClear = []; + $tokenSlices = []; + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals([\T_STRING, 'get_class'], \false)) { + continue; + } + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + continue; + } + $braceOpenIndex = $tokens->getNextMeaningfulToken($index); + $braceCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $braceOpenIndex); + if ($braceCloseIndex === $tokens->getNextMeaningfulToken($braceOpenIndex)) { + continue; + // get_class with no arguments + } + $meaningfulTokensCount = 0; + $variableTokensIndices = []; + for ($i = $braceOpenIndex + 1; $i < $braceCloseIndex; ++$i) { + if (!$tokens[$i]->equalsAny([[\T_WHITESPACE], [\T_COMMENT], [\T_DOC_COMMENT], '(', ')'])) { + ++$meaningfulTokensCount; + } + if (!$tokens[$i]->isGivenKind(\T_VARIABLE)) { + continue; + } + if ('$this' === \strtolower($tokens[$i]->getContent())) { + continue 2; + // get_class($this) + } + $variableTokensIndices[] = $i; + } + if ($meaningfulTokensCount > 1 || 1 !== \count($variableTokensIndices)) { + continue; + // argument contains more logic, or more arguments, or no variable argument + } + $indicesToClear[$index] = [$braceOpenIndex, \current($variableTokensIndices), $braceCloseIndex]; + } + foreach ($indicesToClear as $index => $items) { + $tokenSlices[$index] = $this->getReplacementTokenSlices($tokens, $items[1]); + $this->clearGetClassCall($tokens, $index, $items[0], $items[2]); + } + $tokens->insertSlices($tokenSlices); + } + /** + * @return list + */ + private function getReplacementTokenSlices(Tokens $tokens, int $variableIndex) : array + { + return [new Token([\T_VARIABLE, $tokens[$variableIndex]->getContent()]), new Token([\T_DOUBLE_COLON, '::']), new Token([CT::T_CLASS_CONSTANT, 'class'])]; + } + private function clearGetClassCall(Tokens $tokens, int $index, int $braceOpenIndex, int $braceCloseIndex) : void + { + for ($i = $braceOpenIndex; $i <= $braceCloseIndex; ++$i) { + if ($tokens[$i]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + continue; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->clearAt($prevIndex); + } + $tokens->clearAt($index); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php new file mode 100644 index 00000000000..5786ba019df --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/IsNullFixer.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Vladimir Reznichenko + */ +final class IsNullFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replaces `is_null($var)` expression with `null === $var`.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + static $sequenceNeeded = [[\T_STRING, 'is_null'], '(']; + $functionsAnalyzer = new FunctionsAnalyzer(); + $currIndex = 0; + while (\true) { + // recalculate "end" because we might have added tokens in previous iteration + $matches = $tokens->findSequence($sequenceNeeded, $currIndex, $tokens->count() - 1, \false); + // stop looping if didn't find any new matches + if (null === $matches) { + break; + } + // 0 and 1 accordingly are "is_null", "(" tokens + $matches = \array_keys($matches); + // move the cursor just after the sequence + [$isNullIndex, $currIndex] = $matches; + if (!$functionsAnalyzer->isGlobalFunctionCall($tokens, $matches[0])) { + continue; + } + $next = $tokens->getNextMeaningfulToken($currIndex); + if ($tokens[$next]->equals(')')) { + continue; + } + $prevTokenIndex = $tokens->getPrevMeaningfulToken($matches[0]); + // handle function references with namespaces + if ($tokens[$prevTokenIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + $prevTokenIndex = $tokens->getPrevMeaningfulToken($prevTokenIndex); + } + // check if inversion being used, text comparison is due to not existing constant + $isInvertedNullCheck = \false; + if ($tokens[$prevTokenIndex]->equals('!')) { + $isInvertedNullCheck = \true; + // get rid of inverting for proper transformations + $tokens->removeTrailingWhitespace($prevTokenIndex); + $tokens->clearAt($prevTokenIndex); + } + // before getting rind of `()` around a parameter, ensure it's not assignment/ternary invariant + $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; + } + } + // edge cases: is_null() followed/preceded by ==, ===, !=, !==, <>, (int-or-other-casting) + $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->isCast() || $parentLeftToken->isGivenKind($parentOperations) || $parentRightToken->isGivenKind($parentOperations); + // possible trailing comma removed + $prevIndex = $tokens->getPrevMeaningfulToken($referenceEnd); + if ($tokens[$prevIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($prevIndex); + } + if (!$isContainingDangerousConstructs) { + // closing parenthesis removed with leading spaces + $tokens->removeLeadingWhitespace($referenceEnd); + $tokens->clearAt($referenceEnd); + // opening parenthesis removed with trailing spaces + $tokens->removeLeadingWhitespace($matches[1]); + $tokens->removeTrailingWhitespace($matches[1]); + $tokens->clearAt($matches[1]); + } + // sequence which we'll use as a replacement + $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 ($wrapIntoParentheses) { + \array_unshift($replacement, new Token('(')); + $tokens->insertAt($referenceEnd + 1, new Token(')')); + } + $tokens->overrideRange($isNullIndex, $isNullIndex, $replacement); + // nested is_null calls support + $currIndex = $isNullIndex; + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php new file mode 100644 index 00000000000..5165e50ba82 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NoUnsetOnPropertyFixer.php @@ -0,0 +1,161 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gert de Pagter + */ +final class NoUnsetOnPropertyFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Properties should be set to `null` instead of using `unset`.', [new CodeSample("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() : bool + { + return \true; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_UNSET) && $tokens->isAnyTokenKindsFound([\T_OBJECT_OPERATOR, \T_PAAMAYIM_NEKUDOTAYIM]); + } + /** + * {@inheritdoc} + * + * Must run before CombineConsecutiveUnsetsFixer. + */ + public function getPriority() : int + { + return 25; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + // "last" as we reverse the array below + foreach (\array_reverse($unsetsInfo) as $unsetInfo) { + $this->updateTokens($tokens, $unsetInfo, $isLastUnset); + $isLastUnset = \false; + } + } + } + /** + * @return array> + */ + private function getUnsetsInfo(Tokens $tokens, int $index) : array + { + $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, int $index, int $endIndex) : bool + { + 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; + } + /** + * @param array> $unsetsInfo + */ + private function isAnyUnsetToTransform(array $unsetsInfo) : bool + { + foreach ($unsetsInfo as $unsetInfo) { + if ($unsetInfo['isToTransform']) { + return \true; + } + } + return \false; + } + /** + * @param array $unsetInfo + */ + private function updateTokens(Tokens $tokens, array $unsetInfo, bool $isLastUnset) : void + { + // if entry is first and to be transformed we remove leading "unset(" + if ($unsetInfo['isFirst'] && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getPrevTokenOfKind($unsetInfo['startIndex'], ['(']); + $unsetIndex = $tokens->getPrevTokenOfKind($braceIndex, [[\T_UNSET]]); + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($unsetIndex); + } + // if entry is last and to be transformed we remove trailing ")" + if ($isLastUnset && $unsetInfo['isToTransform']) { + $braceIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [')']); + $previousIndex = $tokens->getPrevMeaningfulToken($braceIndex); + if ($tokens[$previousIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($previousIndex); + // trailing ',' in function call (PHP 7.3) + } + $tokens->clearTokenAndMergeSurroundingWhitespace($braceIndex); + } + // if entry is not last we replace comma with semicolon (last entry already has semicolon - from original unset) + if (!$isLastUnset) { + $commaIndex = $tokens->getNextTokenOfKind($unsetInfo['endIndex'], [',']); + $tokens[$commaIndex] = new Token(';'); + } + // if entry is to be unset and is not last we add trailing ")" + if (!$unsetInfo['isToTransform'] && !$isLastUnset) { + $tokens->insertAt($unsetInfo['endIndex'] + 1, new Token(')')); + } + // if entry is to be unset and is not first we add leading "unset(" + if (!$unsetInfo['isToTransform'] && !$unsetInfo['isFirst']) { + $tokens->insertAt($unsetInfo['startIndex'], [new Token([\T_UNSET, 'unset']), new Token('(')]); + } + // and finally + // if entry is to be transformed we add trailing " = null" + if ($unsetInfo['isToTransform']) { + $tokens->insertAt($unsetInfo['endIndex'] + 1, [new Token([\T_WHITESPACE, ' ']), new Token('='), new Token([\T_WHITESPACE, ' ']), new Token([\T_STRING, 'null'])]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php new file mode 100644 index 00000000000..a4b9f2c7cbe --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/NullableTypeDeclarationFixer.php @@ -0,0 +1,246 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author John Paul E. Balandan, CPA + */ +final class NullableTypeDeclarationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const OPTION_SYNTAX_UNION = 'union'; + private const OPTION_SYNTAX_QUESTION_MARK = 'question_mark'; + /** + * @var int + */ + private $candidateTokenKind; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Nullable single type declaration should be standardised using configured syntax.', [new VersionSpecificCodeSample(" self::OPTION_SYNTAX_UNION]), new VersionSpecificCodeSample(' self::OPTION_SYNTAX_QUESTION_MARK])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return \PHP_VERSION_ID >= 80000 && $tokens->isTokenKindFound($this->candidateTokenKind); + } + /** + * {@inheritdoc} + * + * Must run before OrderedTypesFixer, TypesSpacesFixer. + * Must run after NullableTypeDeclarationForDefaultNullValueFixer, SingleSpaceAroundConstructFixer. + */ + public function getPriority() : int + { + return 2; + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->candidateTokenKind = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax'] ? CT::T_TYPE_ALTERNATION : CT::T_NULLABLE_TYPE; + // `?` -> `|` + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('syntax', 'Whether to use question mark (`?`) or explicit `null` union for nullable type.'))->setAllowedValues([self::OPTION_SYNTAX_UNION, self::OPTION_SYNTAX_QUESTION_MARK])->setDefault(self::OPTION_SYNTAX_QUESTION_MARK)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + foreach (\array_reverse($this->getElements($tokens), \true) as $index => $type) { + if ('property' === $type) { + $this->normalizePropertyType($tokens, $index); + continue; + } + $this->normalizeMethodReturnType($functionsAnalyzer, $tokens, $index); + $this->normalizeMethodArgumentType($functionsAnalyzer, $tokens, $index); + } + } + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens) : array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $elements = \array_map(static function (array $element) : string { + return 'method' === $element['type'] ? 'function' : $element['type']; + }, \array_filter($tokensAnalyzer->getClassyElements(), static function (array $element) : bool { + return \in_array($element['type'], ['method', 'property'], \true); + })); + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_FN) || $token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) { + $elements[$index] = 'function'; + } + } + return $elements; + } + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex) : ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } + private function isTypeNormalizable(TypeAnalysis $typeAnalysis) : bool + { + if (!$typeAnalysis->isNullable()) { + return \false; + } + $type = $typeAnalysis->getName(); + if (\strpos($type, '&') !== \false) { + return \false; + // skip DNF types + } + if (\strpos($type, '|') === \false) { + return \true; + } + return 1 === \substr_count($type, '|') && Preg::match('/(?:\\|null$|^null\\|)/i', $type); + } + private function normalizePropertyType(Tokens $tokens, int $index) : void + { + $propertyEndIndex = $index; + $propertyModifiers = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR]; + if (\defined('T_READONLY')) { + $propertyModifiers[] = \T_READONLY; + // @TODO: Drop condition when PHP 8.1+ is required + } + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyEndIndex); + if (null === $propertyType || !$this->isTypeNormalizable($propertyType)) { + return; + } + $this->normalizeNullableType($tokens, $propertyType); + } + private function normalizeMethodArgumentType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index) : void + { + foreach (\array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index), \true) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + if (null === $argumentType || !$this->isTypeNormalizable($argumentType)) { + continue; + } + $this->normalizeNullableType($tokens, $argumentType); + } + } + private function normalizeMethodReturnType(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index) : void + { + $returnType = $functionsAnalyzer->getFunctionReturnType($tokens, $index); + if (null === $returnType || !$this->isTypeNormalizable($returnType)) { + return; + } + $this->normalizeNullableType($tokens, $returnType); + } + private function normalizeNullableType(Tokens $tokens, TypeAnalysis $typeAnalysis) : void + { + $type = $typeAnalysis->getName(); + if (\strpos($type, '|') === \false && \strpos($type, '&') === \false) { + $type = ($typeAnalysis->isNullable() ? '?' : '') . $type; + } + $isQuestionMarkSyntax = self::OPTION_SYNTAX_QUESTION_MARK === $this->configuration['syntax']; + if ($isQuestionMarkSyntax) { + $normalizedType = $this->convertToNullableType($type); + $normalizedTypeAsString = \implode('', $normalizedType); + } else { + $normalizedType = $this->convertToExplicitUnionType($type); + $normalizedTypeAsString = \implode('|', $normalizedType); + } + if ($normalizedTypeAsString === $type) { + return; + // nothing to fix + } + $tokens->overrideRange($typeAnalysis->getStartIndex(), $typeAnalysis->getEndIndex(), $this->createTypeDeclarationTokens($normalizedType, $isQuestionMarkSyntax)); + } + /** + * @return list + */ + private function convertToNullableType(string $type) : array + { + if (\strncmp($type, '?', \strlen('?')) === 0) { + return [$type]; + // no need to convert; already fixed + } + return ['?', Preg::replace('/(?:\\|null$|^null\\|)/i', '', $type)]; + } + /** + * @return list + */ + private function convertToExplicitUnionType(string $type) : array + { + if (\strpos($type, '|') !== \false) { + return [$type]; + // no need to convert; already fixed + } + return ['null', \substr($type, 1)]; + } + /** + * @param list $types + * + * @return list + */ + private function createTypeDeclarationTokens(array $types, bool $isQuestionMarkSyntax) : array + { + static $specialTypes = ['?' => [CT::T_NULLABLE_TYPE, '?'], 'array' => [CT::T_ARRAY_TYPEHINT, 'array'], 'callable' => [\T_CALLABLE, 'callable'], 'static' => [\T_STATIC, 'static']]; + $count = \count($types); + $newTokens = []; + foreach ($types as $index => $type) { + if (isset($specialTypes[$type])) { + $newTokens[] = new Token($specialTypes[$type]); + } else { + foreach (\explode('\\', $type) as $nsIndex => $value) { + if (0 === $nsIndex && '' === $value) { + continue; + } + if ($nsIndex > 0) { + $newTokens[] = new Token([\T_NS_SEPARATOR, '\\']); + } + $newTokens[] = new Token([\T_STRING, $value]); + } + } + if ($index <= $count - 2 && !$isQuestionMarkSyntax) { + $newTokens[] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } + } + return $newTokens; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php new file mode 100644 index 00000000000..de8e8c08d07 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAfterConstructFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +/** + * @author Andreas Möller + * + * @deprecated + */ +final class SingleSpaceAfterConstructFixer extends AbstractProxyFixer implements ConfigurableFixerInterface, DeprecatedFixerInterface +{ + /** + * @var array + */ + 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, 'enum' => null, '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, 'namespace' => \T_NAMESPACE, '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, 'readonly' => null, 'require' => \T_REQUIRE, 'require_once' => \T_REQUIRE_ONCE, 'return' => \T_RETURN, 'static' => \T_STATIC, 'switch' => \T_SWITCH, 'throw' => \T_THROW, 'trait' => \T_TRAIT, 'try' => \T_TRY, 'type_colon' => CT::T_TYPE_COLON, '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' => \T_YIELD_FROM]; + /** + * @var \PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer + */ + private $singleSpaceAroundConstructFixer; + public function __construct() + { + $this->singleSpaceAroundConstructFixer = new \PhpCsFixer\Fixer\LanguageConstruct\SingleSpaceAroundConstructFixer(); + parent::__construct(); + } + public function getSuccessorsNames() : array + { + return \array_keys($this->proxyFixers); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->singleSpaceAroundConstructFixer->configure(['constructs_contain_a_single_space' => ['yield_from'], 'constructs_preceded_by_a_single_space' => [], 'constructs_followed_by_a_single_space' => $this->configuration['constructs']]); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ensures a single space after language constructs.', [new CodeSample(' ['echo']]), new CodeSample(' ['yield_from']])]); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer. + * Must run after ModernizeStrposFixer. + */ + public function getPriority() : int + { + return parent::getPriority(); + } + protected function createProxyFixers() : array + { + return [$this->singleSpaceAroundConstructFixer]; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $defaults = self::$tokenMap; + $tokens = \array_keys($defaults); + unset($defaults['type_colon']); + return new FixerConfigurationResolver([(new FixerOptionBuilder('constructs', 'List of constructs which must be followed by a single space.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($tokens)])->setDefault(\array_keys($defaults))->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php new file mode 100644 index 00000000000..3b056780844 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/LanguageConstruct/SingleSpaceAroundConstructFixer.php @@ -0,0 +1,248 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\LanguageConstruct; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Andreas Möller + * @author Dariusz Rumiński + */ +final class SingleSpaceAroundConstructFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static $tokenMapContainASingleSpace = [ + // for now, only one case - but we are ready to extend it, when we learn about new cases to cover + 'yield_from' => \T_YIELD_FROM, + ]; + /** + * @var array + */ + private static $tokenMapPrecededByASingleSpace = ['as' => \T_AS, 'use_lambda' => CT::T_USE_LAMBDA]; + /** + * @var array + */ + private static $tokenMapFollowedByASingleSpace = ['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, 'enum' => null, '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, 'namespace' => \T_NAMESPACE, '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, 'readonly' => null, 'require' => \T_REQUIRE, 'require_once' => \T_REQUIRE_ONCE, 'return' => \T_RETURN, 'static' => \T_STATIC, 'switch' => \T_SWITCH, 'throw' => \T_THROW, 'trait' => \T_TRAIT, 'try' => \T_TRY, 'type_colon' => CT::T_TYPE_COLON, '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' => \T_YIELD_FROM]; + /** + * @var array + */ + private $fixTokenMapFollowedByASingleSpace = []; + /** + * @var array + */ + private $fixTokenMapContainASingleSpace = []; + /** + * @var array + */ + private $fixTokenMapPrecededByASingleSpace = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + if (\defined('T_MATCH')) { + // @TODO: drop condition when PHP 8.0+ is required + self::$tokenMapFollowedByASingleSpace['match'] = \T_MATCH; + } + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + self::$tokenMapFollowedByASingleSpace['readonly'] = \T_READONLY; + } + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + self::$tokenMapFollowedByASingleSpace['enum'] = \T_ENUM; + } + $this->fixTokenMapContainASingleSpace = []; + foreach ($this->configuration['constructs_contain_a_single_space'] as $key) { + if (null !== self::$tokenMapContainASingleSpace[$key]) { + $this->fixTokenMapContainASingleSpace[$key] = self::$tokenMapContainASingleSpace[$key]; + } + } + $this->fixTokenMapPrecededByASingleSpace = []; + foreach ($this->configuration['constructs_preceded_by_a_single_space'] as $key) { + if (null !== self::$tokenMapPrecededByASingleSpace[$key]) { + $this->fixTokenMapPrecededByASingleSpace[$key] = self::$tokenMapPrecededByASingleSpace[$key]; + } + } + $this->fixTokenMapFollowedByASingleSpace = []; + foreach ($this->configuration['constructs_followed_by_a_single_space'] as $key) { + if (null !== self::$tokenMapFollowedByASingleSpace[$key]) { + $this->fixTokenMapFollowedByASingleSpace[$key] = self::$tokenMapFollowedByASingleSpace[$key]; + } + } + if (isset($this->fixTokenMapFollowedByASingleSpace['public'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_public'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC; + } + if (isset($this->fixTokenMapFollowedByASingleSpace['protected'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_protected'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED; + } + if (isset($this->fixTokenMapFollowedByASingleSpace['private'])) { + $this->fixTokenMapFollowedByASingleSpace['constructor_private'] = CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ensures a single space after language constructs.', [new CodeSample(' ['yield_from'], 'constructs_followed_by_a_single_space' => ['yield_from']]), new CodeSample(' ['use_lambda'], 'constructs_followed_by_a_single_space' => ['use_lambda']]), new CodeSample(' ['echo']]), new CodeSample(' ['yield_from']])]); + } + /** + * {@inheritdoc} + * + * Must run before BracesFixer, FunctionDeclarationFixer, NullableTypeDeclarationFixer. + * Must run after ModernizeStrposFixer. + */ + public function getPriority() : int + { + return 36; + } + public function isCandidate(Tokens $tokens) : bool + { + $tokenKinds = \array_merge(\array_values($this->fixTokenMapContainASingleSpace), \array_values($this->fixTokenMapPrecededByASingleSpace), \array_values($this->fixTokenMapFollowedByASingleSpace)); + return $tokens->isAnyTokenKindsFound($tokenKinds) && !$tokens->hasAlternativeSyntax(); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokenKindsContainASingleSpace = \array_values($this->fixTokenMapContainASingleSpace); + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsContainASingleSpace)) { + $token = $tokens[$index]; + if ($token->isGivenKind(\T_YIELD_FROM) && 'yield from' !== \strtolower($token->getContent())) { + $tokens[$index] = new Token([\T_YIELD_FROM, Preg::replace('/\\s+/', ' ', $token->getContent())]); + } + } + } + $tokenKindsPrecededByASingleSpace = \array_values($this->fixTokenMapPrecededByASingleSpace); + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($tokenKindsPrecededByASingleSpace)) { + $tokens->ensureWhitespaceAtIndex($index - 1, 1, ' '); + } + } + $tokenKindsFollowedByASingleSpace = \array_values($this->fixTokenMapFollowedByASingleSpace); + for ($index = $tokens->count() - 2; $index >= 0; --$index) { + $token = $tokens[$index]; + if (!$token->isGivenKind($tokenKindsFollowedByASingleSpace)) { + continue; + } + $whitespaceTokenIndex = $index + 1; + if ($tokens[$whitespaceTokenIndex]->equalsAny([',', ';', ')', [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]])) { + continue; + } + if ($token->isGivenKind(\T_STATIC) && !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind([\T_FN, \T_FUNCTION, \T_NS_SEPARATOR, \T_STRING, \T_VARIABLE, CT::T_ARRAY_TYPEHINT, CT::T_NULLABLE_TYPE])) { + continue; + } + if ($token->isGivenKind(\T_OPEN_TAG)) { + if ($tokens[$whitespaceTokenIndex]->equals([\T_WHITESPACE]) && \strpos($tokens[$whitespaceTokenIndex]->getContent(), "\n") === \false && \strpos($token->getContent(), "\n") === \false) { + $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->isGivenKind(\T_CONST) && $this->isMultilineConstant($tokens, $index)) { + continue; + } + if ($token->isComment() || $token->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + if ($tokens[$whitespaceTokenIndex]->equals([\T_WHITESPACE]) && \strpos($tokens[$whitespaceTokenIndex]->getContent(), "\n") !== \false) { + continue; + } + } + $tokens->ensureWhitespaceAtIndex($whitespaceTokenIndex, 0, ' '); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $tokenMapContainASingleSpaceKeys = \array_keys(self::$tokenMapContainASingleSpace); + $tokenMapPrecededByASingleSpaceKeys = \array_keys(self::$tokenMapPrecededByASingleSpace); + $tokenMapFollowedByASingleSpaceKeys = \array_keys(self::$tokenMapFollowedByASingleSpace); + return new FixerConfigurationResolver([(new FixerOptionBuilder('constructs_contain_a_single_space', 'List of constructs which must contain a single space.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($tokenMapContainASingleSpaceKeys)])->setDefault($tokenMapContainASingleSpaceKeys)->getOption(), (new FixerOptionBuilder('constructs_preceded_by_a_single_space', 'List of constructs which must be preceded by a single space.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($tokenMapPrecededByASingleSpaceKeys)])->setDefault($tokenMapPrecededByASingleSpaceKeys)->getOption(), (new FixerOptionBuilder('constructs_followed_by_a_single_space', 'List of constructs which must be followed by a single space.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($tokenMapFollowedByASingleSpaceKeys)])->setDefault($tokenMapFollowedByASingleSpaceKeys)->getOption()]); + } + private function isMultiLineReturn(Tokens $tokens, int $index) : bool + { + ++$index; + $tokenFollowingReturn = $tokens[$index]; + if (!$tokenFollowingReturn->isGivenKind(\T_WHITESPACE) || \strpos($tokenFollowingReturn->getContent(), "\n") === \false) { + return \false; + } + $nestedCount = 0; + for ($indexEnd = \count($tokens) - 1, ++$index; $index < $indexEnd; ++$index) { + if (\strpos($tokens[$index]->getContent(), "\n") !== \false) { + 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, int $index) : bool + { + $hasMoreThanOneAncestor = \false; + while (++$index) { + $token = $tokens[$index]; + if ($token->equals(',')) { + $hasMoreThanOneAncestor = \true; + continue; + } + if ($token->equals('{')) { + return \false; + } + if ($hasMoreThanOneAncestor && \strpos($token->getContent(), "\n") !== \false) { + return \true; + } + } + return \false; + } + private function isMultilineConstant(Tokens $tokens, int $index) : bool + { + $scopeEnd = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]) - 1; + $hasMoreThanOneConstant = null !== $tokens->findSequence([new Token(',')], $index + 1, $scopeEnd); + return $hasMoreThanOneConstant && $tokens->isPartialCodeMultiline($index, $scopeEnd); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php new file mode 100644 index 00000000000..6484479f834 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ListNotation/ListSyntaxFixer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ListNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class ListSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|int + */ + private $candidateTokenKind; + /** + * Use 'syntax' => 'long'|'short'. + * + * @param array $configuration + * + * @throws InvalidFixerConfigurationException + */ + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->candidateTokenKind = 'long' === $this->configuration['syntax'] ? CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN : \T_LIST; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('List (`array` destructuring) assignment should be declared using the configured syntax. Requires PHP >= 7.1.', [new CodeSample(" 'long'])]); + } + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer, TernaryOperatorSpacesFixer. + */ + public function getPriority() : int + { + return 1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound($this->candidateTokenKind); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('syntax', 'Whether to use the `long` or `short` `list` syntax.'))->setAllowedValues(['long', 'short'])->setDefault('short')->getOption()]); + } + private function fixToLongSyntax(Tokens $tokens, int $index) : void + { + 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, int $index) : void + { + $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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php new file mode 100644 index 00000000000..f86492f1dd2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLineAfterNamespaceFixer.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶3. + * + * @author Dariusz Rumiński + */ +final class BlankLineAfterNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST be one blank line after the namespace declaration.', [new CodeSample("isTokenKindFound(\T_NAMESPACE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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, int $index) : int + { + $indexToEnsureBlankLine = $index; + $nextIndex = $tokens->getNonEmptySibling($indexToEnsureBlankLine, 1); + while (null !== $nextIndex) { + $token = $tokens[$nextIndex]; + if ($token->isWhitespace()) { + if (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(string $currentContent, bool $isLastIndex) : Token + { + $ending = $this->whitespacesConfig->getLineEnding(); + $emptyLines = $isLastIndex ? $ending : $ending . $ending; + $indent = Preg::match('/^.*\\R( *)$/s', $currentContent, $matches) ? $matches[1] : ''; + return new Token([\T_WHITESPACE, $emptyLines . $indent]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php new file mode 100644 index 00000000000..a028e6486ff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/BlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,154 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * @author Graham Campbell + * @author Greg Korba + */ +final class BlankLinesBeforeNamespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Controls blank lines before a namespace declaration.', [new CodeSample(" 1]), new CodeSample(" 2]), new CodeSample(" 2]), new CodeSample(" 0, 'max_line_breaks' => 0])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + /** + * {@inheritdoc} + * + * Must run after BlankLineAfterOpeningTagFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('min_line_breaks', 'Minimum line breaks that should exist before namespace declaration.'))->setAllowedTypes(['int'])->setDefault(2)->setNormalizer(function (Options $options, $value) : int { + if ($value < 0) { + throw new InvalidFixerConfigurationException((new self())->getName(), 'Option `min_line_breaks` cannot be lower than 0.'); + } + return $value; + })->getOption(), (new FixerOptionBuilder('max_line_breaks', 'Maximum line breaks that should exist before namespace declaration.'))->setAllowedTypes(['int'])->setDefault(2)->setNormalizer(function (Options $options, $value) : int { + if ($value < 0) { + throw new InvalidFixerConfigurationException((new self())->getName(), 'Option `max_line_breaks` cannot be lower than 0.'); + } + if ($value < $options['min_line_breaks']) { + throw new InvalidFixerConfigurationException((new self())->getName(), 'Option `max_line_breaks` cannot have lower value than `min_line_breaks`.'); + } + return $value; + })->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + if ($token->isGivenKind(\T_NAMESPACE)) { + $this->fixLinesBeforeNamespace($tokens, $index, $this->configuration['min_line_breaks'], $this->configuration['max_line_breaks']); + } + } + } + /** + * Make sure # of line breaks prefixing namespace is within given range. + * + * @param int $expectedMin min. # of line breaks + * @param int $expectedMax max. # of line breaks + */ + protected function fixLinesBeforeNamespace(Tokens $tokens, int $index, int $expectedMin, int $expectedMax) : void + { + // Let's determine the total numbers of new lines before the namespace + // and the opening token + $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 = \strpos($token->getContent(), "\n") !== \false; + 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) { + // Remove all the previous new lines + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + // Remove new lines in opening token + if ($newlineInOpening) { + $tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, \rtrim($openingToken->getContent()) . ' ']); + } + return; + } + $lineEnding = $this->whitespacesConfig->getLineEnding(); + // Allow only as many line breaks as configured: + // - keep as-is when current preceding line breaks are within configured range + // - use configured max line breaks if currently there is more preceding line breaks + // - use configured min line breaks if currently there is less preceding line breaks + $newlinesForWhitespaceToken = $precedingNewlines >= $expectedMax ? $expectedMax : \max($precedingNewlines, $expectedMin); + if (null !== $openingToken) { + // Use the configured line ending for the PHP opening tag + $content = \rtrim($openingToken->getContent()); + $newContent = $content . $lineEnding; + $tokens[$openingTokenIndex] = new Token([\T_OPEN_TAG, $newContent]); + --$newlinesForWhitespaceToken; + } + if (0 === $newlinesForWhitespaceToken) { + // We have all the needed new lines in the opening tag + if ($previous->isWhitespace()) { + // Let's remove the previous token containing extra new lines + $tokens->clearAt($previousIndex); + } + return; + } + if ($previous->isWhitespace()) { + // Fix the previous whitespace token + $tokens[$previousIndex] = new Token([\T_WHITESPACE, \str_repeat($lineEnding, $newlinesForWhitespaceToken) . \substr($previous->getContent(), \strrpos($previous->getContent(), "\n") + 1)]); + } else { + // Add a new whitespace token + $tokens->insertAt($index, new Token([\T_WHITESPACE, \str_repeat($lineEnding, $newlinesForWhitespaceToken)])); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php new file mode 100644 index 00000000000..249bf308f63 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/CleanNamespaceFixer.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Tokens; +final class CleanNamespaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + $samples = []; + foreach (['namespace Foo \\ Bar;', 'echo foo /* comment */ \\ bar();'] as $sample) { + $samples[] = new VersionSpecificCodeSample("isTokenKindFound(\T_NS_SEPARATOR); + } + /** + * {@inheritdoc} + * + * Must run before PhpUnitDataProviderReturnTypeFixer. + */ + public function getPriority() : int + { + return 1; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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); + } + } + } + /** + * @param int $index start of namespace + */ + private function fixNamespace(Tokens $tokens, int $index) : int + { + $tillIndex = $index; + // go to the end of the namespace + while ($tokens[$tillIndex]->isGivenKind([\T_NS_SEPARATOR, \T_STRING])) { + $tillIndex = $tokens->getNextMeaningfulToken($tillIndex); + } + $tillIndex = $tokens->getPrevMeaningfulToken($tillIndex); + $spaceIndices = []; + for (; $index <= $tillIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_WHITESPACE)) { + $spaceIndices[] = $index; + } elseif ($tokens[$index]->isComment()) { + $tokens->clearAt($index); + } + } + if ($tokens[$index - 1]->isWhitespace()) { + \array_pop($spaceIndices); + } + foreach ($spaceIndices as $i) { + $tokens->clearAt($i); + } + return $index; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php new file mode 100644 index 00000000000..f6e53d6b8a0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoBlankLinesBeforeNamespaceFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 0, 'max_line_breaks' => 1] + */ +final class NoBlankLinesBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames() : array + { + return \array_keys($this->proxyFixers); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should be no blank lines before a namespace declaration.', [new CodeSample("configure(['min_line_breaks' => 0, 'max_line_breaks' => 1]); + return [$blankLineBeforeNamespace]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php new file mode 100644 index 00000000000..8d5e58841b9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/NoLeadingNamespaceWhitespaceFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Bram Gotink + * @author Dariusz Rumiński + */ +final class NoLeadingNamespaceWhitespaceFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_NAMESPACE); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The namespace declaration line shouldn\'t contain leading whitespace.', [new CodeSample('isGivenKind(\T_NAMESPACE)) { + continue; + } + $beforeNamespaceIndex = $index - 1; + $beforeNamespace = $tokens[$beforeNamespaceIndex]; + if (!$beforeNamespace->isWhitespace()) { + if (!self::endsWithWhitespace($beforeNamespace->getContent())) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding()])); + } + continue; + } + $lastNewline = \strrpos($beforeNamespace->getContent(), "\n"); + if (\false === $lastNewline) { + $beforeBeforeNamespace = $tokens[$index - 2]; + if (self::endsWithWhitespace($beforeBeforeNamespace->getContent())) { + $tokens->clearAt($beforeNamespaceIndex); + } else { + $tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens[$beforeNamespaceIndex] = new Token([\T_WHITESPACE, \substr($beforeNamespace->getContent(), 0, $lastNewline + 1)]); + } + } + } + private static function endsWithWhitespace(string $str) : bool + { + if ('' === $str) { + return \false; + } + return '' === \trim(\substr($str, -1)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php new file mode 100644 index 00000000000..147831ba094 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/NamespaceNotation/SingleBlankLineBeforeNamespaceFixer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\NamespaceNotation; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\Fixer\DeprecatedFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + * + * @deprecated Use `blank_lines_before_namespace` with config: ['min_line_breaks' => 2, 'max_line_breaks' => 2] (default) + */ +final class SingleBlankLineBeforeNamespaceFixer extends AbstractProxyFixer implements WhitespacesAwareFixerInterface, DeprecatedFixerInterface +{ + public function getSuccessorsNames() : array + { + return \array_keys($this->proxyFixers); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should be exactly one blank line before a namespace declaration.', [new CodeSample("isTokenKindFound(\T_NAMESPACE); + } + protected function createProxyFixers() : array + { + $blankLineBeforeNamespace = new \PhpCsFixer\Fixer\NamespaceNotation\BlankLinesBeforeNamespaceFixer(); + $blankLineBeforeNamespace->configure(['min_line_breaks' => 2, 'max_line_breaks' => 2]); + return [$blankLineBeforeNamespace]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php new file mode 100644 index 00000000000..7525a40da02 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Naming/NoHomoglyphNamesFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Naming; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Fred Cox + * @author Dariusz Rumiński + */ +final class NoHomoglyphNamesFixer extends AbstractFixer +{ + /** + * Used the program https://github.com/mcfedr/homoglyph-download + * to generate this list from + * http://homoglyphs.net/?text=abcdefghijklmnopqrstuvwxyz&lang=en&exc7=1&exc8=1&exc13=1&exc14=1. + * + * Symbols replaced include + * - Latin homoglyphs + * - IPA extensions + * - Greek and Coptic + * - Cyrillic + * - Cyrillic Supplement + * - Letterlike Symbols + * - Latin Numbers + * - Fullwidth Latin + * + * This is not the complete list of unicode homographs, but limited + * to those you are more likely to have typed/copied by accident + * + * @var array + */ + private static $replacements = ['O' => '0', '0' => '0', 'I' => '1', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', 'Α' => 'A', 'А' => 'A', 'A' => 'A', 'ʙ' => 'B', 'Β' => 'B', 'В' => 'B', 'B' => 'B', 'Ϲ' => 'C', 'С' => 'C', 'Ⅽ' => 'C', 'C' => 'C', 'Ⅾ' => 'D', 'D' => 'D', 'Ε' => 'E', 'Е' => 'E', 'E' => 'E', 'Ϝ' => 'F', 'F' => 'F', 'ɢ' => 'G', 'Ԍ' => 'G', 'G' => 'G', 'ʜ' => 'H', 'Η' => 'H', 'Н' => 'H', 'H' => 'H', 'l' => 'I', 'Ι' => 'I', 'І' => 'I', 'Ⅰ' => 'I', 'I' => 'I', 'Ј' => 'J', 'J' => 'J', 'Κ' => 'K', 'К' => 'K', 'K' => 'K', 'K' => 'K', 'ʟ' => 'L', 'Ⅼ' => 'L', 'L' => 'L', 'Μ' => 'M', 'М' => 'M', 'Ⅿ' => 'M', 'M' => 'M', 'ɴ' => 'N', 'Ν' => 'N', 'N' => 'N', 'Ο' => 'O', 'О' => 'O', 'O' => 'O', 'Ρ' => 'P', 'Р' => 'P', 'P' => 'P', 'Q' => 'Q', 'ʀ' => 'R', 'R' => 'R', 'Ѕ' => 'S', 'S' => 'S', 'Τ' => 'T', 'Т' => 'T', 'T' => 'T', 'U' => 'U', 'Ѵ' => 'V', 'Ⅴ' => 'V', 'V' => 'V', 'W' => 'W', 'Χ' => 'X', 'Х' => 'X', 'Ⅹ' => 'X', 'X' => 'X', 'ʏ' => 'Y', 'Υ' => 'Y', 'Ү' => 'Y', 'Y' => 'Y', 'Ζ' => 'Z', 'Z' => 'Z', '_' => '_', 'ɑ' => 'a', 'а' => 'a', 'a' => 'a', 'Ь' => 'b', 'b' => 'b', 'ϲ' => 'c', 'с' => 'c', 'ⅽ' => 'c', 'c' => 'c', 'ԁ' => 'd', 'ⅾ' => 'd', 'd' => 'd', 'е' => 'e', 'e' => 'e', 'f' => 'f', 'ɡ' => 'g', 'g' => 'g', 'һ' => 'h', 'h' => 'h', 'ɩ' => 'i', 'і' => 'i', 'ⅰ' => 'i', 'i' => 'i', 'ј' => 'j', 'j' => 'j', 'k' => 'k', 'ⅼ' => 'l', 'l' => 'l', 'ⅿ' => 'm', 'm' => 'm', 'n' => 'n', 'ο' => 'o', 'о' => 'o', 'o' => 'o', 'р' => 'p', 'p' => 'p', 'q' => 'q', 'r' => 'r', 'ѕ' => 's', 's' => 's', 't' => 't', 'u' => 'u', 'ν' => 'v', 'ѵ' => 'v', 'ⅴ' => 'v', 'v' => 'v', 'ѡ' => 'w', 'w' => 'w', 'х' => 'x', 'ⅹ' => 'x', 'x' => 'x', 'у' => 'y', 'y' => 'y', 'z' => 'z']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace accidental usage of homoglyphs (non ascii characters) in names.', [new CodeSample("isAnyTokenKindsFound([\T_VARIABLE, \T_STRING]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind([\T_VARIABLE, \T_STRING])) { + continue; + } + $replaced = Preg::replaceCallback('/[^[:ascii:]]/u', static function (array $matches) : string { + return self::$replacements[$matches[0]] ?? $matches[0]; + }, $token->getContent(), -1, $count); + if ($count) { + $tokens->offsetSet($index, new Token([$token->getId(), $replaced])); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php new file mode 100644 index 00000000000..12bf87eef33 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/AssignNullCoalescingToCoalesceEqualFixer.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class AssignNullCoalescingToCoalesceEqualFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Use the null coalescing assignment operator `??=` where possible.', [new VersionSpecificCodeSample("isTokenKindFound(\T_COALESCE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 1; $index > 3; --$index) { + if (!$tokens[$index]->isGivenKind(\T_COALESCE)) { + continue; + } + // make sure after '??' does not contain '? :' + $nextIndex = $tokens->getNextTokenOfKind($index, ['?', ';', [\T_CLOSE_TAG]]); + if ($tokens[$nextIndex]->equals('?')) { + continue; + } + // get what is before '??' + $beforeRange = $this->getBeforeOperator($tokens, $index); + $equalsIndex = $tokens->getPrevMeaningfulToken($beforeRange['start']); + // make sure that before that is '=' + if (!$tokens[$equalsIndex]->equals('=')) { + continue; + } + // get what is before '=' + $assignRange = $this->getBeforeOperator($tokens, $equalsIndex); + $beforeAssignmentIndex = $tokens->getPrevMeaningfulToken($assignRange['start']); + // make sure that before that is ';', '{', '}', '(', ')' or 'equalsAny([';', '{', '}', ')', '(', [\T_OPEN_TAG]])) { + continue; + } + // make sure before and after are the same + if (!RangeAnalyzer::rangeEqualsRange($tokens, $assignRange, $beforeRange)) { + continue; + } + $tokens[$equalsIndex] = new Token([\T_COALESCE_EQUAL, '??=']); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + $this->clearMeaningfulFromRange($tokens, $beforeRange); + foreach ([$equalsIndex, $assignRange['end']] as $i) { + $i = $tokens->getNonEmptySibling($i, 1); + if ($tokens[$i]->isWhitespace(" \t")) { + $tokens[$i] = new Token([\T_WHITESPACE, ' ']); + } elseif (!$tokens[$i]->isWhitespace()) { + $tokens->insertAt($i, new Token([\T_WHITESPACE, ' '])); + } + } + } + } + /** + * @return array{start: int, end: int} + */ + private function getBeforeOperator(Tokens $tokens, int $index) : array + { + $controlStructureWithoutBracesTypes = [\T_IF, \T_ELSE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE]; + $index = $tokens->getPrevMeaningfulToken($index); + $range = ['start' => $index, 'end' => $index]; + $previousIndex = $index; + $previousToken = $tokens[$previousIndex]; + while ($previousToken->equalsAny(['$', ']', ')', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [\T_NS_SEPARATOR], [\T_STRING], [\T_VARIABLE]])) { + $blockType = Tokens::detectBlockType($previousToken); + if (null !== $blockType) { + $blockStart = $tokens->findBlockStart($blockType['type'], $previousIndex); + if ($tokens[$previousIndex]->equals(')') && $tokens[$tokens->getPrevMeaningfulToken($blockStart)]->isGivenKind($controlStructureWithoutBracesTypes)) { + break; + // we went too far back + } + $previousIndex = $blockStart; + } + $index = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + $previousToken = $tokens[$previousIndex]; + } + if ($previousToken->isGivenKind(\T_OBJECT_OPERATOR)) { + $index = $this->getBeforeOperator($tokens, $previousIndex)['start']; + } elseif ($previousToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + $index = $this->getBeforeOperator($tokens, $tokens->getPrevMeaningfulToken($previousIndex))['start']; + } + $range['start'] = $index; + return $range; + } + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range) : void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php new file mode 100644 index 00000000000..7b13d9c6e72 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/BinaryOperatorSpacesFixer.php @@ -0,0 +1,662 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Dariusz Rumiński + */ +final class BinaryOperatorSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const SINGLE_SPACE = 'single_space'; + /** + * @internal + */ + public const NO_SPACE = 'no_space'; + /** + * @internal + */ + public const ALIGN = 'align'; + /** + * @internal + */ + public const ALIGN_BY_SCOPE = 'align_by_scope'; + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE = 'align_single_space'; + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_BY_SCOPE = 'align_single_space_by_scope'; + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL = 'align_single_space_minimal'; + /** + * @internal + */ + public const ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE = 'align_single_space_minimal_by_scope'; + /** + * @internal + * + * @const Placeholder used as anchor for right alignment. + */ + public const ALIGN_PLACEHOLDER = "\x02 ALIGNABLE%d \x03"; + /** + * @var string[] + */ + private const SUPPORTED_OPERATORS = ['=', '*', '/', '%', '<', '>', '|', '^', '+', '-', '&', '&=', '&&', '||', '.=', '/=', '=>', '==', '>=', '===', '!=', '<>', '!==', '<=', 'and', 'or', 'xor', '-=', '%=', '*=', '|=', '+=', '<<', '<<=', '>>', '>>=', '^=', '**', '**=', '<=>', '??', '??=']; + /** + * Keep track of the deepest level ever achieved while + * parsing the code. Used later to replace alignment + * placeholders with spaces. + * @var int + */ + private $deepestLevel; + /** + * Level counter of the current nest level. + * So one level alignments are not mixed with + * other level ones. + * @var int + */ + private $currentLevel; + /** + * @var array + */ + private static $allowedValues = [self::ALIGN, self::ALIGN_BY_SCOPE, self::ALIGN_SINGLE_SPACE, self::ALIGN_SINGLE_SPACE_MINIMAL, self::ALIGN_SINGLE_SPACE_BY_SCOPE, self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE, self::SINGLE_SPACE, self::NO_SPACE, null]; + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + /** + * @var array + */ + private $alignOperatorTokens = []; + /** + * @var array + */ + private $operators = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->operators = $this->resolveOperatorsFromConfig(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Binary operators should be surrounded by space as configured.', [new CodeSample(" ['=' => 'align', 'xor' => null]]), new CodeSample(' ['+=' => 'align_single_space']]), new CodeSample(' ['===' => 'align_single_space_minimal']]), new CodeSample(' ['|' => 'no_space']]), new CodeSample(' 1, + "baaaaaaaaaaar" => 11, +]; +', ['operators' => ['=>' => 'single_space']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align_by_scope']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align_single_space']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align_single_space_by_scope']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align_single_space_minimal']]), new CodeSample(' 12, + "baaaaaaaaaaar" => 13, + + "baz" => 1, +]; +', ['operators' => ['=>' => 'align_single_space_minimal_by_scope']])]); + } + /** + * {@inheritdoc} + * + * Must run after ArrayIndentationFixer, ArraySyntaxFixer, AssignNullCoalescingToCoalesceEqualFixer, ListSyntaxFixer, ModernizeStrposFixer, NoMultilineWhitespaceAroundDoubleArrowFixer, NoUnsetCastFixer, PowToExponentiationFixer, StandardizeNotEqualsFixer, StrictComparisonFixer. + */ + public function getPriority() : int + { + return -32; + } + public function isCandidate(Tokens $tokens) : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + // last and first tokens cannot be an operator + 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; + // skip `declare(foo ==bar)`, see `declare_equal_normalize` + } + } else { + $this->fixWhiteSpaceAroundOperator($tokens, $index); + } + // previous of binary operator is now never an operator / previous of declare statement cannot be an operator + --$index; + } + if (\count($this->alignOperatorTokens) > 0) { + $this->fixAlignment($tokens, $this->alignOperatorTokens); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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. Supported are: ' . Utils::naturalLanguageJoinWithBackticks(self::SUPPORTED_OPERATORS) . '.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $option) : bool { + foreach ($option as $operator => $value) { + if (!\in_array($operator, self::SUPPORTED_OPERATORS, \true)) { + throw new InvalidOptionsException(\sprintf('Unexpected "operators" key, expected any of %s, got "%s".', Utils::naturalLanguageJoin(self::SUPPORTED_OPERATORS), \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, Utils::naturalLanguageJoin(\array_map(static function ($value) : string { + return Utils::toString($value); + }, self::$allowedValues)), \is_object($value) ? \get_class($value) : (null === $value ? 'null' : \gettype($value) . '#' . $value))); + } + } + return \true; + }])->setDefault([])->getOption()]); + } + private function fixWhiteSpaceAroundOperator(Tokens $tokens, int $index) : void + { + $tokenContent = \strtolower($tokens[$index]->getContent()); + if (!\array_key_exists($tokenContent, $this->operators)) { + return; + // not configured to be changed + } + if (self::SINGLE_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToSingleSpace($tokens, $index); + return; + } + if (self::NO_SPACE === $this->operators[$tokenContent]) { + $this->fixWhiteSpaceAroundOperatorToNoSpace($tokens, $index); + return; + } + // schedule for alignment + $this->alignOperatorTokens[$tokenContent] = $this->operators[$tokenContent]; + if (self::ALIGN === $this->operators[$tokenContent] || self::ALIGN_BY_SCOPE === $this->operators[$tokenContent]) { + return; + } + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + if (self::ALIGN_SINGLE_SPACE_MINIMAL === $this->operators[$tokenContent] || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $this->operators[$tokenContent]) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + return; + } + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + private function fixWhiteSpaceAroundOperatorToSingleSpace(Tokens $tokens, int $index) : void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (' ' !== $content && \strpos($content, "\n") === \false && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens[$index + 1] = new Token([\T_WHITESPACE, ' ']); + } + } else { + $tokens->insertAt($index + 1, new Token([\T_WHITESPACE, ' '])); + } + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && \strpos($content, "\n") === \false && !$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, int $index) : void + { + // fix white space after operator + if ($tokens[$index + 1]->isWhitespace()) { + $content = $tokens[$index + 1]->getContent(); + if (\strpos($content, "\n") === \false && !$tokens[$tokens->getNextNonWhitespace($index + 1)]->isComment()) { + $tokens->clearAt($index + 1); + } + } + // fix white space before operator + if ($tokens[$index - 1]->isWhitespace()) { + $content = $tokens[$index - 1]->getContent(); + if (\strpos($content, "\n") === \false && !$tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } + /** + * @return false|int index of T_DECLARE where the `=` belongs to or `false` + */ + private function isEqualPartOfDeclareStatement(Tokens $tokens, int $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; + } + /** + * @return array + */ + private function resolveOperatorsFromConfig() : array + { + $operators = []; + if (null !== $this->configuration['default']) { + foreach (self::SUPPORTED_OPERATORS as $operator) { + $operators[$operator] = $this->configuration['default']; + } + } + foreach ($this->configuration['operators'] as $operator => $value) { + if (null === $value) { + unset($operators[$operator]); + } else { + $operators[$operator] = $value; + } + } + return $operators; + } + // Alignment logic related methods + /** + * @param array $toAlign + */ + private function fixAlignment(Tokens $tokens, array $toAlign) : void + { + $this->deepestLevel = 0; + $this->currentLevel = 0; + foreach ($toAlign as $tokenContent => $alignStrategy) { + // This fixer works partially on Tokens and partially on string representation of code. + // During the process of fixing internal state of single Token may be affected by injecting ALIGN_PLACEHOLDER to its content. + // The placeholder will be resolved by `replacePlaceholders` method by removing placeholder or changing it into spaces. + // That way of fixing the code causes disturbances in marking Token as changed - if code is perfectly valid then placeholder + // still be injected and removed, which will cause the `changed` flag to be set. + // To handle that unwanted behavior we work on clone of Tokens collection and then override original collection with fixed collection. + $tokensClone = clone $tokens; + if ('=>' === $tokenContent) { + $this->injectAlignmentPlaceholdersForArrow($tokensClone, 0, \count($tokens)); + } else { + $this->injectAlignmentPlaceholdersDefault($tokensClone, 0, \count($tokens), $tokenContent); + } + // for all tokens that should be aligned but do not have anything to align with, fix spacing if needed + if (self::ALIGN_SINGLE_SPACE === $alignStrategy || self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy) { + if ('=>' === $tokenContent) { + for ($index = $tokens->count() - 2; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind(\T_DOUBLE_ARROW)) { + // always binary operator, never part of declare statement + $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)) { + // never part of declare statement + $this->fixWhiteSpaceBeforeOperator($tokensClone, $index, $alignStrategy); + } + } + } + } + $tokens->setCode($this->replacePlaceholders($tokensClone, $alignStrategy, $tokenContent)); + } + } + private function injectAlignmentPlaceholdersDefault(Tokens $tokens, int $startAt, int $endAt, string $tokenContent) : void + { + $newLineFoundSinceLastPlaceholder = \true; + for ($index = $startAt; $index < $endAt; ++$index) { + $token = $tokens[$index]; + $content = $token->getContent(); + if (\strpos($content, "\n") !== \false) { + $newLineFoundSinceLastPlaceholder = \true; + } + if (\strtolower($content) === $tokenContent && $this->tokensAnalyzer->isBinaryOperator($index) && ('=' !== $content || !$this->isEqualPartOfDeclareStatement($tokens, $index)) && $newLineFoundSinceLastPlaceholder) { + $tokens[$index] = new Token(\sprintf(self::ALIGN_PLACEHOLDER, $this->currentLevel) . $content); + $newLineFoundSinceLastPlaceholder = \false; + continue; + } + if ($token->isGivenKind(\T_FN)) { + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->getLastTokenIndexOfFn($tokens, $index); + $this->injectAlignmentPlaceholders($tokens, $from + 1, $until - 1, $tokenContent); + $index = $until; + continue; + } + if ($token->isGivenKind([\T_FUNCTION, \T_CLASS])) { + $index = $tokens->getNextTokenOfKind($index, ['{', ';', '(']); + // We don't align `=` on multi-line definition of function parameters with default values + if ($tokens[$index]->equals('(')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + continue; + } + if ($tokens[$index]->equals(';')) { + continue; + } + // Update the token to the `{` one in order to apply the following logic + $token = $tokens[$index]; + } + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + continue; + } + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + continue; + } + if ($token->equals('[')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_INDEX_SQUARE_BRACE, $index); + continue; + } + if ($token->isGivenKind(CT::T_ARRAY_SQUARE_BRACE_OPEN)) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $index); + $this->injectAlignmentPlaceholders($tokens, $index + 1, $until - 1, $tokenContent); + $index = $until; + continue; + } + } + } + private function injectAlignmentPlaceholders(Tokens $tokens, int $from, int $until, string $tokenContent) : void + { + // Only inject placeholders for multi-line code + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersDefault($tokens, $from, $until, $tokenContent); + $this->currentLevel = $currentLevel; + } + } + private function injectAlignmentPlaceholdersForArrow(Tokens $tokens, int $startAt, int $endAt) : void + { + $newLineFoundSinceLastPlaceholder = \true; + $yieldFoundSinceLastPlaceholder = \false; + for ($index = $startAt; $index < $endAt; ++$index) { + /** @var Token $token */ + $token = $tokens[$index]; + $content = $token->getContent(); + if (\strpos($content, "\n") !== \false) { + $newLineFoundSinceLastPlaceholder = \true; + } + if ($token->isGivenKind(\T_YIELD)) { + $yieldFoundSinceLastPlaceholder = \true; + } + if ($token->isGivenKind(\T_FN)) { + $yieldFoundSinceLastPlaceholder = \false; + $from = $tokens->getNextMeaningfulToken($index); + $until = $this->getLastTokenIndexOfFn($tokens, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + $index = $until; + continue; + } + if ($token->isGivenKind(\T_ARRAY)) { + // don't use "$tokens->isArray()" here, short arrays are handled in the next case + $yieldFoundSinceLastPlaceholder = \false; + $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)) { + $yieldFoundSinceLastPlaceholder = \false; + $from = $index; + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE, $from); + $index = $until; + $this->injectArrayAlignmentPlaceholders($tokens, $from + 1, $until - 1); + continue; + } + // no need to analyze for `isBinaryOperator` (always true), nor if part of declare statement (not valid PHP) + // there is also no need to analyse the second arrow of a line + if ($token->isGivenKind(\T_DOUBLE_ARROW) && $newLineFoundSinceLastPlaceholder) { + if ($yieldFoundSinceLastPlaceholder) { + ++$this->deepestLevel; + ++$this->currentLevel; + } + $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]); + $newLineFoundSinceLastPlaceholder = \false; + $yieldFoundSinceLastPlaceholder = \false; + continue; + } + if ($token->equals(';')) { + ++$this->deepestLevel; + ++$this->currentLevel; + continue; + } + if ($token->equals(',')) { + for ($i = $index; $i < $endAt - 1; ++$i) { + if (\strpos($tokens[$i - 1]->getContent(), "\n") !== \false) { + $newLineFoundSinceLastPlaceholder = \true; + 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; + } + } + if ($token->equals('{')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + continue; + } + if ($token->equals('(')) { + $until = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $this->injectArrayAlignmentPlaceholders($tokens, $index + 1, $until - 1); + $index = $until; + continue; + } + } + } + private function injectArrayAlignmentPlaceholders(Tokens $tokens, int $from, int $until) : void + { + // Only inject placeholders for multi-line arrays + if ($tokens->isPartialCodeMultiline($from, $until)) { + ++$this->deepestLevel; + $currentLevel = $this->currentLevel; + $this->currentLevel = $this->deepestLevel; + $this->injectAlignmentPlaceholdersForArrow($tokens, $from, $until); + $this->currentLevel = $currentLevel; + } + } + private function fixWhiteSpaceBeforeOperator(Tokens $tokens, int $index, string $alignStrategy) : void + { + // fix white space after operator is not needed as BinaryOperatorSpacesFixer took care of this (if strategy is _not_ ALIGN) + if (!$tokens[$index - 1]->isWhitespace()) { + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + return; + } + if (self::ALIGN_SINGLE_SPACE_MINIMAL !== $alignStrategy && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy || $tokens[$tokens->getPrevNonWhitespace($index - 1)]->isComment()) { + return; + } + $content = $tokens[$index - 1]->getContent(); + if (' ' !== $content && \strpos($content, "\n") === \false) { + $tokens[$index - 1] = new Token([\T_WHITESPACE, ' ']); + } + } + /** + * Look for group of placeholders and provide vertical alignment. + */ + private function replacePlaceholders(Tokens $tokens, string $alignStrategy, string $tokenContent) : string + { + $tmpCode = $tokens->generateCode(); + for ($j = 0; $j <= $this->deepestLevel; ++$j) { + $placeholder = \sprintf(self::ALIGN_PLACEHOLDER, $j); + if (\strpos($tmpCode, $placeholder) === \false) { + continue; + } + $lines = \explode("\n", $tmpCode); + $groups = []; + $groupIndex = 0; + $groups[$groupIndex] = []; + foreach ($lines as $index => $line) { + if (\substr_count($line, $placeholder) > 0) { + $groups[$groupIndex][] = $index; + } elseif (self::ALIGN_BY_SCOPE !== $alignStrategy && self::ALIGN_SINGLE_SPACE_BY_SCOPE !== $alignStrategy && self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE !== $alignStrategy) { + ++$groupIndex; + $groups[$groupIndex] = []; + } + } + foreach ($groups as $group) { + if (\count($group) < 1) { + continue; + } + if (self::ALIGN !== $alignStrategy) { + // move placeholders to match strategy + foreach ($group as $index) { + $currentPosition = \strpos($lines[$index], $placeholder); + $before = \substr($lines[$index], 0, $currentPosition); + if (self::ALIGN_SINGLE_SPACE === $alignStrategy || self::ALIGN_SINGLE_SPACE_BY_SCOPE === $alignStrategy) { + if (\substr_compare($before, ' ', -\strlen(' ')) !== 0) { + // if last char of before-content is not ' '; add it + $before .= ' '; + } + } elseif (self::ALIGN_SINGLE_SPACE_MINIMAL === $alignStrategy || self::ALIGN_SINGLE_SPACE_MINIMAL_BY_SCOPE === $alignStrategy) { + if (!Preg::match('/^\\h+$/', $before)) { + // if indent; do not move, leave to other fixer + $before = \rtrim($before) . ' '; + } + } + $lines[$index] = $before . \substr($lines[$index], $currentPosition); + } + } + $rightmostSymbol = 0; + foreach ($group as $index) { + $rightmostSymbol = \max($rightmostSymbol, \mb_strpos($lines[$index], $placeholder)); + } + foreach ($group as $index) { + $line = $lines[$index]; + $currentSymbol = \mb_strpos($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; + } + private function getLastTokenIndexOfFn(Tokens $tokens, int $index) : int + { + $index = $tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); + while (\true) { + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->equalsAny([';', ',', [\T_CLOSE_TAG]])) { + break; + } + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null === $blockType) { + continue; + } + if ($blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + continue; + } + break; + } + return $index; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php new file mode 100644 index 00000000000..d309415a49b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ConcatSpaceFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class ConcatSpaceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var null|string + */ + private $fixCallback; + public function configure(array $configuration) : void + { + parent::configure($configuration); + if ('one' === $this->configuration['spacing']) { + $this->fixCallback = 'fixConcatenationToSingleSpace'; + } else { + $this->fixCallback = 'fixConcatenationToNoSpace'; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Concatenation should be spaced according to configuration.', [new CodeSample(" 'none']), new CodeSample(" 'one'])]); + } + /** + * {@inheritdoc} + * + * Must run after NoUnneededControlParenthesesFixer, SingleLineThrowFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('.'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $callBack = $this->fixCallback; + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if ($tokens[$index]->equals('.')) { + $this->{$callBack}($tokens, $index); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('spacing', 'Spacing to apply around concatenation operator.'))->setAllowedValues(['one', 'none'])->setDefault('none')->getOption()]); + } + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToNoSpace(Tokens $tokens, int $index) : void + { + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + if (!$prevNonWhitespaceToken->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT]) || \strncmp($prevNonWhitespaceToken->getContent(), '/*', \strlen('/*')) === 0) { + $tokens->removeLeadingWhitespace($index, " \t"); + } + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isGivenKind([\T_LNUMBER, \T_COMMENT, \T_DOC_COMMENT])) { + $tokens->removeTrailingWhitespace($index, " \t"); + } + } + /** + * @param int $index index of concatenation '.' token + */ + private function fixConcatenationToSingleSpace(Tokens $tokens, int $index) : void + { + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, 1); + $this->fixWhiteSpaceAroundConcatToken($tokens, $index, -1); + } + /** + * @param int $index index of concatenation '.' token + * @param int $offset 1 or -1 + */ + private function fixWhiteSpaceAroundConcatToken(Tokens $tokens, int $index, int $offset) : void + { + $offsetIndex = $index + $offset; + if (!$tokens[$offsetIndex]->isWhitespace()) { + $tokens->insertAt($index + (1 === $offset ?: 0), new Token([\T_WHITESPACE, ' '])); + return; + } + if (\strpos($tokens[$offsetIndex]->getContent(), "\n") !== \false) { + return; + } + if ($tokens[$index + $offset * 2]->isComment()) { + return; + } + $tokens[$offsetIndex] = new Token([\T_WHITESPACE, ' ']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php new file mode 100644 index 00000000000..f094e38e0f9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/IncrementStyleFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gregor Harlan + * @author Kuba Werłos + */ +final class IncrementStyleFixer extends AbstractIncrementOperatorFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const STYLE_PRE = 'pre'; + /** + * @internal + */ + public const STYLE_POST = 'post'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Pre- or post-increment and decrement operators should be used if possible.', [new CodeSample(" self::STYLE_POST])]); + } + /** + * {@inheritdoc} + * + * Must run before NoSpacesInsideParenthesisFixer. + * Must run after StandardizeIncrementFixer. + */ + public function getPriority() : int + { + return 15; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_INC, \T_DEC]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $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, int $index) : int + { + $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->isObjectOperator()) { + return $this->findEnd($tokens, $nextIndex); + } + if ($nextToken->isGivenKind(\T_PAAMAYIM_NEKUDOTAYIM)) { + return $this->findEnd($tokens, $tokens->getNextMeaningfulToken($nextIndex)); + } + return $index; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php new file mode 100644 index 00000000000..f738fa2c25a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/LogicalOperatorsFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Haralan Dobrev + */ +final class LogicalOperatorsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Use `&&` and `||` logical operators instead of `and` and `or`.', [new CodeSample('isAnyTokenKindsFound([\T_LOGICAL_AND, \T_LOGICAL_OR]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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, '||']); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php new file mode 100644 index 00000000000..609bcbb50dc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NewWithBracesFixer.php @@ -0,0 +1,110 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class NewWithBracesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All instances created with `new` keyword must (not) be followed by braces.', [new CodeSample(" \false]), new CodeSample(" \false])]); + } + /** + * {@inheritdoc} + * + * Must run before ClassDefinitionFixer. + */ + public function getPriority() : int + { + return 37; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_NEW); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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], [\T_SPACESHIP], [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_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG')) { + // @TODO: drop condition when PHP 8.1+ is required + $nextTokenKinds[] = [\T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG]; + $nextTokenKinds[] = [\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG]; + } + } + for ($index = $tokens->count() - 3; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_NEW)) { + continue; + } + $nextIndex = $tokens->getNextTokenOfKind($index, $nextTokenKinds); + // new anonymous class definition + if ($tokens[$nextIndex]->isGivenKind(\T_CLASS)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + if ($this->configuration['anonymous_class']) { + $this->ensureBracesAt($tokens, $nextIndex); + } else { + $this->ensureNoBracesAt($tokens, $nextIndex); + } + continue; + } + // entrance into array index syntax - need to look for exit + while ($tokens[$nextIndex]->equals('[') || $tokens[$nextIndex]->isGivenKind(CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN)) { + $nextIndex = $tokens->findBlockEnd(Tokens::detectBlockType($tokens[$nextIndex])['type'], $nextIndex); + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + if ($this->configuration['named_class']) { + $this->ensureBracesAt($tokens, $nextIndex); + } else { + $this->ensureNoBracesAt($tokens, $nextIndex); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('named_class', 'Whether named classes should be followed by parentheses.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption(), (new FixerOptionBuilder('anonymous_class', 'Whether anonymous classes should be followed by parentheses.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + private function ensureBracesAt(Tokens $tokens, int $index) : void + { + $token = $tokens[$index]; + if (!$token->equals('(') && !$token->isObjectOperator()) { + $tokens->insertAt($tokens->getPrevMeaningfulToken($index) + 1, [new Token('('), new Token(')')]); + } + } + private function ensureNoBracesAt(Tokens $tokens, int $index) : void + { + if (!$tokens[$index]->equals('(')) { + return; + } + $closingIndex = $tokens->getNextMeaningfulToken($index); + // constructor has arguments - braces can not be removed + if (!$tokens[$closingIndex]->equals(')')) { + return; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($closingIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php new file mode 100644 index 00000000000..03150e4fdf8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoSpaceAroundDoubleColonFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +final class NoSpaceAroundDoubleColonFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must be no space around double colons (also called Scope Resolution Operator or Paamayim Nekudotayim).', [new CodeSample("isTokenKindFound(\T_DOUBLE_COLON); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = \count($tokens) - 2; $index > 1; --$index) { + if ($tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + $this->removeSpace($tokens, $index, 1); + $this->removeSpace($tokens, $index, -1); + } + } + } + /** + * @param -1|1 $direction + */ + private function removeSpace(Tokens $tokens, int $index, int $direction) : void + { + if (!$tokens[$index + $direction]->isWhitespace()) { + return; + } + if ($tokens[$tokens->getNonWhitespaceSibling($index, $direction)]->isComment()) { + return; + } + $tokens->clearAt($index + $direction); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php new file mode 100644 index 00000000000..e0684d3965b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessConcatOperatorFixer.php @@ -0,0 +1,240 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUselessConcatOperatorFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const STR_DOUBLE_QUOTE = 0; + private const STR_DOUBLE_QUOTE_VAR = 1; + private const STR_SINGLE_QUOTE = 2; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be useless concat operations.', [new CodeSample(" \true])]); + } + /** + * {@inheritdoc} + * + * Must run before DateTimeCreateFromFormatCallFixer, EregToPregFixer, PhpUnitDedicateAssertInternalTypeFixer, RegularCallableCallFixer, SetTypeToCastFixer. + * Must run after NoBinaryStringFixer, SingleQuoteFixer. + */ + public function getPriority() : int + { + return 5; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound('.') && $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, '"']); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->equals('.')) { + continue; + } + $nextMeaningfulTokenIndex = $tokens->getNextMeaningfulToken($index); + if ($this->containsLinebreak($tokens, $index, $nextMeaningfulTokenIndex)) { + continue; + } + $secondOperand = $this->getConcatOperandType($tokens, $nextMeaningfulTokenIndex, 1); + if (null === $secondOperand) { + continue; + } + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + if ($this->containsLinebreak($tokens, $prevMeaningfulTokenIndex, $index)) { + continue; + } + $firstOperand = $this->getConcatOperandType($tokens, $prevMeaningfulTokenIndex, -1); + if (null === $firstOperand) { + continue; + } + $this->fixConcatOperation($tokens, $firstOperand, $index, $secondOperand); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('juggle_simple_strings', 'Allow for simple string quote juggling if it results in more concat-operations merges.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function fixConcatOperation(Tokens $tokens, array $firstOperand, int $concatIndex, array $secondOperand) : void + { + // if both operands are of the same type then these operands can always be merged + if (self::STR_DOUBLE_QUOTE === $firstOperand['type'] && self::STR_DOUBLE_QUOTE === $secondOperand['type'] || self::STR_SINGLE_QUOTE === $firstOperand['type'] && self::STR_SINGLE_QUOTE === $secondOperand['type']) { + $this->mergeContantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + return; + } + if (self::STR_DOUBLE_QUOTE_VAR === $firstOperand['type'] && self::STR_DOUBLE_QUOTE_VAR === $secondOperand['type']) { + $this->mergeContantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + return; + } + // if any is double and the other is not, check for simple other, than merge with " + $operands = [[$firstOperand, $secondOperand], [$secondOperand, $firstOperand]]; + foreach ($operands as $operandPair) { + [$operand1, $operand2] = $operandPair; + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_DOUBLE_QUOTE === $operand2['type']) { + $this->mergeContantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + return; + } + if (!$this->configuration['juggle_simple_strings']) { + continue; + } + if (self::STR_DOUBLE_QUOTE === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + if ($this->isSimpleQuotedStringContent($operantContent)) { + $this->mergeContantEscapedStringOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + return; + } + if (self::STR_DOUBLE_QUOTE_VAR === $operand1['type'] && self::STR_SINGLE_QUOTE === $operand2['type']) { + $operantContent = $tokens[$operand2['start']]->getContent(); + if ($this->isSimpleQuotedStringContent($operantContent)) { + $this->mergeContantEscapedStringVarOperands($tokens, $firstOperand, $concatIndex, $secondOperand); + } + return; + } + } + } + /** + * @param -1|1 $direction + * + * @return null|array{ + * start: int, + * end: int, + * type: self::STR_*, + * } + */ + private function getConcatOperandType(Tokens $tokens, int $index, int $direction) : ?array + { + if ($tokens[$index]->isGivenKind(\T_CONSTANT_ENCAPSED_STRING)) { + $firstChar = $tokens[$index]->getContent(); + if ('b' === $firstChar[0] || 'B' === $firstChar[0]) { + return null; + // we don't care about these, priorities are set to do deal with these cases + } + return ['start' => $index, 'end' => $index, 'type' => '"' === $firstChar[0] ? self::STR_DOUBLE_QUOTE : self::STR_SINGLE_QUOTE]; + } + if ($tokens[$index]->equals('"')) { + $end = $tokens->getTokenOfKindSibling($index, $direction, ['"']); + return ['start' => 1 === $direction ? $index : $end, 'end' => 1 === $direction ? $end : $index, 'type' => self::STR_DOUBLE_QUOTE_VAR]; + } + return null; + } + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function mergeContantEscapedStringOperands(Tokens $tokens, array $firstOperand, int $concatOperatorIndex, array $secondOperand) : void + { + $quote = self::STR_DOUBLE_QUOTE === $firstOperand['type'] || self::STR_DOUBLE_QUOTE === $secondOperand['type'] ? '"' : "'"; + $firstOperandTokenContent = $tokens[$firstOperand['start']]->getContent(); + $secondOperandTokenContent = $tokens[$secondOperand['start']]->getContent(); + $tokens[$firstOperand['start']] = new Token([\T_CONSTANT_ENCAPSED_STRING, $quote . \substr($firstOperandTokenContent, 1, -1) . \substr($secondOperandTokenContent, 1, -1) . $quote]); + $tokens->clearTokenAndMergeSurroundingWhitespace($secondOperand['start']); + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + } + /** + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $firstOperand + * @param array{ + * start: int, + * end: int, + * type: self::STR_*, + * } $secondOperand + */ + private function mergeContantEscapedStringVarOperands(Tokens $tokens, array $firstOperand, int $concatOperatorIndex, array $secondOperand) : void + { + // build uo the new content + $newContent = ''; + foreach ([$firstOperand, $secondOperand] as $operant) { + $operandContent = ''; + for ($i = $operant['start']; $i <= $operant['end'];) { + $operandContent .= $tokens[$i]->getContent(); + $i = $tokens->getNextMeaningfulToken($i); + } + $newContent .= \substr($operandContent, 1, -1); + } + // remove tokens making up the concat statement + for ($i = $secondOperand['end']; $i >= $secondOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + $this->clearConcatAndAround($tokens, $concatOperatorIndex); + for ($i = $firstOperand['end']; $i > $firstOperand['start'];) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + $i = $tokens->getPrevMeaningfulToken($i); + } + // insert new tokens based on the new content + $newTokens = Tokens::fromCode('overrideRange($firstOperand['start'], $firstOperand['start'], $insertTokens); + } + private function clearConcatAndAround(Tokens $tokens, int $concatOperatorIndex) : void + { + if ($tokens[$concatOperatorIndex + 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex + 1); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex); + if ($tokens[$concatOperatorIndex - 1]->isWhitespace()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($concatOperatorIndex - 1); + } + } + private function isSimpleQuotedStringContent(string $candidate) : bool + { + return !Preg::match('#[\\$"\'\\\\]#', \substr($candidate, 1, -1)); + } + private function containsLinebreak(Tokens $tokens, int $startIndex, int $endIndex) : bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\\R/', $tokens[$i]->getContent())) { + return \true; + } + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php new file mode 100644 index 00000000000..e60beea07ea --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NoUselessNullsafeOperatorFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUselessNullsafeOperatorFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be useless `null-safe-operators` `?->` used.', [new VersionSpecificCodeSample('parentMethod(); + } +} +', new VersionSpecification(80000))]); + } + public function isCandidate(Tokens $tokens) : bool + { + return \PHP_VERSION_ID >= 80000 && $tokens->isAllTokenKindsFound([\T_VARIABLE, \T_NULLSAFE_OBJECT_OPERATOR]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_NULLSAFE_OBJECT_OPERATOR)) { + continue; + } + $nullsafeObjectOperatorIndex = $index; + $index = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + continue; + } + if ('$this' !== \strtolower($tokens[$index]->getContent())) { + continue; + } + $tokens[$nullsafeObjectOperatorIndex] = new Token([\T_OBJECT_OPERATOR, '->']); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php new file mode 100644 index 00000000000..421e744e311 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSpaceFixer.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Javier Spagnoletti + */ +final class NotOperatorWithSpaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Logical NOT operators (`!`) should have leading and trailing whitespaces.', [new CodeSample('isTokenKindFound('!'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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, ' '])); + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php new file mode 100644 index 00000000000..a70dd5e08da --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/NotOperatorWithSuccessorSpaceFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Javier Spagnoletti + */ +final class NotOperatorWithSuccessorSpaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Logical NOT operators (`!`) should have one trailing whitespace.', [new CodeSample('isTokenKindFound('!'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + $token = $tokens[$index]; + if ($token->equals('!')) { + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ' '); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php new file mode 100644 index 00000000000..b3281285367 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/ObjectOperatorWithoutWhitespaceFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class ObjectOperatorWithoutWhitespaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be space before or after object operators `->` and `?->`.', [new CodeSample(" b;\n")]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // [Structure] there should not be space before or after "->" or "?->" + foreach ($tokens as $index => $token) { + if (!$token->isObjectOperator()) { + continue; + } + // clear whitespace before -> + if ($tokens[$index - 1]->isWhitespace(" \t") && !$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + // clear whitespace after -> + if ($tokens[$index + 1]->isWhitespace(" \t") && !$tokens[$index + 2]->isComment()) { + $tokens->clearAt($index + 1); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php new file mode 100644 index 00000000000..ffae799e34f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/OperatorLinebreakFixer.php @@ -0,0 +1,234 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\ReferenceAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class OperatorLinebreakFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const BOOLEAN_OPERATORS = [[\T_BOOLEAN_AND], [\T_BOOLEAN_OR], [\T_LOGICAL_AND], [\T_LOGICAL_OR], [\T_LOGICAL_XOR]]; + /** + * @var string + */ + private $position = 'beginning'; + /** + * @var array|string> + */ + private $operators = []; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Operators - when multiline - must always be at the beginning or at the end of the line.', [new CodeSample(' 'end'])]); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->position = $this->configuration['position']; + $this->operators = self::BOOLEAN_OPERATORS; + if (\false === $this->configuration['only_booleans']) { + $this->operators = \array_merge($this->operators, self::getNonBooleanOperators()); + } + } + public function isCandidate(Tokens $tokens) : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $referenceAnalyzer = new ReferenceAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + $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 ($alternativeSyntaxAnalyzer->belongsToAlternativeSyntax($tokens, $index)) { + continue; + } + if (\in_array($index, $excludedIndices, \true)) { + continue; + } + $operatorIndices = [$index]; + if ($tokens[$index]->equals(':')) { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equals('?')) { + $operatorIndices = [$prevIndex, $index]; + $index = $prevIndex; + } + } + $this->fixOperatorLinebreak($tokens, $operatorIndices); + } + } + /** + * Currently only colons from "switch". + * + * @return int[] + */ + private function getExcludedIndices(Tokens $tokens) : array + { + $colonIndices = []; + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + foreach ($analysis->getCases() as $case) { + $colonIndices[] = $case->getColonIndex(); + } + $defaultAnalysis = $analysis->getDefaultAnalysis(); + if (null !== $defaultAnalysis) { + $colonIndices[] = $defaultAnalysis->getColonIndex(); + } + } + return $colonIndices; + } + /** + * @param int[] $operatorIndices + */ + private function fixOperatorLinebreak(Tokens $tokens, array $operatorIndices) : void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(\min($operatorIndices)); + $indexStart = $prevIndex + 1; + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(\max($operatorIndices)); + $indexEnd = $nextIndex - 1; + if (!$this->isMultiline($tokens, $indexStart, $indexEnd)) { + return; + // operator is not surrounded by multiline whitespaces, do not touch it + } + if ('beginning' === $this->position) { + if (!$this->isMultiline($tokens, \max($operatorIndices), $indexEnd)) { + return; + // operator already is placed correctly + } + $this->fixMoveToTheBeginning($tokens, $operatorIndices); + return; + } + if (!$this->isMultiline($tokens, $indexStart, \min($operatorIndices))) { + return; + // operator already is placed correctly + } + $this->fixMoveToTheEnd($tokens, $operatorIndices); + } + /** + * @param int[] $operatorIndices + */ + private function fixMoveToTheBeginning(Tokens $tokens, array $operatorIndices) : void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getNonEmptySibling(\min($operatorIndices), -1); + /** @var int $nextIndex */ + $nextIndex = $tokens->getNextMeaningfulToken(\max($operatorIndices)); + for ($i = $nextIndex - 1; $i > \max($operatorIndices); --$i) { + if ($tokens[$i]->isWhitespace() && 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; + } + } + } + /** + * @param int[] $operatorIndices + */ + private function fixMoveToTheEnd(Tokens $tokens, array $operatorIndices) : void + { + /** @var int $prevIndex */ + $prevIndex = $tokens->getPrevMeaningfulToken(\min($operatorIndices)); + /** @var int $nextIndex */ + $nextIndex = $tokens->getNonEmptySibling(\max($operatorIndices), 1); + for ($i = $prevIndex + 1; $i < \max($operatorIndices); ++$i) { + if ($tokens[$i]->isWhitespace() && 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; + } + } + } + /** + * @param int[] $indices + * + * @return Token[] + */ + private function getReplacementsAndClear(Tokens $tokens, array $indices, int $direction) : array + { + return \array_map(static function (int $index) use($tokens, $direction) : Token { + $clone = $tokens[$index]; + if ($tokens[$index + $direction]->isWhitespace()) { + $tokens->clearAt($index + $direction); + } + $tokens->clearAt($index); + return $clone; + }, $indices); + } + private function isMultiline(Tokens $tokens, int $indexStart, int $indexEnd) : bool + { + for ($index = $indexStart; $index <= $indexEnd; ++$index) { + if (\strpos($tokens[$index]->getContent(), "\n") !== \false) { + return \true; + } + } + return \false; + } + private static function getNonBooleanOperators() : array + { + return \array_merge(['%', '&', '*', '+', '-', '.', '/', ':', '<', '=', '>', '?', '^', '|', [\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_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], [\T_COALESCE], [\T_SPACESHIP]], \array_map(static function ($id) : array { + return [$id]; + }, Token::getObjectOperatorKinds())); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php new file mode 100644 index 00000000000..d824a8a43b7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeIncrementFixer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\Fixer\AbstractIncrementOperatorFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author ntzm + */ +final class StandardizeIncrementFixer extends AbstractIncrementOperatorFixer +{ + private const EXPRESSION_END_TOKENS = [';', ')', ']', ',', ':', [CT::T_DYNAMIC_PROP_BRACE_CLOSE], [CT::T_DYNAMIC_VAR_BRACE_CLOSE], [\T_CLOSE_TAG]]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Increment and decrement operators should be used if possible.', [new CodeSample("isAnyTokenKindsFound([\T_PLUS_EQUAL, \T_MINUS_EQUAL]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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, '--'])); + } + } + /** + * Clear tokens in the given range unless they are comments. + */ + private function clearRangeLeaveComments(Tokens $tokens, int $indexStart, int $indexEnd) : void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $token = $tokens[$i]; + if ($token->isComment()) { + continue; + } + if ($token->isWhitespace("\n\r")) { + continue; + } + $tokens->clearAt($i); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php new file mode 100644 index 00000000000..8716c199c91 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/StandardizeNotEqualsFixer.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class StandardizeNotEqualsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Replace all `<>` with `!=`.', [new CodeSample(" \$c;\n")]); + } + /** + * {@inheritdoc} + * + * Must run before BinaryOperatorSpacesFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_IS_NOT_EQUAL); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_IS_NOT_EQUAL)) { + $tokens[$index] = new Token([\T_IS_NOT_EQUAL, '!=']); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php new file mode 100644 index 00000000000..16a821215c5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryOperatorSpacesFixer.php @@ -0,0 +1,123 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\ControlCaseStructuresAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class TernaryOperatorSpacesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Standardize spaces around ternary operator.', [new CodeSample("isAllTokenKindsFound(['?', ':']); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + $gotoLabelAnalyzer = new GotoLabelAnalyzer(); + $ternaryOperatorIndices = []; + $excludedIndices = $this->getColonIndicesForSwitch($tokens); + foreach ($tokens as $index => $token) { + if (!$token->equalsAny(['?', ':'])) { + continue; + } + if (\in_array($index, $excludedIndices, \true)) { + continue; + } + if ($alternativeSyntaxAnalyzer->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(':')) { + // for `$a ?: $b` remove spaces between `?` and `:` + $tokens->ensureWhitespaceAtIndex($index + 1, 0, ''); + } else { + // for `$a ? $b : $c` ensure space after `?` + $this->ensureWhitespaceExistence($tokens, $index + 1, \true); + } + // for `$a ? $b : $c` ensure space before `?` + $this->ensureWhitespaceExistence($tokens, $index - 1, \false); + continue; + } + if ($token->equals(':')) { + // for `$a ? $b : $c` ensure space after `:` + $this->ensureWhitespaceExistence($tokens, $index + 1, \true); + $prevNonWhitespaceToken = $tokens[$tokens->getPrevNonWhitespace($index)]; + if (!$prevNonWhitespaceToken->equals('?')) { + // for `$a ? $b : $c` ensure space before `:` + $this->ensureWhitespaceExistence($tokens, $index - 1, \false); + } + } + } + } + /** + * @return int[] + */ + private function getColonIndicesForSwitch(Tokens $tokens) : array + { + $colonIndices = []; + /** @var SwitchAnalysis $analysis */ + foreach (ControlCaseStructuresAnalyzer::findControlStructures($tokens, [\T_SWITCH]) as $analysis) { + foreach ($analysis->getCases() as $case) { + $colonIndices[] = $case->getColonIndex(); + } + $defaultAnalysis = $analysis->getDefaultAnalysis(); + if (null !== $defaultAnalysis) { + $colonIndices[] = $defaultAnalysis->getColonIndex(); + } + } + return $colonIndices; + } + private function ensureWhitespaceExistence(Tokens $tokens, int $index, bool $after) : void + { + if ($tokens[$index]->isWhitespace()) { + if (\strpos($tokens[$index]->getContent(), "\n") === \false && !$tokens[$index - 1]->isComment()) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + return; + } + $index += $after ? 0 : 1; + $tokens->insertAt($index, new Token([\T_WHITESPACE, ' '])); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php new file mode 100644 index 00000000000..bdaa35519c0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToElvisOperatorFixer.php @@ -0,0 +1,180 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\RangeAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +final class TernaryToElvisOperatorFixer extends AbstractFixer +{ + /** + * Lower precedence and other valid preceding tokens. + * + * Ordered by most common types first. + * + * @var list + */ + private 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() : FixerDefinitionInterface + { + return new FixerDefinition('Use the Elvis operator `?:` where possible.', [new CodeSample("isTokenKindFound('?'); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + // Elvis is alive! + } + // get and check what is before the `?` operator + $beforeOperator = $this->getBeforeOperator($tokens, $index, $blockEdgeDefinitions); + if (null === $beforeOperator) { + continue; + // contains something we cannot fix because of priorities + } + // get what is after the `?` token + $afterOperator = $this->getAfterOperator($tokens, $index); + // if before and after the `?` operator are the same (in meaningful matter), clear after + if (RangeAnalyzer::rangeEqualsRange($tokens, $beforeOperator, $afterOperator)) { + $this->clearMeaningfulFromRange($tokens, $afterOperator); + } + } + } + /** + * @return null|array{start: int, end: int} null if contains ++/-- operator + */ + private function getBeforeOperator(Tokens $tokens, int $index, array $blockEdgeDefinitions) : ?array + { + $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; + } + /** + * @return array{start: int, end: int} + */ + private function getAfterOperator(Tokens $tokens, int $index) : array + { + $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; + } + /** + * @param array{start: int, end: int} $range + */ + private function clearMeaningfulFromRange(Tokens $tokens, array $range) : void + { + // $range['end'] must be meaningful! + for ($i = $range['end']; $i >= $range['start']; $i = $tokens->getPrevMeaningfulToken($i)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php new file mode 100644 index 00000000000..74253cf0c4e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/TernaryToNullCoalescingFixer.php @@ -0,0 +1,146 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class TernaryToNullCoalescingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Use `null` coalescing operator `??` where possible. Requires PHP >= 7.0.', [new CodeSample("isTokenKindFound(\T_ISSET); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $issetIndices = \array_keys($tokens->findGivenKind(\T_ISSET)); + while ($issetIndex = \array_pop($issetIndices)) { + $this->fixIsset($tokens, $issetIndex); + } + } + /** + * @param int $index of `T_ISSET` token + */ + private function fixIsset(Tokens $tokens, int $index) : void + { + $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; + // we are not in a ternary operator + } + // search what is inside the isset() + $issetTokens = $this->getMeaningfulSequence($tokens, $startBraceIndex, $endBraceIndex); + if ($this->hasChangingContent($issetTokens)) { + return; + // some weird stuff inside the isset + } + $issetCode = $issetTokens->generateCode(); + if ('$this' === $issetCode) { + return; + // null coalescing operator does not with $this + } + // search what is inside the middle argument of ternary operator + $ternaryColonIndex = $tokens->getNextTokenOfKind($ternaryQuestionMarkIndex, [':']); + $ternaryFirstOperandTokens = $this->getMeaningfulSequence($tokens, $ternaryQuestionMarkIndex, $ternaryColonIndex); + if ($issetCode !== $ternaryFirstOperandTokens->generateCode()) { + return; + // regardless of non-meaningful tokens, the operands are different + } + $ternaryFirstOperandIndex = $tokens->getNextMeaningfulToken($ternaryQuestionMarkIndex); + // preserve comments and spaces + $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); + } + /** + * Get the sequence of meaningful tokens and returns a new Tokens instance. + * + * @param int $start start index + * @param int $end end index + */ + private function getMeaningfulSequence(Tokens $tokens, int $start, int $end) : Tokens + { + $sequence = []; + $index = $start; + while ($index < $end) { + $index = $tokens->getNextMeaningfulToken($index); + if ($index >= $end || null === $index) { + break; + } + $sequence[] = $tokens[$index]; + } + return Tokens::fromArray($sequence); + } + /** + * Check if the requested token is an operator computed + * before the ternary operator along with the `isset()`. + */ + private function isHigherPrecedenceAssociativityOperator(Token $token) : bool + { + 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); + } + /** + * Check if the `isset()` content may change if called multiple times. + * + * @param Tokens $tokens The original token list + */ + private function hasChangingContent(Tokens $tokens) : bool + { + 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php new file mode 100644 index 00000000000..00702fa24e8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Operator/UnaryOperatorSpacesFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Operator; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gregor Harlan + */ +final class UnaryOperatorSpacesFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Unary operators should be placed adjacent to their operands.', [new CodeSample("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; + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php new file mode 100644 index 00000000000..992f9639123 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/BlankLineAfterOpeningTagFixer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Ceeram + */ +final class BlankLineAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + 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("isTokenKindFound(\T_OPEN_TAG); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + // ignore files with short open tag and ignore non-monolithic files + if (!$tokens[0]->isGivenKind(\T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { + return; + } + $newlineFound = \false; + /** @var Token $token */ + foreach ($tokens as $token) { + if ($token->isWhitespace() && \strpos($token->getContent(), "\n") !== \false) { + $newlineFound = \true; + break; + } + } + // ignore one-line files + if (!$newlineFound) { + return; + } + $token = $tokens[0]; + if (\strpos($token->getContent(), "\n") === \false) { + $tokens[0] = new Token([$token->getId(), \rtrim($token->getContent()) . $lineEnding]); + } + if (\strpos($tokens[1]->getContent(), "\n") === \false) { + if ($tokens[1]->isWhitespace()) { + $tokens[1] = new Token([\T_WHITESPACE, $lineEnding . $tokens[1]->getContent()]); + } else { + $tokens->insertAt(1, new Token([\T_WHITESPACE, $lineEnding])); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php new file mode 100644 index 00000000000..d62d03f6c9f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/EchoTagSyntaxFixer.php @@ -0,0 +1,181 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Michele Locati + */ +final class EchoTagSyntaxFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** @internal */ + public const OPTION_FORMAT = 'format'; + /** @internal */ + public const OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY = 'shorten_simple_statements_only'; + /** @internal */ + public const OPTION_LONG_FUNCTION = 'long_function'; + /** @internal */ + public const FORMAT_SHORT = 'short'; + /** @internal */ + public const FORMAT_LONG = 'long'; + /** @internal */ + public const LONG_FUNCTION_ECHO = 'echo'; + /** @internal */ + public const LONG_FUNCTION_PRINT = 'print'; + private const SUPPORTED_FORMAT_OPTIONS = [self::FORMAT_LONG, self::FORMAT_SHORT]; + private const SUPPORTED_LONGFUNCTION_OPTIONS = [self::LONG_FUNCTION_ECHO, self::LONG_FUNCTION_PRINT]; + public function getDefinition() : FixerDefinitionInterface + { + $sample = <<<'EOT' + + + + + +EOT; + return new FixerDefinition('Replaces short-echo ` 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); + } + /** + * {@inheritdoc} + * + * Must run before NoMixedEchoPrintFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + 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() : FixerConfigurationResolverInterface + { + 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) : void + { + if (self::FORMAT_SHORT === $this->configuration[self::OPTION_FORMAT]) { + $this->longToShort($tokens); + } else { + $this->shortToLong($tokens); + } + } + private function longToShort(Tokens $tokens) : void + { + $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 (\true === $this->configuration[self::OPTION_SHORTEN_SIMPLE_STATEMENTS_ONLY] && $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) : void + { + 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, 'isWhitespace()) { + $replace[] = new Token([\T_WHITESPACE, ' ']); + } + $tokens->overrideRange($index, $index, $replace); + ++$index; + } + } + /** + * Check if $tokens, starting at $index, contains "complex code", that is, the content + * of the echo tag contains more than a simple "echo something". + * + * This is done by a very quick test: if the tag contains non-whitespace tokens after + * a semicolon, we consider it as "complex". + * + * @example `` is false (not complex) + * @example `` is false (not "complex") + * @example `` is true ("complex") + */ + private function isComplexCode(Tokens $tokens, int $index) : bool + { + $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; + } + /** + * Builds the list of tokens that replace a long echo sequence. + * + * @return Token[] + */ + private function buildLongToShortTokens(Tokens $tokens, int $openTagIndex, int $echoTagIndex) : array + { + $result = [new Token([\T_OPEN_TAG_WITH_ECHO, 'getNextNonWhitespace($openTagIndex); + if ($start === $echoTagIndex) { + // No non-whitespace tokens between $openTagIndex and $echoTagIndex + return $result; + } + // Find the last non-whitespace index before $echoTagIndex + $end = $echoTagIndex - 1; + while ($tokens[$end]->isWhitespace()) { + --$end; + } + // Copy the non-whitespace tokens between $openTagIndex and $echoTagIndex + for ($index = $start; $index <= $end; ++$index) { + $result[] = clone $tokens[$index]; + } + return $result; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php new file mode 100644 index 00000000000..6a6fc59b987 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/FullOpeningTagFixer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR1 ¶2.1. + * + * @author Dariusz Rumiński + */ +final class FullOpeningTagFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHP code must use the long `generateCode(); + // replace all echo ' echo ' $token) { + if ($token->isGivenKind(\T_OPEN_TAG)) { + $tokenContent = $token->getContent(); + $possibleOpenContent = \substr($content, $tokensOldContentLength, 5); + if (\false === $possibleOpenContent || 'isGivenKind([\T_COMMENT, \T_DOC_COMMENT, \T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_STRING])) { + $tokenContent = ''; + $tokenContentLength = 0; + $parts = \explode('getContent()); + $iLast = \count($parts) - 1; + foreach ($parts as $i => $part) { + $tokenContent .= $part; + $tokenContentLength += \strlen($part); + if ($i !== $iLast) { + $originalTokenContent = \substr($content, $tokensOldContentLength + $tokenContentLength, 5); + if ('getId(), $tokenContent]); + $token = $newTokens[$index]; + } + $tokensOldContentLength += \strlen($token->getContent()); + } + $tokens->overrideRange(0, $tokens->count() - 1, $newTokens); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php new file mode 100644 index 00000000000..0aeee27149c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/LinebreakAfterOpeningTagFixer.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Ceeram + */ +final class LinebreakAfterOpeningTagFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ensure there is no code on the same line as the PHP open tag.', [new CodeSample("isTokenKindFound(\T_OPEN_TAG); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // ignore files with short open tag and ignore non-monolithic files + if (!$tokens[0]->isGivenKind(\T_OPEN_TAG) || !$tokens->isMonolithicPhp()) { + return; + } + // ignore if linebreak already present + if (\strpos($tokens[0]->getContent(), "\n") !== \false) { + return; + } + $newlineFound = \false; + foreach ($tokens as $token) { + if ($token->isWhitespace() && \strpos($token->getContent(), "\n") !== \false) { + $newlineFound = \true; + break; + } + } + // ignore one-line files + if (!$newlineFound) { + return; + } + $tokens[0] = new Token([\T_OPEN_TAG, \rtrim($tokens[0]->getContent()) . $this->whitespacesConfig->getLineEnding()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php new file mode 100644 index 00000000000..4ead0e5bfd6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpTag/NoClosingTagFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpTag; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Dariusz Rumiński + */ +final class NoClosingTagFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The closing `?>` tag MUST be omitted from files containing only PHP.', [new CodeSample("\n")]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_CLOSE_TAG); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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(';')); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php new file mode 100644 index 00000000000..cbe88eaee15 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitConstructFixer.php @@ -0,0 +1,129 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitConstructFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static $assertionFixers = ['assertSame' => 'fixAssertPositive', 'assertEquals' => 'fixAssertPositive', 'assertNotEquals' => 'fixAssertNegative', 'assertNotSame' => 'fixAssertNegative']; + public function isRisky() : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPUnit assertion method calls like `->assertSame(true, $foo)` should be written with dedicated method like `->assertTrue($foo)`.', [new CodeSample('assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } +} +'), new CodeSample('assertEquals(false, $b); + $this->assertSame(true, $a); + $this->assertNotEquals(null, $c); + $this->assertNotSame(null, $d); + } +} +', ['assertions' => ['assertSame', 'assertNotSame']])], null, 'Fixer could be risky if one is overriding PHPUnit\'s native methods.'); + } + /** + * {@inheritdoc} + * + * Must run before PhpUnitDedicateAssertFixer. + */ + public function getPriority() : int + { + return -8; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + // no assertions to be fixed - fast return + if ([] === $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('assertions', 'List of assertion methods to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(\array_keys(self::$assertionFixers))])->setDefault(['assertEquals', 'assertSame', 'assertNotEquals', 'assertNotSame'])->getOption()]); + } + private function fixAssertNegative(Tokens $tokens, int $index, string $method) : ?int + { + static $map = ['false' => 'assertNotFalse', 'null' => 'assertNotNull', 'true' => 'assertNotTrue']; + return $this->fixAssert($map, $tokens, $index, $method); + } + private function fixAssertPositive(Tokens $tokens, int $index, string $method) : ?int + { + static $map = ['false' => 'assertFalse', 'null' => 'assertNull', 'true' => 'assertTrue']; + return $this->fixAssert($map, $tokens, $index, $method); + } + /** + * @param array $map + */ + private function fixAssert(array $map, Tokens $tokens, int $index, string $method) : ?int + { + $functionsAnalyzer = new FunctionsAnalyzer(); + $sequence = $tokens->findSequence([[\T_STRING, $method], '('], $index); + if (null === $sequence) { + return null; + } + $sequenceIndices = \array_keys($sequence); + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $sequenceIndices[0])) { + return null; + } + $sequenceIndices[2] = $tokens->getNextMeaningfulToken($sequenceIndices[1]); + $firstParameterToken = $tokens[$sequenceIndices[2]]; + if (!$firstParameterToken->isNativeConstant()) { + return $sequenceIndices[2]; + } + $sequenceIndices[3] = $tokens->getNextMeaningfulToken($sequenceIndices[2]); + // return if first method argument is an expression, not value + if (!$tokens[$sequenceIndices[3]]->equals(',')) { + return $sequenceIndices[3]; + } + $tokens[$sequenceIndices[0]] = new Token([\T_STRING, $map[\strtolower($firstParameterToken->getContent())]]); + $tokens->clearRange($sequenceIndices[2], $tokens->getNextNonWhitespace($sequenceIndices[3]) - 1); + return $sequenceIndices[3]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php new file mode 100644 index 00000000000..3814e1055e3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderNameFixer.php @@ -0,0 +1,120 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderNameFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Data provider names must match the name of the test.', [new CodeSample(' 'data_', 'suffix' => '']), new CodeSample(' 'provides', 'suffix' => 'Data'])], null, 'Fixer could be risky if one is calling data provider by name as function.'); + } + public function getConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('prefix', 'Prefix that replaces "test".'))->setAllowedTypes(['string'])->setDefault('provide')->getOption(), (new FixerOptionBuilder('suffix', 'Suffix to be present at the end.'))->setAllowedTypes(['string'])->setDefault('Cases')->getOption()]); + } + public function getPriority() : int + { + return 0; + } + public function isRisky() : bool + { + return \true; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $dataProviderAnalyzer = new DataProviderAnalyzer(); + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderAnalysis) { + if (\count($dataProviderAnalysis->getUsageIndices()) > 1) { + continue; + } + $usageIndex = $dataProviderAnalysis->getUsageIndices()[0]; + if (\substr_count($tokens[$usageIndex]->getContent(), '@dataProvider') > 1) { + continue; + } + $testNameIndex = $tokens->getNextTokenOfKind($usageIndex, [[\T_STRING]]); + $dataProviderNewName = $this->getProviderNameForTestName($tokens[$testNameIndex]->getContent()); + if (null !== $tokens->findSequence([[\T_FUNCTION], [\T_STRING, $dataProviderNewName]], $startIndex, $endIndex)) { + continue; + } + $tokens[$dataProviderAnalysis->getNameIndex()] = new Token([\T_STRING, $dataProviderNewName]); + $newCommentContent = Preg::replace(\sprintf('/(@dataProvider\\s+)%s/', $dataProviderAnalysis->getName()), \sprintf('$1%s', $dataProviderNewName), $tokens[$usageIndex]->getContent()); + $tokens[$usageIndex] = new Token([\T_DOC_COMMENT, $newCommentContent]); + } + } + private function getProviderNameForTestName(string $name) : string + { + $name = Preg::replace('/^test_*/i', '', $name); + if ('' === $this->configuration['prefix']) { + $name = \lcfirst($name); + } elseif ('_' !== \substr($this->configuration['prefix'], -1)) { + $name = \ucfirst($name); + } + return $this->configuration['prefix'] . $name . $this->configuration['suffix']; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php new file mode 100644 index 00000000000..689756c3be6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderReturnTypeFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderReturnTypeFixer extends AbstractPhpUnitFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The return type of PHPUnit data provider must be `iterable`.', [new CodeSample('getDataProviders($tokens, $startIndex, $endIndex)) as $dataProviderAnalysis) { + $typeAnalysis = $functionsAnalyzer->getFunctionReturnType($tokens, $dataProviderAnalysis->getNameIndex()); + if (null === $typeAnalysis) { + $argumentsStart = $tokens->getNextTokenOfKind($dataProviderAnalysis->getNameIndex(), ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); + $tokens->insertAt($argumentsEnd + 1, [new Token([CT::T_TYPE_COLON, ':']), new Token([\T_WHITESPACE, ' ']), new Token([\T_STRING, 'iterable'])]); + continue; + } + if ('iterable' === $typeAnalysis->getName()) { + continue; + } + $typeStartIndex = $tokens->getNextMeaningfulToken($typeAnalysis->getStartIndex() - 1); + $typeEndIndex = $typeAnalysis->getEndIndex(); + // @TODO: drop condition and it's body when PHP 8+ is required + if ($tokens->generatePartialCode($typeStartIndex, $typeEndIndex) !== $typeAnalysis->getName()) { + continue; + } + $tokens->overrideRange($typeStartIndex, $typeEndIndex, [new Token([\T_STRING, 'iterable'])]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php new file mode 100644 index 00000000000..29a882fa481 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDataProviderStaticFixer.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\DataProviderAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Kuba Werłos + */ +final class PhpUnitDataProviderStaticFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Data providers must be static.', [new CodeSample('getData1(); } + public function provideSomethingCases2() { self::getData2(); } +} +', ['force' => \true]), new CodeSample('getData1(); } + public function provideSomething2Cases() { self::getData2(); } +} +', ['force' => \false])], null, 'Fixer could be risky if one is calling data provider function dynamically.'); + } + public function isRisky() : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('force', 'Whether to make the data providers static even if they have a dynamic class call' . ' (may introduce fatal error "using $this when not in object context",' . ' and you may have to adjust the code manually by converting dynamic calls to static ones).'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $dataProviderAnalyzer = new DataProviderAnalyzer(); + $tokensAnalyzer = new TokensAnalyzer($tokens); + $inserts = []; + foreach ($dataProviderAnalyzer->getDataProviders($tokens, $startIndex, $endIndex) as $dataProviderDefinitionIndex) { + $methodStartIndex = $tokens->getNextTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), ['{']); + if (null !== $methodStartIndex) { + $methodEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $methodStartIndex); + if (!$this->configuration['force'] && null !== $tokens->findSequence([[\T_VARIABLE, '$this']], $methodStartIndex, $methodEndIndex)) { + continue; + } + } + $functionIndex = $tokens->getPrevTokenOfKind($dataProviderDefinitionIndex->getNameIndex(), [[\T_FUNCTION]]); + $methodAttributes = $tokensAnalyzer->getMethodAttributes($functionIndex); + if (\false !== $methodAttributes['static']) { + continue; + } + $inserts[$functionIndex] = [new Token([\T_STATIC, 'static']), new Token([\T_WHITESPACE, ' '])]; + } + $tokens->insertSlices($inserts); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php new file mode 100644 index 00000000000..c8b1088e87c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertFixer.php @@ -0,0 +1,404 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitDedicateAssertFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array|true> + */ + private static $fixMap = ['array_key_exists' => ['positive' => 'assertArrayHasKey', 'negative' => 'assertArrayNotHasKey', 'argument_count' => 2], 'empty' => ['positive' => 'assertEmpty', 'negative' => 'assertNotEmpty'], 'file_exists' => ['positive' => 'assertFileExists', 'negative' => 'assertFileNotExists'], 'is_array' => \true, 'is_bool' => \true, 'is_callable' => \true, 'is_dir' => ['positive' => 'assertDirectoryExists', 'negative' => 'assertDirectoryNotExists'], 'is_double' => \true, 'is_float' => \true, 'is_infinite' => ['positive' => 'assertInfinite', 'negative' => 'assertFinite'], 'is_int' => \true, 'is_integer' => \true, 'is_long' => \true, 'is_nan' => ['positive' => 'assertNan', 'negative' => \false], 'is_null' => ['positive' => 'assertNull', 'negative' => 'assertNotNull'], 'is_numeric' => \true, 'is_object' => \true, 'is_readable' => ['positive' => 'assertIsReadable', 'negative' => 'assertNotIsReadable'], 'is_real' => \true, 'is_resource' => \true, 'is_scalar' => \true, 'is_string' => \true, 'is_writable' => ['positive' => 'assertIsWritable', 'negative' => 'assertNotIsWritable'], 'str_contains' => [ + // since 7.5 + 'positive' => 'assertStringContainsString', + 'negative' => 'assertStringNotContainsString', + 'argument_count' => 2, + 'swap_arguments' => \true, + ], 'str_ends_with' => [ + // since 3.4 + 'positive' => 'assertStringEndsWith', + 'negative' => 'assertStringEndsNotWith', + 'argument_count' => 2, + 'swap_arguments' => \true, + ], 'str_starts_with' => [ + // since 3.4 + 'positive' => 'assertStringStartsWith', + 'negative' => 'assertStringStartsNotWith', + 'argument_count' => 2, + 'swap_arguments' => \true, + ]]; + /** + * @var string[] + */ + private $functions = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + // assertions added in 3.0: assertArrayNotHasKey assertArrayHasKey assertFileNotExists assertFileExists assertNotNull, assertNull + $this->functions = ['array_key_exists', 'file_exists', 'is_null', 'str_ends_with', 'str_starts_with']; + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_3_5)) { + // assertions added in 3.5: assertInternalType assertNotEmpty assertEmpty + $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_scalar', 'is_string']); + } + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_0)) { + // assertions added in 5.0: assertFinite assertInfinite assertNan + $this->functions = \array_merge($this->functions, ['is_infinite', 'is_nan']); + } + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6)) { + // assertions added in 5.6: assertDirectoryExists assertDirectoryNotExists assertIsReadable assertNotIsReadable assertIsWritable assertNotIsWritable + $this->functions = \array_merge($this->functions, ['is_dir', 'is_readable', 'is_writable']); + } + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_7_5)) { + $this->functions = \array_merge($this->functions, ['str_contains']); + } + } + public function isRisky() : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPUnit assertions like `assertInternalType`, `assertFileExists`, should be used over `assertTrue`.', [new CodeSample('assertTrue(is_float( $a), "my message"); + $this->assertTrue(is_nan($a)); + } +} +'), new CodeSample('assertTrue(is_dir($a)); + $this->assertTrue(is_writable($a)); + $this->assertTrue(is_readable($a)); + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6])], null, 'Fixer could be risky if one is overriding PHPUnit\'s native methods.'); + } + /** + * {@inheritdoc} + * + * Must run before NoUnusedImportsFixer, PhpUnitDedicateAssertInternalTypeFixer. + * Must run after ModernizeStrposFixer, NoAliasFunctionsFixer, PhpUnitConstructFixer. + */ + public function getPriority() : int + { + return -9; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + foreach ($this->getPreviousAssertCall($tokens, $startIndex, $endIndex) as $assertCall) { + // test and fix for assertTrue/False to dedicated asserts + if ('asserttrue' === $assertCall['loweredName'] || 'assertfalse' === $assertCall['loweredName']) { + $this->fixAssertTrueFalse($tokens, $argumentsAnalyzer, $assertCall); + continue; + } + if ('assertsame' === $assertCall['loweredName'] || 'assertnotsame' === $assertCall['loweredName'] || 'assertequals' === $assertCall['loweredName'] || 'assertnotequals' === $assertCall['loweredName']) { + $this->fixAssertSameEquals($tokens, $assertCall); + continue; + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_3_0, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_3_5, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_0, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption()]); + } + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalse(Tokens $tokens, ArgumentsAnalyzer $argumentsAnalyzer, array $assertCall) : void + { + $testDefaultNamespaceTokenIndex = null; + $testIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + if (!$tokens[$testIndex]->isGivenKind([\T_EMPTY, \T_STRING])) { + if ($this->fixAssertTrueFalseInstanceof($tokens, $assertCall, $testIndex)) { + return; + } + 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; + } + $content = \strtolower($tokens[$testIndex]->getContent()); + if (!\in_array($content, $this->functions, \true)) { + return; + } + $arguments = $argumentsAnalyzer->getArguments($tokens, $testOpenIndex, $testCloseIndex); + $isPositive = 'asserttrue' === $assertCall['loweredName']; + if (\is_array(self::$fixMap[$content])) { + $expectedCount = self::$fixMap[$content]['argument_count'] ?? 1; + if ($expectedCount !== \count($arguments)) { + return; + } + $isPositive = $isPositive ? 'positive' : 'negative'; + if (\false === self::$fixMap[$content][$isPositive]) { + return; + } + $tokens[$assertCall['index']] = new Token([\T_STRING, self::$fixMap[$content][$isPositive]]); + $this->removeFunctionCall($tokens, $testDefaultNamespaceTokenIndex, $testIndex, $testOpenIndex, $testCloseIndex); + if (self::$fixMap[$content]['swap_arguments'] ?? \false) { + if (2 !== $expectedCount) { + throw new \RuntimeException('Can only swap two arguments, please update map or logic.'); + } + $this->swapArguments($tokens, $arguments); + } + return; + } + if (1 !== \count($arguments)) { + 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 (null !== $testDefaultNamespaceTokenIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($testDefaultNamespaceTokenIndex); + } + } + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertTrueFalseInstanceof(Tokens $tokens, array $assertCall, int $testIndex) : bool + { + if ($tokens[$testIndex]->equals('!')) { + $variableIndex = $tokens->getNextMeaningfulToken($testIndex); + $positive = \false; + } else { + $variableIndex = $testIndex; + $positive = \true; + } + if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) { + return \false; + } + $instanceOfIndex = $tokens->getNextMeaningfulToken($variableIndex); + if (!$tokens[$instanceOfIndex]->isGivenKind(\T_INSTANCEOF)) { + return \false; + } + $classEndIndex = $instanceOfIndex; + $classPartTokens = []; + do { + $classEndIndex = $tokens->getNextMeaningfulToken($classEndIndex); + $classPartTokens[] = $tokens[$classEndIndex]; + } while ($tokens[$classEndIndex]->isGivenKind([\T_STRING, \T_NS_SEPARATOR, \T_VARIABLE])); + if ($tokens[$classEndIndex]->equalsAny([',', ')'])) { + // do the fixing + \array_pop($classPartTokens); + $isInstanceOfVar = \reset($classPartTokens)->isGivenKind(\T_VARIABLE); + $insertIndex = $testIndex - 1; + $newTokens = []; + foreach ($classPartTokens as $token) { + $newTokens[++$insertIndex] = clone $token; + } + if (!$isInstanceOfVar) { + $newTokens[++$insertIndex] = new Token([\T_DOUBLE_COLON, '::']); + $newTokens[++$insertIndex] = new Token([CT::T_CLASS_CONSTANT, 'class']); + } + $newTokens[++$insertIndex] = new Token(','); + $newTokens[++$insertIndex] = new Token([\T_WHITESPACE, ' ']); + $newTokens[++$insertIndex] = clone $tokens[$variableIndex]; + for ($i = $classEndIndex - 1; $i >= $testIndex; --$i) { + if (!$tokens[$i]->isComment()) { + $tokens->clearTokenAndMergeSurroundingWhitespace($i); + } + } + $tokens->insertSlices($newTokens); + $tokens[$assertCall['index']] = new Token([\T_STRING, $positive ? 'assertInstanceOf' : 'assertNotInstanceOf']); + } + return \true; + } + /** + * @param array{ + * index: int, + * loweredName: string, + * openBraceIndex: int, + * closeBraceIndex: int, + * } $assertCall + */ + private function fixAssertSameEquals(Tokens $tokens, array $assertCall) : void + { + // @ $this->/self::assertEquals/Same([$nextIndex]) + $expectedIndex = $tokens->getNextMeaningfulToken($assertCall['openBraceIndex']); + // do not fix + // let $a = [1,2]; $b = "2"; + // "$this->assertEquals("2", count($a)); $this->assertEquals($b, count($a)); $this->assertEquals(2.1, count($a));" + if ($tokens[$expectedIndex]->isGivenKind([\T_VARIABLE])) { + if (!$tokens[$tokens->getNextMeaningfulToken($expectedIndex)]->equals(',')) { + return; + } + } elseif (!$tokens[$expectedIndex]->isGivenKind([\T_LNUMBER, \T_VARIABLE])) { + return; + } + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex]) + $commaIndex = $tokens->getNextMeaningfulToken($expectedIndex); + if (!$tokens[$commaIndex]->equals(',')) { + return; + } + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,$countCallIndex]) + $countCallIndex = $tokens->getNextMeaningfulToken($commaIndex); + if ($tokens[$countCallIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $defaultNamespaceTokenIndex = $countCallIndex; + $countCallIndex = $tokens->getNextMeaningfulToken($countCallIndex); + } else { + $defaultNamespaceTokenIndex = null; + } + if (!$tokens[$countCallIndex]->isGivenKind(\T_STRING)) { + return; + } + $lowerContent = \strtolower($tokens[$countCallIndex]->getContent()); + if ('count' !== $lowerContent && 'sizeof' !== $lowerContent) { + return; + // not a call to "count" or "sizeOf" + } + // @ $this->/self::assertEquals/Same([$nextIndex,$commaIndex,[$defaultNamespaceTokenIndex,]$countCallIndex,$countCallOpenBraceIndex]) + $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']); + } + /** + * @return iterable + */ + private function getPreviousAssertCall(Tokens $tokens, int $startIndex, int $endIndex) : iterable + { + $functionsAnalyzer = new FunctionsAnalyzer(); + for ($index = $endIndex; $index > $startIndex; --$index) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_STRING]]); + if (null === $index) { + return; + } + // test if "assert" something call + $loweredContent = \strtolower($tokens[$index]->getContent()); + if (\strncmp($loweredContent, 'assert', \strlen('assert')) !== 0) { + continue; + } + // test candidate for simple calls like: ([\]+'some fixable call'(...)) + $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, ?int $callNSIndex, int $callIndex, int $openIndex, int $closeIndex) : void + { + $tokens->clearTokenAndMergeSurroundingWhitespace($callIndex); + if (null !== $callNSIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($callNSIndex); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($openIndex); + $commaIndex = $tokens->getPrevMeaningfulToken($closeIndex); + if ($tokens[$commaIndex]->equals(',')) { + $tokens->removeTrailingWhitespace($commaIndex); + $tokens->clearAt($commaIndex); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($closeIndex); + } + /** + * @param array $argumentsIndices + */ + private function swapArguments(Tokens $tokens, array $argumentsIndices) : void + { + [$firstArgumentIndex, $secondArgumentIndex] = \array_keys($argumentsIndices); + $firstArgumentEndIndex = $argumentsIndices[$firstArgumentIndex]; + $secondArgumentEndIndex = $argumentsIndices[$secondArgumentIndex]; + $firstClone = $this->cloneAndClearTokens($tokens, $firstArgumentIndex, $firstArgumentEndIndex); + $secondClone = $this->cloneAndClearTokens($tokens, $secondArgumentIndex, $secondArgumentEndIndex); + if (!$firstClone[0]->isWhitespace()) { + \array_unshift($firstClone, new Token([\T_WHITESPACE, ' '])); + } + $tokens->insertAt($secondArgumentIndex, $firstClone); + if ($secondClone[0]->isWhitespace()) { + \array_shift($secondClone); + } + $tokens->insertAt($firstArgumentIndex, $secondClone); + } + /** + * @return list + */ + private function cloneAndClearTokens(Tokens $tokens, int $start, int $end) : array + { + $clone = []; + for ($i = $start; $i <= $end; ++$i) { + if ('' === $tokens[$i]->getContent()) { + continue; + } + $clone[] = clone $tokens[$i]; + $tokens->clearAt($i); + } + return $clone; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php new file mode 100644 index 00000000000..33fdfd744e2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitDedicateAssertInternalTypeFixer.php @@ -0,0 +1,124 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Filippo Tessarotto + */ +final class PhpUnitDedicateAssertInternalTypeFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + 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() : FixerDefinitionInterface + { + return new FixerDefinition('PHPUnit assertions like `assertIsArray` should be used over `assertInternalType`.', [new CodeSample('assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } +} +'), new CodeSample('assertInternalType("array", $var); + $this->assertInternalType("boolean", $var); + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_7_5])], null, 'Risky when PHPUnit methods are overridden or when project has PHPUnit incompatibilities.'); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run after NoBinaryStringFixer, NoUselessConcatOperatorFixer, PhpUnitDedicateAssertFixer. + */ + public function getPriority() : int + { + return -16; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_7_5, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption()]); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $anonymousClassIndices = []; + $tokenAnalyzer = new TokensAnalyzer($tokens); + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$tokenAnalyzer->isAnonymousClass($index)) { + continue; + } + $openingBraceIndex = $tokens->getNextTokenOfKind($index, ['{']); + $closingBraceIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $openingBraceIndex); + $anonymousClassIndices[$closingBraceIndex] = $openingBraceIndex; + } + for ($index = $endIndex - 1; $index > $startIndex; --$index) { + if (isset($anonymousClassIndices[$index])) { + $index = $anonymousClassIndices[$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->isGivenKind(\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('(')]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php new file mode 100644 index 00000000000..9548894f74f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitExpectationFixer.php @@ -0,0 +1,197 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitExpectationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var array + */ + private $methodMap = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->methodMap = ['setExpectedException' => 'expectExceptionMessage']; + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageRegExp'; + } + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_8_4)) { + $this->methodMap['setExpectedExceptionRegExp'] = 'expectExceptionMessageMatches'; + $this->methodMap['expectExceptionMessageRegExp'] = 'expectExceptionMessageMatches'; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Usages of `->setExpectedException*` methods MUST be replaced by `->expectException*` methods.', [new CodeSample('setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +'), new CodeSample('setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_8_4]), new CodeSample('setExpectedException("RuntimeException", null, 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6]), new CodeSample('setExpectedException("RuntimeException", "Msg", 123); + foo(); + } + + public function testBar() + { + $this->setExpectedExceptionRegExp("RuntimeException", "/Msg.*/", 123); + bar(); + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_2])], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.'); + } + /** + * {@inheritdoc} + * + * Must run after PhpUnitNoExpectationAnnotationFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isRisky() : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_2, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_6, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_8_4, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption()]); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + foreach (Token::getObjectOperatorKinds() as $objectOperator) { + $this->applyPhpUnitClassFixWithObjectOperator($tokens, $startIndex, $endIndex, $objectOperator); + } + } + private function applyPhpUnitClassFixWithObjectOperator(Tokens $tokens, int $startIndex, int $endIndex, int $objectOperator) : void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + $oldMethodSequence = [[\T_VARIABLE, '$this'], [$objectOperator], [\T_STRING]]; + for ($index = $startIndex; $startIndex < $endIndex; ++$index) { + $match = $tokens->findSequence($oldMethodSequence, $index); + if (null === $match) { + return; + } + [$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]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php new file mode 100644 index 00000000000..7495a69e2a7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitFqcnAnnotationFixer.php @@ -0,0 +1,69 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Roland Franssen + */ +final class PhpUnitFqcnAnnotationFixer extends AbstractPhpUnitFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPUnit annotations should be a FQCNs including a root namespace.', [new CodeSample('getPrevTokenOfKind($startIndex, [[\T_DOC_COMMENT]]); + if (null !== $prevDocCommentIndex) { + $startIndex = $prevDocCommentIndex; + } + $this->fixPhpUnitClass($tokens, $startIndex, $endIndex); + } + private function fixPhpUnitClass(Tokens $tokens, int $startIndex, int $endIndex) : void + { + 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())]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php new file mode 100644 index 00000000000..d1259ad17ea --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitInternalClassFixer.php @@ -0,0 +1,70 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gert de Pagter + */ +final class PhpUnitInternalClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All PHPUnit test classes should be marked as internal.', [new CodeSample(" ['final']])]); + } + /** + * {@inheritdoc} + * + * Must run before FinalInternalClassFixer, PhpdocSeparationFixer. + */ + public function getPriority() : int + { + return 68; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $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, int $startIndex, int $endIndex) : void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + if (!$this->isAllowedByConfiguration($tokens, $classIndex)) { + return; + } + $this->ensureIsDockBlockWithAnnotation($tokens, $classIndex, 'internal', ['internal']); + } + private function isAllowedByConfiguration(Tokens $tokens, int $index) : bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifiers = $tokensAnalyzer->getClassyModifiers($index); + if (isset($modifiers['final'])) { + return \in_array('final', $this->configuration['types'], \true); + } + if (isset($modifiers['abstract'])) { + return \in_array('abstract', $this->configuration['types'], \true); + } + return \in_array('normal', $this->configuration['types'], \true); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php new file mode 100644 index 00000000000..adc2500d3ff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMethodCasingFixer.php @@ -0,0 +1,146 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +/** + * @author Filippo Tessarotto + */ +final class PhpUnitMethodCasingFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const CAMEL_CASE = 'camel_case'; + /** + * @internal + */ + public const SNAKE_CASE = 'snake_case'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Enforce camel (or snake) case for PHPUnit test methods, following configuration.', [new CodeSample(' self::SNAKE_CASE])]); + } + /** + * {@inheritdoc} + * + * Must run after PhpUnitTestAnnotationFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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, int $startIndex, int $endIndex) : void + { + 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(string $functionName) : string + { + $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, int $index) : bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return \false; + } + // if the function name starts with test it's a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + if (\strncmp($functionName, 'test', \strlen('test')) === 0) { + return \true; + } + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + return $this->isPHPDoc($tokens, $docBlockIndex) && \strpos($tokens[$docBlockIndex]->getContent(), '@test') !== \false; + } + private function isMethod(Tokens $tokens, int $index) : bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + private function updateDocBlock(Tokens $tokens, int $docBlockIndex) : void + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + $docBlockNeedsUpdate = \false; + for ($inc = 0; $inc < \count($lines); ++$inc) { + $lineContent = $lines[$inc]->getContent(); + if (\strpos($lineContent, '@depends') === \false) { + continue; + } + $newLineContent = Preg::replaceCallback('/(@depends\\s+)(.+)(\\b)/', function (array $matches) : string { + 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]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php new file mode 100644 index 00000000000..7219f07ed78 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockFixer.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitMockFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var bool + */ + private $fixCreatePartialMock; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Usages of `->getMock` and `->getMockWithoutInvokingTheOriginalConstructor` methods MUST be replaced by `->createMock` or `->createPartialMock` methods.', [new CodeSample('getMockWithoutInvokingTheOriginalConstructor("Foo"); + $mock1 = $this->getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); + $mock1 = $this->getMock("Baz", ["aaa"], ["argument"]); // version with more than 2 params is not supported + } +} +'), new CodeSample('getMock("Foo"); + $mock1 = $this->getMock("Bar", ["aaa"]); // version with multiple params is not supported + } +} +', ['target' => \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_4])], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.'); + } + public function isRisky() : bool + { + return \true; + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->fixCreatePartialMock = \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_5); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $argumentsAnalyzer = new ArgumentsAnalyzer(); + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + 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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_4, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_5, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php new file mode 100644 index 00000000000..6aa4d280314 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitMockShortWillReturnFixer.php @@ -0,0 +1,95 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Michał Adamski + * @author Kuba Werłos + */ +final class PhpUnitMockShortWillReturnFixer extends AbstractPhpUnitFixer +{ + private const RETURN_METHODS_MAP = ['returnargument' => 'willReturnArgument', 'returncallback' => 'willReturnCallback', 'returnself' => 'willReturnSelf', 'returnvalue' => 'willReturn', 'returnvaluemap' => 'willReturnMap']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Usage of PHPUnit\'s mock e.g. `->will($this->returnValue(..))` must be replaced by its shorter equivalent such as `->willReturn(...)`.', [new CodeSample('createMock(Some::class); + $someMock->method("some")->will($this->returnSelf()); + $someMock->method("some")->will($this->returnValue("example")); + $someMock->method("some")->will($this->returnArgument(2)); + $someMock->method("some")->will($this->returnCallback("str_rot13")); + $someMock->method("some")->will($this->returnValueMap(["a","b","c"])); + } +} +')], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.'); + } + public function isRisky() : bool + { + return \true; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + 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); + $functionToRemoveIndex = $tokens->getNextMeaningfulToken($objectOperatorIndex); + if (!$functionsAnalyzer->isTheSameClassCall($tokens, $functionToRemoveIndex)) { + continue; + } + if (!\array_key_exists(\strtolower($tokens[$functionToRemoveIndex]->getContent()), self::RETURN_METHODS_MAP)) { + continue; + } + $openingBraceIndex = $tokens->getNextMeaningfulToken($functionToRemoveIndex); + if (!$tokens[$openingBraceIndex]->equals('(')) { + continue; + } + if ($tokens[$tokens->getNextMeaningfulToken($openingBraceIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + 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); + $commaAfterClosingBraceIndex = $tokens->getNextMeaningfulToken($closingBraceIndex); + if ($tokens[$commaAfterClosingBraceIndex]->equals(',')) { + $tokens->clearTokenAndMergeSurroundingWhitespace($commaAfterClosingBraceIndex); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php new file mode 100644 index 00000000000..7b2a8d84e9c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNamespacedFixer.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ClassyAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitNamespacedFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string + */ + private $originalClassRegEx; + /** + * Class Mappings. + * + * * [original classname => new classname] Some classes which match the + * original class regular expression do not have a same-compound name- + * space class and need a dedicated translation table. This trans- + * lation table is defined in @see configure. + * + * @var array|string[] Class Mappings + */ + private $classMap; + public function getDefinition() : FixerDefinitionInterface + { + $codeSample = ' \PhpCsFixer\Fixer\PhpUnit\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) : bool + { + return $tokens->isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + if (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_6_0)) { + $this->originalClassRegEx = '/^PHPUnit_\\w+$/i'; + // @noinspection ClassConstantCanBeUsedInspection + $this->classMap = ['PHPUnit_Extensions_PhptTestCase' => 'ECSPrefix202307\\PHPUnit\\Runner\\PhptTestCase', 'PHPUnit_Framework_Constraint' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\Constraint', 'PHPUnit_Framework_Constraint_StringMatches' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\StringMatchesFormatDescription', 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\JsonMatchesErrorMessageProvider', 'PHPUnit_Framework_Constraint_PCREMatch' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\RegularExpression', 'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\ExceptionMessageRegularExpression', 'PHPUnit_Framework_Constraint_And' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\LogicalAnd', 'PHPUnit_Framework_Constraint_Or' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\LogicalOr', 'PHPUnit_Framework_Constraint_Not' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\LogicalNot', 'PHPUnit_Framework_Constraint_Xor' => 'ECSPrefix202307\\PHPUnit\\Framework\\Constraint\\LogicalXor', 'PHPUnit_Framework_Error' => 'ECSPrefix202307\\PHPUnit\\Framework\\Error\\Error', 'PHPUnit_Framework_TestSuite_DataProvider' => 'ECSPrefix202307\\PHPUnit\\Framework\\DataProviderTestSuite', 'PHPUnit_Framework_MockObject_Invocation_Static' => 'ECSPrefix202307\\PHPUnit\\Framework\\MockObject\\Invocation\\StaticInvocation', 'PHPUnit_Framework_MockObject_Invocation_Object' => 'ECSPrefix202307\\PHPUnit\\Framework\\MockObject\\Invocation\\ObjectInvocation', 'PHPUnit_Framework_MockObject_Stub_Return' => 'ECSPrefix202307\\PHPUnit\\Framework\\MockObject\\Stub\\ReturnStub', 'PHPUnit_Runner_Filter_Group_Exclude' => 'ECSPrefix202307\\PHPUnit\\Runner\\Filter\\ExcludeGroupFilterIterator', 'PHPUnit_Runner_Filter_Group_Include' => 'ECSPrefix202307\\PHPUnit\\Runner\\Filter\\IncludeGroupFilterIterator', 'PHPUnit_Runner_Filter_Test' => 'ECSPrefix202307\\PHPUnit\\Runner\\Filter\\NameFilterIterator', 'PHPUnit_Util_PHP' => 'ECSPrefix202307\\PHPUnit\\Util\\PHP\\AbstractPhpProcess', 'PHPUnit_Util_PHP_Default' => 'ECSPrefix202307\\PHPUnit\\Util\\PHP\\DefaultPhpProcess', 'PHPUnit_Util_PHP_Windows' => 'ECSPrefix202307\\PHPUnit\\Util\\PHP\\WindowsPhpProcess', 'PHPUnit_Util_Regex' => 'ECSPrefix202307\\PHPUnit\\Util\\RegularExpression', 'PHPUnit_Util_TestDox_ResultPrinter_XML' => 'ECSPrefix202307\\PHPUnit\\Util\\TestDox\\XmlResultPrinter', 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => 'ECSPrefix202307\\PHPUnit\\Util\\TestDox\\HtmlResultPrinter', 'PHPUnit_Util_TestDox_ResultPrinter_Text' => 'ECSPrefix202307\\PHPUnit\\Util\\TestDox\\TextResultPrinter', 'PHPUnit_Util_TestSuiteIterator' => 'ECSPrefix202307\\PHPUnit\\Framework\\TestSuiteIterator', 'PHPUnit_Util_XML' => 'ECSPrefix202307\\PHPUnit\\Util\\Xml']; + } elseif (\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_7)) { + $this->originalClassRegEx = '/^PHPUnit_Framework_(TestCase|Assert|BaseTestListener|TestListener)+$/i'; + $this->classMap = []; + } else { + $this->originalClassRegEx = '/^PHPUnit_Framework_TestCase$/i'; + $this->classMap = []; + } + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $importedOriginalClassesMap = []; + $currIndex = 0; + while (\true) { + $currIndex = $tokens->getNextTokenOfKind($currIndex, [[\T_STRING]]); + if (null === $currIndex) { + break; + } + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + if ($tokens[$prevIndex]->isGivenKind([\T_CONST, \T_DOUBLE_COLON])) { + continue; + } + $originalClass = $tokens[$currIndex]->getContent(); + $allowedReplacementScenarios = (new ClassyAnalyzer())->isClassyInvocation($tokens, $currIndex) || $this->isImport($tokens, $currIndex); + if (!$allowedReplacementScenarios || !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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_4_8, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_5_7, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_6_0, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption()]); + } + private function generateReplacement(string $originalClassName) : Tokens + { + $delimiter = '_'; + $string = $originalClassName; + $map = \array_change_key_case($this->classMap); + if (isset($map[\strtolower($originalClassName)])) { + $delimiter = '\\'; + $string = $map[\strtolower($originalClassName)]; + } + $parts = \explode($delimiter, $string); + $tokensArray = []; + while ([] !== $parts) { + $tokensArray[] = new Token([\T_STRING, \array_shift($parts)]); + if ([] !== $parts) { + $tokensArray[] = new Token([\T_NS_SEPARATOR, '\\']); + } + } + return Tokens::fromArray($tokensArray); + } + private function isImport(Tokens $tokens, int $currIndex) : bool + { + $prevIndex = $tokens->getPrevMeaningfulToken($currIndex); + if ($tokens[$prevIndex]->isGivenKind([\T_NS_SEPARATOR])) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + return $tokens[$prevIndex]->isGivenKind([\T_USE]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php new file mode 100644 index 00000000000..1c8e704a87c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitNoExpectationAnnotationFixer.php @@ -0,0 +1,193 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitNoExpectationAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var bool + */ + private $fixMessageRegExp; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->fixMessageRegExp = \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::fulfills($this->configuration['target'], \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_4_3); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Usages of `@expectedException*` annotations MUST be replaced by `->setExpectedException*` methods.', [new CodeSample(' \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_3_2])], null, 'Risky when PHPUnit classes are overridden or not accessible, or when project has PHPUnit incompatibilities.'); + } + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitExpectationFixer. + */ + public function getPriority() : int + { + return 10; + } + public function isRisky() : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('target', 'Target version of PHPUnit.'))->setAllowedTypes(['string'])->setAllowedValues([\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_3_2, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_4_3, \PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST])->setDefault(\PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion::VERSION_NEWEST)->getOption(), (new FixerOptionBuilder('use_class_const', 'Use ::class notation.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $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; + // ignore abstract functions + $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 = '' . (isset($annotations['expectedExceptionMessageRegExp']) ? 'setExpectedExceptionRegExp' : 'setExpectedException') . '(' . \implode(', ', $paramList) . ');'; + $newMethods = Tokens::fromCode($newMethodsCode); + $newMethods[0] = new Token([\T_WHITESPACE, $this->whitespacesConfig->getLineEnding() . $originalIndent . $this->whitespacesConfig->getIndent()]); + // apply changes + $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) : string + { + $tag = $annotation->getTag()->getName(); + if (!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); + } + /** + * @param array $annotations + * + * @return list + */ + private function annotationsToParamList(array $annotations) : array + { + $params = []; + $exceptionClass = \ltrim($annotations['expectedException'], '\\'); + if (\strpos($exceptionClass, '*') !== \false) { + $exceptionClass = \substr($exceptionClass, 0, \strpos($exceptionClass, '*')); + } + $exceptionClass = \trim($exceptionClass); + if (\true === $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php new file mode 100644 index 00000000000..833f3dd1b21 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSetUpTearDownVisibilityFixer.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gert de Pagter + */ +final class PhpUnitSetUpTearDownVisibilityFixer extends AbstractPhpUnitFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Changes the visibility of the `setUp()` and `tearDown()` functions of PHPUnit to `protected`, to match the PHPUnit TestCase.', [new CodeSample('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() : bool + { + return \true; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $counter = 0; + $tokensAnalyzer = new TokensAnalyzer($tokens); + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + if (2 === $counter) { + break; + // we've seen both method we are interested in, so stop analyzing this class + } + 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, int $index) : bool + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php new file mode 100644 index 00000000000..2ba93024f01 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitSizeClassFixer.php @@ -0,0 +1,61 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jefersson Nathan + */ +final class PhpUnitSizeClassFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + private const SIZES = ['small', 'medium', 'large']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All PHPUnit test cases should have `@small`, `@medium` or `@large` annotation to enable run time limits.', [new CodeSample(" 'medium'])], 'The special groups [small, medium, large] provides a way to identify tests that are taking long to be executed.'); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocSeparationFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('group', 'Define a specific group to be used in case no group is already in use.'))->setAllowedValues(self::SIZES)->setDefault('small')->getOption()]); + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + if ($this->isAbstractClass($tokens, $classIndex)) { + return; + } + $this->ensureIsDockBlockWithAnnotation($tokens, $classIndex, $this->configuration['group'], self::SIZES); + } + private function isAbstractClass(Tokens $tokens, int $i) : bool + { + $typeIndex = $tokens->getPrevMeaningfulToken($i); + return $tokens[$typeIndex]->isGivenKind(\T_ABSTRACT); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php new file mode 100644 index 00000000000..83241ae489e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitStrictFixer.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitStrictFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @var array + */ + private static $assertionMap = ['assertAttributeEquals' => 'assertAttributeSame', 'assertAttributeNotEquals' => 'assertAttributeNotSame', 'assertEquals' => 'assertSame', 'assertNotEquals' => 'assertNotSame']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPUnit methods like `assertSame` should be used instead of `assertEquals`.', [new CodeSample('assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } +} +'), new CodeSample('assertAttributeEquals(a(), b()); + $this->assertAttributeNotEquals(a(), b()); + $this->assertEquals(a(), b()); + $this->assertNotEquals(a(), b()); + } +} +', ['assertions' => ['assertEquals']])], null, 'Risky when any of the functions are overridden or when testing object equality.'); + } + public function isRisky() : bool + { + return \true; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('assertions', 'List of assertion methods to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(\array_keys(self::$assertionMap))])->setDefault(['assertAttributeEquals', 'assertAttributeNotEquals', 'assertEquals', 'assertNotEquals'])->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php new file mode 100644 index 00000000000..cff8cdc8350 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTargetVersion.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use ECSPrefix202307\Composer\Semver\Comparator; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class PhpUnitTargetVersion +{ + public const VERSION_3_0 = '3.0'; + public const VERSION_3_2 = '3.2'; + public const VERSION_3_5 = '3.5'; + public const VERSION_4_3 = '4.3'; + public const VERSION_4_8 = '4.8'; + public const VERSION_5_0 = '5.0'; + public const VERSION_5_2 = '5.2'; + public const VERSION_5_4 = '5.4'; + public const VERSION_5_5 = '5.5'; + public const VERSION_5_6 = '5.6'; + public const VERSION_5_7 = '5.7'; + public const VERSION_6_0 = '6.0'; + public const VERSION_7_5 = '7.5'; + public const VERSION_8_4 = '8.4'; + public const VERSION_NEWEST = 'newest'; + private function __construct() + { + } + public static function fulfills(string $candidate, string $target) : bool + { + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php new file mode 100644 index 00000000000..1d6c971ce72 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestAnnotationFixer.php @@ -0,0 +1,310 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gert de Pagter + */ +final class PhpUnitTestAnnotationFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function isRisky() : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Adds or removes @test annotations from tests, following configuration.', [new CodeSample('whitespacesConfig->getLineEnding()), new CodeSample('whitespacesConfig->getLineEnding(), ['style' => 'annotation'])], null, 'This fixer may change the name of your tests, and could cause incompatibility with' . ' abstract classes or interfaces.'); + } + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpUnitMethodCasingFixer, PhpdocTrimFixer. + */ + public function getPriority() : int + { + return 10; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + if ('annotation' === $this->configuration['style']) { + $this->applyTestAnnotation($tokens, $startIndex, $endIndex); + } else { + $this->applyTestPrefix($tokens, $startIndex, $endIndex); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('style', 'Whether to use the @test annotation or not.'))->setAllowedValues(['prefix', 'annotation'])->setDefault('prefix')->getOption()]); + } + private function applyTestAnnotation(Tokens $tokens, int $startIndex, int $endIndex) : void + { + 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 { + // Create a new docblock if it didn't have one before; + $this->createDocBlock($tokens, $docBlockIndex); + } + } + } + private function applyTestPrefix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + for ($i = $endIndex - 1; $i > $startIndex; --$i) { + // We explicitly check again if the function has a doc block to save some time. + 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, int $index) : bool + { + // Check if we are dealing with a (non-abstract, non-lambda) function + if (!$this->isMethod($tokens, $index)) { + return \false; + } + // if the function name starts with test it is a test + $functionNameIndex = $tokens->getNextMeaningfulToken($index); + $functionName = $tokens[$functionNameIndex]->getContent(); + if ($this->hasTestPrefix($functionName)) { + return \true; + } + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + // If the function doesn't have test in its name, and no doc block, it is not a test + return $this->isPHPDoc($tokens, $docBlockIndex) && \strpos($tokens[$docBlockIndex]->getContent(), '@test') !== \false; + } + private function isMethod(Tokens $tokens, int $index) : bool + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + return $tokens[$index]->isGivenKind(\T_FUNCTION) && !$tokensAnalyzer->isLambda($index); + } + private function hasTestPrefix(string $functionName) : bool + { + return \strncmp($functionName, 'test', \strlen('test')) === 0; + } + private function hasProperTestAnnotation(Tokens $tokens, int $index) : bool + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + $doc = $tokens[$docBlockIndex]->getContent(); + return Preg::match('/\\*\\s+@test\\b/', $doc); + } + private function removeTestPrefix(string $functionName) : string + { + $remainder = Preg::replace('/^test(?=[A-Z_])_?/', '', $functionName); + if ('' === $remainder) { + return $functionName; + } + return \lcfirst($remainder); + } + private function addTestPrefix(string $functionName) : string + { + return 'test' . \ucfirst($functionName); + } + private function createDocBlock(Tokens $tokens, int $docBlockIndex) : void + { + $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); + } + /** + * @return Line[] + */ + private function updateDocBlock(Tokens $tokens, int $docBlockIndex) : array + { + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + $lines = $doc->getLines(); + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + /** + * @param Line[] $lines + * + * @return Line[] + */ + private function updateLines(array $lines, Tokens $tokens, int $docBlockIndex) : array + { + $needsAnnotation = 'annotation' === $this->configuration['style']; + $doc = new DocBlock($tokens[$docBlockIndex]->getContent()); + for ($i = 0; $i < \count($lines); ++$i) { + // If we need to add test annotation and it is a single line comment we need to deal with that separately + if ($needsAnnotation && ($lines[$i]->isTheStart() && $lines[$i]->isTheEnd())) { + if (!$this->doesDocBlockContainTest($doc)) { + $lines = $this->splitUpDocBlock($lines, $tokens, $docBlockIndex); + return $this->updateLines($lines, $tokens, $docBlockIndex); + } + // One we split it up, we run the function again, so we deal with other things in a proper way + } + if (!$needsAnnotation && \strpos($lines[$i]->getContent(), ' @test') !== \false && \strpos($lines[$i]->getContent(), '@testWith') === \false && \strpos($lines[$i]->getContent(), '@testdox') === \false) { + // We remove @test from the doc block + $lines[$i] = new Line(\str_replace(' @test', '', $lines[$i]->getContent())); + } + // ignore the line if it isn't @depends + if (\strpos($lines[$i]->getContent(), '@depends') === \false) { + continue; + } + $lines[$i] = $this->updateDependsAnnotation($lines[$i]); + } + return $lines; + } + /** + * Take a one line doc block, and turn it into a multi line doc block. + * + * @param Line[] $lines + * + * @return Line[] + */ + private function splitUpDocBlock(array $lines, Tokens $tokens, int $docBlockIndex) : array + { + $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 . ' */')]; + } + /** + * @todo check whether it's doable to use \PhpCsFixer\DocBlock\DocBlock::getSingleLineDocBlockEntry instead + * + * @param Line[] $lines + */ + private function getSingleLineDocBlockEntry(array $lines) : string + { + $line = $lines[0]; + $line = \str_replace('*/', '', $line->getContent()); + $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); + } + /** + * Updates the depends tag on the current doc block. + */ + private function updateDependsAnnotation(Line $line) : Line + { + if ('annotation' === $this->configuration['style']) { + return $this->removeTestPrefixFromDependsAnnotation($line); + } + return $this->addTestPrefixToDependsAnnotation($line); + } + private function removeTestPrefixFromDependsAnnotation(Line $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 + { + $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); + } + /** + * Helps to find where the function name in the doc block starts. + * + * @param list $line + */ + private function findWhereDependsFunctionNameStarts(array $line) : int + { + $index = \stripos(\implode('', $line), '@depends') + 8; + while (' ' === $line[$index]) { + ++$index; + } + return $index; + } + /** + * @param Line[] $lines + * + * @return Line[] + */ + private function addTestAnnotation(array $lines, Tokens $tokens, int $docBlockIndex) : array + { + $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) : bool + { + return 0 !== \count($doc->getAnnotationsOfType('test')); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php new file mode 100644 index 00000000000..d6334c582ea --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestCaseStaticMethodCallsFixer.php @@ -0,0 +1,397 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Filippo Tessarotto + */ +final class PhpUnitTestCaseStaticMethodCallsFixer extends AbstractPhpUnitFixer implements ConfigurableFixerInterface +{ + /** + * @internal + */ + public const CALL_TYPE_THIS = 'this'; + /** + * @internal + */ + public const CALL_TYPE_SELF = 'self'; + /** + * @internal + */ + public const CALL_TYPE_STATIC = 'static'; + /** + * @var array + */ + private $allowedValues = [self::CALL_TYPE_THIS => \true, self::CALL_TYPE_SELF => \true, self::CALL_TYPE_STATIC => \true]; + /** + * @var array + */ + private $staticMethods = [ + // Assert methods + '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, + // TestCase methods + '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, + ]; + /** + * @var array>> + */ + 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() : FixerDefinitionInterface + { + $codeSample = 'assertSame(1, 2); + self::assertSame(1, 2); + static::assertSame(1, 2); + } +} +'; + return new FixerDefinition('Calls to `PHPUnit\\Framework\\TestCase` static methods must all be of the same type, either `$this->`, `self::` or `static::`.', [new CodeSample($codeSample), new CodeSample($codeSample, ['call_type' => self::CALL_TYPE_THIS])], null, 'Risky when PHPUnit methods are overridden or not accessible, or when project has PHPUnit incompatibilities.'); + } + /** + * {@inheritdoc} + * + * Must run before SelfStaticAccessorFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isRisky() : bool + { + return \true; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $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 (array $option) use($thisFixer) : bool { + foreach ($option as $method => $value) { + if (!isset($thisFixer->staticMethods[$method])) { + throw new InvalidOptionsException(\sprintf('Unexpected "methods" key, expected any of %s, got "%s".', Utils::naturalLanguageJoin(\array_keys($thisFixer->staticMethods)), \gettype($method) . '#' . $method)); + } + if (!isset($thisFixer->allowedValues[$value])) { + throw new InvalidOptionsException(\sprintf('Unexpected value for method "%s", expected any of %s, got "%s".', $method, Utils::naturalLanguageJoin(\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, int $startIndex, int $endIndex) : void + { + $analyzer = new TokensAnalyzer($tokens); + for ($index = $startIndex; $index < $endIndex; ++$index) { + // skip anonymous classes + if ($tokens[$index]->isGivenKind(\T_CLASS)) { + $index = $this->findEndOfNextBlock($tokens, $index); + continue; + } + $callType = $this->configuration['call_type']; + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + // skip lambda + if ($analyzer->isLambda($index)) { + $index = $this->findEndOfNextBlock($tokens, $index); + continue; + } + // do not change `self` to `this` in static methods + 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; + } + if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + 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, int $index, int $referenceIndex, string $callType) : bool + { + $functionsAnalyzer = new FunctionsAnalyzer(); + return $functionsAnalyzer->isTheSameClassCall($tokens, $index) && !$tokens[$referenceIndex]->equals($this->conversionMap[$callType][1], \false); + } + private function findEndOfNextBlock(Tokens $tokens, int $index) : int + { + $nextIndex = $tokens->getNextTokenOfKind($index, [';', '{']); + return $tokens[$nextIndex]->equals('{') ? $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextIndex) : $nextIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php new file mode 100644 index 00000000000..e8546f424aa --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/PhpUnit/PhpUnitTestClassRequiresCoversFixer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\PhpUnit; + +use PhpCsFixer\Fixer\AbstractPhpUnitFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + */ +final class PhpUnitTestClassRequiresCoversFixer extends AbstractPhpUnitFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Adds a default `@coversNothing` annotation to PHPUnit test classes that have no `@covers*` annotation.', [new CodeSample('assertSame(a(), b()); + } +} +')]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocSeparationFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function applyPhpUnitClassFix(Tokens $tokens, int $startIndex, int $endIndex) : void + { + $classIndex = $tokens->getPrevTokenOfKind($startIndex, [[\T_CLASS]]); + $tokensAnalyzer = new TokensAnalyzer($tokens); + $modifiers = $tokensAnalyzer->getClassyModifiers($classIndex); + if (isset($modifiers['abstract'])) { + return; + // don't add `@covers` annotation for abstract base classes + } + $this->ensureIsDockBlockWithAnnotation($tokens, $classIndex, 'coversNothing', ['covers', 'coversDefaultClass', 'coversNothing']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php new file mode 100644 index 00000000000..7c75bb76e2f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/AlignMultilineCommentFixer.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + * @author Julien Falque + */ +final class AlignMultilineCommentFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var null|int[] + */ + private $tokenKinds; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->tokenKinds = [\T_DOC_COMMENT]; + if ('phpdocs_only' !== $this->configuration['comment_type']) { + $this->tokenKinds[] = \T_COMMENT; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Each line of multi-line DocComments must have an asterisk [PSR-5] and must be aligned with the first one.', [new CodeSample(' 'phpdocs_like']), new CodeSample(' 'all_multiline'])]); + } + /** + * {@inheritdoc} + * + * Must run before CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after ArrayIndentationFixer. + */ + public function getPriority() : int + { + return 27; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound($this->tokenKinds); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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 (!Preg::match('/\\R(\\h*)$/', $whitespace, $matches)) { + continue; + } + if ($token->isGivenKind(\T_COMMENT) && 'all_multiline' !== $this->configuration['comment_type'] && 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() : FixerConfigurationResolverInterface + { + 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()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php new file mode 100644 index 00000000000..c810393a68b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocAnnotationRemoveFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class GeneralPhpdocAnnotationRemoveFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Configured annotations should be omitted from PHPDoc.', [new CodeSample(' ['author']]), new CodeSample(' ['author'], 'case_sensitive' => \false]), new CodeSample(' ['package', 'subpackage']])]); + } + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, PhpdocLineSpanFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (0 === \count($this->configuration['annotations'])) { + return; + } + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $doc = new DocBlock($token->getContent()); + $annotations = $this->getAnnotationsToRemove($doc); + // nothing to do if there are no annotations + if (0 === \count($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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('annotations', 'List of annotations to remove, e.g. `["author"]`.'))->setAllowedTypes(['array'])->setDefault([])->getOption(), (new FixerOptionBuilder('case_sensitive', 'Should annotations be case sensitive.'))->setAllowedTypes(['bool'])->setDefault(\true)->getOption()]); + } + /** + * @return list + */ + private function getAnnotationsToRemove(DocBlock $doc) : array + { + if (\true === $this->configuration['case_sensitive']) { + return $doc->getAnnotationsOfType($this->configuration['annotations']); + } + $typesToSearchFor = \array_map(function (string $type) : string { + return \strtolower($type); + }, $this->configuration['annotations']); + $annotations = []; + foreach ($doc->getAnnotations() as $annotation) { + $tagName = \strtolower($annotation->getTag()->getName()); + if (\in_array($tagName, $typesToSearchFor, \true)) { + $annotations[] = $annotation; + } + } + return $annotations; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php new file mode 100644 index 00000000000..a2811fc062e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/GeneralPhpdocTagRenameFixer.php @@ -0,0 +1,114 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +final class GeneralPhpdocTagRenameFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Renames PHPDoc tags.', [new CodeSample(" ['inheritDocs' => 'inheritDoc']]), new CodeSample(" ['inheritDocs' => 'inheritDoc'], 'fix_annotation' => \false]), new CodeSample(" ['inheritDocs' => 'inheritDoc'], 'fix_inline' => \false]), new CodeSample(" ['inheritDocs' => 'inheritDoc'], 'case_sensitive' => \true])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + // must be run before PhpdocAddMissingParamAnnotationFixer + return 11; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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(static function (Options $options, $value) : array { + $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 (!Preg::match('#^\\S+$#', $to) || \strpos($to, '*/') !== \false) { + 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) : void + { + if (0 === \count($this->configuration['replacements'])) { + return; + } + if (\true === $this->configuration['fix_annotation']) { + if ($this->configuration['fix_inline']) { + $regex = '/"[^"]*"(*SKIP)(*FAIL)|\\b(?<=@)(%s)\\b/'; + } else { + $regex = '/"[^"]*"(*SKIP)(*FAIL)|(?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, static function (array $matches) use($caseInsensitive, $replacements) { + if ($caseInsensitive) { + $matches[1] = \strtolower($matches[1]); + } + return $replacements[$matches[1]]; + }, $token->getContent())]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php new file mode 100644 index 00000000000..7f1510ee23d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoBlankLinesAfterPhpdocFixer.php @@ -0,0 +1,79 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class NoBlankLinesAfterPhpdocFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be blank lines between docblock and the documented element.', [new CodeSample(' $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + // get the next non-whitespace token inc comments, provided + // that there is whitespace between it and the current token + $next = $tokens->getNextNonWhitespace($index); + if ($index + 2 === $next && \false === $tokens[$next]->isGivenKind($forbiddenSuccessors)) { + $this->fixWhitespace($tokens, $index + 1); + } + } + } + /** + * Cleanup a whitespace token. + */ + private function fixWhitespace(Tokens $tokens, int $index) : void + { + $content = $tokens[$index]->getContent(); + // if there is more than one new line in the whitespace, then we need to fix it + if (\substr_count($content, "\n") > 1) { + // the final bit of the whitespace must be the next statement's indentation + $tokens[$index] = new Token([\T_WHITESPACE, \substr($content, \strrpos($content, "\n"))]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php new file mode 100644 index 00000000000..05d1e0fe197 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoEmptyPhpdocFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +final class NoEmptyPhpdocFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be empty PHPDoc blocks.', [new CodeSample("isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + if (Preg::match('#^/\\*\\*[\\s\\*]*\\*/$#', $token->getContent())) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php new file mode 100644 index 00000000000..683d07b6f23 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/NoSuperfluousPhpdocTagsFixer.php @@ -0,0 +1,483 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +final class NoSuperfluousPhpdocTagsFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const NO_TYPE_INFO = ['types' => [], 'allows_null' => \true]; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes `@param`, `@return` and `@var` tags that don\'t provide any useful information.', [new CodeSample(' \true]), new CodeSample(' \true]), new CodeSample(' \true])]); + } + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, PhpdocAlignFixer, VoidReturnFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, FullyQualifiedStrictTypesFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocLineSpanFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 6; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespaceUseAnalyzer = new NamespaceUsesAnalyzer(); + $shortNames = []; + $currentSymbol = null; + $currentSymbolEndIndex = null; + foreach ($namespaceUseAnalyzer->getDeclarationsFromTokens($tokens) as $namespaceUseAnalysis) { + $shortNames[\strtolower($namespaceUseAnalysis->getShortName())] = '\\' . \strtolower($namespaceUseAnalysis->getFullName()); + } + $symbolKinds = [\T_CLASS, \T_INTERFACE]; + if (\defined('T_ENUM')) { + // @TODO drop the condition when requiring PHP 8.1+ + $symbolKinds[] = \T_ENUM; + } + foreach ($tokens as $index => $token) { + if ($index === $currentSymbolEndIndex) { + $currentSymbol = null; + $currentSymbolEndIndex = null; + continue; + } + if ($token->isGivenKind(\T_CLASS) && $tokensAnalyzer->isAnonymousClass($index)) { + continue; + } + if ($token->isGivenKind($symbolKinds)) { + $currentSymbol = $tokens[$tokens->getNextMeaningfulToken($index)]->getContent(); + $currentSymbolEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tokens->getNextTokenOfKind($index, ['{'])); + continue; + } + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $documentedElement = $this->findDocumentedElement($tokens, $index); + if (null === $documentedElement) { + continue; + } + $content = $initialContent = $token->getContent(); + if (\true === $this->configuration['remove_inheritdoc']) { + $content = $this->removeSuperfluousInheritDoc($content); + } + if ('function' === $documentedElement['type']) { + $content = $this->fixFunctionDocComment($content, $tokens, $documentedElement, $currentSymbol, $shortNames); + } elseif ('property' === $documentedElement['type']) { + $content = $this->fixPropertyDocComment($content, $tokens, $documentedElement, $currentSymbol, $shortNames); + } elseif ('classy' === $documentedElement['type']) { + $content = $this->fixClassDocComment($content, $documentedElement); + } else { + throw new \RuntimeException('Unknown type.'); + } + if ('' === $content) { + $content = '/** */'; + } + if ($content !== $initialContent) { + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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()]); + } + /** + * @return null|array{ + * index: int, + * type: 'classy'|'function'|'property', + * modifiers: array, + * types: array, + * } + */ + private function findDocumentedElement(Tokens $tokens, int $docCommentIndex) : ?array + { + $modifierKinds = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_ABSTRACT, \T_FINAL, \T_STATIC]; + $typeKinds = [CT::T_NULLABLE_TYPE, CT::T_ARRAY_TYPEHINT, CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION, \T_STRING, \T_NS_SEPARATOR]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $modifierKinds[] = \T_READONLY; + } + $element = ['modifiers' => [], 'types' => []]; + $index = $tokens->getNextMeaningfulToken($docCommentIndex); + // @TODO: drop condition when PHP 8.0+ is required + if (null !== $index && \defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(\T_ATTRIBUTE)) { + do { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $tokens->getNextMeaningfulToken($index); + } while (null !== $index && $tokens[$index]->isGivenKind(\T_ATTRIBUTE)); + } + while (\true) { + if (null === $index) { + break; + } + if ($tokens[$index]->isClassy()) { + $element['index'] = $index; + $element['type'] = 'classy'; + return $element; + } + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $element['index'] = $index; + $element['type'] = 'function'; + return $element; + } + if ($tokens[$index]->isGivenKind(\T_VARIABLE)) { + $element['index'] = $index; + $element['type'] = 'property'; + return $element; + } + if ($tokens[$index]->isGivenKind($modifierKinds)) { + $element['modifiers'][$index] = $tokens[$index]; + } elseif ($tokens[$index]->isGivenKind($typeKinds)) { + $element['types'][$index] = $tokens[$index]; + } else { + break; + } + $index = $tokens->getNextMeaningfulToken($index); + } + return null; + } + /** + * @param array{ + * index: int, + * type: 'function', + * modifiers: array, + * types: array, + * } $element + * @param array $shortNames + */ + private function fixFunctionDocComment(string $content, Tokens $tokens, array $element, ?string $currentSymbol, array $shortNames) : string + { + $docBlock = new DocBlock($content); + $openingParenthesisIndex = $tokens->getNextTokenOfKind($element['index'], ['(']); + $closingParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $openingParenthesisIndex); + $argumentsInfo = $this->getArgumentsInfo($tokens, $openingParenthesisIndex + 1, $closingParenthesisIndex - 1); + foreach ($docBlock->getAnnotationsOfType('param') as $annotation) { + $argumentName = $annotation->getVariableName(); + if (null === $argumentName) { + if ($this->annotationIsSuperfluous($annotation, self::NO_TYPE_INFO, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + continue; + } + if (!isset($argumentsInfo[$argumentName]) && \true === $this->configuration['allow_unused_params']) { + continue; + } + if (!isset($argumentsInfo[$argumentName]) || $this->annotationIsSuperfluous($annotation, $argumentsInfo[$argumentName], $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + $returnTypeInfo = $this->getReturnTypeInfo($tokens, $closingParenthesisIndex); + foreach ($docBlock->getAnnotationsOfType('return') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $returnTypeInfo, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + return $docBlock->getContent(); + } + /** + * @param array{ + * index: int, + * type: 'property', + * modifiers: array, + * types: array, + * } $element + * @param array $shortNames + */ + private function fixPropertyDocComment(string $content, Tokens $tokens, array $element, ?string $currentSymbol, array $shortNames) : string + { + if (\count($element['types']) > 0) { + \reset($element['types']); + $propertyTypeInfo = $this->parseTypeHint($tokens, \key($element['types'])); + } else { + $propertyTypeInfo = self::NO_TYPE_INFO; + } + $docBlock = new DocBlock($content); + foreach ($docBlock->getAnnotationsOfType('var') as $annotation) { + if ($this->annotationIsSuperfluous($annotation, $propertyTypeInfo, $currentSymbol, $shortNames)) { + $annotation->remove(); + } + } + return $docBlock->getContent(); + } + /** + * @param array{ + * index: int, + * type: 'classy', + * modifiers: array, + * types: array, + * } $element + */ + private function fixClassDocComment(string $content, array $element) : string + { + $docBlock = new DocBlock($content); + $this->removeSuperfluousModifierAnnotation($docBlock, $element); + return $docBlock->getContent(); + } + /** + * @return array, allows_null: bool}> + */ + private function getArgumentsInfo(Tokens $tokens, int $start, int $end) : array + { + $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 = self::NO_TYPE_INFO; + } + if (!$info['allows_null']) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->equals('=') && $tokens[$tokens->getNextMeaningfulToken($nextIndex)]->equals([\T_STRING, 'null'], \false)) { + $info['allows_null'] = \true; + } + } + $argumentsInfo[$token->getContent()] = $info; + } + return $argumentsInfo; + } + /** + * @return array{types: list, allows_null: bool} + */ + private function getReturnTypeInfo(Tokens $tokens, int $closingParenthesisIndex) : array + { + $colonIndex = $tokens->getNextMeaningfulToken($closingParenthesisIndex); + return $tokens[$colonIndex]->isGivenKind(CT::T_TYPE_COLON) ? $this->parseTypeHint($tokens, $tokens->getNextMeaningfulToken($colonIndex)) : self::NO_TYPE_INFO; + } + /** + * @param int $index The index of the first token of the type hint + * + * @return array{types: list, allows_null: bool} + */ + private function parseTypeHint(Tokens $tokens, int $index) : array + { + $allowsNull = \false; + $types = []; + while (\true) { + $type = ''; + if (\defined('T_READONLY') && $tokens[$index]->isGivenKind(\T_READONLY)) { + // @TODO: simplify condition when PHP 8.1+ is required + $index = $tokens->getNextMeaningfulToken($index); + } + if ($tokens[$index]->isGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE])) { + $index = $tokens->getNextMeaningfulToken($index); + continue; + } + if ($tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + $allowsNull = \true; + $index = $tokens->getNextMeaningfulToken($index); + } + while ($tokens[$index]->isGivenKind([\T_NS_SEPARATOR, \T_STATIC, \T_STRING, CT::T_ARRAY_TYPEHINT, \T_CALLABLE])) { + $type .= $tokens[$index]->getContent(); + $index = $tokens->getNextMeaningfulToken($index); + } + if ('' === $type) { + break; + } + $types[] = $type; + if (!$tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + break; + } + $index = $tokens->getNextMeaningfulToken($index); + } + return ['types' => $types, 'allows_null' => $allowsNull]; + } + /** + * @param array $symbolShortNames + */ + private function annotationIsSuperfluous(Annotation $annotation, array $info, ?string $currentSymbol, array $symbolShortNames) : bool + { + if ('param' === $annotation->getTag()->getName()) { + $regex = '{@param(?:\\s+' . TypeExpression::REGEX_TYPES . ')?(?:\\s+(?:\\&\\s*)?(?:\\.{3}\\s*)?\\$\\S+)?(?:\\s+(?(?!\\*+\\/)\\S+))?}s'; + } elseif ('var' === $annotation->getTag()->getName()) { + $regex = '{@var(?:\\s+' . TypeExpression::REGEX_TYPES . ')?(?:\\s+\\$\\S+)?(?:\\s+(?(?!\\*\\/)\\S+))?}s'; + } else { + $regex = '{@return(?:\\s+' . TypeExpression::REGEX_TYPES . ')?(?:\\s+(?(?!\\*\\/)\\S+))?}s'; + } + if (!Preg::match($regex, $annotation->getContent(), $matches)) { + // Unable to match the annotation, it must be malformed or has unsupported format. + // Either way we don't want to tinker with it. + return \false; + } + if (isset($matches['description'])) { + return \false; + } + if (!isset($matches['types']) || '' === $matches['types']) { + // If there's no type info in the annotation, further checks make no sense, exit early. + return \true; + } + $annotationTypes = $this->toComparableNames($annotation->getTypes(), $currentSymbol, $symbolShortNames); + if (['null'] === $annotationTypes) { + return \false; + } + if (['mixed'] === $annotationTypes && [] === $info['types']) { + return \false === $this->configuration['allow_mixed']; + } + $actualTypes = $info['types']; + if ($info['allows_null']) { + $actualTypes[] = 'null'; + } + return $annotationTypes === $this->toComparableNames($actualTypes, $currentSymbol, $symbolShortNames); + } + /** + * Normalizes types to make them comparable. + * + * Converts given types to lowercase, replaces imports aliases with + * their matching FQCN, and finally sorts the result. + * + * @param string[] $types The types to normalize + * @param array $symbolShortNames The imports aliases + * + * @return array The normalized types + */ + private function toComparableNames(array $types, ?string $currentSymbol, array $symbolShortNames) : array + { + $normalized = \array_map(static function (string $type) use($currentSymbol, $symbolShortNames) : string { + if ('self' === $type && null !== $currentSymbol) { + $type = $currentSymbol; + } + $type = \strtolower($type); + if (\strpos($type, '&') !== \false) { + $intersects = \explode('&', $type); + \sort($intersects); + return \implode('&', $intersects); + } + return $symbolShortNames[$type] ?? $type; + }, $types); + \sort($normalized); + return $normalized; + } + private function removeSuperfluousInheritDoc(string $docComment) : string + { + 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); + } + private function removeSuperfluousModifierAnnotation(DocBlock $docBlock, array $element) : void + { + foreach (['abstract' => \T_ABSTRACT, 'final' => \T_FINAL] as $annotationType => $modifierToken) { + $annotations = $docBlock->getAnnotationsOfType($annotationType); + foreach ($element['modifiers'] as $token) { + if ($token->isGivenKind($modifierToken)) { + foreach ($annotations as $annotation) { + $annotation->remove(); + } + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php new file mode 100644 index 00000000000..fc352977b4b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAddMissingParamAnnotationFixer.php @@ -0,0 +1,182 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpdocAddMissingParamAnnotationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPDoc should contain `@param` for all params.', [new CodeSample(' \true]), new CodeSample(' \false])]); + } + /** + * {@inheritdoc} + * + * Must run before NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer, PhpdocOrderFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocTagRenameFixer, PhpdocIndentFixer, PhpdocNoAliasTagFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + } + // ignore one-line phpdocs like `/** foo */`, as there is no place to put new annotations + if (\strpos($tokenContent, "\n") === \false) { + 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])) { + $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 (\false === $this->configuration['only_untyped'] || '' === $argumentInfo['type']) { + $arguments[$argumentInfo['name']] = $argumentInfo; + } + } + if (0 === \count($arguments)) { + continue; + } + $doc = new DocBlock($tokenContent); + $lastParamLine = null; + foreach ($doc->getAnnotationsOfType('param') as $annotation) { + $pregMatched = Preg::match('/^[^$]+(\\$\\w+).*$/s', $annotation->getContent(), $matches); + if ($pregMatched) { + unset($arguments[$matches[1]]); + } + $lastParamLine = \max($lastParamLine, $annotation->getEnd()); + } + if (0 === \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 (\strncmp($type, '?', \strlen('?')) !== 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 > 0 ? $lastParamLine + 1 : $linesCount - 1, 0, $newLines); + $tokens[$mainIndex] = new Token([\T_DOC_COMMENT, \implode('', $lines)]); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('only_untyped', 'Whether to add missing `@param` annotations for untyped parameters only.'))->setDefault(\true)->setAllowedTypes(['bool'])->getOption()]); + } + /** + * @return array{default: string, name: string, type: string} + */ + private function prepareArgumentInformation(Tokens $tokens, int $start, int $end) : array + { + $info = ['default' => '', 'name' => '', 'type' => '']; + $sawName = \false; + for ($index = $start; $index <= $end; ++$index) { + $token = $tokens[$index]; + if ($token->isComment() || $token->isWhitespace() || $token->isGivenKind([CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC]) || \defined('T_READONLY') && $token->isGivenKind(\T_READONLY)) { + 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->equals('&')) { + if ($token->isGivenKind(\T_ELLIPSIS)) { + if ('' === $info['type']) { + $info['type'] = 'array'; + } else { + $info['type'] .= '[]'; + } + } else { + $info['type'] .= $token->getContent(); + } + } + } + return $info; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php new file mode 100644 index 00000000000..4833494a4c5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAlignFixer.php @@ -0,0 +1,301 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Fabien Potencier + * @author Jordi Boggiano + * @author Sebastiaan Stok + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocAlignFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const ALIGN_LEFT = 'left'; + /** + * @internal + */ + public const ALIGN_VERTICAL = 'vertical'; + private const DEFAULT_TAGS = ['method', 'param', 'property', 'return', 'throws', 'type', 'var']; + private const TAGS_WITH_NAME = ['param', 'property', 'property-read', 'property-write', 'phpstan-param', 'phpstan-property', 'phpstan-property-read', 'phpstan-property-write', 'phpstan-assert', 'phpstan-assert-if-true', 'phpstan-assert-if-false', 'psalm-param', 'psalm-param-out', 'psalm-property', 'psalm-property-read', 'psalm-property-write', 'psalm-assert', 'psalm-assert-if-true', 'psalm-assert-if-false']; + private const TAGS_WITH_METHOD_SIGNATURE = ['method', 'phpstan-method', 'psalm-method']; + /** + * @var string + */ + private $regex; + /** + * @var string + */ + private $regexCommentLine; + /** + * @var string + */ + private $align; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $tagsWithNameToAlign = \array_intersect($this->configuration['tags'], self::TAGS_WITH_NAME); + $tagsWithMethodSignatureToAlign = \array_intersect($this->configuration['tags'], self::TAGS_WITH_METHOD_SIGNATURE); + $tagsWithoutNameToAlign = \array_diff($this->configuration['tags'], $tagsWithNameToAlign, $tagsWithMethodSignatureToAlign); + $indentRegex = '^(?P(?:\\ {2}|\\t)*)\\ ?'; + $types = []; + // e.g. @param <$var> + if ([] !== $tagsWithNameToAlign) { + $types[] = '(?P' . \implode('|', $tagsWithNameToAlign) . ')\\s+(?P(?:' . TypeExpression::REGEX_TYPES . ')?)\\s*(?P(?:&|\\.{3})?\\$\\S+)'; + } + // e.g. @return + if ([] !== $tagsWithoutNameToAlign) { + $types[] = '(?P' . \implode('|', $tagsWithoutNameToAlign) . ')\\s+(?P(?:' . TypeExpression::REGEX_TYPES . ')?)'; + } + // e.g. @method + if ([] !== $tagsWithMethodSignatureToAlign) { + $types[] = '(?P' . \implode('|', $tagsWithMethodSignatureToAlign) . ')(\\s+(?Pstatic))?(\\s+(?P(?:' . TypeExpression::REGEX_TYPES . ')?))\\s+(?P.+\\))'; + } + // optional + $desc = '(?:\\s+(?P\\V*))'; + $this->regex = '/' . $indentRegex . '\\*\\h*@(?J)(?:' . \implode('|', $types) . ')' . $desc . '\\h*\\r?$/'; + $this->regexCommentLine = '/' . $indentRegex . '\\*(?!\\h?+@)(?:\\s+(?P\\V+))(?align = $this->configuration['align']; + } + public function getDefinition() : FixerDefinitionInterface + { + $code = <<<'EOF' + self::ALIGN_VERTICAL]), new CodeSample($code, ['align' => self::ALIGN_LEFT])]); + } + /** + * {@inheritdoc} + * + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToCommentFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + */ + public function getPriority() : int + { + /* + * Should be run after all other docblock fixers. This because they + * modify other annotations to change their type and or separation + * which totally change the behavior of this fixer. It's important that + * annotations are of the correct type, and are grouped correctly + * before running this fixer. + */ + return -42; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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() : FixerConfigurationResolverInterface + { + $tags = new FixerOptionBuilder('tags', 'The tags that should be aligned.'); + $tags->setAllowedTypes(['array'])->setDefault(self::DEFAULT_TAGS); + $align = new FixerOptionBuilder('align', 'How comments should be aligned.'); + $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) : void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + for ($i = 0, $l = \count($docBlock->getLines()); $i < $l; ++$i) { + $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; + } + // compute the max length of the tag, hint and variables + $hasStatic = \false; + $tagMax = 0; + $hintMax = 0; + $varMax = 0; + foreach ($items as $item) { + if (null === $item['tag']) { + continue; + } + $hasStatic |= '' !== $item['static']; + $tagMax = \max($tagMax, \strlen($item['tag'])); + $hintMax = \max($hintMax, \strlen($item['hint'])); + $varMax = \max($varMax, \strlen($item['var'])); + } + $currTag = null; + // update + foreach ($items as $j => $item) { + if (null === $item['tag']) { + if ('@' === $item['desc'][0]) { + $line = $item['indent'] . ' * ' . $item['desc']; + $docBlock->getLine($current + $j)->setContent($line . $lineEnding); + continue; + } + $extraIndent = 2; + if (\in_array($currTag, self::TAGS_WITH_NAME, \true) || \in_array($currTag, self::TAGS_WITH_METHOD_SIGNATURE, \true)) { + $extraIndent += $varMax + 1; + } + if ($hasStatic) { + $extraIndent += 7; + // \strlen('static '); + } + $line = $item['indent'] . ' * ' . $this->getIndent($tagMax + $hintMax + $extraIndent, $this->getLeftAlignedDescriptionIndent($items, $j)) . $item['desc']; + $docBlock->getLine($current + $j)->setContent($line . $lineEnding); + continue; + } + $currTag = $item['tag']; + $line = $item['indent'] . ' * @' . $item['tag']; + if ($hasStatic) { + $line .= $this->getIndent($tagMax - \strlen($item['tag']) + 1, '' !== $item['static'] ? 1 : 0) . ($item['static'] ?: $this->getIndent(6, 0)); + $hintVerticalAlignIndent = 1; + } else { + $hintVerticalAlignIndent = $tagMax - \strlen($item['tag']) + 1; + } + $line .= $this->getIndent($hintVerticalAlignIndent, '' !== $item['hint'] ? 1 : 0) . $item['hint']; + if ('' !== $item['var']) { + $line .= $this->getIndent(($hintMax ?: -1) - \strlen($item['hint']) + 1) . $item['var'] . ('' !== $item['desc'] ? $this->getIndent($varMax - \strlen($item['var']) + 1) . $item['desc'] : ''); + } elseif ('' !== $item['desc']) { + $line .= $this->getIndent($hintMax - \strlen($item['hint']) + 1) . $item['desc']; + } + $docBlock->getLine($current + $j)->setContent($line . $lineEnding); + } + } + } + /** + * @TODO Introduce proper DTO instead of an array + * + * @return null|array{indent: null|string, tag: null|string, hint: string, var: null|string, static: string, desc?: null|string} + */ + private function getMatches(string $line, bool $matchCommentOnly = \false) : ?array + { + if (Preg::match($this->regex, $line, $matches)) { + if (isset($matches['tag2']) && '' !== $matches['tag2']) { + $matches['tag'] = $matches['tag2']; + $matches['hint'] = $matches['hint2']; + $matches['var'] = ''; + } + if (isset($matches['tag3']) && '' !== $matches['tag3']) { + $matches['tag'] = $matches['tag3']; + $matches['hint'] = $matches['hint3']; + $matches['var'] = $matches['signature']; + // Since static can be both a return type declaration & a keyword that defines static methods + // we assume it's a type declaration when only one value is present + if ('' === $matches['hint'] && '' !== $matches['static']) { + $matches['hint'] = $matches['static']; + $matches['static'] = ''; + } + } + if (isset($matches['hint'])) { + $matches['hint'] = \trim($matches['hint']); + } + if (!isset($matches['static'])) { + $matches['static'] = ''; + } + return $matches; + } + if ($matchCommentOnly && Preg::match($this->regexCommentLine, $line, $matches)) { + $matches['tag'] = null; + $matches['var'] = ''; + $matches['hint'] = ''; + $matches['static'] = ''; + return $matches; + } + return null; + } + private function getIndent(int $verticalAlignIndent, int $leftAlignIndent = 1) : string + { + $indent = self::ALIGN_VERTICAL === $this->align ? $verticalAlignIndent : $leftAlignIndent; + return \str_repeat(' ', $indent); + } + /** + * @param non-empty-list $items + */ + private function getLeftAlignedDescriptionIndent(array $items, int $index) : int + { + if (self::ALIGN_LEFT !== $this->align) { + return 0; + } + // Find last tagged line: + $item = null; + for (; $index >= 0; --$index) { + $item = $items[$index]; + if (null !== $item['tag']) { + break; + } + } + // No last tag found — no indent: + if (null === $item) { + return 0; + } + // Indent according to existing values: + return $this->getSentenceIndent($item['static']) + $this->getSentenceIndent($item['tag']) + $this->getSentenceIndent($item['hint']) + $this->getSentenceIndent($item['var']); + } + /** + * Get indent for sentence. + */ + private function getSentenceIndent(?string $sentence) : int + { + if (null === $sentence) { + return 0; + } + $length = \strlen($sentence); + return 0 === $length ? 0 : $length + 1; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php new file mode 100644 index 00000000000..4fa5c4b4ea9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocAnnotationWithoutDotFixer.php @@ -0,0 +1,94 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class PhpdocAnnotationWithoutDotFixer extends AbstractFixer +{ + /** + * @var string[] + */ + private $tags = ['throws', 'return', 'param', 'internal', 'deprecated', 'var', 'type']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPDoc annotation descriptions should not be a sentence.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotations(); + if (0 === \count($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 || \strncmp($lineAfterAnnotationTrimmed, '*', \strlen('*')) !== 0) { + // malformed PHPDoc, missing asterisk ! + continue; + } + } + $content = $annotation->getContent(); + if (!Preg::match('/[.。]\\h*$/u', $content) || Preg::match('/[.。](?!\\h*$)/u', $content, $matches)) { + continue; + } + $endLine = $doc->getLine($annotation->getEnd()); + $endLine->setContent(Preg::replace('/(?getContent())); + $startLine = $doc->getLine($annotation->getStart()); + $optionalTypeRegEx = $annotation->supportTypes() ? \sprintf('(?:%s\\s+(?:\\$\\w+\\s+)?)?', \preg_quote(\implode('|', $annotation->getTypes()), '/')) : ''; + $content = Preg::replaceCallback('/^(\\s*\\*\\s*@\\w+\\s+' . $optionalTypeRegEx . ')(\\p{Lu}?(?=\\p{Ll}|\\p{Zs}))(.*)$/', static function (array $matches) : string { + return $matches[1] . \mb_strtolower($matches[2]) . $matches[3]; + }, $startLine->getContent(), 1); + $startLine->setContent($content); + } + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php new file mode 100644 index 00000000000..24038ab58d1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocIndentFixer.php @@ -0,0 +1,112 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Utils; +/** + * @author Ceeram + * @author Graham Campbell + */ +final class PhpdocIndentFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Docblocks should have the same indentation as the documented subject.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $nextIndex = $tokens->getNextMeaningfulToken($index); + // skip if there is no next token or if next token is block end `}` + if (null === $nextIndex || $tokens[$nextIndex]->equals('}')) { + continue; + } + $prevIndex = $index - 1; + $prevToken = $tokens[$prevIndex]; + // ignore inline docblocks + if ($prevToken->isGivenKind(\T_OPEN_TAG) || $prevToken->isWhitespace(" \t") && !$tokens[$index - 2]->isGivenKind(\T_OPEN_TAG) || $prevToken->equalsAny([';', ',', '{', '('])) { + continue; + } + if ($tokens[$nextIndex - 1]->isWhitespace()) { + $indent = Utils::calculateTrailingWhitespaceIndent($tokens[$nextIndex - 1]); + } else { + $indent = ''; + } + $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)]); + } + } + /** + * Fix indentation of Docblock. + * + * @param string $content Docblock contents + * @param string $indent Indentation to apply + * + * @return string Dockblock contents including correct indentation + */ + private function fixDocBlock(string $content, string $indent) : string + { + return \ltrim(Preg::replace('/^\\h*\\*/m', $indent . ' *', $content)); + } + /** + * @param string $content Whitespace before Docblock + * @param string $indent Indentation of the documented subject + * + * @return string Whitespace including correct indentation for Dockblock after this whitespace + */ + private function fixWhitespaceBeforeDocblock(string $content, string $indent) : string + { + return \rtrim($content, " \t") . $indent; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php new file mode 100644 index 00000000000..c83aebdc427 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocInlineTagNormalizerFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class PhpdocInlineTagNormalizerFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Fixes PHPDoc inline tags.', [new CodeSample(" ['TUTORIAL']])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + // Move `@` inside tag, for example @{tag} -> {@tag}, replace multiple curly brackets, + // remove spaces between '{' and '@', remove white space between end + // of text and closing bracket and between the tag and inline comment. + $content = Preg::replaceCallback(\sprintf('#(?:@{+|{+\\h*@)\\h*(%s)s?([^}]*)(?:}+)#i', \implode('|', \array_map(static function (string $tag) : string { + return \preg_quote($tag, '/'); + }, $this->configuration['tags']))), static function (array $matches) : string { + $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() : FixerConfigurationResolverInterface + { + 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()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php new file mode 100644 index 00000000000..8b31e576d95 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocLineSpanFixer.php @@ -0,0 +1,102 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Gert de Pagter + */ +final class PhpdocLineSpanFixer extends AbstractFixer implements WhitespacesAwareFixerInterface, ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Changes doc blocks from single to multi line, or reversed. Works for class constants, properties and methods only.', [new CodeSample(" 'single'])]); + } + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 7; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('const', 'Whether const blocks should be single or multi line.'))->setAllowedValues(['single', 'multi', null])->setDefault('multi')->getOption(), (new FixerOptionBuilder('property', 'Whether property doc blocks should be single or multi line.'))->setAllowedValues(['single', 'multi', null])->setDefault('multi')->getOption(), (new FixerOptionBuilder('method', 'Whether method doc blocks should be single or multi line.'))->setAllowedValues(['single', 'multi', null])->setDefault('multi')->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $analyzer = new TokensAnalyzer($tokens); + foreach ($analyzer->getClassyElements() as $index => $element) { + if (!$this->hasDocBlock($tokens, $index)) { + continue; + } + $type = $element['type']; + if (!isset($this->configuration[$type])) { + continue; + } + $docIndex = $this->getDocBlockIndex($tokens, $index); + $doc = new DocBlock($tokens[$docIndex]->getContent()); + if ('multi' === $this->configuration[$type]) { + $doc->makeMultiLine(WhitespacesAnalyzer::detectIndent($tokens, $docIndex), $this->whitespacesConfig->getLineEnding()); + } elseif ('single' === $this->configuration[$type]) { + $doc->makeSingleLine(); + } + $tokens->offsetSet($docIndex, new Token([\T_DOC_COMMENT, $doc->getContent()])); + } + } + private function hasDocBlock(Tokens $tokens, int $index) : bool + { + $docBlockIndex = $this->getDocBlockIndex($tokens, $index); + return $tokens[$docBlockIndex]->isGivenKind(\T_DOC_COMMENT); + } + private function getDocBlockIndex(Tokens $tokens, int $index) : int + { + $propertyPartKinds = [\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]; + if (\defined('T_ATTRIBUTE')) { + // @TODO: drop condition when PHP 8.0+ is required + $propertyPartKinds[] = \T_ATTRIBUTE; + } + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $propertyPartKinds[] = \T_READONLY; + } + do { + $index = $tokens->getPrevNonWhitespace($index); + if ($tokens[$index]->isGivenKind(CT::T_ATTRIBUTE_CLOSE)) { + $index = $tokens->getPrevTokenOfKind($index, [[\T_ATTRIBUTE]]); + } + } while ($tokens[$index]->isGivenKind($propertyPartKinds)); + return $index; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php new file mode 100644 index 00000000000..c1c62e8bba2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAccessFixer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoAccessFixer extends AbstractProxyFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('`@access` annotations should be omitted from PHPDoc.', [new CodeSample('configure(['annotations' => ['access']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php new file mode 100644 index 00000000000..f226ce61445 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoAliasTagFixer.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +/** + * Case-sensitive tag replace fixer (does not process inline tags like {@inheritdoc}). + * + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoAliasTagFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('No alias PHPDoc tags should be used.', [new CodeSample(' ['link' => 'website']])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocSingleLineVarSpacingFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return parent::getPriority(); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('replacements', 'Mapping between replaced annotations with new ones.'))->setAllowedTypes(['array'])->setDefault(['property-read' => 'property', 'property-write' => 'property', 'type' => 'var', 'link' => 'see'])->getOption()]); + } + protected function createProxyFixers() : array + { + return [new \PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php new file mode 100644 index 00000000000..bbf1af1375d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoEmptyReturnFixer.php @@ -0,0 +1,91 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class PhpdocNoEmptyReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('`@return void` and `@return null` annotations should be omitted from PHPDoc.', [new CodeSample(' $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType('return'); + if (0 === \count($annotations)) { + continue; + } + foreach ($annotations as $annotation) { + $this->fixAnnotation($annotation); + } + $newContent = $doc->getContent(); + if ($newContent === $token->getContent()) { + continue; + } + if ('' === $newContent) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + continue; + } + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + /** + * Remove `return void` or `return null` annotations. + */ + private function fixAnnotation(Annotation $annotation) : void + { + $types = $annotation->getNormalizedTypes(); + if (1 === \count($types) && ('null' === $types[0] || 'void' === $types[0])) { + $annotation->remove(); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php new file mode 100644 index 00000000000..0bacca8f1e7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoPackageFixer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocNoPackageFixer extends AbstractProxyFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('`@package` and `@subpackage` annotations should be omitted from PHPDoc.', [new CodeSample('configure(['annotations' => ['package', 'subpackage']]); + return [$fixer]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php new file mode 100644 index 00000000000..ce99526b5f2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocNoUselessInheritdocFixer.php @@ -0,0 +1,119 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Remove inheritdoc tags from classy that does not inherit. + */ +final class PhpdocNoUselessInheritdocFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Classy that does not inherit must not have `@inheritdoc` tags.', [new CodeSample("isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_INTERFACE]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // min. offset 4 as minimal candidate is @: isGivenKind([\T_CLASS, \T_INTERFACE])) { + $index = $this->fixClassy($tokens, $index); + } + } + } + private function fixClassy(Tokens $tokens, int $index) : int + { + // figure out where the classy starts + $classOpenIndex = $tokens->getNextTokenOfKind($index, ['{']); + // figure out where the classy ends + $classEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $classOpenIndex); + // is classy extending or implementing some interface + $extendingOrImplementing = $this->isExtendingOrImplementing($tokens, $index, $classOpenIndex); + if (!$extendingOrImplementing) { + // PHPDoc of classy should not have inherit tag even when using traits as Traits cannot provide this information + $this->fixClassyOutside($tokens, $index); + } + // figure out if the classy uses a trait + if (!$extendingOrImplementing && $this->isUsingTrait($tokens, $index, $classOpenIndex, $classEndIndex)) { + $extendingOrImplementing = \true; + } + $this->fixClassyInside($tokens, $classOpenIndex, $classEndIndex, !$extendingOrImplementing); + return $classEndIndex; + } + private function fixClassyInside(Tokens $tokens, int $classOpenIndex, int $classEndIndex, bool $fixThisLevel) : void + { + 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, int $classIndex) : void + { + $previousIndex = $tokens->getPrevNonWhitespace($classIndex); + if ($tokens[$previousIndex]->isGivenKind(\T_DOC_COMMENT)) { + $this->fixToken($tokens, $previousIndex); + } + } + private function fixToken(Tokens $tokens, int $tokenIndex) : void + { + $count = 0; + $content = Preg::replaceCallback('#(\\h*(?:@{*|{*\\h*@)\\h*inheritdoc\\h*)([^}]*)((?:}*)\\h*)#i', static function (array $matches) : string { + return ' ' . $matches[2]; + }, $tokens[$tokenIndex]->getContent(), -1, $count); + if ($count) { + $tokens[$tokenIndex] = new Token([\T_DOC_COMMENT, $content]); + } + } + private function isExtendingOrImplementing(Tokens $tokens, int $classIndex, int $classOpenIndex) : bool + { + for ($index = $classIndex; $index < $classOpenIndex; ++$index) { + if ($tokens[$index]->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { + return \true; + } + } + return \false; + } + private function isUsingTrait(Tokens $tokens, int $classIndex, int $classOpenIndex, int $classCloseIndex) : bool + { + if ($tokens[$classIndex]->isGivenKind(\T_INTERFACE)) { + // cannot use Trait inside an interface + return \false; + } + $useIndex = $tokens->getNextTokenOfKind($classOpenIndex, [[CT::T_USE_TRAIT]]); + return null !== $useIndex && $useIndex < $classCloseIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php new file mode 100644 index 00000000000..43af2c59c16 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderByValueFixer.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +/** + * @author Filippo Tessarotto + * @author Andreas Möller + */ +final class PhpdocOrderByValueFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Order phpdoc tags by value.', [new CodeSample(' ['author']])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpUnitFqcnAnnotationFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return -10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAllTokenKindsFound([\T_CLASS, \T_DOC_COMMENT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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) || !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.+\\s+)?\\$(?P[^\\s]+).*/', $type); + $replacement = '\\2'; + } elseif ('method' === $type) { + $replacePattern = '/(?s)\\*\\s*@method\\s+(?P.+\\s+)?(?P.+)\\(.*/'; + $replacement = '\\2'; + } else { + $replacePattern = \sprintf('/\\*\\s*@%s\\s+(?P.+)/', $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() : FixerConfigurationResolverInterface + { + $allowedValues = ['author', 'covers', 'coversNothing', 'dataProvider', 'depends', 'group', 'internal', 'method', 'mixin', '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(static function (Options $options, $value) : array { + $normalized = []; + foreach ($value as $annotation) { + // since we will be using "strtolower" on the input annotations when building the sorting + // map we must match the type in lower case as well + $normalized[$annotation] = \strtolower($annotation); + } + return $normalized; + })->setDefault(['covers'])->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php new file mode 100644 index 00000000000..7ad1f4a0262 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocOrderFixer.php @@ -0,0 +1,168 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class PhpdocOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @const string[] + * + * @TODO: 4.0 - change default to ['param', 'return', 'throws'] + */ + private const ORDER_DEFAULT = ['param', 'throws', 'return']; + public function getDefinition() : FixerDefinitionInterface + { + $code = <<<'EOF' + self::ORDER_DEFAULT]), new CodeSample($code, ['order' => ['param', 'return', 'throws']]), new CodeSample($code, ['order' => ['param', 'custom', 'throws', 'return']])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer, PhpdocSeparationFixer, PhpdocTrimFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocIndentFixer, PhpdocNoEmptyReturnFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return -2; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('order', 'Sequence in which annotations in PHPDoc should be ordered.'))->setAllowedTypes(['string[]'])->setAllowedValues([function ($order) { + if (\count($order) < 2) { + throw new InvalidOptionsException('The option "order" value is invalid. Minimum two tags are required.'); + } + return \true; + }])->setDefault(self::ORDER_DEFAULT)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + // assuming annotations are already grouped by tags + $content = $token->getContent(); + // sort annotations + $successors = $this->configuration['order']; + while (\count($successors) >= 3) { + $predecessor = \array_shift($successors); + $content = $this->moveAnnotationsBefore($predecessor, $successors, $content); + } + // we're parsing the content last time to make sure the internal + // state of the docblock is correct after the modifications + $predecessors = $this->configuration['order']; + $last = \array_pop($predecessors); + $content = $this->moveAnnotationsAfter($last, $predecessors, $content); + // persist the content at the end + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + /** + * Move all given annotations in before given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param string[] $before Tags of annotations that should moved annotations be placed before + */ + private function moveAnnotationsBefore(string $move, array $before, string $content) : string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + $others = $doc->getAnnotationsOfType($before); + if (0 === \count($others)) { + return $content; + } + // get the index of the final line of the final toBoMoved annotation + $end = \end($toBeMoved)->getEnd(); + $line = $doc->getLine($end); + // move stuff about if required + foreach ($others as $other) { + if ($other->getStart() < $end) { + // we're doing this to maintain the original line indices + $line->setContent($line->getContent() . $other->getContent()); + $other->remove(); + } + } + return $doc->getContent(); + } + /** + * Move all given annotations after given set of annotations. + * + * @param string $move Tag of annotations that should be moved + * @param string[] $after Tags of annotations that should moved annotations be placed after + */ + private function moveAnnotationsAfter(string $move, array $after, string $content) : string + { + $doc = new DocBlock($content); + $toBeMoved = $doc->getAnnotationsOfType($move); + // nothing to do if there are no annotations to be moved + if (0 === \count($toBeMoved)) { + return $content; + } + $others = $doc->getAnnotationsOfType($after); + // nothing to do if there are no other annotations + if (0 === \count($others)) { + return $content; + } + // get the index of the first line of the first toBeMoved annotation + $start = $toBeMoved[0]->getStart(); + $line = $doc->getLine($start); + // move stuff about if required + foreach (\array_reverse($others) as $other) { + if ($other->getEnd() > $start) { + // we're doing this to maintain the original line indices + $line->setContent($other->getContent() . $line->getContent()); + $other->remove(); + } + } + return $doc->getContent(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php new file mode 100644 index 00000000000..4c5b8a9bfa9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocParamOrderFixer.php @@ -0,0 +1,219 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jonathan Gruber + */ +final class PhpdocParamOrderFixer extends AbstractFixer +{ + private const PARAM_TAG = 'param'; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return parent::getPriority(); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Orders all `@param` annotations in DocBlocks according to method signature.', [new CodeSample(' $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + // Check for function / closure token + $nextFunctionToken = $tokens->getNextTokenOfKind($index, [[\T_FUNCTION], [\T_FN]]); + if (null === $nextFunctionToken) { + return; + } + // Find start index of param block (opening parenthesis) + $paramBlockStart = $tokens->getNextTokenOfKind($index, ['(']); + if (null === $paramBlockStart) { + return; + } + $doc = new DocBlock($tokens[$index]->getContent()); + $paramAnnotations = $doc->getAnnotationsOfType(self::PARAM_TAG); + if ([] === $paramAnnotations) { + continue; + } + $paramNames = $this->getFunctionParamNames($tokens, $paramBlockStart); + $doc = $this->rewriteDocBlock($doc, $paramNames, $paramAnnotations); + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + /** + * @return Token[] + */ + private function getFunctionParamNames(Tokens $tokens, int $paramBlockStart) : array + { + $paramBlockEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $paramBlockStart); + $paramNames = []; + for ($i = $tokens->getNextTokenOfKind($paramBlockStart, [[\T_VARIABLE]]); null !== $i && $i < $paramBlockEnd; $i = $tokens->getNextTokenOfKind($i, [[\T_VARIABLE]])) { + $paramNames[] = $tokens[$i]; + } + return $paramNames; + } + /** + * Overwrite the param annotations in order. + * + * @param Token[] $paramNames + * @param Annotation[] $paramAnnotations + */ + private function rewriteDocBlock(DocBlock $doc, array $paramNames, array $paramAnnotations) : DocBlock + { + $orderedAnnotations = $this->sortParamAnnotations($paramNames, $paramAnnotations); + $otherAnnotations = $this->getOtherAnnotationsBetweenParams($doc, $paramAnnotations); + // Append annotations found between param ones + if ([] !== $otherAnnotations) { + \array_push($orderedAnnotations, ...$otherAnnotations); + } + // Overwrite all annotations between first and last @param tag in order + $paramsStart = \reset($paramAnnotations)->getStart(); + $paramsEnd = \end($paramAnnotations)->getEnd(); + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + $annotation->remove(); + $doc->getLine($annotation->getStart())->setContent(\current($orderedAnnotations)); + \next($orderedAnnotations); + } + return $doc; + } + /** + * Sort the param annotations according to the function parameters. + * + * @param Token[] $funcParamNames + * @param Annotation[] $paramAnnotations + * + * @return string[] + */ + private function sortParamAnnotations(array $funcParamNames, array $paramAnnotations) : array + { + $validParams = []; + foreach ($funcParamNames as $paramName) { + $indices = $this->findParamAnnotationByIdentifier($paramAnnotations, $paramName->getContent()); + // Found an exactly matching @param annotation + if (\is_array($indices)) { + foreach ($indices as $index) { + $validParams[$index] = $paramAnnotations[$index]->getContent(); + } + } + } + // Detect superfluous annotations + /** @var Annotation[] $invalidParams */ + $invalidParams = \array_diff_key($paramAnnotations, $validParams); + $invalidParams = \array_values($invalidParams); + // Append invalid parameters to the (ordered) valid ones + $orderedParams = \array_values($validParams); + foreach ($invalidParams as $params) { + $orderedParams[] = $params->getContent(); + } + return $orderedParams; + } + /** + * Fetch all annotations except the param ones. + * + * @param Annotation[] $paramAnnotations + * + * @return string[] + */ + private function getOtherAnnotationsBetweenParams(DocBlock $doc, array $paramAnnotations) : array + { + if (0 === \count($paramAnnotations)) { + return []; + } + $paramsStart = \reset($paramAnnotations)->getStart(); + $paramsEnd = \end($paramAnnotations)->getEnd(); + $otherAnnotations = []; + foreach ($doc->getAnnotations() as $annotation) { + if ($annotation->getStart() < $paramsStart || $annotation->getEnd() > $paramsEnd) { + continue; + } + if (self::PARAM_TAG !== $annotation->getTag()->getName()) { + $otherAnnotations[] = $annotation->getContent(); + } + } + return $otherAnnotations; + } + /** + * Return the indices of the lines of a specific parameter annotation. + * + * @param Annotation[] $paramAnnotations + * + * @return null|array + */ + private function findParamAnnotationByIdentifier(array $paramAnnotations, string $identifier) : ?array + { + $blockLevel = 0; + $blockMatch = \false; + $blockIndices = []; + $paramRegex = '/\\*\\s*@param\\s*(?:|' . TypeExpression::REGEX_TYPES . '\\s*)&?(?=\\$\\b)' . \preg_quote($identifier) . '\\b/'; + foreach ($paramAnnotations as $i => $param) { + $blockStart = Preg::match('/\\s*{\\s*/', $param->getContent()); + $blockEndMatches = Preg::matchAll('/}[\\*\\s\\n]*/', $param->getContent()); + if (0 === $blockLevel && Preg::match($paramRegex, $param->getContent())) { + if ($blockStart) { + $blockMatch = \true; + // Start of a nested block + } else { + return [$i]; + // Top level match + } + } + if ($blockStart) { + ++$blockLevel; + } + if (0 !== $blockEndMatches) { + $blockLevel -= $blockEndMatches; + } + if ($blockMatch) { + $blockIndices[] = $i; + if (0 === $blockLevel) { + return $blockIndices; + } + } + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php new file mode 100644 index 00000000000..c6bd16dd38b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocReturnSelfReferenceFixer.php @@ -0,0 +1,159 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +final class PhpdocReturnSelfReferenceFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string[] + */ + private static $toTypes = ['$this', 'static', 'self']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The type of `@return` annotations of methods returning a reference to itself must the configured one.', [new CodeSample(' ['this' => 'self']])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return \count($tokens) > 10 && $tokens->isAllTokenKindsFound([\T_DOC_COMMENT, \T_FUNCTION]) && $tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()); + } + /** + * {@inheritdoc} + * + * Must run before NoSuperfluousPhpdocTagsFixer, PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 10; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + foreach ($tokensAnalyzer->getClassyElements() as $index => $element) { + if ('method' === $element['type']) { + $this->fixMethod($tokens, $index); + } + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $default = ['this' => '$this', '@this' => '$this', '$self' => 'self', '@self' => 'self', '$static' => 'static', '@static' => 'static']; + return new FixerConfigurationResolver([(new FixerOptionBuilder('replacements', 'Mapping between replaced return types with new ones.'))->setAllowedTypes(['array'])->setNormalizer(static function (Options $options, array $value) use($default) : array { + $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.', \gettype($from) . '#' . $from, Utils::naturalLanguageJoin(\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), Utils::naturalLanguageJoin(self::$toTypes))); + } + $normalizedValue[$from] = $to; + } + return $normalizedValue; + })->setDefault($default)->getOption()]); + } + private function fixMethod(Tokens $tokens, int $index) : void + { + static $methodModifiers = [\T_STATIC, \T_FINAL, \T_ABSTRACT, \T_PRIVATE, \T_PROTECTED, \T_PUBLIC]; + // find PHPDoc of method (if any) + while (\true) { + $tokenIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$tokenIndex]->isGivenKind($methodModifiers)) { + break; + } + $index = $tokenIndex; + } + $docIndex = $tokens->getPrevNonWhitespace($index); + if (!$tokens[$docIndex]->isGivenKind(\T_DOC_COMMENT)) { + return; + } + // find @return + $docBlock = new DocBlock($tokens[$docIndex]->getContent()); + $returnsBlock = $docBlock->getAnnotationsOfType('return'); + if (0 === \count($returnsBlock)) { + return; + // no return annotation found + } + $returnsBlock = $returnsBlock[0]; + $types = $returnsBlock->getTypes(); + if (0 === \count($types)) { + return; + // no return type(s) found + } + $newTypes = []; + foreach ($types as $type) { + $newTypes[] = $this->configuration['replacements'][\strtolower($type)] ?? $type; + } + if ($types === $newTypes) { + return; + } + $returnsBlock->setTypes($newTypes); + $tokens[$docIndex] = new Token([\T_DOC_COMMENT, $docBlock->getContent()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php new file mode 100644 index 00000000000..ba3c8ffcf89 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocScalarFixer.php @@ -0,0 +1,92 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +/** + * @author Graham Campbell + */ +final class PhpdocScalarFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** + * The types to fix. + * + * @var array + */ + private static $types = ['boolean' => 'bool', 'callback' => 'callable', 'double' => 'float', 'integer' => 'int', 'real' => 'float', 'str' => 'string']; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Scalar types should always be written in the same form. `int` not `integer`, `bool` not `boolean`, `float` not `real` or `double`.', [new CodeSample(' ['boolean']])]); + } + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocTypesFixer. + */ + public function getPriority() : int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run after + * the phpdoc_types_fixer because it can convert types to things that + * we can fix. + */ + return 15; + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $types = \array_keys(self::$types); + return new FixerConfigurationResolver([(new FixerOptionBuilder('types', 'A list of types to fix.'))->setAllowedValues([new AllowedValueSubset($types)])->setDefault($types)->getOption()]); + } + protected function normalize(string $type) : string + { + if (\in_array($type, $this->configuration['types'], \true)) { + return self::$types[$type]; + } + return $type; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php new file mode 100644 index 00000000000..2a4d32b90a6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSeparationFixer.php @@ -0,0 +1,236 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Graham Campbell + * @author Jakub Kwaśniewski + */ +final class PhpdocSeparationFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string[][] + */ + private $groups; + public function getDefinition() : FixerDefinitionInterface + { + $code = <<<'EOF' + [['deprecated', 'link', 'see', 'since'], ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write'], ['param', 'return']]]), new CodeSample($code, ['groups' => [['author', 'throws', 'custom'], ['return', 'param']]]), new CodeSample(<<<'EOF' + [['ORM\\*'], ['Assert\\*']]]), new CodeSample($code, ['skip_unlisted_annotations' => \true])]); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->groups = $this->configuration['groups']; + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, GeneralPhpdocAnnotationRemoveFixer, PhpUnitInternalClassFixer, PhpUnitSizeClassFixer, PhpUnitTestClassRequiresCoversFixer, PhpdocIndentFixer, PhpdocNoAccessFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocOrderFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return -3; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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()]); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $allowTagToBelongToOnlyOneGroup = function ($groups) { + $tags = []; + foreach ($groups as $groupIndex => $group) { + foreach ($group as $member) { + if (isset($tags[$member])) { + if ($groupIndex === $tags[$member]) { + throw new InvalidOptionsException('The option "groups" value is invalid. ' . 'The "' . $member . '" tag is specified more than once.'); + } + throw new InvalidOptionsException('The option "groups" value is invalid. ' . 'The "' . $member . '" tag belongs to more than one group.'); + } + $tags[$member] = $groupIndex; + } + } + return \true; + }; + return new FixerConfigurationResolver([(new FixerOptionBuilder('groups', 'Sets of annotation types to be grouped together. Use `*` to match any tag character.'))->setAllowedTypes(['string[][]'])->setDefault([['deprecated', 'link', 'see', 'since'], ['author', 'copyright', 'license'], ['category', 'package', 'subpackage'], ['property', 'property-read', 'property-write']])->setAllowedValues([$allowTagToBelongToOnlyOneGroup])->getOption(), (new FixerOptionBuilder('skip_unlisted_annotations', 'Whether to skip annotations that are not listed in any group.'))->setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } + /** + * Make sure the description is separated from the annotations. + */ + private function fixDescription(DocBlock $doc) : void + { + 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; + } + } + } + } + /** + * Make sure the annotations are correctly separated. + */ + private function fixAnnotations(DocBlock $doc) : void + { + foreach ($doc->getAnnotations() as $index => $annotation) { + $next = $doc->getAnnotation($index + 1); + if (null === $next) { + break; + } + $shouldBeTogether = $this->shouldBeTogether($annotation, $next, $this->groups); + if (\true === $shouldBeTogether) { + $this->ensureAreTogether($doc, $annotation, $next); + } elseif (\false === $shouldBeTogether || !$this->configuration['skip_unlisted_annotations']) { + $this->ensureAreSeparate($doc, $annotation, $next); + } + } + } + /** + * Force the given annotations to immediately follow each other. + */ + private function ensureAreTogether(DocBlock $doc, Annotation $first, Annotation $second) : void + { + $pos = $first->getEnd(); + $final = $second->getStart(); + for ($pos = $pos + 1; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + /** + * Force the given annotations to have one empty line between each other. + */ + private function ensureAreSeparate(DocBlock $doc, Annotation $first, Annotation $second) : void + { + $pos = $first->getEnd(); + $final = $second->getStart() - 1; + // check if we need to add a line, or need to remove one or more lines + if ($pos === $final) { + $doc->getLine($pos)->addBlank(); + return; + } + for ($pos = $pos + 1; $pos < $final; ++$pos) { + $doc->getLine($pos)->remove(); + } + } + /** + * @param list> $groups + */ + private function shouldBeTogether(Annotation $first, Annotation $second, array $groups) : ?bool + { + $firstName = $this->tagName($first); + $secondName = $this->tagName($second); + // A tag could not be read. + if (null === $firstName || null === $secondName) { + return null; + } + if ($firstName === $secondName) { + return \true; + } + foreach ($groups as $group) { + $firstTagIsInGroup = $this->isInGroup($firstName, $group); + $secondTagIsInGroup = $this->isInGroup($secondName, $group); + if ($firstTagIsInGroup) { + return $secondTagIsInGroup; + } + if ($secondTagIsInGroup) { + return \false; + } + } + return null; + } + private function tagName(Annotation $annotation) : ?string + { + Preg::match('/@([a-zA-Z0-9_\\\\-]+(?=\\s|$|\\())/', $annotation->getContent(), $matches); + return $matches[1] ?? null; + } + /** + * @param list $group + */ + private function isInGroup(string $tag, array $group) : bool + { + foreach ($group as $tagInGroup) { + $tagInGroup = \str_replace('*', '\\*', $tagInGroup); + $tagInGroup = \preg_quote($tagInGroup, '/'); + $tagInGroup = \str_replace('\\\\\\*', '.*?', $tagInGroup); + if (Preg::match("/^{$tagInGroup}\$/", $tag)) { + return \true; + } + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php new file mode 100644 index 00000000000..fa664e6eab8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSingleLineVarSpacingFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for part of rule defined in PSR5 ¶7.22. + */ +final class PhpdocSingleLineVarSpacingFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Single line `@var` PHPDoc should have proper spacing.', [new CodeSample("isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + /** @var Token $token */ + 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(string $content) : string + { + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php new file mode 100644 index 00000000000..961b962581c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocSummaryFixer.php @@ -0,0 +1,80 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class PhpdocSummaryFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPDoc summary should end in either a full stop, exclamation mark, or question mark.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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()]); + } + } + } + } + /** + * Is the last line of the short description correctly formatted? + */ + private function isCorrectlyFormatted(string $content) : bool + { + if (\false !== \stripos($content, '{@inheritdoc}')) { + return \true; + } + return $content !== \rtrim($content, '.。!?¡¿!?'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php new file mode 100644 index 00000000000..73f12be873b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagCasingFixer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractProxyFixer; +use PhpCsFixer\ConfigurationException\InvalidConfigurationException; +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +final class PhpdocTagCasingFixer extends AbstractProxyFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Fixes casing of PHPDoc tags.', [new CodeSample(" ['foo']])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return parent::getPriority(); + } + public function configure(array $configuration) : void + { + parent::configure($configuration); + $replacements = []; + foreach ($this->configuration['tags'] as $tag) { + $replacements[$tag] = $tag; + } + /** @var GeneralPhpdocTagRenameFixer $generalPhpdocTagRenameFixer */ + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('tags', 'List of tags to fix with their expected casing.'))->setAllowedTypes(['array'])->setDefault(['inheritDoc'])->getOption()]); + } + protected function createProxyFixers() : array + { + return [new \PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocTagRenameFixer()]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php new file mode 100644 index 00000000000..804767e2133 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTagTypeFixer.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Options; +final class PhpdocTagTypeFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + private const TAG_REGEX = '/^(?: + (? + (?:@(?.+?)(?:\\s.+)?) + ) + | + {(? + (?:@(?.+?)(?:\\s.+)?) + )} + )$/x'; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Forces PHPDoc tags to be either regular annotations or inline.', [new CodeSample(" ['inheritdoc' => 'inline']])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 0; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + if (0 === \count($this->configuration['tags'])) { + return; + } + $regularExpression = \sprintf('/({?@(?:%s).*?(?:(?=\\s\\*\\/)|(?=\\n)}?))/i', \implode('|', \array_map(static function (string $tag) : string { + return \preg_quote($tag, '/'); + }, \array_keys($this->configuration['tags'])))); + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $parts = Preg::split($regularExpression, $token->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE); + for ($i = 1, $max = \count($parts) - 1; $i < $max; $i += 2) { + if (!Preg::match(self::TAG_REGEX, $parts[$i], $matches)) { + continue; + } + if ('' !== $matches['tag']) { + $tag = $matches['tag']; + $tagName = $matches['tag_name']; + } else { + $tag = $matches['inlined_tag']; + $tagName = $matches['inlined_tag_name']; + } + $tagName = \strtolower($tagName); + if (!isset($this->configuration['tags'][$tagName])) { + continue; + } + if ('inline' === $this->configuration['tags'][$tagName]) { + $parts[$i] = '{' . $tag . '}'; + continue; + } + if (!$this->tagIsSurroundedByText($parts, $i)) { + $parts[$i] = $tag; + } + } + $tokens[$index] = new Token([\T_DOC_COMMENT, \implode('', $parts)]); + } + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('tags', 'The list of tags to fix.'))->setAllowedTypes(['array'])->setAllowedValues([static function (array $value) : bool { + 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(static function (Options $options, $value) : array { + $normalized = []; + foreach ($value as $tag => $type) { + $normalized[\strtolower($tag)] = $type; + } + return $normalized; + })->getOption()]); + } + /** + * @param list $parts + */ + private function tagIsSurroundedByText(array $parts, int $index) : bool + { + 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(string $comment) : string + { + $comment = Preg::replace('/^\\/\\*\\*|\\*\\/$/', '', $comment); + return Preg::replace('/(\\R)(\\h*\\*)?\\h*/', '$1', $comment); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php new file mode 100644 index 00000000000..f2718afd5b2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocToCommentFixer.php @@ -0,0 +1,113 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\CommentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Ceeram + * @author Dariusz Rumiński + */ +final class PhpdocToCommentFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + /** + * @var string[] + */ + private $ignoredTags = []; + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocAnnotationWithoutDotFixer, PhpdocIndentFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer, SingleLineCommentSpacingFixer, SingleLineCommentStyleFixer. + * Must run after CommentToPhpdocFixer. + */ + public function getPriority() : int + { + /* + * Should be run before all other docblock fixers so that these fixers + * don't touch doc comments which are meant to be converted to regular + * comments. + */ + return 25; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Docblocks should only be used on structural elements.', [new CodeSample(' $sqlite) { + $sqlite->open($path); +} +'), new CodeSample(' $sqlite) { + $sqlite->open($path); +} + +/** @todo This should be a PHPDoc as the tag is on "ignored_tags" list */ +foreach($connections as $key => $sqlite) { + $sqlite->open($path); +} +', ['ignored_tags' => ['todo']])]); + } + public function configure(array $configuration = null) : void + { + parent::configure($configuration); + $this->ignoredTags = \array_map(static function (string $tag) : string { + return \strtolower($tag); + }, $this->configuration['ignored_tags']); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('ignored_tags', 'List of ignored tags (matched case insensitively).'))->setAllowedTypes(['array'])->setDefault([])->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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; + } + if (0 < Preg::matchAll('~\\@([a-zA-Z0-9_\\\\-]+)\\b~', $token->getContent(), $matches)) { + foreach ($matches[1] as $match) { + if (\in_array(\strtolower($match), $this->ignoredTags, \true)) { + continue 2; + } + } + } + $tokens[$index] = new Token([\T_COMMENT, '/*' . \ltrim($token->getContent(), '/*')]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php new file mode 100644 index 00000000000..760e1648b40 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimConsecutiveBlankLineSeparationFixer.php @@ -0,0 +1,155 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Nobu Funaki + * @author Dariusz Rumiński + */ +final class PhpdocTrimConsecutiveBlankLineSeparationFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes extra blank lines after summary and after description in PHPDoc.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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, int $summaryEnd) : void + { + $nonBlankLineAfterSummary = $this->findNonBlankLine($doc, $summaryEnd); + $this->removeExtraBlankLinesBetween($doc, $summaryEnd, $nonBlankLineAfterSummary); + } + private function fixDescription(DocBlock $doc, int $summaryEnd) : void + { + $annotationStart = $this->findFirstAnnotationOrEnd($doc); + // assuming the end of the Description appears before the first Annotation + $descriptionEnd = $this->reverseFindLastUsefulContent($doc, $annotationStart); + if (null === $descriptionEnd || $summaryEnd === $descriptionEnd) { + return; + // no Description + } + if ($annotationStart === \count($doc->getLines()) - 1) { + return; + // no content after Description + } + $this->removeExtraBlankLinesBetween($doc, $descriptionEnd, $annotationStart); + } + private function fixAllTheRest(DocBlock $doc) : void + { + $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, int $from, int $to) : void + { + 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) : void + { + if (!$current->isTheEnd() && !$current->containsUsefulContent() && !$next->isTheEnd() && !$next->containsUsefulContent()) { + $current->remove(); + } + } + private function findNonBlankLine(DocBlock $doc, int $after) : ?int + { + 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) : int + { + $index = null; + foreach ($doc->getLines() as $index => $line) { + if ($line->containsATag()) { + return $index; + } + } + return $index; + // no Annotation, return the last line + } + private function reverseFindLastUsefulContent(DocBlock $doc, int $from) : ?int + { + for ($index = $from - 1; $index >= 0; --$index) { + if ($doc->getLine($index)->containsUsefulContent()) { + return $index; + } + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php new file mode 100644 index 00000000000..5203a5ca1bd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTrimFixer.php @@ -0,0 +1,95 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class PhpdocTrimFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('PHPDoc should start and end with content, excluding the very first and last line of the docblocks.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $content = $token->getContent(); + $content = $this->fixStart($content); + // we need re-parse the docblock after fixing the start before + // fixing the end in order for the lines to be correctly indexed + $content = $this->fixEnd($content); + $tokens[$index] = new Token([\T_DOC_COMMENT, $content]); + } + } + /** + * Make sure the first useful line starts immediately after the first line. + */ + private function fixStart(string $content) : string + { + 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); + } + /** + * Make sure the last useful line is immediately before the final line. + */ + private function fixEnd(string $content) : string + { + return Preg::replace('~ + (\\R\\h*(?:\\*\\h*)?\\S.*?) # last line with useful content + (?: + (? + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractPhpdocTypesFixer; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +/** + * @author Graham Campbell + * @author Dariusz Rumiński + */ +final class PhpdocTypesFixer extends AbstractPhpdocTypesFixer implements ConfigurableFixerInterface +{ + /** + * Available types, grouped. + * + * @var array + */ + private const POSSIBLE_TYPES = ['simple' => ['array', 'bool', 'callable', 'float', 'int', 'iterable', 'null', 'object', 'string'], 'alias' => ['boolean', 'double', 'integer'], 'meta' => ['$this', 'false', 'mixed', 'parent', 'resource', 'scalar', 'self', 'static', 'true', 'void']]; + /** @var array */ + private $typesSetToFix; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $typesToFix = \array_merge(...\array_map(static function (string $group) : array { + return self::POSSIBLE_TYPES[$group]; + }, $this->configuration['groups'])); + $this->typesSetToFix = \array_combine($typesToFix, \array_fill(0, \count($typesToFix), \true)); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('The correct case must be used for standard PHP types in PHPDoc.', [new CodeSample(' ['simple', 'alias']])]); + } + /** + * {@inheritdoc} + * + * Must run before GeneralPhpdocAnnotationRemoveFixer, GeneralPhpdocTagRenameFixer, NoBlankLinesAfterPhpdocFixer, NoEmptyPhpdocFixer, NoSuperfluousPhpdocTagsFixer, PhpdocAddMissingParamAnnotationFixer, PhpdocAlignFixer, PhpdocInlineTagNormalizerFixer, PhpdocLineSpanFixer, PhpdocNoAccessFixer, PhpdocNoAliasTagFixer, PhpdocNoEmptyReturnFixer, PhpdocNoPackageFixer, PhpdocNoUselessInheritdocFixer, PhpdocOrderByValueFixer, PhpdocOrderFixer, PhpdocParamOrderFixer, PhpdocReturnSelfReferenceFixer, PhpdocScalarFixer, PhpdocSeparationFixer, PhpdocSingleLineVarSpacingFixer, PhpdocSummaryFixer, PhpdocTagCasingFixer, PhpdocTagTypeFixer, PhpdocToParamTypeFixer, PhpdocToPropertyTypeFixer, PhpdocToReturnTypeFixer, PhpdocTrimConsecutiveBlankLineSeparationFixer, PhpdocTrimFixer, PhpdocTypesOrderFixer, PhpdocVarAnnotationCorrectOrderFixer, PhpdocVarWithoutNameFixer. + * Must run after PhpdocIndentFixer. + */ + public function getPriority() : int + { + /* + * Should be run before all other docblock fixers apart from the + * phpdoc_to_comment and phpdoc_indent fixer to make sure all fixers + * apply correct indentation to new code they add. This should run + * before alignment of params is done since this fixer might change + * the type and thereby un-aligning the params. We also must run before + * the phpdoc_scalar_fixer so that it can make changes after us. + */ + return 16; + } + protected function normalize(string $type) : string + { + return Preg::replaceCallback('/(\\b|(?=\\$|\\\\))(\\$|\\\\)?' . TypeExpression::REGEX_IDENTIFIER . '(?!\\\\|\\h*:)/', function (array $matches) : string { + $valueLower = \strtolower($matches[0]); + if (isset($this->typesSetToFix[$valueLower])) { + return $valueLower; + } + return $matches[0]; + }, $type); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + $possibleGroups = \array_keys(self::POSSIBLE_TYPES); + return new FixerConfigurationResolver([(new FixerOptionBuilder('groups', 'Type groups to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($possibleGroups)])->setDefault($possibleGroups)->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php new file mode 100644 index 00000000000..6b3581a11b0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocTypesOrderFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\Annotation; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class PhpdocTypesOrderFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Sorts PHPDoc types.', [new CodeSample(' 'always_last']), new CodeSample(' 'alpha']), new CodeSample(' 'alpha', 'null_adjustment' => 'always_last']), new CodeSample(' 'alpha', 'null_adjustment' => 'none'])]); + } + /** + * {@inheritdoc} + * + * Must run before PhpdocAlignFixer. + * Must run after AlignMultilineCommentFixer, CommentToPhpdocFixer, PhpdocIndentFixer, PhpdocScalarFixer, PhpdocToCommentFixer, PhpdocTypesFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_DOC_COMMENT); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $doc = new DocBlock($token->getContent()); + $annotations = $doc->getAnnotationsOfType(Annotation::getTagsWithTypes()); + if (0 === \count($annotations)) { + continue; + } + foreach ($annotations as $annotation) { + // fix main types + if (null !== $annotation->getTypeExpression()) { + $annotation->setTypes($this->sortTypes($annotation->getTypeExpression())); + } + // fix @method parameters types + $line = $doc->getLine($annotation->getStart()); + $line->setContent(Preg::replaceCallback('/@method\\s+' . TypeExpression::REGEX_TYPES . '\\s+\\K(?&callable)/', function (array $matches) { + $typeExpression = new TypeExpression($matches[0], null, []); + return \implode('|', $this->sortTypes($typeExpression)); + }, $line->getContent())); + } + $tokens[$index] = new Token([\T_DOC_COMMENT, $doc->getContent()]); + } + } + /** + * @return string[] + */ + private function sortTypes(TypeExpression $typeExpression) : array + { + $normalizeType = static function (string $type) : string { + return Preg::replace('/^\\??\\\\?/', '', $type); + }; + $typeExpression->sortTypes(function (TypeExpression $a, TypeExpression $b) use($normalizeType) : int { + $a = $normalizeType($a->toString()); + $b = $normalizeType($b->toString()); + $lowerCaseA = \strtolower($a); + $lowerCaseB = \strtolower($b); + if ('none' !== $this->configuration['null_adjustment']) { + if ('null' === $lowerCaseA && 'null' !== $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? 1 : -1; + } + if ('null' !== $lowerCaseA && 'null' === $lowerCaseB) { + return 'always_last' === $this->configuration['null_adjustment'] ? -1 : 1; + } + } + if ('alpha' === $this->configuration['sort_algorithm']) { + return \strcasecmp($a, $b); + } + return 0; + }); + return $typeExpression->getTypes(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php new file mode 100644 index 00000000000..1d8a3abbb65 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarAnnotationCorrectOrderFixer.php @@ -0,0 +1,64 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + */ +final class PhpdocVarAnnotationCorrectOrderFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('`@var` and `@type` annotations must have type and name in the correct order.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php new file mode 100644 index 00000000000..51cc552674b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Phpdoc/PhpdocVarWithoutNameFixer.php @@ -0,0 +1,125 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Phpdoc; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\DocBlock\DocBlock; +use PhpCsFixer\DocBlock\Line; +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + * @author Dave van der Brugge + */ +final class PhpdocVarWithoutNameFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('`@var` and `@type` annotations of classy properties should not contain the name.', [new CodeSample('isTokenKindFound(\T_DOC_COMMENT) && $tokens->isAnyTokenKindsFound([\T_CLASS, \T_TRAIT]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + $nextIndex = $tokens->getNextMeaningfulToken($index); + if (null === $nextIndex) { + continue; + } + // For people writing "static public $foo" instead of "public static $foo" + if ($tokens[$nextIndex]->isGivenKind(\T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($nextIndex); + } + // We want only doc blocks that are for properties and thus have specified access modifiers next + $propertyModifierKinds = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_VAR]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $propertyModifierKinds[] = \T_READONLY; + } + if (!$tokens[$nextIndex]->isGivenKind($propertyModifierKinds)) { + 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) : void + { + $content = $line->getContent(); + Preg::matchAll('/ \\$' . TypeExpression::REGEX_IDENTIFIER . '(?setContent(\str_replace($matches[0][0], '', $content)); + } + } + /** + * @return Line[] + */ + private function getFirstLevelLines(DocBlock $docBlock) : array + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php new file mode 100644 index 00000000000..0d0d634b2bd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/NoUselessReturnFixer.php @@ -0,0 +1,84 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +final class NoUselessReturnFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAllTokenKindsFound([\T_FUNCTION, \T_RETURN]); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be an empty `return` statement at the end of a function.', [new CodeSample(' $token) { + if (!$token->isGivenKind(\T_FUNCTION)) { + continue; + } + $index = $tokens->getNextTokenOfKind($index, [';', '{']); + if ($tokens[$index]->equals('{')) { + $this->fixFunction($tokens, $index, $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)); + } + } + } + /** + * @param int $start Token index of the opening brace token of the function + * @param int $end Token index of the closing brace token of the function + */ + private function fixFunction(Tokens $tokens, int $start, int $end) : void + { + 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); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php new file mode 100644 index 00000000000..2200086a52b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/ReturnAssignmentFixer.php @@ -0,0 +1,411 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +final class ReturnAssignmentFixer extends AbstractFixer +{ + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Local, dynamic and directly referenced variables should not be assigned and directly returned by a function or method.', [new CodeSample("isAllTokenKindsFound([\T_FUNCTION, \T_RETURN, \T_VARIABLE]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokenCount = \count($tokens); + $this->tokensAnalyzer = new TokensAnalyzer($tokens); + for ($index = 1; $index < $tokenCount; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + $next = $tokens->getNextMeaningfulToken($index); + if ($tokens[$next]->isGivenKind(CT::T_RETURN_REF)) { + continue; + } + $functionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$functionOpenIndex]->equals(';')) { + // abstract function + $index = $functionOpenIndex - 1; + continue; + } + $functionCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $functionOpenIndex); + $totalTokensAdded = 0; + do { + $tokensAdded = $this->fixFunction($tokens, $index, $functionOpenIndex, $functionCloseIndex); + $functionCloseIndex += $tokensAdded; + $totalTokensAdded += $tokensAdded; + } while ($tokensAdded > 0); + $index = $functionCloseIndex; + $tokenCount += $totalTokensAdded; + } + } + /** + * @param int $functionIndex token index of T_FUNCTION + * @param int $functionOpenIndex token index of the opening brace token of the function + * @param int $functionCloseIndex token index of the closing brace token of the function + * + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function fixFunction(Tokens $tokens, int $functionIndex, int $functionOpenIndex, int $functionCloseIndex) : int + { + static $riskyKinds = [ + CT::T_DYNAMIC_VAR_BRACE_OPEN, + // "$h = ${$g};" case + \T_EVAL, + // "$c = eval('return $this;');" case + \T_GLOBAL, + \T_INCLUDE, + // loading additional symbols we cannot analyze here + \T_INCLUDE_ONCE, + // " + \T_REQUIRE, + // " + \T_REQUIRE_ONCE, + ]; + $inserted = 0; + $candidates = []; + $isRisky = \false; + if ($tokens[$tokens->getNextMeaningfulToken($functionIndex)]->isGivenKind(CT::T_RETURN_REF)) { + $isRisky = \true; + } + // go through the function declaration and check if references are passed + // - check if it will be risky to fix return statements of this function + for ($index = $functionIndex + 1; $index < $functionOpenIndex; ++$index) { + if ($tokens[$index]->equals('&')) { + $isRisky = \true; + break; + } + } + // go through all the tokens of the body of the function: + // - check if it will be risky to fix return statements of this function + // - check nested functions; fix when found and update the upper limit + number of inserted token + // - check for return statements that might be fixed (based on if fixing will be risky, which is only know after analyzing the whole function) + for ($index = $functionOpenIndex + 1; $index < $functionCloseIndex; ++$index) { + if ($tokens[$index]->isGivenKind(\T_FUNCTION)) { + $nestedFunctionOpenIndex = $tokens->getNextTokenOfKind($index, ['{', ';']); + if ($tokens[$nestedFunctionOpenIndex]->equals(';')) { + // abstract function + $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; + // don't bother to look into anything else than nested functions as the current is risky already + } + if ($tokens[$index]->equals('&')) { + $isRisky = \true; + continue; + } + if ($tokens[$index]->isGivenKind(\T_RETURN)) { + $candidates[] = $index; + continue; + } + // test if there is anything in the function body that might + // change global state or indirect changes (like through references, eval, etc.) + if ($tokens[$index]->isGivenKind($riskyKinds)) { + $isRisky = \true; + continue; + } + if ($tokens[$index]->isGivenKind(\T_STATIC)) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$nextIndex]->isGivenKind(\T_FUNCTION)) { + $isRisky = \true; + // "static $a" case + continue; + } + } + if ($tokens[$index]->equals('$')) { + $nextIndex = $tokens->getNextMeaningfulToken($index); + if ($tokens[$nextIndex]->isGivenKind(\T_VARIABLE)) { + $isRisky = \true; + // "$$a" case + continue; + } + } + if ($this->tokensAnalyzer->isSuperGlobal($index)) { + $isRisky = \true; + continue; + } + } + if ($isRisky) { + return $inserted; + } + // fix the candidates in reverse order when applicable + for ($i = \count($candidates) - 1; $i >= 0; --$i) { + $index = $candidates[$i]; + // Check if returning only a variable (i.e. not the result of an expression, function call etc.) + $returnVarIndex = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$returnVarIndex]->isGivenKind(\T_VARIABLE)) { + continue; + // example: "return 1;" + } + $endReturnVarIndex = $tokens->getNextMeaningfulToken($returnVarIndex); + if (!$tokens[$endReturnVarIndex]->equalsAny([';', [\T_CLOSE_TAG]])) { + continue; + // example: "return $a + 1;" + } + // Check that the variable is assigned just before it is returned + $assignVarEndIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$assignVarEndIndex]->equals(';')) { + continue; + // example: "? return $a;" + } + // Note: here we are @ "; return $a;" (or "; return $a ? >") + while (\true) { + $prevMeaningFul = $tokens->getPrevMeaningfulToken($assignVarEndIndex); + if (!$tokens[$prevMeaningFul]->equals(')')) { + break; + } + $assignVarEndIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningFul); + } + $assignVarOperatorIndex = $tokens->getPrevTokenOfKind($assignVarEndIndex, ['=', ';', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO]]); + if ($tokens[$assignVarOperatorIndex]->equals('}')) { + $startIndex = $this->isCloseBracePartOfDefinition($tokens, $assignVarOperatorIndex); + // test for `anonymous class`, `lambda` and `match` + if (null === $startIndex) { + continue; + } + $assignVarOperatorIndex = $tokens->getPrevMeaningfulToken($startIndex); + } + if (!$tokens[$assignVarOperatorIndex]->equals('=')) { + continue; + } + // Note: here we are @ "= [^;{] ; return $a;" + $assignVarIndex = $tokens->getPrevMeaningfulToken($assignVarOperatorIndex); + if (!$tokens[$assignVarIndex]->equals($tokens[$returnVarIndex], \false)) { + continue; + } + // Note: here we are @ "$a = [^;{] ; return $a;" + $beforeAssignVarIndex = $tokens->getPrevMeaningfulToken($assignVarIndex); + if (!$tokens[$beforeAssignVarIndex]->equalsAny([';', '{', '}'])) { + continue; + } + // Check if there is a `catch` or `finally` block between the assignment and the return + if ($this->isUsedInCatchOrFinally($tokens, $returnVarIndex, $functionOpenIndex, $functionCloseIndex)) { + continue; + } + // Note: here we are @ "[;{}] $a = [^;{] ; return $a;" + $inserted += $this->simplifyReturnStatement($tokens, $assignVarIndex, $assignVarOperatorIndex, $index, $endReturnVarIndex); + } + return $inserted; + } + /** + * @return int >= 0 number of tokens inserted into the Tokens collection + */ + private function simplifyReturnStatement(Tokens $tokens, int $assignVarIndex, int $assignVarOperatorIndex, int $returnIndex, int $returnVarEndIndex) : int + { + $inserted = 0; + $originalIndent = $tokens[$assignVarIndex - 1]->isWhitespace() ? $tokens[$assignVarIndex - 1]->getContent() : null; + // remove the return statement + if ($tokens[$returnVarEndIndex]->equals(';')) { + // do not remove PHP close tags + $tokens->clearTokenAndMergeSurroundingWhitespace($returnVarEndIndex); + } + for ($i = $returnIndex; $i <= $returnVarEndIndex - 1; ++$i) { + $this->clearIfSave($tokens, $i); + } + // remove no longer needed indentation of the old/remove return statement + 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]); + } + // remove the variable and the assignment + for ($i = $assignVarIndex; $i <= $assignVarOperatorIndex; ++$i) { + $this->clearIfSave($tokens, $i); + } + // insert new return statement + $tokens->insertAt($assignVarIndex, new Token([\T_RETURN, 'return'])); + ++$inserted; + // use the original indent of the var assignment for the new return statement + if (null !== $originalIndent && $tokens[$assignVarIndex - 1]->isWhitespace() && $originalIndent !== $tokens[$assignVarIndex - 1]->getContent()) { + $tokens[$assignVarIndex - 1] = new Token([\T_WHITESPACE, $originalIndent]); + } + // remove trailing space after the new return statement which might be added during the cleanup process + $nextIndex = $tokens->getNonEmptySibling($assignVarIndex, 1); + if (!$tokens[$nextIndex]->isWhitespace()) { + $tokens->insertAt($nextIndex, new Token([\T_WHITESPACE, ' '])); + ++$inserted; + } + return $inserted; + } + private function clearIfSave(Tokens $tokens, int $index) : void + { + if ($tokens[$index]->isComment()) { + return; + } + if ($tokens[$index]->isWhitespace() && $tokens[$tokens->getPrevNonWhitespace($index)]->isComment()) { + return; + } + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + } + /** + * @param int $index open brace index + * + * @return null|int index of the first token of a definition (lambda, anonymous class or match) or `null` if not an anonymous + */ + private function isCloseBracePartOfDefinition(Tokens $tokens, int $index) : ?int + { + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + $candidateIndex = $this->isOpenBraceOfLambda($tokens, $index); + if (null !== $candidateIndex) { + return $candidateIndex; + } + $candidateIndex = $this->isOpenBraceOfAnonymousClass($tokens, $index); + return $candidateIndex ?? $this->isOpenBraceOfMatch($tokens, $index); + } + /** + * @param int $index open brace index + * + * @return null|int index of T_NEW of anonymous class or `null` if not an anonymous + */ + private function isOpenBraceOfAnonymousClass(Tokens $tokens, int $index) : ?int + { + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while ($tokens[$index]->equalsAny([',', [\T_STRING], [\T_IMPLEMENTS], [\T_EXTENDS], [\T_NS_SEPARATOR]])); + if ($tokens[$index]->equals(')')) { + // skip constructor braces and content within + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->tokensAnalyzer->isAnonymousClass($index)) { + return null; + } + return $tokens->getPrevTokenOfKind($index, [[\T_NEW]]); + } + /** + * @param int $index open brace index + * + * @return null|int index of T_FUNCTION or T_STATIC of lambda or `null` if not a lambda + */ + private function isOpenBraceOfLambda(Tokens $tokens, int $index) : ?int + { + $index = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$index]->equals(')')) { + return null; + } + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$index]->isGivenKind(CT::T_USE_LAMBDA)) { + $index = $tokens->getPrevTokenOfKind($index, [')']); + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + } + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + $index = $tokens->getPrevMeaningfulToken($index); + } + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + return null; + } + $staticCandidate = $tokens->getPrevMeaningfulToken($index); + return $tokens[$staticCandidate]->isGivenKind(\T_STATIC) ? $staticCandidate : $index; + } + /** + * @param int $index open brace index + * + * @return null|int index of T_MATCH or `null` if not a `match` + */ + private function isOpenBraceOfMatch(Tokens $tokens, int $index) : ?int + { + if (!\defined('T_MATCH') || !$tokens->isTokenKindFound(\T_MATCH)) { + // @TODO: drop condition when PHP 8.0+ is required + return null; + } + $index = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$index]->equals(')')) { + return null; + } + $index = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $index = $tokens->getPrevMeaningfulToken($index); + return $tokens[$index]->isGivenKind(\T_MATCH) ? $index : null; + } + private function isUsedInCatchOrFinally(Tokens $tokens, int $returnVarIndex, int $functionOpenIndex, int $functionCloseIndex) : bool + { + // Find try + $tryIndex = $tokens->getPrevTokenOfKind($returnVarIndex, [[\T_TRY]]); + if (null === $tryIndex || $tryIndex <= $functionOpenIndex) { + return \false; + } + $tryOpenIndex = $tokens->getNextTokenOfKind($tryIndex, ['{']); + $tryCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $tryOpenIndex); + // Find catch or finally + $nextIndex = $tokens->getNextMeaningfulToken($tryCloseIndex); + if (null === $nextIndex) { + return \false; + } + // Find catches + while ($tokens[$nextIndex]->isGivenKind(\T_CATCH)) { + $catchOpenIndex = $tokens->getNextTokenOfKind($nextIndex, ['{']); + $catchCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $catchOpenIndex); + if ($catchCloseIndex >= $functionCloseIndex) { + return \false; + } + $varIndex = $tokens->getNextTokenOfKind($catchOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $catchCloseIndex) { + return \true; + } + $nextIndex = $tokens->getNextMeaningfulToken($catchCloseIndex); + if (null === $nextIndex) { + return \false; + } + } + if (!$tokens[$nextIndex]->isGivenKind(\T_FINALLY)) { + return \false; + } + $finallyIndex = $nextIndex; + if ($finallyIndex >= $functionCloseIndex) { + return \false; + } + $finallyOpenIndex = $tokens->getNextTokenOfKind($finallyIndex, ['{']); + $finallyCloseIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $finallyOpenIndex); + $varIndex = $tokens->getNextTokenOfKind($finallyOpenIndex, [$tokens[$returnVarIndex]]); + // Check if the variable is used in the finally block + if (null !== $varIndex && $varIndex < $finallyCloseIndex) { + return \true; + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php new file mode 100644 index 00000000000..54cb1d10af6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/ReturnNotation/SimplifiedNullReturnFixer.php @@ -0,0 +1,138 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\ReturnNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class SimplifiedNullReturnFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('A return statement wishing to return `void` should not return `null`.', [new CodeSample("isTokenKindFound(\T_RETURN); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_RETURN)) { + continue; + } + if ($this->needFixing($tokens, $index)) { + $this->clear($tokens, $index); + } + } + } + /** + * Clear the return statement located at a given index. + */ + private function clear(Tokens $tokens, int $index) : void + { + while (!$tokens[++$index]->equals(';')) { + if ($this->shouldClearToken($tokens, $index)) { + $tokens->clearAt($index); + } + } + } + /** + * Does the return statement located at a given index need fixing? + */ + private function needFixing(Tokens $tokens, int $index) : bool + { + 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); + } + /** + * Is the return within a function with a non-void or nullable return type? + * + * @param int $returnIndex Current return token index + */ + private function isStrictOrNullableReturnTypeFunction(Tokens $tokens, int $returnIndex) : bool + { + $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; + } + /** + * Should we clear the specific token? + * + * If the token is a comment, or is whitespace that is immediately before a + * comment, then we'll leave it alone. + */ + private function shouldClearToken(Tokens $tokens, int $index) : bool + { + $token = $tokens[$index]; + return !$token->isComment() && !($token->isWhitespace() && $tokens[$index + 1]->isComment()); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 00000000000..354ceac6efa --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/MultilineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,172 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + * @author Egidijus Girčys + */ +final class MultilineWhitespaceBeforeSemicolonsFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @internal + */ + public const STRATEGY_NO_MULTI_LINE = 'no_multi_line'; + /** + * @internal + */ + public const STRATEGY_NEW_LINE_FOR_CHAINED_CALLS = 'new_line_for_chained_calls'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Forbid multi-line whitespace before the closing semicolon or move the semicolon to the new line for chained calls.', [new CodeSample('method1() + ->method2() + ->method(3); +', ['strategy' => self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS])]); + } + /** + * {@inheritdoc} + * + * Must run before SpaceAfterSemicolonFixer. + * Must run after CombineConsecutiveIssetsFixer, GetClassToClassKeywordFixer, NoEmptyStatementFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(';'); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + for ($index = 0, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->equals(';')) { + continue; + } + $previousIndex = $index - 1; + $previous = $tokens[$previousIndex]; + $indent = $this->findWhitespaceBeforeFirstCall($index, $tokens); + if (self::STRATEGY_NEW_LINE_FOR_CHAINED_CALLS === $this->configuration['strategy'] && null !== $indent) { + if ($previous->isWhitespace() && $previous->getContent() === $lineEnding . $indent) { + continue; + } + // unset whitespace and semicolon + if ($previous->isWhitespace()) { + $tokens->clearAt($previousIndex); + } + $tokens->clearAt($index); + // find the line ending token index after the semicolon + $index = $this->getNewLineIndex($index, $tokens); + // appended new line to the last method call + $newline = new Token([\T_WHITESPACE, $lineEnding . $indent]); + // insert the new line with indented semicolon + $tokens->insertAt($index++, [$newline, new Token(';')]); + } else { + if (!$previous->isWhitespace() || \strpos($previous->getContent(), "\n") === \false) { + continue; + } + $content = $previous->getContent(); + if (\strncmp($content, $lineEnding, \strlen($lineEnding)) === 0 && $tokens[$index - 2]->isComment()) { + // if there is comment between closing bracket and semicolon + // unset whitespace and semicolon + $tokens->clearAt($previousIndex); + $tokens->clearAt($index); + // find the significant token index before the semicolon + $significantTokenIndex = $this->getPreviousSignificantTokenIndex($index, $tokens); + // insert the semicolon + $tokens->insertAt($significantTokenIndex + 1, [new Token(';')]); + } else { + // if there is whitespace between closing bracket and semicolon, just remove it + $tokens->clearAt($previousIndex); + } + } + } + } + /** + * Find the index for the next new line. Return the given index when there's no new line. + */ + private function getNewLineIndex(int $index, Tokens $tokens) : int + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + for ($index, $count = \count($tokens); $index < $count; ++$index) { + if (\false !== \strstr($tokens[$index]->getContent(), $lineEnding)) { + return $index; + } + } + return $index; + } + /** + * Find the index for the previous significant token. Return the given index when there's no significant token. + */ + private function getPreviousSignificantTokenIndex(int $index, Tokens $tokens) : int + { + $stopTokens = [\T_LNUMBER, \T_DNUMBER, \T_STRING, \T_VARIABLE, \T_CONSTANT_ENCAPSED_STRING]; + for ($index; $index > 0; --$index) { + if ($tokens[$index]->isGivenKind($stopTokens) || $tokens[$index]->equals(')')) { + return $index; + } + } + return $index; + } + /** + * Checks if the semicolon closes a multiline call and returns the whitespace of the first call at $index. + * i.e. it will return the whitespace marked with '____' in the example underneath. + * + * .. + * ____$this->methodCall() + * ->anotherCall(); + * .. + */ + private function findWhitespaceBeforeFirstCall(int $index, Tokens $tokens) : ?string + { + $isMultilineCall = \false; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + while (!$tokens[$prevIndex]->equalsAny([';', ':', '{', '}', [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_ELSE]])) { + $index = $prevIndex; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $blockType = Tokens::detectBlockType($tokens[$index]); + if (null !== $blockType && !$blockType['isStart']) { + $prevIndex = $tokens->findBlockStart($blockType['type'], $index); + continue; + } + if ($tokens[$index]->isObjectOperator() || $tokens[$index]->isGivenKind(\T_DOUBLE_COLON)) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $isMultilineCall |= $tokens->isPartialCodeMultiline($prevIndex, $index); + } + } + return $isMultilineCall ? WhitespacesAnalyzer::detectIndent($tokens, $index) : null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php new file mode 100644 index 00000000000..d4e6ed80e77 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoEmptyStatementFixer.php @@ -0,0 +1,140 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + */ +final class NoEmptyStatementFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove useless (semicolon) statements.', [new CodeSample("isTokenKindFound(';'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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; + } + // skip T_FOR parenthesis to ignore double `;` like `for ($i = 1; ; ++$i) {...}` + 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); + // A semicolon can always be removed if it follows a semicolon, '{' or opening tag. + if ($tokens[$previousMeaningfulIndex]->equalsAny(['{', ';', [\T_OPEN_TAG]])) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + continue; + } + // A semicolon might be removed if it follows a '}' but only if the brace is part of certain structures. + if ($tokens[$previousMeaningfulIndex]->equals('}')) { + $this->fixSemicolonAfterCurlyBraceClose($tokens, $index, $previousMeaningfulIndex); + continue; + } + // A semicolon might be removed together with its noop statement, for example "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); + } + } + } + /** + * Fix semicolon after closing curly brace if needed. + * + * Test for the following cases + * - just '{' '}' block (following open tag or ';') + * - if, else, elseif + * - interface, trait, class (but not anonymous) + * - catch, finally (but not try) + * - for, foreach, while (but not 'do - while') + * - switch + * - function (declaration, but not lambda) + * - declare (with '{' '}') + * - namespace (with '{' '}') + * + * @param int $index Semicolon index + */ + private function fixSemicolonAfterCurlyBraceClose(Tokens $tokens, int $index, int $curlyCloseIndex) : void + { + 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; + } + // check for namespaces and class, interface and trait definitions + 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; + } + // early return check, below only control structures with conditions are fixed + 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; + } + // check for function definition + if ($tokens[$beforeOpeningBraceIndex]->isGivenKind(\T_STRING)) { + $beforeStringIndex = $tokens->getPrevMeaningfulToken($beforeOpeningBraceIndex); + if ($tokens[$beforeStringIndex]->isGivenKind(\T_FUNCTION)) { + $tokens->clearTokenAndMergeSurroundingWhitespace($index); + // implicit return + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php new file mode 100644 index 00000000000..96e294ed9ec --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/NoSinglelineWhitespaceBeforeSemicolonsFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Graham Campbell + */ +final class NoSinglelineWhitespaceBeforeSemicolonsFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Single-line whitespace before closing semicolon are prohibited.', [new CodeSample("foo() ;\n")]); + } + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveIssetsFixer, FunctionToConstantFixer, NoEmptyStatementFixer, NoUnneededImportAliasFixer, SimplifiedIfReturnFixer, SingleImportPerStatementFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(';'); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->equals(';') || !$tokens[$index - 1]->isWhitespace(" \t")) { + continue; + } + if ($tokens[$index - 2]->equals(';')) { + // do not remove all whitespace before the semicolon because it is also whitespace after another semicolon + $tokens->ensureWhitespaceAtIndex($index - 1, 0, ' '); + } elseif (!$tokens[$index - 2]->isComment()) { + $tokens->clearAt($index - 1); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php new file mode 100644 index 00000000000..c2c9ecfe57c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SemicolonAfterInstructionFixer.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SemicolonAfterInstructionFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Instructions must be terminated with a semicolon.', [new CodeSample("\n")]); + } + /** + * {@inheritdoc} + * + * Must run before SimplifiedIfReturnFixer. + */ + public function getPriority() : int + { + return 2; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_CLOSE_TAG); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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(';')); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php new file mode 100644 index 00000000000..200a036a957 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Semicolon/SpaceAfterSemicolonFixer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Semicolon; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class SpaceAfterSemicolonFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Fix whitespace after a semicolon.', [new CodeSample(" \true])]); + } + /** + * {@inheritdoc} + * + * Must run after CombineConsecutiveUnsetsFixer, MultilineWhitespaceBeforeSemicolonsFixer, NoEmptyStatementFixer, OrderedClassElementsFixer, SingleImportPerStatementFixer, SingleTraitInsertPerStatementFixer. + */ + public function getPriority() : int + { + return -1; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(';'); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + $insideForParenthesesUntil = null; + for ($index = 0, $max = \count($tokens) - 1; $index < $max; ++$index) { + if (\true === $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]]) && (\false === $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, ' ']); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php new file mode 100644 index 00000000000..5b38f433444 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/DeclareStrictTypesFixer.php @@ -0,0 +1,105 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jordi Boggiano + */ +final class DeclareStrictTypesFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Force strict types declaration in all files. Requires PHP >= 7.0.', [new CodeSample("isGivenKind(\T_OPEN_TAG); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + // check if the declaration is already done + $searchIndex = $tokens->getNextMeaningfulToken(0); + if (null === $searchIndex) { + $this->insertSequence($tokens); + // declaration not found, insert one + return; + } + $sequenceLocation = $tokens->findSequence([[\T_DECLARE, 'declare'], '(', [\T_STRING, 'strict_types'], '=', [\T_LNUMBER], ')'], $searchIndex, null, \false); + if (null === $sequenceLocation) { + $this->insertSequence($tokens); + // declaration not found, insert one + return; + } + $this->fixStrictTypesCasingAndValue($tokens, $sequenceLocation); + } + /** + * @param array $sequence + */ + private function fixStrictTypesCasingAndValue(Tokens $tokens, array $sequence) : void + { + /** @var int $index */ + /** @var Token $token */ + 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) : void + { + $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); + // start index of the sequence is always 1 here, 0 is always open tag + // transform "getContent(), "\n") !== \false) { + $tokens[0] = new Token([$tokens[0]->getId(), \trim($tokens[0]->getContent()) . ' ']); + } + if ($endIndex === \count($tokens) - 1) { + return; + // no more tokens after sequence, single_blank_line_at_eof might add a line + } + $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")]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php new file mode 100644 index 00000000000..68d03a7a38b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictComparisonFixer.php @@ -0,0 +1,57 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class StrictComparisonFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Comparisons should be strict.', [new CodeSample("isAnyTokenKindsFound([\T_IS_EQUAL, \T_IS_NOT_EQUAL]); + } + public function isRisky() : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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']]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php new file mode 100644 index 00000000000..d0b014c0dce --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Strict/StrictParamFixer.php @@ -0,0 +1,121 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Strict; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class StrictParamFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Functions should be used with `$strict` param set to `true`.', [new CodeSample("isTokenKindFound(\T_STRING); + } + public function isRisky() : bool + { + return \true; + } + /** + * {@inheritdoc} + * + * Must run before MethodArgumentSpaceFixer, NativeFunctionInvocationFixer. + */ + public function getPriority() : int + { + return 31; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + 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 (isset($map[$lowercaseContent]) && $functionsAnalyzer->isGlobalFunctionCall($tokens, $index)) { + $this->fixFunction($tokens, $index, $map[$lowercaseContent]); + } + } + } + private function fixFunction(Tokens $tokens, int $functionIndex, array $functionParams) : void + { + $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) { + // function call do not have all params that are required to set useStrict flag, exit from method! + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php new file mode 100644 index 00000000000..2a283bae06d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/EscapeImplicitBackslashesFixer.php @@ -0,0 +1,103 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class EscapeImplicitBackslashesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + $codeSample = <<<'EOF' + \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) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING]); + } + /** + * {@inheritdoc} + * + * Must run before HeredocToNowdocFixer, SingleQuoteFixer. + * Must run after BacktickToShellExecFixer. + */ + public function getPriority() : int + { + return 15; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + static $singleQuotedRegex = '/(? $token) { + $content = $token->getContent(); + if ($token->equalsAny(['"', 'b"', 'B"'])) { + $doubleQuoteOpened = !$doubleQuoteOpened; + } + if (!$token->isGivenKind([\T_ENCAPSED_AND_WHITESPACE, \T_CONSTANT_ENCAPSED_STRING]) || \strpos($content, '\\') === \false) { + continue; + } + // Nowdoc syntax + 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() : FixerConfigurationResolverInterface + { + 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()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php new file mode 100644 index 00000000000..2376d7605fc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/ExplicitStringVariableFixer.php @@ -0,0 +1,120 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Filippo Tessarotto + */ +final class ExplicitStringVariableFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts implicit variables into explicit ones in double-quoted strings or heredoc syntax.', [new CodeSample(<<<'EOT' +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.'); + } + /** + * {@inheritdoc} + * + * Must run after BacktickToShellExecFixer. + */ + public function getPriority() : int + { + return 0; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_VARIABLE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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_CURLY_OPEN, '{']), new Token([\T_VARIABLE, $singleVariableToken->getContent()]), new Token([CT::T_CURLY_CLOSE, '}'])]); + } 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, '{'])); + } + } + } + } + /** + * Check if token is a part of a string. + * + * @param Token $token The token to check + */ + private function isStringPartToken(Token $token) : bool + { + return $token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE) || $token->isGivenKind(\T_START_HEREDOC) || '"' === $token->getContent() || 'b"' === \strtolower($token->getContent()); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php new file mode 100644 index 00000000000..992dbef6a1e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/HeredocToNowdocFixer.php @@ -0,0 +1,85 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class HeredocToNowdocFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Convert `heredoc` to `nowdoc` where possible.', [new CodeSample(<<<'EOF' +isTokenKindFound(\T_START_HEREDOC); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->isGivenKind(\T_START_HEREDOC) || \strpos($token->getContent(), "'") !== \false) { + 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(); + // regex: odd number of backslashes, not followed by dollar + if (Preg::match('/(?convertToNowdoc($token); + $content = \str_replace(['\\\\', '\\$'], ['\\', '$'], $content); + $tokens[$index + 1] = new Token([$tokens[$index + 1]->getId(), $content]); + } + } + /** + * Transforms the heredoc start token to nowdoc notation. + */ + private function convertToNowdoc(Token $token) : Token + { + return new Token([$token->getId(), Preg::replace('/^([Bb]?<<<)(\\h*)"?([^\\s"]+)"?/', '$1$2\'$3\'', $token->getContent())]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php new file mode 100644 index 00000000000..8d64fd507b8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoBinaryStringFixer.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author ntzm + */ +final class NoBinaryStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_START_HEREDOC, 'b"']); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There should not be a binary flag before strings.', [new CodeSample(" $token) { + if ($token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_START_HEREDOC])) { + $content = $token->getContent(); + if ('b' === \strtolower($content[0])) { + $tokens[$index] = new Token([$token->getId(), \substr($content, 1)]); + } + } elseif ($token->equals('b"')) { + $tokens[$index] = new Token('"'); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php new file mode 100644 index 00000000000..4b836d59142 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/NoTrailingWhitespaceInStringFixer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class NoTrailingWhitespaceInStringFixer extends AbstractFixer +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]); + } + public function isRisky() : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There must be no trailing whitespace in strings.', [new CodeSample("count() - 1, $last = \true; $index >= 0; --$index, $last = \false) { + /** @var Token $token */ + $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; + // @phpstan-ignore-line due to https://github.com/phpstan/phpstan/issues/1215 , awaiting PHP8 as min requirement of Fixer + } + $this->updateContent($tokens, $index, $content); + } + } + private function updateContent(Tokens $tokens, int $index, string $content) : void + { + if ('' === $content) { + $tokens->clearAt($index); + return; + } + $tokens[$index] = new Token([$tokens[$index]->getId(), $content]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php new file mode 100644 index 00000000000..f8bbcb07551 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SimpleToComplexStringVariableFixer.php @@ -0,0 +1,89 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dave van der Brugge + */ +final class SimpleToComplexStringVariableFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Converts explicit variables in double-quoted strings and heredoc syntax from simple to complex format (`${` to `{$`).', [new CodeSample(<<<'EOT' +isTokenKindFound(\T_DOLLAR_OPEN_CURLY_BRACES); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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_compare($stringContent, '$', -\strlen('$')) === 0 && \substr_compare($stringContent, '\\$', -\strlen('\\$')) !== 0) { + $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, '}'])]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php new file mode 100644 index 00000000000..c043d1ad85e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/SingleQuoteFixer.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class SingleQuoteFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + $codeSample = <<<'EOF' + \true])]); + } + /** + * {@inheritdoc} + * + * Must run before NoUselessConcatOperatorFixer. + * Must run after BacktickToShellExecFixer, EscapeImplicitBackslashesFixer. + */ + public function getPriority() : int + { + return 10; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_CONSTANT_ENCAPSED_STRING); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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'] || \strpos($content, "'") === \false) && !Preg::match('/(?setAllowedTypes(['bool'])->setDefault(\false)->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php new file mode 100644 index 00000000000..21840f140e5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLengthToEmptyFixer.php @@ -0,0 +1,250 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFunctionReferenceFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\ArgumentsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class StringLengthToEmptyFixer extends AbstractFunctionReferenceFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('String tests for empty must be done against `\'\'`, not with `strlen`.', [new CodeSample("findStrLengthCalls($tokens) as $candidate) { + [$functionNameIndex, $openParenthesisIndex, $closeParenthesisIndex] = $candidate; + $arguments = $argumentsAnalyzer->getArguments($tokens, $openParenthesisIndex, $closeParenthesisIndex); + if (1 !== \count($arguments)) { + continue; + // must be one argument + } + // test for leading `\` before `strlen` call + $nextIndex = $tokens->getNextMeaningfulToken($closeParenthesisIndex); + $previousIndex = $tokens->getPrevMeaningfulToken($functionNameIndex); + if ($tokens[$previousIndex]->isGivenKind(\T_NS_SEPARATOR)) { + $namespaceSeparatorIndex = $previousIndex; + $previousIndex = $tokens->getPrevMeaningfulToken($previousIndex); + } else { + $namespaceSeparatorIndex = null; + } + // test for yoda vs non-yoda fix case + if ($this->isOperatorOfInterest($tokens[$previousIndex])) { + // test if valid yoda case to fix + $operatorIndex = $previousIndex; + $operandIndex = $tokens->getPrevMeaningfulToken($previousIndex); + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { + // test if operand is `0` or `1` + continue; + } + $replacement = $this->getReplacementYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + if (null === $replacement) { + continue; + } + if ($this->isOfHigherPrecedence($tokens[$nextIndex])) { + // is of higher precedence right; continue + continue; + } + if ($this->isOfHigherPrecedence($tokens[$tokens->getPrevMeaningfulToken($operandIndex)])) { + // is of higher precedence left; continue + continue; + } + } elseif ($this->isOperatorOfInterest($tokens[$nextIndex])) { + // test if valid !yoda case to fix + $operatorIndex = $nextIndex; + $operandIndex = $tokens->getNextMeaningfulToken($nextIndex); + if (!$this->isOperandOfInterest($tokens[$operandIndex])) { + // test if operand is `0` or `1` + continue; + } + $replacement = $this->getReplacementNotYoda($tokens[$operatorIndex], $tokens[$operandIndex]); + if (null === $replacement) { + continue; + } + if ($this->isOfHigherPrecedence($tokens[$tokens->getNextMeaningfulToken($operandIndex)])) { + // is of higher precedence right; continue + continue; + } + if ($this->isOfHigherPrecedence($tokens[$previousIndex])) { + // is of higher precedence left; continue + continue; + } + } else { + continue; + } + // prepare for fixing + $keepParentheses = $this->keepParentheses($tokens, $openParenthesisIndex, $closeParenthesisIndex); + if (\T_IS_IDENTICAL === $replacement) { + $operandContent = '==='; + } else { + // T_IS_NOT_IDENTICAL === $replacement + $operandContent = '!=='; + } + // apply fixing + $tokens[$operandIndex] = new Token([\T_CONSTANT_ENCAPSED_STRING, "''"]); + $tokens[$operatorIndex] = new Token([$replacement, $operandContent]); + if (!$keepParentheses) { + $tokens->clearTokenAndMergeSurroundingWhitespace($closeParenthesisIndex); + $tokens->clearTokenAndMergeSurroundingWhitespace($openParenthesisIndex); + } + $tokens->clearTokenAndMergeSurroundingWhitespace($functionNameIndex); + if (null !== $namespaceSeparatorIndex) { + $tokens->clearTokenAndMergeSurroundingWhitespace($namespaceSeparatorIndex); + } + } + } + private function getReplacementYoda(Token $operator, Token $operand) : ?int + { + /* Yoda 0 + + 0 === strlen($b) | '' === $b + 0 !== strlen($b) | '' !== $b + 0 <= strlen($b) | X makes no sense, assume overridden + 0 >= strlen($b) | '' === $b + 0 < strlen($b) | '' !== $b + 0 > strlen($b) | X makes no sense, assume overridden + */ + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_GREATER_OR_EQUAL])) { + return \T_IS_IDENTICAL; + } + if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('<')) { + return \T_IS_NOT_IDENTICAL; + } + return null; + } + /* Yoda 1 + + 1 === strlen($b) | X cannot simplify + 1 !== strlen($b) | X cannot simplify + 1 <= strlen($b) | '' !== $b + 1 >= strlen($b) | cannot simplify + 1 < strlen($b) | cannot simplify + 1 > strlen($b) | '' === $b + */ + if ($operator->isGivenKind(\T_IS_SMALLER_OR_EQUAL)) { + return \T_IS_NOT_IDENTICAL; + } + if ($operator->equals('>')) { + return \T_IS_IDENTICAL; + } + return null; + } + private function getReplacementNotYoda(Token $operator, Token $operand) : ?int + { + /* Not Yoda 0 + + strlen($b) === 0 | $b === '' + strlen($b) !== 0 | $b !== '' + strlen($b) <= 0 | $b === '' + strlen($b) >= 0 | X makes no sense, assume overridden + strlen($b) < 0 | X makes no sense, assume overridden + strlen($b) > 0 | $b !== '' + */ + if ('0' === $operand->getContent()) { + if ($operator->isGivenKind([\T_IS_IDENTICAL, \T_IS_SMALLER_OR_EQUAL])) { + return \T_IS_IDENTICAL; + } + if ($operator->isGivenKind(\T_IS_NOT_IDENTICAL) || $operator->equals('>')) { + return \T_IS_NOT_IDENTICAL; + } + return null; + } + /* Not Yoda 1 + + strlen($b) === 1 | X cannot simplify + strlen($b) !== 1 | X cannot simplify + strlen($b) <= 1 | X cannot simplify + strlen($b) >= 1 | $b !== '' + strlen($b) < 1 | $b === '' + strlen($b) > 1 | X cannot simplify + */ + if ($operator->isGivenKind(\T_IS_GREATER_OR_EQUAL)) { + return \T_IS_NOT_IDENTICAL; + } + if ($operator->equals('<')) { + return \T_IS_IDENTICAL; + } + return null; + } + private function isOperandOfInterest(Token $token) : bool + { + if (!$token->isGivenKind(\T_LNUMBER)) { + return \false; + } + $content = $token->getContent(); + return '0' === $content || '1' === $content; + } + private function isOperatorOfInterest(Token $token) : bool + { + return $token->isGivenKind([\T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL, \T_IS_SMALLER_OR_EQUAL, \T_IS_GREATER_OR_EQUAL]) || $token->equals('<') || $token->equals('>'); + } + private function isOfHigherPrecedence(Token $token) : bool + { + static $operatorsPerContent = ['!', '%', '*', '+', '-', '.', '/', '~', '?']; + return $token->isGivenKind([\T_INSTANCEOF, \T_POW, \T_SL, \T_SR]) || $token->equalsAny($operatorsPerContent); + } + private function keepParentheses(Tokens $tokens, int $openParenthesisIndex, int $closeParenthesisIndex) : bool + { + $i = $tokens->getNextMeaningfulToken($openParenthesisIndex); + if ($tokens[$i]->isCast()) { + $i = $tokens->getNextMeaningfulToken($i); + } + for (; $i < $closeParenthesisIndex; ++$i) { + $token = $tokens[$i]; + if ($token->isGivenKind([\T_VARIABLE, \T_STRING]) || $token->isObjectOperator() || $token->isWhitespace() || $token->isComment()) { + continue; + } + $blockType = Tokens::detectBlockType($token); + if (null !== $blockType && $blockType['isStart']) { + $i = $tokens->findBlockEnd($blockType['type'], $i); + continue; + } + return \true; + } + return \false; + } + private function findStrLengthCalls(Tokens $tokens) : \Generator + { + $candidates = []; + $count = \count($tokens); + for ($i = 0; $i < $count; ++$i) { + $candidate = $this->find('strlen', $tokens, $i, $count); + if (null === $candidate) { + break; + } + $i = $candidate[1]; + // proceed to openParenthesisIndex + $candidates[] = $candidate; + } + foreach (\array_reverse($candidates) as $candidate) { + (yield $candidate); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php new file mode 100644 index 00000000000..822dc1760ee --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/StringNotation/StringLineEndingFixer.php @@ -0,0 +1,52 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\StringNotation; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixes the line endings in multi-line strings. + * + * @author Ilija Tovilo + */ +final class StringLineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML]); + } + public function isRisky() : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All multi-line strings must use correct line ending.', [new CodeSample("whitespacesConfig->getLineEnding(); + foreach ($tokens as $tokenIndex => $token) { + if (!$token->isGivenKind([\T_CONSTANT_ENCAPSED_STRING, \T_ENCAPSED_AND_WHITESPACE, \T_INLINE_HTML])) { + continue; + } + $tokens[$tokenIndex] = new Token([$token->getId(), Preg::replace('#\\R#u', $ending, $token->getContent())]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php new file mode 100644 index 00000000000..0608d2253cc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/ArrayIndentationFixer.php @@ -0,0 +1,127 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class ArrayIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Each element of an array must be indented exactly once.', [new CodeSample(" [\n 'baz' => true,\n ],\n];\n")]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound([\T_ARRAY, CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + /** + * {@inheritdoc} + * + * Must run before AlignMultilineCommentFixer, BinaryOperatorSpacesFixer. + * Must run after MethodArgumentSpaceFixer. + */ + public function getPriority() : int + { + return 29; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $lastIndent = ''; + $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' => $lastIndent]; + continue; + } + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + 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]); + $lastIndent = $this->extractIndent($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, int $index, int $parentScopeEndIndex) : int + { + $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; + } + } + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php new file mode 100644 index 00000000000..d1bdb277efa --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBeforeStatementFixer.php @@ -0,0 +1,198 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + * @author Andreas Möller + */ +final class BlankLineBeforeStatementFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var array + */ + private static $tokenMap = ['break' => \T_BREAK, 'case' => \T_CASE, 'continue' => \T_CONTINUE, 'declare' => \T_DECLARE, 'default' => \T_DEFAULT, '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, 'phpdoc' => \T_DOC_COMMENT, '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, 'yield_from' => \T_YIELD_FROM]; + /** + * @var list + */ + private $fixTokenMap = []; + public function configure(array $configuration) : void + { + parent::configure($configuration); + $this->fixTokenMap = []; + foreach ($this->configuration['statements'] as $key) { + $this->fixTokenMap[$key] = self::$tokenMap[$key]; + } + $this->fixTokenMap = \array_values($this->fixTokenMap); + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('An empty line feed must precede any configured statement.', [new CodeSample('process(); + break; + case 44: + break; +} +', ['statements' => ['break']]), new CodeSample('isTired()) { + $bar->sleep(); + continue; + } +} +', ['statements' => ['continue']]), new CodeSample(' 0); +', ['statements' => ['do']]), new CodeSample(' ['exit']]), new CodeSample(' ['goto']]), new CodeSample(' ['if']]), new CodeSample(' ['return']]), new CodeSample(' ['switch']]), new CodeSample('bar(); + throw new \\UnexpectedValueException("A cannot be null."); +} +', ['statements' => ['throw']]), new CodeSample('bar(); +} catch (\\Exception $exception) { + $a = -1; +} +', ['statements' => ['try']]), new CodeSample(' ['yield']])]); + } + /** + * {@inheritdoc} + * + * Must run after NoExtraBlankLinesFixer, NoUselessReturnFixer, ReturnAssignmentFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority() : int + { + return -21; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound($this->fixTokenMap); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('statements', 'List of statements which must be preceded by an empty line.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(\array_keys(self::$tokenMap))])->setDefault(['break', 'continue', 'declare', 'return', 'throw', 'try'])->getOption()]); + } + private function shouldAddBlankLine(Tokens $tokens, int $prevNonWhitespace) : bool + { + $prevNonWhitespaceToken = $tokens[$prevNonWhitespace]; + if ($prevNonWhitespaceToken->isComment()) { + for ($j = $prevNonWhitespace - 1; $j >= 0; --$j) { + if (\strpos($tokens[$j]->getContent(), "\n") !== \false) { + return \false; + } + if ($tokens[$j]->isWhitespace() || $tokens[$j]->isComment()) { + continue; + } + return $tokens[$j]->equalsAny([';', '}']); + } + } + return $prevNonWhitespaceToken->equalsAny([';', '}']); + } + private function insertBlankLine(Tokens $tokens, int $index) : void + { + $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])); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php new file mode 100644 index 00000000000..598a4ee9490 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/BlankLineBetweenImportGroupsFixer.php @@ -0,0 +1,139 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Sander Verkuil + */ +final class BlankLineBetweenImportGroupsFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + private const IMPORT_TYPE_CLASS = 'class'; + private const IMPORT_TYPE_CONST = 'const'; + private const IMPORT_TYPE_FUNCTION = 'function'; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Putting blank lines between `use` statement groups.', [new CodeSample('isTokenKindFound(\T_USE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $namespacesImports = $tokensAnalyzer->getImportUseIndexes(\true); + foreach (\array_reverse($namespacesImports) as $uses) { + $this->walkOverUses($tokens, $uses); + } + } + /** + * @param int[] $uses + */ + private function walkOverUses(Tokens $tokens, array $uses) : void + { + $usesCount = \count($uses); + if ($usesCount < 2) { + return; + // nothing to fix + } + $previousType = null; + for ($i = $usesCount - 1; $i >= 0; --$i) { + $index = $uses[$i]; + $startIndex = $tokens->getNextMeaningfulToken($index + 1); + $endIndex = $tokens->getNextTokenOfKind($startIndex, [';', [\T_CLOSE_TAG]]); + if ($tokens[$startIndex]->isGivenKind(CT::T_CONST_IMPORT)) { + $type = self::IMPORT_TYPE_CONST; + } elseif ($tokens[$startIndex]->isGivenKind(CT::T_FUNCTION_IMPORT)) { + $type = self::IMPORT_TYPE_FUNCTION; + } else { + $type = self::IMPORT_TYPE_CLASS; + } + if (null !== $previousType && $type !== $previousType) { + $this->ensureLine($tokens, $endIndex + 1); + } + $previousType = $type; + } + } + private function ensureLine(Tokens $tokens, int $index) : void + { + static $lineEnding; + if (null === $lineEnding) { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + $lineEnding .= $lineEnding; + } + $index = $this->getInsertIndex($tokens, $index); + $indent = WhitespacesAnalyzer::detectIndent($tokens, $index); + $tokens->ensureWhitespaceAtIndex($index, 1, $lineEnding . $indent); + } + private function getInsertIndex(Tokens $tokens, int $index) : int + { + $tokensCount = \count($tokens); + for (; $index < $tokensCount - 1; ++$index) { + if (!$tokens[$index]->isWhitespace() && !$tokens[$index]->isComment()) { + return $index - 1; + } + $content = $tokens[$index]->getContent(); + if (\strpos($content, "\n") !== \false) { + return $index; + } + } + return $index; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php new file mode 100644 index 00000000000..e875a8ac42e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/CompactNullableTypehintFixer.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Jack Cherng + */ +final class CompactNullableTypehintFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove extra spaces in a nullable typehint.', [new CodeSample("isTokenKindFound(CT::T_NULLABLE_TYPE); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + static $typehintKinds = [CT::T_ARRAY_TYPEHINT, \T_CALLABLE, \T_NS_SEPARATOR, \T_STATIC, \T_STRING]; + for ($index = $tokens->count() - 1; $index >= 0; --$index) { + if (!$tokens[$index]->isGivenKind(CT::T_NULLABLE_TYPE)) { + continue; + } + // remove whitespaces only if there are only whitespaces + // between '?' and the variable type + if ($tokens[$index + 1]->isWhitespace() && $tokens[$index + 2]->isGivenKind($typehintKinds)) { + $tokens->removeTrailingWhitespace($index); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php new file mode 100644 index 00000000000..ddcefaf5ebd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/HeredocIndentationFixer.php @@ -0,0 +1,141 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\FixerDefinition\VersionSpecification; +use PhpCsFixer\FixerDefinition\VersionSpecificCodeSample; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\WhitespacesAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Gregor Harlan + */ +final class HeredocIndentationFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Heredoc/nowdoc content must be properly indented. Requires PHP >= 7.3.', [new VersionSpecificCodeSample(<<<'SAMPLE' + 'same_as_start'])]); + } + /** + * {@inheritdoc} + * + * Must run after BracesFixer, StatementIndentationFixer. + */ + public function getPriority() : int + { + return -26; + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isTokenKindFound(\T_START_HEREDOC); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + 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) : void + { + 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, int $start, int $end) : void + { + $indent = WhitespacesAnalyzer::detectIndent($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 || \strncmp($content, $currentIndent, \strlen($currentIndent)) === 0)) { + $content = $indent . \substr($content, $currentIndentLength); + } elseif ($currentIndent) { + $content = Preg::replace('/^(?!' . $currentIndent . ')\\h+/', '', $content); + } + $tokens[$index] = new Token([\T_ENCAPSED_AND_WHITESPACE, $content]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php new file mode 100644 index 00000000000..dfadbdc275e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/IndentationTypeFixer.php @@ -0,0 +1,116 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.4. + * + * @author Dariusz Rumiński + */ +final class IndentationTypeFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + /** + * @var string + */ + private $indent; + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Code MUST use configured indentation type.', [new CodeSample("isAnyTokenKindsFound([\T_COMMENT, \T_DOC_COMMENT, \T_WHITESPACE]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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, int $index) : Token + { + $content = Preg::replace('/^(?:(?getContent(), -1, $count); + // Also check for more tabs. + while (0 !== $count) { + $content = Preg::replace('/^(\\ +)?\\t/m', '\\1 ', $content, -1, $count); + } + $indent = $this->indent; + // change indent to expected one + $content = Preg::replaceCallback('/^(?: )+/m', function (array $matches) use($indent) : string { + return $this->getExpectedIndent($matches[0], $indent); + }, $content); + return new Token([$tokens[$index]->getId(), $content]); + } + private function fixIndentToken(Tokens $tokens, int $index) : Token + { + $content = $tokens[$index]->getContent(); + $previousTokenHasTrailingLinebreak = \false; + // @TODO this can be removed when we have a transformer for "T_OPEN_TAG" to "T_OPEN_TAG + T_WHITESPACE" + if (\strpos($tokens[$index - 1]->getContent(), "\n") !== \false) { + $content = "\n" . $content; + $previousTokenHasTrailingLinebreak = \true; + } + $indent = $this->indent; + $newContent = Preg::replaceCallback( + '/(\\R)(\\h+)/', + // find indent + function (array $matches) use($indent) : string { + // normalize mixed indent + $content = Preg::replace('/(?:(?getExpectedIndent($content, $indent); + }, + $content + ); + if ($previousTokenHasTrailingLinebreak) { + $newContent = \substr($newContent, 1); + } + return new Token([\T_WHITESPACE, $newContent]); + } + /** + * @return string mixed + */ + private function getExpectedIndent(string $content, string $indent) : string + { + if ("\t" === $indent) { + $content = \str_replace(' ', $indent, $content); + } + return $content; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php new file mode 100644 index 00000000000..72a25addc4f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/LineEndingFixer.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class LineEndingFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function isCandidate(Tokens $tokens) : bool + { + return \true; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('All PHP files must use same line ending.', [new CodeSample("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())]); + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php new file mode 100644 index 00000000000..66c4f3e5df0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/MethodChainingIndentationFixer.php @@ -0,0 +1,157 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Vladimir Boliev + */ +final class MethodChainingIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Method chaining MUST be properly indented. Method chaining with different levels of indentation is not supported.', [new CodeSample("setEmail('voff.web@gmail.com')\n ->setPassword('233434');\n")]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(Token::getObjectOperatorKinds()); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $lineEnding = $this->whitespacesConfig->getLineEnding(); + for ($index = 1, $count = \count($tokens); $index < $count; ++$index) { + if (!$tokens[$index]->isObjectOperator()) { + continue; + } + $endParenthesisIndex = $tokens->getNextTokenOfKind($index, ['(', ';', ',', [\T_CLOSE_TAG]]); + if (null === $endParenthesisIndex || !$tokens[$endParenthesisIndex]->equals('(')) { + 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; + ++$endParenthesisIndex; + } + } + $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]); + } + $endParenthesisIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endParenthesisIndex); + for ($searchIndex = $index + 1; $searchIndex < $endParenthesisIndex; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + if (!$searchToken->isWhitespace()) { + continue; + } + $content = $searchToken->getContent(); + if (!Preg::match('/\\R/', $content)) { + continue; + } + $content = Preg::replace('/(\\R)' . $currentIndent . '(\\h*)$/D', '$1' . $expectedIndent . '$2', $content); + $tokens[$searchIndex] = new Token([$searchToken->getId(), $content]); + } + } + } + /** + * @param int $index index of the first token on the line to indent + */ + private function getExpectedIndentAt(Tokens $tokens, int $index) : string + { + $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; + } + /** + * @param int $index position of the object operator token ("->" or "?->") + */ + private function canBeMovedToNextLine(int $index, Tokens $tokens) : bool + { + $prevMeaningful = $tokens->getPrevMeaningfulToken($index); + $hasCommentBefore = \false; + for ($i = $index - 1; $i > $prevMeaningful; --$i) { + if ($tokens[$i]->isComment()) { + $hasCommentBefore = \true; + continue; + } + if ($tokens[$i]->isWhitespace() && Preg::match('/\\R/', $tokens[$i]->getContent())) { + return $hasCommentBefore; + } + } + return \false; + } + /** + * @param int $index index of the indentation token + */ + private function getIndentAt(Tokens $tokens, int $index) : ?string + { + if (Preg::match('/\\R{1}(\\h*)$/', $this->getIndentContentAt($tokens, $index), $matches)) { + return $matches[1]; + } + return null; + } + private function getIndentContentAt(Tokens $tokens, int $index) : string + { + 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 ''; + } + /** + * @param int $start index of first meaningful token on previous line + * @param int $end index of last token on previous line + */ + private function currentLineRequiresExtraIndentLevel(Tokens $tokens, int $start, int $end) : bool + { + $firstMeaningful = $tokens->getNextMeaningfulToken($start); + if ($tokens[$firstMeaningful]->isObjectOperator()) { + $thirdMeaningful = $tokens->getNextMeaningfulToken($tokens->getNextMeaningfulToken($firstMeaningful)); + return $tokens[$thirdMeaningful]->equals('(') && $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $thirdMeaningful) > $end; + } + return !$tokens[$end]->equals(')') || $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $end) >= $start; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php new file mode 100644 index 00000000000..f55be6ee408 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoExtraBlankLinesFixer.php @@ -0,0 +1,327 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +use PhpCsFixer\Utils; +/** + * @author Dariusz Rumiński + */ +final class NoExtraBlankLinesFixer extends AbstractFixer implements ConfigurableFixerInterface, WhitespacesAwareFixerInterface +{ + /** + * @var string[] + */ + private static $availableTokens = ['attribute', 'break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use', 'use_trait']; + /** + * @var array key is token id, value is name of callback + */ + private $tokenKindCallbackMap; + /** + * @var array token prototype, value is name of callback + */ + private $tokenEqualsMap; + /** + * @var \PhpCsFixer\Tokenizer\Tokens + */ + private $tokens; + /** + * @var \PhpCsFixer\Tokenizer\TokensAnalyzer + */ + private $tokensAnalyzer; + public function configure(array $configuration) : void + { + if (isset($configuration['tokens']) && \in_array('use_trait', $configuration['tokens'], \true)) { + Utils::triggerDeprecation(new \RuntimeException('Option "tokens: use_trait" used in `no_extra_blank_lines` rule is deprecated, use the rule `class_attributes_separation` with `elements: trait_import` instead.')); + } + parent::configure($configuration); + $tokensConfiguration = $this->configuration['tokens']; + $this->tokenEqualsMap = []; + if (\in_array('curly_brace_block', $tokensConfiguration, \true)) { + $this->tokenEqualsMap['{'] = 'fixStructureOpenCloseIfMultiLine'; + // i.e. not: CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN + } + if (\in_array('parenthesis_brace_block', $tokensConfiguration, \true)) { + $this->tokenEqualsMap['('] = 'fixStructureOpenCloseIfMultiLine'; + // i.e. not: CT::T_BRACE_CLASS_INSTANTIATION_OPEN + } + static $configMap = ['attribute' => [CT::T_ATTRIBUTE_CLOSE, 'fixAfterToken'], 'break' => [\T_BREAK, 'fixAfterToken'], 'case' => [\T_CASE, 'fixAfterCaseToken'], 'continue' => [\T_CONTINUE, 'fixAfterToken'], 'default' => [\T_DEFAULT, 'fixAfterToken'], 'extra' => [\T_WHITESPACE, 'removeMultipleBlankLines'], 'return' => [\T_RETURN, 'fixAfterToken'], 'square_brace_block' => [CT::T_ARRAY_SQUARE_BRACE_OPEN, 'fixStructureOpenCloseIfMultiLine'], 'switch' => [\T_SWITCH, 'fixAfterToken'], 'throw' => [\T_THROW, 'fixAfterThrowToken'], 'use' => [\T_USE, 'removeBetweenUse'], 'use_trait' => [CT::T_USE_TRAIT, 'removeBetweenUse']]; + $this->tokenKindCallbackMap = []; + foreach ($tokensConfiguration as $config) { + if (isset($configMap[$config])) { + $this->tokenKindCallbackMap[$configMap[$config][0]] = $configMap[$config][1]; + } + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Removes extra blank lines and/or blank lines following configuration.', [new CodeSample(' ['break']]), new CodeSample(' ['continue']]), new CodeSample(' ['curly_brace_block']]), new CodeSample(' ['extra']]), new CodeSample(' ['parenthesis_brace_block']]), new CodeSample(' ['return']]), new CodeSample(' ['square_brace_block']]), new CodeSample(' ['throw']]), new CodeSample(' ['use']]), new CodeSample(' ['switch', 'case', 'default']])]); + } + /** + * {@inheritdoc} + * + * Must run before BlankLineBeforeStatementFixer. + * Must run after ClassAttributesSeparationFixer, CombineConsecutiveUnsetsFixer, EmptyLoopBodyFixer, EmptyLoopConditionFixer, FunctionToConstantFixer, ModernizeStrposFixer, NoEmptyCommentFixer, NoEmptyPhpdocFixer, NoEmptyStatementFixer, NoUnusedImportsFixer, NoUselessElseFixer, NoUselessReturnFixer, NoUselessSprintfFixer, StringLengthToEmptyFixer, YieldFromArrayToYieldsFixer. + */ + public function getPriority() : int + { + return -20; + } + public function isCandidate(Tokens $tokens) : bool + { + return \true; + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $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() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('tokens', 'List of tokens to fix.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(self::$availableTokens)])->setDefault(['extra'])->getOption()]); + } + private function fixByToken(Token $token, int $index) : void + { + 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(int $index) : void + { + $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; + } + $this->removeEmptyLinesAfterLineWithTokenAt($next); + } + private function removeMultipleBlankLines(int $index) : void + { + $expected = $this->tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) && 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(int $index) : void + { + 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() && \strpos($this->tokens[$i]->getContent(), "\n") !== \false) { + break; + } + } + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + private function fixAfterCaseToken(int $index) : void + { + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + $enumSwitchIndex = $this->tokens->getPrevTokenOfKind($index, [[\T_SWITCH], [\T_ENUM]]); + if (!$this->tokens[$enumSwitchIndex]->isGivenKind(\T_SWITCH)) { + return; + } + } + $this->removeEmptyLinesAfterLineWithTokenAt($index); + } + private function fixAfterThrowToken(int $index) : void + { + if ($this->tokens[$this->tokens->getPrevMeaningfulToken($index)]->equalsAny([';', '{', '}', ':', [\T_OPEN_TAG]])) { + $this->fixAfterToken($index); + } + } + /** + * Remove white line(s) after the index of a block type, + * but only if the block is not on one line. + * + * @param int $index body start + */ + private function fixStructureOpenCloseIfMultiLine(int $index) : void + { + $blockTypeInfo = Tokens::detectBlockType($this->tokens[$index]); + $bodyEnd = $this->tokens->findBlockEnd($blockTypeInfo['type'], $index); + for ($i = $bodyEnd - 1; $i >= $index; --$i) { + if (\strpos($this->tokens[$i]->getContent(), "\n") !== \false) { + $this->removeEmptyLinesAfterLineWithTokenAt($i); + $this->removeEmptyLinesAfterLineWithTokenAt($index); + break; + } + } + } + private function removeEmptyLinesAfterLineWithTokenAt(int $index) : void + { + // find the line break + $parenthesesDepth = 0; + $tokenCount = \count($this->tokens); + for ($end = $index; $end < $tokenCount; ++$end) { + if ($this->tokens[$end]->equals('(')) { + ++$parenthesesDepth; + continue; + } + if ($this->tokens[$end]->equals(')')) { + --$parenthesesDepth; + if ($parenthesesDepth < 0) { + return; + } + continue; + } + if ($this->tokens[$end]->equals('}') || \strpos($this->tokens[$end]->getContent(), "\n") !== \false) { + break; + } + } + if ($end === $tokenCount) { + return; + // not found, early 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; + } + $newContent = Preg::replace('/^.*\\R(\\h*)$/s', $ending . '$1', $content); + $this->tokens[$i] = new Token([\T_WHITESPACE, $newContent]); + } + } + private function containsLinebreak(int $startIndex, int $endIndex) : bool + { + for ($i = $endIndex; $i > $startIndex; --$i) { + if (Preg::match('/\\R/', $this->tokens[$i]->getContent())) { + return \true; + } + } + return \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php new file mode 100644 index 00000000000..b17da237a4a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesAroundOffsetFixer.php @@ -0,0 +1,74 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Javier Spagnoletti + */ +final class NoSpacesAroundOffsetFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('There MUST NOT be spaces around offset braces.', [new CodeSample(" ['inside']]), new CodeSample(" ['outside']])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(['[', CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + 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); + } + // remove space after opening `[` or `{` + if ($tokens[$index + 1]->isWhitespace(" \t")) { + $tokens->clearAt($index + 1); + } + // remove space before closing `]` or `}` + 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() : FixerConfigurationResolverInterface + { + $values = ['inside', 'outside']; + return new FixerConfigurationResolver([(new FixerOptionBuilder('positions', 'Whether spacing should be fixed inside and/or outside the offset braces.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset($values)])->setDefault($values)->getOption()]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php new file mode 100644 index 00000000000..f110e3222d3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoSpacesInsideParenthesisFixer.php @@ -0,0 +1,78 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶4.3, ¶4.6, ¶5. + * + * @author Marc Aubé + * @author Dariusz Rumiński + */ +final class NoSpacesInsideParenthesisFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + 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("isTokenKindFound('('); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + foreach ($tokens as $index => $token) { + if (!$token->equals('(')) { + continue; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + // ignore parenthesis for T_ARRAY + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind(\T_ARRAY)) { + continue; + } + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + // remove space after opening `(` + if (!$tokens[$tokens->getNextNonWhitespace($index)]->isComment()) { + $this->removeSpaceAroundToken($tokens, $index + 1); + } + // remove space before closing `)` if it is not `list($a, $b, )` case + if (!$tokens[$tokens->getPrevMeaningfulToken($endIndex)]->equals(',')) { + $this->removeSpaceAroundToken($tokens, $endIndex - 1); + } + } + } + /** + * Remove spaces from token at a given index. + */ + private function removeSpaceAroundToken(Tokens $tokens, int $index) : void + { + $token = $tokens[$index]; + if ($token->isWhitespace() && \strpos($token->getContent(), "\n") === \false) { + $tokens->clearAt($index); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php new file mode 100644 index 00000000000..fc6cdfb5a1e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoTrailingWhitespaceFixer.php @@ -0,0 +1,83 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Fixer for rules defined in PSR2 ¶2.3. + * + * Don't add trailing spaces at the end of non-blank lines. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class NoTrailingWhitespaceFixer extends AbstractFixer +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove trailing whitespace at the end of non-blank lines.', [new CodeSample("= 0; --$index) { + $token = $tokens[$index]; + if ($token->isGivenKind(\T_OPEN_TAG) && $tokens->offsetExists($index + 1) && $tokens[$index + 1]->isWhitespace() && Preg::match('/(.*)\\h$/', $token->getContent(), $openTagMatches) && Preg::match('/^(\\R)(.*)$/s', $tokens[$index + 1]->getContent(), $whitespaceMatches)) { + $tokens[$index] = new Token([\T_OPEN_TAG, $openTagMatches[1] . $whitespaceMatches[1]]); + $tokens->ensureWhitespaceAtIndex($index + 1, 0, $whitespaceMatches[2]); + continue; + } + if (!$token->isWhitespace()) { + continue; + } + $lines = Preg::split('/(\\R+)/', $token->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE); + $linesSize = \count($lines); + // fix only multiline whitespaces or singleline whitespaces at the end of file + if ($linesSize > 1 || !isset($tokens[$index + 1])) { + if (!$tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) || !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); + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php new file mode 100644 index 00000000000..3c7d8f65513 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/NoWhitespaceInBlankLineFixer.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + */ +final class NoWhitespaceInBlankLineFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Remove trailing whitespace at the end of blank lines.', [new CodeSample("isWhitespace()) { + $this->fixWhitespaceToken($tokens, $i); + } + } + } + private function fixWhitespaceToken(Tokens $tokens, int $index) : void + { + $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); + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php new file mode 100644 index 00000000000..3768dd0637a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/SingleBlankLineAtEofFixer.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Tokens; +/** + * A file must always end with a line endings character. + * + * Fixer for rules defined in PSR2 ¶2.2. + * + * @author Fabien Potencier + * @author Dariusz Rumiński + */ +final class SingleBlankLineAtEofFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('A PHP file without end tag must always end with a single empty line feed.', [new CodeSample("count(); + if ($count > 0 && !$tokens[$count - 1]->isGivenKind([\T_INLINE_HTML, \T_CLOSE_TAG, \T_OPEN_TAG])) { + $tokens->ensureWhitespaceAtIndex($count - 1, 1, $this->whitespacesConfig->getLineEnding()); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php new file mode 100644 index 00000000000..d5e98d89ffe --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/StatementIndentationFixer.php @@ -0,0 +1,417 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\Indentation; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +final class StatementIndentationFixer extends AbstractFixer implements WhitespacesAwareFixerInterface +{ + use Indentation; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\AlternativeSyntaxAnalyzer + */ + private $alternativeSyntaxAnalyzer; + /** + * @var bool + */ + private $bracesFixerCompatibility; + public function __construct(bool $bracesFixerCompatibility = \false) + { + parent::__construct(); + $this->bracesFixerCompatibility = $bracesFixerCompatibility; + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Each statement must be indented.', [new CodeSample('alternativeSyntaxAnalyzer = new AlternativeSyntaxAnalyzer(); + $blockSignatureFirstTokens = [\T_USE, \T_IF, \T_ELSE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_WHILE, \T_SWITCH, \T_CASE, \T_DEFAULT, \T_TRY, \T_CLASS, \T_INTERFACE, \T_TRAIT, \T_EXTENDS, \T_IMPLEMENTS]; + if (\defined('T_MATCH')) { + // @TODO: drop condition when PHP 8.0+ is required + $blockSignatureFirstTokens[] = \T_MATCH; + } + $blockFirstTokens = ['{', [CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN], [CT::T_USE_TRAIT], [CT::T_GROUP_IMPORT_BRACE_OPEN]]; + if (\defined('T_ATTRIBUTE')) { + // @TODO: drop condition when PHP 8.0+ is required + $blockFirstTokens[] = [\T_ATTRIBUTE]; + } + $endIndex = \count($tokens) - 1; + if ($tokens[$endIndex]->isWhitespace()) { + --$endIndex; + } + $lastIndent = $this->getLineIndentationWithBracesCompatibility($tokens, 0, $this->extractIndent($this->computeNewLineContent($tokens, 0))); + $methodModifierTokens = [ + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-visibility-modifier + \T_PUBLIC, + \T_PROTECTED, + \T_PRIVATE, + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-static-modifier + \T_STATIC, + // https://github.com/php/php-langspec/blob/master/spec/19-grammar.md#grammar-class-modifier + \T_ABSTRACT, + \T_FINAL, + ]; + $methodModifierIndents = []; + /** + * @var list $scopes + */ + $scopes = [['type' => 'block', 'skip' => \false, 'end_index' => $endIndex, 'end_index_inclusive' => \true, 'initial_indent' => $lastIndent, 'is_indented_block' => \false]]; + $previousLineInitialIndent = ''; + $previousLineNewIndent = ''; + $alternativeBlockStarts = []; + $caseBlockStarts = []; + foreach ($tokens as $index => $token) { + $currentScope = \count($scopes) - 1; + if ($token->equalsAny($blockFirstTokens) || $token->equals('(') && !$tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_ARRAY) || isset($alternativeBlockStarts[$index]) || isset($caseBlockStarts[$index])) { + $endIndexInclusive = \true; + if ($token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])) { + $endIndex = $tokens->getNextTokenOfKind($index, ['{']); + } elseif ($token->isGivenKind(CT::T_USE_TRAIT)) { + $endIndex = $tokens->getNextTokenOfKind($index, [';']); + } elseif ($token->equals(':')) { + if (isset($caseBlockStarts[$index])) { + [$endIndex, $endIndexInclusive] = $this->findCaseBlockEnd($tokens, $index); + } else { + $endIndex = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $alternativeBlockStarts[$index]); + } + } elseif ($token->isGivenKind(CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE]]); + } elseif ($token->isGivenKind(CT::T_GROUP_IMPORT_BRACE_OPEN)) { + $endIndex = $tokens->getNextTokenOfKind($index, [[CT::T_GROUP_IMPORT_BRACE_CLOSE]]); + } elseif ($token->equals('{')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + } elseif ($token->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + } else { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + } + if ('block_signature' === $scopes[$currentScope]['type']) { + $initialIndent = $scopes[$currentScope]['initial_indent']; + } else { + $initialIndent = $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent); + } + $skip = \false; + if ($this->bracesFixerCompatibility) { + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (null !== $prevIndex) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + } + if (null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FUNCTION, \T_FN])) { + $skip = \true; + } + } + $scopes[] = ['type' => 'block', 'skip' => $skip, 'end_index' => $endIndex, 'end_index_inclusive' => $endIndexInclusive, 'initial_indent' => $initialIndent, 'is_indented_block' => \true]; + ++$currentScope; + while ($index >= $scopes[$currentScope]['end_index']) { + \array_pop($scopes); + --$currentScope; + } + continue; + } + if ($token->isGivenKind($blockSignatureFirstTokens)) { + for ($endIndex = $index + 1, $max = \count($tokens); $endIndex < $max; ++$endIndex) { + if ($tokens[$endIndex]->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + continue; + } + if ($tokens[$endIndex]->equalsAny(['{', ';', [\T_DOUBLE_ARROW], [\T_IMPLEMENTS]])) { + break; + } + if ($tokens[$endIndex]->equals(':')) { + if ($token->isGivenKind([\T_CASE, \T_DEFAULT])) { + $caseBlockStarts[$endIndex] = $index; + } else { + $alternativeBlockStarts[$endIndex] = $index; + } + break; + } + } + $scopes[] = ['type' => 'block_signature', 'skip' => \false, 'end_index' => $endIndex, 'end_index_inclusive' => \true, 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), 'is_indented_block' => $token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])]; + continue; + } + if ($token->isGivenKind($methodModifierTokens)) { + $methodModifierIndents[$index] = $lastIndent; + continue; + } + if ($token->isGivenKind(\T_FUNCTION)) { + $x = $tokens->getPrevMeaningfulToken($index); + while (null !== $x && $tokens[$x]->isGivenKind($methodModifierTokens) && \array_key_exists($x, $methodModifierIndents)) { + $lastIndent = $methodModifierIndents[$x]; + $x = $tokens->getPrevMeaningfulToken($x); + } + $methodModifierIndents = []; + for ($endIndex = $index + 1, $max = \count($tokens); $endIndex < $max; ++$endIndex) { + if ($tokens[$endIndex]->equals('(')) { + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + continue; + } + if ($tokens[$endIndex]->equalsAny(['{', ';'])) { + break; + } + } + $scopes[] = ['type' => 'block_signature', 'skip' => \false, 'end_index' => $endIndex, 'end_index_inclusive' => \true, 'initial_indent' => $this->getLineIndentationWithBracesCompatibility($tokens, $index, $lastIndent), 'is_indented_block' => $token->isGivenKind([\T_EXTENDS, \T_IMPLEMENTS])]; + continue; + } + if ($token->isWhitespace() || $index > 0 && $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG)) { + $previousOpenTagContent = $tokens[$index - 1]->isGivenKind(\T_OPEN_TAG) ? Preg::replace('/\\S/', '', $tokens[$index - 1]->getContent()) : ''; + $content = $previousOpenTagContent . ($token->isWhitespace() ? $token->getContent() : ''); + if (!Preg::match('/\\R/', $content)) { + continue; + } + $nextToken = $tokens[$index + 1] ?? null; + if ($this->bracesFixerCompatibility && null !== $nextToken && $nextToken->isComment() && !$this->isCommentWithFixableIndentation($tokens, $index + 1)) { + continue; + } + if ('block' === $scopes[$currentScope]['type'] || 'block_signature' === $scopes[$currentScope]['type']) { + $indent = \false; + if ($scopes[$currentScope]['is_indented_block']) { + $firstNonWhitespaceTokenIndex = null; + $nextNewlineIndex = null; + for ($searchIndex = $index + 1, $max = \count($tokens); $searchIndex < $max; ++$searchIndex) { + $searchToken = $tokens[$searchIndex]; + if (!$searchToken->isWhitespace()) { + if (null === $firstNonWhitespaceTokenIndex) { + $firstNonWhitespaceTokenIndex = $searchIndex; + } + continue; + } + if (Preg::match('/\\R/', $searchToken->getContent())) { + $nextNewlineIndex = $searchIndex; + break; + } + } + $endIndex = $scopes[$currentScope]['end_index']; + if (!$scopes[$currentScope]['end_index_inclusive']) { + ++$endIndex; + } + if (null !== $firstNonWhitespaceTokenIndex && $firstNonWhitespaceTokenIndex < $endIndex || null !== $nextNewlineIndex && $nextNewlineIndex < $endIndex) { + $indent = \true; + } + } + $previousLineInitialIndent = $this->extractIndent($content); + if ($scopes[$currentScope]['skip']) { + $whitespaces = $previousLineInitialIndent; + } else { + $whitespaces = $scopes[$currentScope]['initial_indent'] . ($indent ? $this->whitespacesConfig->getIndent() : ''); + } + $content = Preg::replace('/(\\R+)\\h*$/', '$1' . $whitespaces, $content); + $previousLineNewIndent = $this->extractIndent($content); + } else { + $content = Preg::replace('/(\\R)' . $scopes[$currentScope]['initial_indent'] . '(\\h*)$/D', '$1' . $scopes[$currentScope]['new_indent'] . '$2', $content); + } + $lastIndent = $this->extractIndent($content); + if ('' !== $previousOpenTagContent) { + $content = Preg::replace("/^{$previousOpenTagContent}/", '', $content); + } + if ('' !== $content) { + $tokens->ensureWhitespaceAtIndex($index, 0, $content); + } elseif ($token->isWhitespace()) { + $tokens->clearAt($index); + } + if (null !== $nextToken && $nextToken->isComment()) { + $tokens[$index + 1] = new Token([$nextToken->getId(), Preg::replace('/(\\R)' . \preg_quote($previousLineInitialIndent, '/') . '(\\h*\\S+.*)/', '$1' . $previousLineNewIndent . '$2', $nextToken->getContent())]); + } + if ($token->isWhitespace()) { + continue; + } + } + if ($this->isNewLineToken($tokens, $index)) { + $lastIndent = $this->extractIndent($this->computeNewLineContent($tokens, $index)); + } + while ($index >= $scopes[$currentScope]['end_index']) { + \array_pop($scopes); + if ([] === $scopes) { + return; + } + --$currentScope; + } + if ($token->isComment() || $token->equalsAny([';', ',', '}', [\T_OPEN_TAG], [\T_CLOSE_TAG], [CT::T_ATTRIBUTE_CLOSE]])) { + continue; + } + if ('statement' !== $scopes[$currentScope]['type'] && 'block_signature' !== $scopes[$currentScope]['type']) { + $endIndex = $this->findStatementEndIndex($tokens, $index, $scopes[$currentScope]['end_index']); + if ($endIndex === $index) { + continue; + } + $scopes[] = ['type' => 'statement', 'skip' => \false, 'end_index' => $endIndex, 'end_index_inclusive' => \false, 'initial_indent' => $previousLineInitialIndent, 'new_indent' => $previousLineNewIndent]; + } + } + } + private function findStatementEndIndex(Tokens $tokens, int $index, int $parentScopeEndIndex) : int + { + $endIndex = null; + for ($searchEndIndex = $index; $searchEndIndex <= $parentScopeEndIndex; ++$searchEndIndex) { + $searchEndToken = $tokens[$searchEndIndex]; + if ($searchEndToken->equalsAny(['(', '{', [CT::T_ARRAY_SQUARE_BRACE_OPEN]])) { + if ($searchEndToken->equals('(')) { + $blockType = Tokens::BLOCK_TYPE_PARENTHESIS_BRACE; + } elseif ($searchEndToken->equals('{')) { + $blockType = Tokens::BLOCK_TYPE_CURLY_BRACE; + } else { + $blockType = Tokens::BLOCK_TYPE_ARRAY_SQUARE_BRACE; + } + $searchEndIndex = $tokens->findBlockEnd($blockType, $searchEndIndex); + continue; + } + if ($searchEndToken->equalsAny([';', ',', '}', [\T_CLOSE_TAG]])) { + $endIndex = $tokens->getPrevNonWhitespace($searchEndIndex); + break; + } + } + return $endIndex ?? $tokens->getPrevMeaningfulToken($parentScopeEndIndex); + } + /** + * @return array{int, bool} + */ + private function findCaseBlockEnd(Tokens $tokens, int $index) : array + { + for ($max = \count($tokens); $index < $max; ++$index) { + if ($tokens[$index]->isGivenKind(\T_SWITCH)) { + $braceIndex = $tokens->getNextMeaningfulToken($tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $tokens->getNextMeaningfulToken($index))); + if ($tokens[$braceIndex]->equals(':')) { + $index = $this->alternativeSyntaxAnalyzer->findAlternativeSyntaxBlockEnd($tokens, $index); + } else { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $braceIndex); + } + continue; + } + if ($tokens[$index]->equals('{')) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index); + continue; + } + if ($tokens[$index]->equalsAny([[\T_CASE], [\T_DEFAULT]])) { + return [$index, \true]; + } + if ($tokens[$index]->equalsAny(['}', [\T_ENDSWITCH]])) { + return [$tokens->getPrevNonWhitespace($index), \false]; + } + } + throw new \LogicException('End of case block not found.'); + } + private function getLineIndentationWithBracesCompatibility(Tokens $tokens, int $index, string $regularIndent) : string + { + if ($this->bracesFixerCompatibility && $tokens[$index]->isGivenKind(\T_OPEN_TAG) && Preg::match('/\\R/', $tokens[$index]->getContent()) && isset($tokens[$index + 1]) && $tokens[$index + 1]->isWhitespace() && Preg::match('/\\h+$/D', $tokens[$index + 1]->getContent())) { + return Preg::replace('/.*?(\\h+)$/sD', '$1', $tokens[$index + 1]->getContent()); + } + return $regularIndent; + } + /** + * Returns whether the token at given index is a comment whose indentation + * can be fixed. + * + * Indentation of a comment is not changed when the comment is part of a + * multi-line message whose lines are all single-line comments and at least + * one line has meaningful content. + */ + private function isCommentWithFixableIndentation(Tokens $tokens, int $index) : bool + { + if (!$tokens[$index]->isComment()) { + return \false; + } + if (\strncmp($tokens[$index]->getContent(), '/*', \strlen('/*')) === 0) { + return \true; + } + $indent = \preg_quote($this->whitespacesConfig->getIndent(), '~'); + if (Preg::match("~^(//|#)({$indent}.*)?\$~", $tokens[$index]->getContent())) { + return \false; + } + $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, int $index, bool $after) : ?int + { + $siblingIndex = $index; + do { + if ($after) { + $siblingIndex = $tokens->getNextTokenOfKind($siblingIndex, [[\T_COMMENT]]); + } else { + $siblingIndex = $tokens->getPrevTokenOfKind($siblingIndex, [[\T_COMMENT]]); + } + if (null === $siblingIndex) { + return null; + } + } while (\strncmp($tokens[$siblingIndex]->getContent(), '/*', \strlen('/*')) === 0); + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php new file mode 100644 index 00000000000..36cbd11c2a1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypeDeclarationSpacesFixer.php @@ -0,0 +1,147 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\AllowedValueSubset; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\FunctionsAnalyzer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @author Dariusz Rumiński + * @author John Paul E. Balandan, CPA + */ +final class TypeDeclarationSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('Ensure single space between a variable and its type declaration in function arguments and properties.', [new CodeSample(' (string) $c; + } +} +', ['elements' => ['function']]), new CodeSample(' ['property']])]); + } + public function isCandidate(Tokens $tokens) : bool + { + return $tokens->isAnyTokenKindsFound(\array_merge(Token::getClassyTokenKinds(), [\T_FN, \T_FUNCTION])); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('elements', 'Structural elements where the spacing after the type declaration should be fixed.'))->setAllowedTypes(['array'])->setAllowedValues([new AllowedValueSubset(['function', 'property'])])->setDefault(['function', 'property'])->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $functionsAnalyzer = new FunctionsAnalyzer(); + foreach (\array_reverse($this->getElements($tokens), \true) as $index => $type) { + if ('property' === $type && \in_array('property', $this->configuration['elements'], \true)) { + $this->ensureSingleSpaceAtPropertyTypehint($tokens, $index); + continue; + } + if ('method' === $type && \in_array('function', $this->configuration['elements'], \true)) { + $this->ensureSingleSpaceAtFunctionArgumentTypehint($functionsAnalyzer, $tokens, $index); + // implicit continue; + } + } + } + /** + * @return array + * + * @phpstan-return array + */ + private function getElements(Tokens $tokens) : array + { + $tokensAnalyzer = new TokensAnalyzer($tokens); + $elements = \array_map(static function (array $element) : string { + return $element['type']; + }, \array_filter($tokensAnalyzer->getClassyElements(), static function (array $element) : bool { + return \in_array($element['type'], ['method', 'property'], \true); + })); + foreach ($tokens as $index => $token) { + if ($token->isGivenKind(\T_FN) || $token->isGivenKind(\T_FUNCTION) && !isset($elements[$index])) { + $elements[$index] = 'method'; + } + } + return $elements; + } + private function ensureSingleSpaceAtFunctionArgumentTypehint(FunctionsAnalyzer $functionsAnalyzer, Tokens $tokens, int $index) : void + { + foreach (\array_reverse($functionsAnalyzer->getFunctionArguments($tokens, $index)) as $argumentInfo) { + $argumentType = $argumentInfo->getTypeAnalysis(); + if (null === $argumentType) { + continue; + } + $tokens->ensureWhitespaceAtIndex($argumentType->getEndIndex() + 1, 0, ' '); + } + } + private function ensureSingleSpaceAtPropertyTypehint(Tokens $tokens, int $index) : void + { + $propertyIndex = $index; + $propertyModifiers = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_STATIC, \T_VAR]; + if (\defined('T_READONLY')) { + $propertyModifiers[] = \T_READONLY; + // @TODO drop condition when PHP 8.1 is supported + } + do { + $index = $tokens->getPrevMeaningfulToken($index); + } while (!$tokens[$index]->isGivenKind($propertyModifiers)); + $propertyType = $this->collectTypeAnalysis($tokens, $index, $propertyIndex); + if (null === $propertyType) { + return; + } + $tokens->ensureWhitespaceAtIndex($propertyType->getEndIndex() + 1, 0, ' '); + } + private function collectTypeAnalysis(Tokens $tokens, int $startIndex, int $endIndex) : ?TypeAnalysis + { + $type = ''; + $typeStartIndex = $tokens->getNextMeaningfulToken($startIndex); + $typeEndIndex = $typeStartIndex; + for ($i = $typeStartIndex; $i < $endIndex; ++$i) { + if ($tokens[$i]->isWhitespace() || $tokens[$i]->isComment()) { + continue; + } + $type .= $tokens[$i]->getContent(); + $typeEndIndex = $i; + } + return '' !== $type ? new TypeAnalysis($type, $typeStartIndex, $typeEndIndex) : null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php new file mode 100644 index 00000000000..45645e52084 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/Whitespace/TypesSpacesFixer.php @@ -0,0 +1,108 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer\Whitespace; + +use PhpCsFixer\AbstractFixer; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolver; +use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface; +use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; +use PhpCsFixer\FixerDefinition\CodeSample; +use PhpCsFixer\FixerDefinition\FixerDefinition; +use PhpCsFixer\FixerDefinition\FixerDefinitionInterface; +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 TypesSpacesFixer extends AbstractFixer implements ConfigurableFixerInterface +{ + public function configure(array $configuration) : void + { + parent::configure($configuration); + if (!isset($this->configuration['space_multiple_catch'])) { + $this->configuration['space_multiple_catch'] = $this->configuration['space']; + } + } + public function getDefinition() : FixerDefinitionInterface + { + return new FixerDefinition('A single space or none should be around union type and intersection type operators.', [new CodeSample(" 'single']), new VersionSpecificCodeSample("isAnyTokenKindsFound([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION]); + } + protected function createConfigurationDefinition() : FixerConfigurationResolverInterface + { + return new FixerConfigurationResolver([(new FixerOptionBuilder('space', 'Spacing to apply around union type and intersection type operators.'))->setAllowedValues(['none', 'single'])->setDefault('none')->getOption(), (new FixerOptionBuilder('space_multiple_catch', 'Spacing to apply around type operator when catching exceptions of multiple types, use `null` to follow the value configured for `space`.'))->setAllowedValues(['none', 'single', null])->setDefault(null)->getOption()]); + } + protected function applyFix(\SplFileInfo $file, Tokens $tokens) : void + { + $tokenCount = $tokens->count() - 1; + for ($index = 0; $index < $tokenCount; ++$index) { + if ($tokens[$index]->isGivenKind([CT::T_TYPE_ALTERNATION, CT::T_TYPE_INTERSECTION])) { + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space']); + continue; + } + if ($tokens[$index]->isGivenKind(\T_CATCH)) { + while (\true) { + $index = $tokens->getNextTokenOfKind($index, [')', [CT::T_TYPE_ALTERNATION]]); + if ($tokens[$index]->equals(')')) { + break; + } + $tokenCount += $this->fixSpacing($tokens, $index, 'single' === $this->configuration['space_multiple_catch']); + } + // implicit continue + } + } + } + private function fixSpacing(Tokens $tokens, int $index, bool $singleSpace) : int + { + if (!$singleSpace) { + $this->ensureNoSpace($tokens, $index + 1); + $this->ensureNoSpace($tokens, $index - 1); + return 0; + } + $addedTokenCount = 0; + $addedTokenCount += $this->ensureSingleSpace($tokens, $index + 1, 0); + $addedTokenCount += $this->ensureSingleSpace($tokens, $index - 1, 1); + return $addedTokenCount; + } + private function ensureSingleSpace(Tokens $tokens, int $index, int $offset) : int + { + if (!$tokens[$index]->isWhitespace()) { + $tokens->insertSlices([$index + $offset => new Token([\T_WHITESPACE, ' '])]); + return 1; + } + if (' ' !== $tokens[$index]->getContent() && !Preg::match('/\\R/', $tokens[$index]->getContent())) { + $tokens[$index] = new Token([\T_WHITESPACE, ' ']); + } + return 0; + } + private function ensureNoSpace(Tokens $tokens, int $index) : void + { + if ($tokens[$index]->isWhitespace() && !Preg::match('/\\R/', $tokens[$index]->getContent())) { + $tokens->clearAt($index); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php new file mode 100644 index 00000000000..4540f745611 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Fixer/WhitespacesAwareFixerInterface.php @@ -0,0 +1,22 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Fixer; + +use PhpCsFixer\WhitespacesFixerConfig; +/** + * @author Dariusz Rumiński + */ +interface WhitespacesAwareFixerInterface extends \PhpCsFixer\Fixer\FixerInterface +{ + public function setWhitespacesConfig(WhitespacesFixerConfig $config) : void; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php new file mode 100644 index 00000000000..fa85703cb7d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOption.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @internal + */ +final class AliasedFixerOption implements \PhpCsFixer\FixerConfiguration\FixerOptionInterface +{ + /** + * @var \PhpCsFixer\FixerConfiguration\FixerOptionInterface + */ + private $fixerOption; + /** + * @var string + */ + private $alias; + public function __construct(\PhpCsFixer\FixerConfiguration\FixerOptionInterface $fixerOption, string $alias) + { + $this->fixerOption = $fixerOption; + $this->alias = $alias; + } + public function getAlias() : string + { + return $this->alias; + } + public function getName() : string + { + return $this->fixerOption->getName(); + } + public function getDescription() : string + { + return $this->fixerOption->getDescription(); + } + public function hasDefault() : bool + { + return $this->fixerOption->hasDefault(); + } + public function getDefault() + { + return $this->fixerOption->getDefault(); + } + public function getAllowedTypes() : ?array + { + return $this->fixerOption->getAllowedTypes(); + } + public function getAllowedValues() : ?array + { + return $this->fixerOption->getAllowedValues(); + } + public function getNormalizer() : ?\Closure + { + return $this->fixerOption->getNormalizer(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php new file mode 100644 index 00000000000..e4458f8f4f5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AliasedFixerOptionBuilder.php @@ -0,0 +1,68 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +/** + * @author ntzm + * + * @internal + */ +final class AliasedFixerOptionBuilder +{ + /** + * @var \PhpCsFixer\FixerConfiguration\FixerOptionBuilder + */ + private $optionBuilder; + /** + * @var string + */ + private $alias; + public function __construct(\PhpCsFixer\FixerConfiguration\FixerOptionBuilder $optionBuilder, string $alias) + { + $this->optionBuilder = $optionBuilder; + $this->alias = $alias; + } + /** + * @param mixed $default + */ + public function setDefault($default) : self + { + $this->optionBuilder->setDefault($default); + return $this; + } + /** + * @param list $allowedTypes + */ + public function setAllowedTypes(array $allowedTypes) : self + { + $this->optionBuilder->setAllowedTypes($allowedTypes); + return $this; + } + /** + * @param list $allowedValues + */ + public function setAllowedValues(array $allowedValues) : self + { + $this->optionBuilder->setAllowedValues($allowedValues); + return $this; + } + public function setNormalizer(\Closure $normalizer) : self + { + $this->optionBuilder->setNormalizer($normalizer); + return $this; + } + public function getOption() : \PhpCsFixer\FixerConfiguration\AliasedFixerOption + { + return new \PhpCsFixer\FixerConfiguration\AliasedFixerOption($this->optionBuilder->getOption(), $this->alias); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php new file mode 100644 index 00000000000..acbd75314f1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/AllowedValueSubset.php @@ -0,0 +1,56 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +/** + * @internal + */ +final class AllowedValueSubset +{ + /** + * @var list + */ + private $allowedValues; + /** + * @param list $allowedValues + */ + public function __construct(array $allowedValues) + { + $this->allowedValues = $allowedValues; + \sort($this->allowedValues, \SORT_FLAG_CASE | \SORT_STRING); + } + /** + * Checks whether the given values are a subset of the allowed ones. + * + * @param mixed $values the value to validate + */ + public function __invoke($values) : bool + { + if (!\is_array($values)) { + return \false; + } + foreach ($values as $value) { + if (!\in_array($value, $this->allowedValues, \true)) { + return \false; + } + } + return \true; + } + /** + * @return list + */ + public function getAllowedValues() : array + { + return $this->allowedValues; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php new file mode 100644 index 00000000000..57c2a3850ba --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOption.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +final class DeprecatedFixerOption implements \PhpCsFixer\FixerConfiguration\DeprecatedFixerOptionInterface +{ + /** + * @var \PhpCsFixer\FixerConfiguration\FixerOptionInterface + */ + private $option; + /** + * @var string + */ + private $deprecationMessage; + public function __construct(\PhpCsFixer\FixerConfiguration\FixerOptionInterface $option, string $deprecationMessage) + { + $this->option = $option; + $this->deprecationMessage = $deprecationMessage; + } + public function getName() : string + { + return $this->option->getName(); + } + public function getDescription() : string + { + return $this->option->getDescription(); + } + public function hasDefault() : bool + { + return $this->option->hasDefault(); + } + public function getDefault() + { + return $this->option->getDefault(); + } + public function getAllowedTypes() : ?array + { + return $this->option->getAllowedTypes(); + } + public function getAllowedValues() : ?array + { + return $this->option->getAllowedValues(); + } + public function getNormalizer() : ?\Closure + { + return $this->option->getNormalizer(); + } + public function getDeprecationMessage() : string + { + return $this->deprecationMessage; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php new file mode 100644 index 00000000000..d2f5e02dd46 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/DeprecatedFixerOptionInterface.php @@ -0,0 +1,18 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +interface DeprecatedFixerOptionInterface extends \PhpCsFixer\FixerConfiguration\FixerOptionInterface +{ + public function getDeprecationMessage() : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php new file mode 100644 index 00000000000..ccff5fe475e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolver.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +use PhpCsFixer\Utils; +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +use ECSPrefix202307\Symfony\Component\OptionsResolver\OptionsResolver; +final class FixerConfigurationResolver implements \PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface +{ + /** + * @var list + */ + private $options = []; + /** + * @var list + */ + private $registeredNames = []; + /** + * @param iterable $options + */ + public function __construct(iterable $options) + { + foreach ($options as $option) { + $this->addOption($option); + } + if (0 === \count($this->registeredNames)) { + throw new \LogicException('Options cannot be empty.'); + } + } + public function getOptions() : array + { + return $this->options; + } + public function resolve(array $configuration) : array + { + $resolver = new OptionsResolver(); + foreach ($this->options as $option) { + $name = $option->getName(); + if ($option instanceof \PhpCsFixer\FixerConfiguration\AliasedFixerOption) { + $alias = $option->getAlias(); + if (\array_key_exists($alias, $configuration)) { + if (\array_key_exists($name, $configuration)) { + throw new InvalidOptionsException(\sprintf('Aliased option "%s"/"%s" is passed multiple times.', $name, $alias)); + } + Utils::triggerDeprecation(new \RuntimeException(\sprintf('Option "%s" is deprecated, use "%s" instead.', $alias, $name))); + $configuration[$name] = $configuration[$alias]; + unset($configuration[$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($configuration); + } + /** + * @throws \LogicException when the option is already defined + */ + private function addOption(\PhpCsFixer\FixerConfiguration\FixerOptionInterface $option) : void + { + $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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php new file mode 100644 index 00000000000..bc288d10519 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerConfigurationResolverInterface.php @@ -0,0 +1,27 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +interface FixerConfigurationResolverInterface +{ + /** + * @return list + */ + public function getOptions() : array; + /** + * @param array $configuration + * + * @return array + */ + public function resolve(array $configuration) : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php new file mode 100644 index 00000000000..016591f5b3a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOption.php @@ -0,0 +1,122 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +final class FixerOption implements \PhpCsFixer\FixerConfiguration\FixerOptionInterface +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $description; + /** + * @var bool + */ + private $isRequired; + /** + * @var mixed + */ + private $default; + /** + * @var null|list + */ + private $allowedTypes; + /** + * @var null|list + */ + private $allowedValues; + /** + * @var null|\Closure + */ + private $normalizer; + /** + * @param mixed $default + * @param null|list $allowedTypes + * @param null|list $allowedValues + */ + public function __construct(string $name, string $description, bool $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() : string + { + return $this->name; + } + public function getDescription() : string + { + return $this->description; + } + public function hasDefault() : bool + { + return !$this->isRequired; + } + public function getDefault() + { + if (!$this->hasDefault()) { + throw new \LogicException('No default value defined.'); + } + return $this->default; + } + public function getAllowedTypes() : ?array + { + return $this->allowedTypes; + } + public function getAllowedValues() : ?array + { + return $this->allowedValues; + } + public function getNormalizer() : ?\Closure + { + return $this->normalizer; + } + /** + * Unbinds the given closure to avoid memory leaks. + * + * The closures provided to this class were probably defined in a fixer + * class and thus bound to it by default. The configuration will then be + * stored in {@see AbstractFixer::$configurationDefinition}, leading to the + * following cyclic reference: + * + * fixer -> configuration definition -> options -> closures -> fixer + * + * This cyclic reference prevent the garbage collector to free memory as + * all elements are still referenced. + * + * See {@see https://bugs.php.net/bug.php?id=69639 Bug #69639} for details. + */ + private function unbind(\Closure $closure) : \Closure + { + return $closure->bindTo(null); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php new file mode 100644 index 00000000000..cf9b16d3d00 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionBuilder.php @@ -0,0 +1,109 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +final class FixerOptionBuilder +{ + /** + * @var string + */ + private $name; + /** + * @var string + */ + private $description; + /** + * @var mixed + */ + private $default; + /** + * @var bool + */ + private $isRequired = \true; + /** + * @var null|list + */ + private $allowedTypes; + /** + * @var null|list + */ + private $allowedValues; + /** + * @var null|\Closure + */ + private $normalizer; + /** + * @var null|string + */ + private $deprecationMessage; + public function __construct(string $name, string $description) + { + $this->name = $name; + $this->description = $description; + } + /** + * @param mixed $default + * + * @return $this + */ + public function setDefault($default) : self + { + $this->default = $default; + $this->isRequired = \false; + return $this; + } + /** + * @param list $allowedTypes + * + * @return $this + */ + public function setAllowedTypes(array $allowedTypes) : self + { + $this->allowedTypes = $allowedTypes; + return $this; + } + /** + * @param list $allowedValues + * + * @return $this + */ + public function setAllowedValues(array $allowedValues) : self + { + $this->allowedValues = $allowedValues; + return $this; + } + /** + * @return $this + */ + public function setNormalizer(\Closure $normalizer) : self + { + $this->normalizer = $normalizer; + return $this; + } + /** + * @return $this + */ + public function setDeprecationMessage(?string $deprecationMessage) : self + { + $this->deprecationMessage = $deprecationMessage; + return $this; + } + public function getOption() : \PhpCsFixer\FixerConfiguration\FixerOptionInterface + { + $option = new \PhpCsFixer\FixerConfiguration\FixerOption($this->name, $this->description, $this->isRequired, $this->default, $this->allowedTypes, $this->allowedValues, $this->normalizer); + if (null !== $this->deprecationMessage) { + $option = new \PhpCsFixer\FixerConfiguration\DeprecatedFixerOption($option, $this->deprecationMessage); + } + return $option; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php new file mode 100644 index 00000000000..c11e1a5782f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/FixerOptionInterface.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +interface FixerOptionInterface +{ + public function getName() : string; + public function getDescription() : string; + public function hasDefault() : bool; + /** + * @return mixed + * + * @throws \LogicException when no default value is defined + */ + public function getDefault(); + /** + * @return null|list + */ + public function getAllowedTypes() : ?array; + /** + * @return null|list + */ + public function getAllowedValues() : ?array; + public function getNormalizer() : ?\Closure; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php new file mode 100644 index 00000000000..1d62e15d27a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerConfiguration/InvalidOptionsForEnvException.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerConfiguration; + +use ECSPrefix202307\Symfony\Component\OptionsResolver\Exception\InvalidOptionsException; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class InvalidOptionsForEnvException extends InvalidOptionsException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php new file mode 100644 index 00000000000..05ffe899000 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSample.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +final class CodeSample implements \PhpCsFixer\FixerDefinition\CodeSampleInterface +{ + /** + * @var string + */ + private $code; + /** + * @var null|array + */ + private $configuration; + /** + * @param null|array $configuration + */ + public function __construct(string $code, ?array $configuration = null) + { + $this->code = $code; + $this->configuration = $configuration; + } + public function getCode() : string + { + return $this->code; + } + public function getConfiguration() : ?array + { + return $this->configuration; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php new file mode 100644 index 00000000000..d0529c3fb89 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/CodeSampleInterface.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +interface CodeSampleInterface +{ + public function getCode() : string; + /** + * @return null|array + */ + public function getConfiguration() : ?array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php new file mode 100644 index 00000000000..8f7fd09647b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSample.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FileSpecificCodeSample implements \PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface +{ + /** + * @var \PhpCsFixer\FixerDefinition\CodeSampleInterface + */ + private $codeSample; + /** + * @var \SplFileInfo + */ + private $splFileInfo; + /** + * @param null|array $configuration + */ + public function __construct(string $code, \SplFileInfo $splFileInfo, ?array $configuration = null) + { + $this->codeSample = new \PhpCsFixer\FixerDefinition\CodeSample($code, $configuration); + $this->splFileInfo = $splFileInfo; + } + public function getCode() : string + { + return $this->codeSample->getCode(); + } + public function getConfiguration() : ?array + { + return $this->codeSample->getConfiguration(); + } + public function getSplFileInfo() : \SplFileInfo + { + return $this->splFileInfo; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php new file mode 100644 index 00000000000..f49c6f4edde --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FileSpecificCodeSampleInterface.php @@ -0,0 +1,23 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +interface FileSpecificCodeSampleInterface extends \PhpCsFixer\FixerDefinition\CodeSampleInterface +{ + public function getSplFileInfo() : \SplFileInfo; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php new file mode 100644 index 00000000000..8b47230f6a3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinition.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +final class FixerDefinition implements \PhpCsFixer\FixerDefinition\FixerDefinitionInterface +{ + /** + * @var string + */ + private $summary; + /** + * @var list + */ + private $codeSamples; + /** + * Description of Fixer and benefit of using it. + * @var string|null + */ + private $description; + /** + * Description why Fixer is risky. + * @var string|null + */ + private $riskyDescription; + /** + * @param list $codeSamples array of samples, where single sample is [code, configuration] + * @param null|string $riskyDescription null for non-risky fixer + */ + public function __construct(string $summary, array $codeSamples, ?string $description = null, ?string $riskyDescription = null) + { + $this->summary = $summary; + $this->codeSamples = $codeSamples; + $this->description = $description; + $this->riskyDescription = $riskyDescription; + } + public function getSummary() : string + { + return $this->summary; + } + public function getDescription() : ?string + { + return $this->description; + } + public function getRiskyDescription() : ?string + { + return $this->riskyDescription; + } + public function getCodeSamples() : array + { + return $this->codeSamples; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php new file mode 100644 index 00000000000..431bf300af7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/FixerDefinitionInterface.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Dariusz Rumiński + */ +interface FixerDefinitionInterface +{ + public function getSummary() : string; + public function getDescription() : ?string; + /** + * @return null|string null for non-risky fixer + */ + public function getRiskyDescription() : ?string; + /** + * Array of samples, where single sample is [code, configuration]. + * + * @return list + */ + public function getCodeSamples() : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php new file mode 100644 index 00000000000..89bc73432bc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSample.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +final class VersionSpecificCodeSample implements \PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface +{ + /** + * @var \PhpCsFixer\FixerDefinition\CodeSampleInterface + */ + private $codeSample; + /** + * @var \PhpCsFixer\FixerDefinition\VersionSpecificationInterface + */ + private $versionSpecification; + /** + * @param null|array $configuration + */ + public function __construct(string $code, \PhpCsFixer\FixerDefinition\VersionSpecificationInterface $versionSpecification, ?array $configuration = null) + { + $this->codeSample = new \PhpCsFixer\FixerDefinition\CodeSample($code, $configuration); + $this->versionSpecification = $versionSpecification; + } + public function getCode() : string + { + return $this->codeSample->getCode(); + } + public function getConfiguration() : ?array + { + return $this->codeSample->getConfiguration(); + } + public function isSuitableFor(int $version) : bool + { + return $this->versionSpecification->isSatisfiedBy($version); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php new file mode 100644 index 00000000000..4e1f631c96d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificCodeSampleInterface.php @@ -0,0 +1,21 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Moeller + */ +interface VersionSpecificCodeSampleInterface extends \PhpCsFixer\FixerDefinition\CodeSampleInterface +{ + public function isSuitableFor(int $version) : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php new file mode 100644 index 00000000000..15b4ff11304 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecification.php @@ -0,0 +1,63 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +final class VersionSpecification implements \PhpCsFixer\FixerDefinition\VersionSpecificationInterface +{ + /** + * @var null|int<1, max> + */ + private $minimum; + /** + * @var null|int<1, max> + */ + private $maximum; + /** + * @param null|int<1, max> $minimum + * @param null|int<1, max> $maximum + * + * @throws \InvalidArgumentException + */ + public function __construct(?int $minimum = null, ?int $maximum = null) + { + if (null === $minimum && null === $maximum) { + throw new \InvalidArgumentException('Minimum or maximum need to be specified.'); + } + if (null !== $minimum && 1 > $minimum) { + throw new \InvalidArgumentException('Minimum needs to be either null or an integer greater than 0.'); + } + if (null !== $maximum) { + if (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(int $version) : bool + { + if (null !== $this->minimum && $version < $this->minimum) { + return \false; + } + if (null !== $this->maximum && $version > $this->maximum) { + return \false; + } + return \true; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php new file mode 100644 index 00000000000..cc3ae08cd2b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerDefinition/VersionSpecificationInterface.php @@ -0,0 +1,21 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\FixerDefinition; + +/** + * @author Andreas Möller + */ +interface VersionSpecificationInterface +{ + public function isSatisfiedBy(int $version) : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php b/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php new file mode 100644 index 00000000000..0d9b6d74c34 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerFactory.php @@ -0,0 +1,193 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +use PhpCsFixer\Fixer\ConfigurableFixerInterface; +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Fixer\WhitespacesAwareFixerInterface; +use PhpCsFixer\RuleSet\RuleSetInterface; +use ECSPrefix202307\Symfony\Component\Finder\Finder as SymfonyFinder; +use ECSPrefix202307\Symfony\Component\Finder\SplFileInfo; +/** + * Class provides a way to create a group of fixers. + * + * Fixers may be registered (made the factory aware of them) by + * registering a custom fixer and default, built in fixers. + * Then, one can attach Config instance to fixer instances. + * + * Finally factory creates a ready to use group of fixers. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerFactory +{ + /** + * @var \PhpCsFixer\FixerNameValidator + */ + private $nameValidator; + /** + * @var list + */ + private $fixers = []; + /** + * @var array + */ + private $fixersByName = []; + public function __construct() + { + $this->nameValidator = new \PhpCsFixer\FixerNameValidator(); + } + public function setWhitespacesConfig(\PhpCsFixer\WhitespacesFixerConfig $config) : self + { + foreach ($this->fixers as $fixer) { + if ($fixer instanceof WhitespacesAwareFixerInterface) { + $fixer->setWhitespacesConfig($config); + } + } + return $this; + } + /** + * @return list + */ + public function getFixers() : array + { + $this->fixers = \PhpCsFixer\Utils::sortFixers($this->fixers); + return $this->fixers; + } + /** + * @return $this + */ + public function registerBuiltInFixers() : self + { + static $builtInFixers = null; + if (null === $builtInFixers) { + $builtInFixers = []; + /** @var SplFileInfo $file */ + foreach (SymfonyFinder::create()->files()->in(__DIR__ . '/Fixer')->name('*Fixer.php')->depth(1) as $file) { + $relativeNamespace = $file->getRelativePath(); + $fixerClass = 'PhpCsFixer\\Fixer\\' . ('' !== $relativeNamespace ? $relativeNamespace . '\\' : '') . $file->getBasename('.php'); + $builtInFixers[] = $fixerClass; + } + } + foreach ($builtInFixers as $class) { + $this->registerFixer(new $class(), \false); + } + return $this; + } + /** + * @param FixerInterface[] $fixers + * + * @return $this + */ + public function registerCustomFixers(iterable $fixers) : self + { + foreach ($fixers as $fixer) { + $this->registerFixer($fixer, \true); + } + return $this; + } + /** + * @return $this + */ + public function registerFixer(FixerInterface $fixer, bool $isCustom) : self + { + $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; + } + /** + * Apply RuleSet on fixers to filter out all unwanted fixers. + * + * @return $this + */ + public function useRuleSet(RuleSetInterface $ruleSet) : self + { + $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 (\count($config) < 1) { + 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; + } + /** + * Check if fixer exists. + */ + public function hasRule(string $name) : bool + { + return isset($this->fixersByName[$name]); + } + /** + * @return string[] + */ + private function getFixersConflicts(FixerInterface $fixer) : array + { + static $conflictMap = ['blank_lines_before_namespace' => ['no_blank_lines_before_namespace', 'single_blank_line_before_namespace'], '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] : []; + } + /** + * @param array $fixerConflicts + */ + private function generateConflictMessage(array $fixerConflicts) : string + { + $message = 'Rule contains conflicting fixers:'; + $report = []; + foreach ($fixerConflicts as $fixer => $fixers) { + // filter mutual conflicts + $report[$fixer] = \array_filter($fixers, static function (string $candidate) use($report, $fixer) : bool { + return !\array_key_exists($candidate, $report) || !\in_array($fixer, $report[$candidate], \true); + }); + if (\count($report[$fixer]) > 0) { + $message .= \sprintf("\n- \"%s\" with %s", $fixer, \PhpCsFixer\Utils::naturalLanguageJoin($report[$fixer])); + } + } + return $message; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php b/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php new file mode 100644 index 00000000000..9c6a921c1aa --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerFileProcessedEvent.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use ECSPrefix202307\Symfony\Contracts\EventDispatcher\Event; +/** + * Event that is fired when file was processed by Fixer. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerFileProcessedEvent extends Event +{ + /** + * Event name. + */ + public const NAME = 'fixer.file_processed'; + public const STATUS_INVALID = 1; + public const STATUS_SKIPPED = 2; + public const STATUS_NO_CHANGES = 3; + public const STATUS_FIXED = 4; + public const STATUS_EXCEPTION = 5; + public const STATUS_LINT = 6; + /** + * @var int + */ + private $status; + public function __construct(int $status) + { + $this->status = $status; + } + public function getStatus() : int + { + return $this->status; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php b/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php new file mode 100644 index 00000000000..ef96d01f00d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/FixerNameValidator.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class FixerNameValidator +{ + public function isValid(string $name, bool $isCustom) : bool + { + if (!$isCustom) { + return \PhpCsFixer\Preg::match('/^[a-z][a-z0-9_]*$/', $name); + } + return \PhpCsFixer\Preg::match('/^[A-Z][a-zA-Z0-9]*\\/[a-z][a-z0-9_]*$/', $name); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php b/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php new file mode 100644 index 00000000000..03a563561f7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Indicator/PhpUnitTestCaseIndicator.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Indicator; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class PhpUnitTestCaseIndicator +{ + public function isPhpUnitClass(Tokens $tokens, int $index) : bool + { + 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 (!$tokens[$index]->isGivenKind(\T_STRING)) { + return \false; + } + $extendsIndex = $tokens->getNextTokenOfKind($index, ['{', [\T_EXTENDS]]); + if (!$tokens[$extendsIndex]->isGivenKind(\T_EXTENDS)) { + return \false; + } + if (Preg::match('/(?:Test|TestCase)$/', $tokens[$index]->getContent())) { + return \true; + } + while (null !== ($index = $tokens->getNextMeaningfulToken($index))) { + if ($tokens[$index]->equals('{')) { + break; + // end of class signature + } + if (!$tokens[$index]->isGivenKind(\T_STRING)) { + continue; + // not part of extends nor part of implements; so continue + } + if (Preg::match('/(?:Test|TestCase)(?:Interface)?$/', $tokens[$index]->getContent())) { + return \true; + } + } + return \false; + } + /** + * Returns an indices of PHPUnit classes in reverse appearance order. + * Order is important - it's reverted, so if we inject tokens into collection, + * we do it for bottom of file first, and then to the top of the file, so we + * mitigate risk of not visiting whole collcetion (final indices). + * + * @return iterable array of [int start, int end] indices from later to earlier classes + */ + public function findPhpUnitClasses(Tokens $tokens) : iterable + { + for ($index = $tokens->count() - 1; $index > 0; --$index) { + if (!$tokens[$index]->isGivenKind(\T_CLASS) || !$this->isPhpUnitClass($tokens, $index)) { + continue; + } + $startIndex = $tokens->getNextTokenOfKind($index, ['{']); + if (null === $startIndex) { + return; + } + $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex); + (yield [$startIndex, $endIndex]); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php new file mode 100644 index 00000000000..93b125ef468 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/CachingLinter.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class CachingLinter implements \PhpCsFixer\Linter\LinterInterface +{ + /** + * @var \PhpCsFixer\Linter\LinterInterface + */ + private $sublinter; + /** + * @var array + */ + private $cache = []; + public function __construct(\PhpCsFixer\Linter\LinterInterface $linter) + { + $this->sublinter = $linter; + } + public function isAsync() : bool + { + return $this->sublinter->isAsync(); + } + public function lintFile(string $path) : \PhpCsFixer\Linter\LintingResultInterface + { + $checksum = \md5(\file_get_contents($path)); + if (!isset($this->cache[$checksum])) { + $this->cache[$checksum] = $this->sublinter->lintFile($path); + } + return $this->cache[$checksum]; + } + public function lintSource(string $source) : \PhpCsFixer\Linter\LintingResultInterface + { + $checksum = \md5($source); + if (!isset($this->cache[$checksum])) { + $this->cache[$checksum] = $this->sublinter->lintSource($source); + } + return $this->cache[$checksum]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php new file mode 100644 index 00000000000..7bf75537984 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/Linter.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * Handle PHP code linting process. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class Linter implements \PhpCsFixer\Linter\LinterInterface +{ + /** + * @var \PhpCsFixer\Linter\LinterInterface + */ + private $subLinter; + public function __construct() + { + $this->subLinter = new \PhpCsFixer\Linter\TokenizerLinter(); + } + public function isAsync() : bool + { + return $this->subLinter->isAsync(); + } + public function lintFile(string $path) : \PhpCsFixer\Linter\LintingResultInterface + { + return $this->subLinter->lintFile($path); + } + public function lintSource(string $source) : \PhpCsFixer\Linter\LintingResultInterface + { + return $this->subLinter->lintSource($source); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php new file mode 100644 index 00000000000..a4f2885c944 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/LinterInterface.php @@ -0,0 +1,31 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * Interface for PHP code linting process manager. + * + * @author Dariusz Rumiński + */ +interface LinterInterface +{ + public function isAsync() : bool; + /** + * Lint PHP file. + */ + public function lintFile(string $path) : \PhpCsFixer\Linter\LintingResultInterface; + /** + * Lint PHP code. + */ + public function lintSource(string $source) : \PhpCsFixer\Linter\LintingResultInterface; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php new file mode 100644 index 00000000000..9ea719ffa45 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + */ +class LintingException extends \RuntimeException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php new file mode 100644 index 00000000000..73667c3a01f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/LintingResultInterface.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + */ +interface LintingResultInterface +{ + /** + * Check if linting process was successful and raise LintingException if not. + */ + public function check() : void; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php new file mode 100644 index 00000000000..1b4882534f6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinter.php @@ -0,0 +1,134 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\FileRemoval; +use ECSPrefix202307\Symfony\Component\Filesystem\Exception\IOException; +use ECSPrefix202307\Symfony\Component\Process\PhpExecutableFinder; +use ECSPrefix202307\Symfony\Component\Process\Process; +/** + * Handle PHP code linting using separated process of `php -l _file_`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLinter implements \PhpCsFixer\Linter\LinterInterface +{ + /** + * @var \PhpCsFixer\FileRemoval + */ + private $fileRemoval; + /** + * @var \PhpCsFixer\Linter\ProcessLinterProcessBuilder + */ + private $processBuilder; + /** + * Temporary file for code linting. + * + * @var null|string + */ + private $temporaryFile; + /** + * @param null|string $executable PHP executable, null for autodetection + */ + public function __construct(?string $executable = null) + { + if (null === $executable) { + $executableFinder = new PhpExecutableFinder(); + $executable = $executableFinder->find(\false); + if (\false === $executable) { + throw new \PhpCsFixer\Linter\UnavailableLinterException('Cannot find PHP executable.'); + } + if ('phpdbg' === \PHP_SAPI) { + if (\strpos($executable, 'phpdbg') === \false) { + throw new \PhpCsFixer\Linter\UnavailableLinterException('Automatically found PHP executable is non-standard phpdbg. Could not find proper PHP executable.'); + } + // automatically found executable is `phpdbg`, let us try to fallback to regular `php` + $executable = \str_replace('phpdbg', 'php', $executable); + if (!\is_executable($executable)) { + throw new \PhpCsFixer\Linter\UnavailableLinterException('Automatically found PHP executable is phpdbg. Could not find proper PHP executable.'); + } + } + } + $this->processBuilder = new \PhpCsFixer\Linter\ProcessLinterProcessBuilder($executable); + $this->fileRemoval = new FileRemoval(); + } + public function __destruct() + { + if (null !== $this->temporaryFile) { + $this->fileRemoval->delete($this->temporaryFile); + } + } + /** + * This class is not intended to be serialized, + * and cannot be deserialized (see __wakeup method). + */ + public function __sleep() : array + { + throw new \BadMethodCallException('Cannot serialize ' . __CLASS__); + } + /** + * Disable the deserialization of the class to prevent attacker executing + * code by leveraging the __destruct method. + * + * @see https://owasp.org/www-community/vulnerabilities/PHP_Object_Injection + */ + public function __wakeup() : void + { + throw new \BadMethodCallException('Cannot unserialize ' . __CLASS__); + } + public function isAsync() : bool + { + return \true; + } + public function lintFile(string $path) : \PhpCsFixer\Linter\LintingResultInterface + { + return new \PhpCsFixer\Linter\ProcessLintingResult($this->createProcessForFile($path), $path); + } + public function lintSource(string $source) : \PhpCsFixer\Linter\LintingResultInterface + { + return new \PhpCsFixer\Linter\ProcessLintingResult($this->createProcessForSource($source), $this->temporaryFile); + } + /** + * @param string $path path to file + */ + private function createProcessForFile(string $path) : Process + { + // in case php://stdin + if (!\is_file($path)) { + return $this->createProcessForSource(FileReader::createSingleton()->read($path)); + } + $process = $this->processBuilder->build($path); + $process->setTimeout(10); + $process->start(); + return $process; + } + /** + * Create process that lint PHP code. + * + * @param string $source code + */ + private function createProcessForSource(string $source) : Process + { + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php new file mode 100644 index 00000000000..cb4d4c3cb3e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLinterProcessBuilder.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +use ECSPrefix202307\Symfony\Component\Process\Process; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLinterProcessBuilder +{ + /** + * @var string + */ + private $executable; + /** + * @param string $executable PHP executable + */ + public function __construct(string $executable) + { + $this->executable = $executable; + } + public function build(string $path) : Process + { + return new Process([$this->executable, '-l', $path]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php new file mode 100644 index 00000000000..e94307483d9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/ProcessLintingResult.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +use ECSPrefix202307\Symfony\Component\Process\Process; +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class ProcessLintingResult implements \PhpCsFixer\Linter\LintingResultInterface +{ + /** + * @var \Symfony\Component\Process\Process + */ + private $process; + /** + * @var string|null + */ + private $path; + /** + * @var bool|null + */ + private $isSuccessful; + public function __construct(Process $process, ?string $path = null) + { + $this->process = $process; + $this->path = $path; + } + public function check() : void + { + if (!$this->isSuccessful()) { + // on some systems stderr is used, but on others, it's not + throw new \PhpCsFixer\Linter\LintingException($this->getProcessErrorMessage(), $this->process->getExitCode()); + } + } + private function getProcessErrorMessage() : string + { + $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() : bool + { + if (null === $this->isSuccessful) { + $this->process->wait(); + $this->isSuccessful = $this->process->isSuccessful(); + } + return $this->isSuccessful; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php new file mode 100644 index 00000000000..237d5075eb8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLinter.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +use PhpCsFixer\FileReader; +use PhpCsFixer\Tokenizer\CodeHasher; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Handle PHP code linting. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TokenizerLinter implements \PhpCsFixer\Linter\LinterInterface +{ + public function isAsync() : bool + { + return \false; + } + public function lintFile(string $path) : \PhpCsFixer\Linter\LintingResultInterface + { + return $this->lintSource(FileReader::createSingleton()->read($path)); + } + public function lintSource(string $source) : \PhpCsFixer\Linter\LintingResultInterface + { + try { + // To lint, we will parse the source into Tokens. + // During that process, it might throw a ParseError or CompileError. + // If it won't, cache of tokenized version of source will be kept, which is great for Runner. + // Yet, first we need to clear already existing cache to not hit it and lint the code indeed. + $codeHash = CodeHasher::calculateCodeHash($source); + Tokens::clearCache($codeHash); + Tokens::fromCode($source); + return new \PhpCsFixer\Linter\TokenizerLintingResult(); + } catch (\ParseError|\CompileError $e) { + return new \PhpCsFixer\Linter\TokenizerLintingResult($e); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php new file mode 100644 index 00000000000..55d334c124d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/TokenizerLintingResult.php @@ -0,0 +1,40 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class TokenizerLintingResult implements \PhpCsFixer\Linter\LintingResultInterface +{ + /** + * @var \Error|null + */ + private $error; + public function __construct(?\Error $error = null) + { + $this->error = $error; + } + public function check() : void + { + if (null !== $this->error) { + throw new \PhpCsFixer\Linter\LintingException(\sprintf('%s: %s on line %d.', $this->getMessagePrefix(), $this->error->getMessage(), $this->error->getLine()), $this->error->getCode(), $this->error); + } + } + private function getMessagePrefix() : string + { + return $this->error instanceof \ParseError ? 'Parse error' : 'Fatal error'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php b/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php new file mode 100644 index 00000000000..f19be60fc28 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Linter/UnavailableLinterException.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Linter; + +/** + * Exception that is thrown when the chosen linter is not available on the environment. + * + * @author Dariusz Rumiński + * + * @final + * + * @TODO 4.0 make class "final" + */ +class UnavailableLinterException extends \RuntimeException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php b/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php new file mode 100644 index 00000000000..3521a677649 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/PharChecker.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @internal + */ +final class PharChecker implements \PhpCsFixer\PharCheckerInterface +{ + public function checkFileValidity(string $filename) : ?string + { + try { + $phar = new \Phar($filename); + // free the variable to unlock the file + unset($phar); + } catch (\Exception $e) { + if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { + throw $e; + } + return 'Failed to create Phar instance. ' . $e->getMessage(); + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php new file mode 100644 index 00000000000..63ac1f7202a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/PharCheckerInterface.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @internal + */ +interface PharCheckerInterface +{ + /** + * @return null|string the invalidity reason if any, null otherwise + */ + public function checkFileValidity(string $filename) : ?string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Preg.php b/vendor/friendsofphp/php-cs-fixer/src/Preg.php new file mode 100644 index 00000000000..7bea08a2344 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Preg.php @@ -0,0 +1,165 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * This class replaces preg_* functions to better handling UTF8 strings, + * ensuring no matter "u" modifier is present or absent subject will be handled correctly. + * + * @author Kuba Werłos + * + * @internal + */ +final class Preg +{ + /** + * @param null|string[] $matches + * @param int-mask<0, 256, 512> $flags + * + * @throws PregException + */ + public static function match(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0) : bool + { + $result = @\preg_match(self::addUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (\false !== $result && \PREG_NO_ERROR === \preg_last_error()) { + return 1 === $result; + } + $result = @\preg_match(self::removeUtf8Modifier($pattern), $subject, $matches, $flags, $offset); + if (\false !== $result && \PREG_NO_ERROR === \preg_last_error()) { + return 1 === $result; + } + throw self::newPregException(\preg_last_error(), __METHOD__, (array) $pattern); + } + /** + * @param null|string[] $matches + * + * @throws PregException + */ + public static function matchAll(string $pattern, string $subject, ?array &$matches = null, int $flags = \PREG_PATTERN_ORDER, int $offset = 0) : int + { + $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); + } + /** + * @param string|string[] $subject + * + * @throws PregException + */ + public static function replace(string $pattern, string $replacement, $subject, int $limit = -1, ?int &$count = null) : string + { + $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); + } + /** + * @throws PregException + */ + public static function replaceCallback(string $pattern, callable $callback, string $subject, int $limit = -1, ?int &$count = null) : string + { + $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); + } + /** + * @return string[] + * + * @throws PregException + */ + public static function split(string $pattern, string $subject, int $limit = -1, int $flags = 0) : array + { + $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); + } + /** + * @param string|string[] $pattern + * + * @return string|string[] + */ + private static function addUtf8Modifier($pattern) + { + if (\is_array($pattern)) { + return \array_map(__METHOD__, $pattern); + } + return $pattern . 'u'; + } + /** + * @param string|string[] $pattern + * + * @return string|string[] + */ + 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)); + } + /** + * Create PregException. + * + * Create the generic PregException message and if possible due to finding + * an invalid pattern, tell more about such kind of error in the message. + * + * @param string[] $patterns + */ + private static function newPregException(int $error, string $method, array $patterns) : \PhpCsFixer\PregException + { + 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 \PhpCsFixer\PregException(\sprintf('%s(): Invalid PCRE pattern "%s": %s (version: %s)', $method, $pattern, $message, \PCRE_VERSION), $code); + } + return new \PhpCsFixer\PregException(\sprintf('Error occurred when calling %s.', $method), $error); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/PregException.php b/vendor/friendsofphp/php-cs-fixer/src/PregException.php new file mode 100644 index 00000000000..da050a28472 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/PregException.php @@ -0,0 +1,24 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * Exception that is thrown when PCRE function encounters an error. + * + * @author Kuba Werłos + * + * @internal + */ +final class PregException extends \RuntimeException +{ +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php new file mode 100644 index 00000000000..d0d618063ba --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractMigrationSetDescription.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\Preg; +/** + * @internal + */ +abstract class AbstractMigrationSetDescription extends \PhpCsFixer\RuleSet\AbstractRuleSetDescription +{ + public function getDescription() : string + { + $name = $this->getName(); + if (Preg::match('#^@PHPUnit(\\d+)(\\d)Migration.*$#', $name, $matches)) { + return \sprintf('Rules to improve tests code for PHPUnit %d.%d compatibility.', $matches[1], $matches[2]); + } + if (Preg::match('#^@PHP([\\d]{2})Migration.*$#', $name, $matches)) { + return \sprintf('Rules to improve code for PHP %d.%d compatibility.', $matches[1][0], $matches[1][1]); + } + throw new \RuntimeException(\sprintf('Cannot generate description for "%s" "%s".', static::class, $name)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php new file mode 100644 index 00000000000..d28ff8e0f10 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/AbstractRuleSetDescription.php @@ -0,0 +1,32 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +/** + * @internal + */ +abstract class AbstractRuleSetDescription implements \PhpCsFixer\RuleSet\RuleSetDescriptionInterface +{ + public function __construct() + { + } + public function getName() : string + { + $name = \substr(static::class, 1 + \strrpos(static::class, '\\'), -3); + return '@' . \str_replace('Risky', ':risky', $name); + } + public function isRisky() : bool + { + return \strpos(static::class, 'Risky') !== \false; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php new file mode 100644 index 00000000000..7d3eb476bb5 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSet.php @@ -0,0 +1,119 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +use PhpCsFixer\ConfigurationException\InvalidFixerConfigurationException; +/** + * Set of rules to be used by fixer. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class RuleSet implements \PhpCsFixer\RuleSet\RuleSetInterface +{ + /** + * Group of rules generated from input set. + * + * The key is name of rule, value is bool if the rule/set should be used. + * The key must not point to any set. + * + * @var array|bool> + */ + private $rules; + public function __construct(array $set = []) + { + foreach ($set as $name => $value) { + if ('' === $name) { + throw new \InvalidArgumentException('Rule/set name must not be empty.'); + } + if (\is_int($name)) { + throw new \InvalidArgumentException(\sprintf('Missing value for "%s" rule/set.', $value)); + } + if (!\is_bool($value) && !\is_array($value)) { + $message = \strncmp($name, '@', \strlen('@')) === 0 ? 'Set must be enabled (true) or disabled (false). Other values are not allowed.' : 'Rule must be enabled (true), disabled (false) or configured (non-empty, assoc array). Other values are not allowed.'; + if (null === $value) { + $message .= ' To disable the ' . (\strncmp($name, '@', \strlen('@')) === 0 ? 'set' : 'rule') . ', use "FALSE" instead of "NULL".'; + } + throw new InvalidFixerConfigurationException($name, $message); + } + } + $this->resolveSet($set); + } + public function hasRule(string $rule) : bool + { + return \array_key_exists($rule, $this->rules); + } + public function getRuleConfiguration(string $rule) : ?array + { + 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() : array + { + return $this->rules; + } + /** + * Resolve input set into group of rules. + * + * @param array|bool> $rules + */ + private function resolveSet(array $rules) : void + { + $resolvedRules = []; + // expand sets + foreach ($rules as $name => $value) { + if (\strncmp($name, '@', \strlen('@')) === 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; + } + } + // filter out all resolvedRules that are off + $resolvedRules = \array_filter($resolvedRules); + $this->rules = $resolvedRules; + } + /** + * Resolve set rules as part of another set. + * + * If set value is false then disable all fixers in set, + * if not then get value from set item. + * + * @return array|bool> + */ + private function resolveSubset(string $setName, bool $setValue) : array + { + $rules = \PhpCsFixer\RuleSet\RuleSets::getSetDefinition($setName)->getRules(); + foreach ($rules as $name => $value) { + if (\strncmp($name, '@', \strlen('@')) === 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; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php new file mode 100644 index 00000000000..8a87bba94ff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetDescriptionInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +/** + * @internal + */ +interface RuleSetDescriptionInterface +{ + public function getDescription() : string; + public function getName() : string; + /** + * Get all rules from rules set. + * + * @return array|bool> + */ + public function getRules() : array; + public function isRisky() : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php new file mode 100644 index 00000000000..1237e3954e9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSetInterface.php @@ -0,0 +1,44 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +/** + * Set of rules to be used by fixer. + * + * Example of set: ["@PSR2" => true, "@PSR1" => false, "strict" => true]. + * + * @author Dariusz Rumiński + */ +interface RuleSetInterface +{ + /** + * @param array|bool> $set + */ + public function __construct(array $set = []); + /** + * Get configuration for given rule. + * + * @return null|array + */ + public function getRuleConfiguration(string $rule) : ?array; + /** + * Get all rules from rules set. + * + * @return array|bool> + */ + public function getRules() : array; + /** + * Check given rule is in rules set. + */ + public function hasRule(string $rule) : bool; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php new file mode 100644 index 00000000000..224263debae --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/RuleSets.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet; + +use ECSPrefix202307\Symfony\Component\Finder\Finder; +/** + * Set of rule sets to be used by fixer. + * + * @internal + */ +final class RuleSets +{ + /** + * @var array + */ + private static $setDefinitions; + /** + * @return array + */ + public static function getSetDefinitions() : array + { + 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; + } + \uksort(self::$setDefinitions, static function (string $x, string $y) : int { + return \strnatcmp($x, $y); + }); + } + return self::$setDefinitions; + } + /** + * @return string[] + */ + public static function getSetDefinitionNames() : array + { + return \array_keys(self::getSetDefinitions()); + } + public static function getSetDefinition(string $name) : \PhpCsFixer\RuleSet\RuleSetDescriptionInterface + { + $definitions = self::getSetDefinitions(); + if (!isset($definitions[$name])) { + throw new \InvalidArgumentException(\sprintf('Set "%s" does not exist.', $name)); + } + return $definitions[$name]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php new file mode 100644 index 00000000000..0b62796406f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/DoctrineAnnotationSet.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class DoctrineAnnotationSet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + 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() : string + { + return 'Rules covering Doctrine annotations with configuration based on examples found in `Doctrine Annotation documentation `_ and `Symfony documentation `_.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php new file mode 100644 index 00000000000..212d6ece08c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0RiskySet.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + */ +final class PERCS1x0RiskySet extends AbstractRuleSetDescription +{ + public function getName() : string + { + return '@PER-CS1.0:risky'; + } + public function getRules() : array + { + return ['@PSR12:risky' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow `PER Coding Style 1.0 `_.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php new file mode 100644 index 00000000000..5ca7743e161 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERCS1x0Set.php @@ -0,0 +1,37 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + * + * PER Coding Style v1.0. + * + * @see https://github.com/php-fig/per-coding-style/blob/1.0.0/spec.md + */ +final class PERCS1x0Set extends AbstractRuleSetDescription +{ + public function getName() : string + { + return '@PER-CS1.0'; + } + public function getRules() : array + { + return ['@PSR12' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow `PER Coding Style 1.0 `_.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php new file mode 100644 index 00000000000..b0ccad66d2b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERRiskySet.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + * + * @deprecated + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style + */ +final class PERRiskySet extends AbstractRuleSetDescription +{ + public function getName() : string + { + return '@PER:risky'; + } + public function getRules() : array + { + return ['@PER-CS1.0:risky' => \true]; + } + public function getDescription() : string + { + return 'Alias for the PER-CS risky rules. It is recommended you use ``@PER-CS1.0:risky`` instead.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php new file mode 100644 index 00000000000..919b6cd6a7c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PERSet.php @@ -0,0 +1,35 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + * + * @deprecated + * + * @TODO 4.0 remove me + * + * Last updated to PER Coding Style v1.0. + */ +final class PERSet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@PER-CS1.0' => \true]; + } + public function getDescription() : string + { + return 'Alias for the PER-CS rules. It is recommended you use ``@PER-CS1.0`` instead.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php new file mode 100644 index 00000000000..c7aab7c42ab --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP54MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP54MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['array_syntax' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php new file mode 100644 index 00000000000..292ac68058b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP56MigrationRiskySet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP56MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['pow_to_exponentiation' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php new file mode 100644 index 00000000000..79f9f7f6b4e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationRiskySet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP70MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP56Migration:risky' => \true, 'combine_nested_dirname' => \true, 'declare_strict_types' => \true, 'non_printable_character' => \true, 'random_api_migration' => ['replacements' => ['mt_rand' => 'random_int', 'rand' => 'random_int']]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php new file mode 100644 index 00000000000..8c9204f0517 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP70MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP70MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP54Migration' => \true, 'ternary_to_null_coalescing' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php new file mode 100644 index 00000000000..dfae48528fe --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationRiskySet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP71MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP70Migration:risky' => \true, 'void_return' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php new file mode 100644 index 00000000000..1dd1124dfa2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP71MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP71MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP70Migration' => \true, 'list_syntax' => \true, 'visibility_required' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php new file mode 100644 index 00000000000..5dfb6dc23e0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP73MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP73MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + 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' => ['after_heredoc' => \true]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php new file mode 100644 index 00000000000..8f3f5a65cf7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationRiskySet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP74MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP71Migration:risky' => \true, 'implode_call' => \true, 'no_alias_functions' => \true, 'use_arrow_functions' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php new file mode 100644 index 00000000000..815eea026f8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP74MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP74MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP73Migration' => \true, 'assign_null_coalescing_to_coalesce_equal' => \true, 'normalize_index_brace' => \true, 'short_scalar_cast' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php new file mode 100644 index 00000000000..b59615530ca --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationRiskySet.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP80MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return [ + '@PHP74Migration:risky' => \true, + 'get_class_to_class_keyword' => \true, + 'modernize_strpos' => \true, + 'no_alias_functions' => ['sets' => ['@all']], + 'no_php4_constructor' => \true, + 'no_unneeded_final_method' => \true, + // final private method (not constructor) are no longer allowed >= PHP8.0 + 'no_unreachable_default_argument_value' => \true, + ]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php new file mode 100644 index 00000000000..5d4264475b2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP80MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP80MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP74Migration' => \true, 'clean_namespace' => \true, 'no_unset_cast' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php new file mode 100644 index 00000000000..c889aa20da2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP81MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP81MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP80Migration' => \true, 'octal_notation' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php new file mode 100644 index 00000000000..ec680ab5dcb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHP82MigrationSet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHP82MigrationSet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHP81Migration' => \true, 'simple_to_complex_string_variable' => \true]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php new file mode 100644 index 00000000000..da3fe53e0fd --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit100MigrationRiskySet.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit100MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit84Migration:risky' => \true, 'php_unit_data_provider_static' => ['force' => \true]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php new file mode 100644 index 00000000000..a59fbd414bb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit30MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit30MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['php_unit_dedicate_assert' => ['target' => PhpUnitTargetVersion::VERSION_3_0]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php new file mode 100644 index 00000000000..c82e44bd936 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit32MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit32MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit30Migration:risky' => \true, 'php_unit_no_expectation_annotation' => ['target' => PhpUnitTargetVersion::VERSION_3_2]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php new file mode 100644 index 00000000000..dc736a88479 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit35MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit35MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit32Migration:risky' => \true, 'php_unit_dedicate_assert' => ['target' => PhpUnitTargetVersion::VERSION_3_5]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php new file mode 100644 index 00000000000..c425cd5d53f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit43MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit43MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit35Migration:risky' => \true, 'php_unit_no_expectation_annotation' => ['target' => PhpUnitTargetVersion::VERSION_4_3]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php new file mode 100644 index 00000000000..550afe466e7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit48MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit48MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit43Migration:risky' => \true, 'php_unit_namespaced' => ['target' => PhpUnitTargetVersion::VERSION_4_8]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php new file mode 100644 index 00000000000..f49b1fb277b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit50MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit50MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit48Migration:risky' => \true, 'php_unit_dedicate_assert' => ['target' => PhpUnitTargetVersion::VERSION_5_0]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php new file mode 100644 index 00000000000..9e985167744 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit52MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit52MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit50Migration:risky' => \true, 'php_unit_expectation' => ['target' => PhpUnitTargetVersion::VERSION_5_2]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php new file mode 100644 index 00000000000..b21bbbe961e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit54MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit54MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit52Migration:risky' => \true, 'php_unit_mock' => ['target' => PhpUnitTargetVersion::VERSION_5_4]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php new file mode 100644 index 00000000000..850d5aa816f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit55MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit55MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit54Migration:risky' => \true, 'php_unit_mock' => ['target' => PhpUnitTargetVersion::VERSION_5_5]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php new file mode 100644 index 00000000000..40f2b4dcc72 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit56MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit56MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit55Migration:risky' => \true, 'php_unit_dedicate_assert' => ['target' => PhpUnitTargetVersion::VERSION_5_6], 'php_unit_expectation' => ['target' => PhpUnitTargetVersion::VERSION_5_6]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php new file mode 100644 index 00000000000..6732bb849b6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit57MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit57MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit56Migration:risky' => \true, 'php_unit_namespaced' => ['target' => PhpUnitTargetVersion::VERSION_5_7]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php new file mode 100644 index 00000000000..d00ab07a330 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit60MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit60MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit57Migration:risky' => \true, 'php_unit_namespaced' => ['target' => PhpUnitTargetVersion::VERSION_6_0]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php new file mode 100644 index 00000000000..6c34ce63114 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit75MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit75MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit60Migration:risky' => \true, 'php_unit_dedicate_assert_internal_type' => ['target' => PhpUnitTargetVersion::VERSION_7_5]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php new file mode 100644 index 00000000000..53aafb14d86 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PHPUnit84MigrationRiskySet.php @@ -0,0 +1,26 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion; +use PhpCsFixer\RuleSet\AbstractMigrationSetDescription; +/** + * @internal + */ +final class PHPUnit84MigrationRiskySet extends AbstractMigrationSetDescription +{ + public function getRules() : array + { + return ['@PHPUnit60Migration:risky' => \true, '@PHPUnit75Migration:risky' => \true, 'php_unit_expectation' => ['target' => PhpUnitTargetVersion::VERSION_8_4]]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php new file mode 100644 index 00000000000..6581722fad7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12RiskySet.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PSR12RiskySet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['no_trailing_whitespace_in_string' => \true, 'no_unreachable_default_argument_value' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php new file mode 100644 index 00000000000..8ae2134ec12 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR12Set.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PSR12Set extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@PSR2' => \true, 'blank_line_after_opening_tag' => \true, 'blank_line_between_import_groups' => \true, 'blank_lines_before_namespace' => \true, 'class_definition' => [ + 'inline_constructor_arguments' => \false, + // handled by method_argument_space fixer + 'space_before_parenthesis' => \true, + ], 'compact_nullable_typehint' => \true, 'curly_braces_position' => ['allow_single_line_empty_anonymous_classes' => \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_import_per_statement' => ['group_to_single_imports' => \false], 'single_trait_insert_per_statement' => \true, 'ternary_operator_spaces' => \true, 'visibility_required' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow `PSR-12 `_ standard.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php new file mode 100644 index 00000000000..198cdbf9a6d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR1Set.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PSR1Set extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['encoding' => \true, 'full_opening_tag' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow `PSR-1 `_ standard.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php new file mode 100644 index 00000000000..1604f055224 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PSR2Set.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PSR2Set extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@PSR1' => \true, 'blank_line_after_namespace' => \true, 'class_definition' => \true, 'constant_case' => \true, 'control_structure_braces' => \true, 'control_structure_continuation_position' => \true, 'curly_braces_position' => \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_multiple_statements_per_line' => \true, 'no_space_around_double_colon' => \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, 'statement_indentation' => \true, 'switch_case_semicolon_to_colon' => \true, 'switch_case_space' => \true, 'visibility_required' => ['elements' => ['method', 'property']]]; + } + public function getDescription() : string + { + return 'Rules that follow `PSR-2 `_ standard.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php new file mode 100644 index 00000000000..f4b12f13058 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerRiskySet.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PhpCsFixerRiskySet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return [ + '@PER:risky' => \true, + '@Symfony:risky' => \true, + 'comment_to_phpdoc' => \true, + 'final_internal_class' => \true, + 'get_class_to_class_keyword' => \false, + 'modernize_strpos' => \false, + // @TODO: consider switching to `true`, like in @Symfony + '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_data_provider_name' => \true, + 'php_unit_data_provider_return_type' => \true, + 'php_unit_strict' => \true, + 'php_unit_test_case_static_method_calls' => ['call_type' => 'self'], + 'strict_comparison' => \true, + 'strict_param' => \true, + ]; + } + public function getDescription() : string + { + return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php new file mode 100644 index 00000000000..93b50c83ebe --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/PhpCsFixerSet.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class PhpCsFixerSet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@PER' => \true, '@Symfony' => \true, 'array_indentation' => \true, 'blank_line_before_statement' => ['statements' => ['break', 'case', 'continue', 'declare', 'default', 'exit', 'goto', 'include', 'include_once', 'phpdoc', 'require', 'require_once', 'return', 'switch', 'throw', 'try', 'yield', 'yield_from']], 'combine_consecutive_issets' => \true, 'combine_consecutive_unsets' => \true, 'empty_loop_body' => \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' => ['attribute', 'break', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'return', 'square_brace_block', 'switch', 'throw', 'use']], 'no_superfluous_elseif' => \true, 'no_superfluous_phpdoc_tags' => ['allow_mixed' => \true, 'remove_inheritdoc' => \true], 'no_unneeded_control_parentheses' => ['statements' => ['break', 'clone', 'continue', 'echo_print', 'negative_instanceof', 'others', 'return', 'switch_case', 'yield', 'yield_from']], 'no_useless_else' => \true, 'no_useless_return' => \true, 'nullable_type_declaration_for_default_null_value' => \false, '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_by_value' => \true, 'phpdoc_types_order' => \true, 'phpdoc_var_annotation_correct_order' => \true, 'protected_to_private' => \true, 'return_assignment' => \true, 'self_static_accessor' => \true, 'single_line_comment_style' => \true, 'single_line_throw' => \false, 'whitespace_after_comma_in_array' => ['ensure_single_space' => \true]]; + } + public function getDescription() : string + { + return 'Rule set as used by the PHP-CS-Fixer development team, highly opinionated.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php new file mode 100644 index 00000000000..0092215097b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonyRiskySet.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class SymfonyRiskySet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@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' => \true, 'get_class_to_class_keyword' => \true, 'implode_call' => \true, 'is_null' => \true, 'logical_operators' => \true, 'modernize_strpos' => \true, 'modernize_types_casting' => \true, 'native_constant_invocation' => ['strict' => \false], '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_length_to_empty' => \true, 'string_line_ending' => \true, 'ternary_to_elvis_operator' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow the official `Symfony Coding Standards `_.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php new file mode 100644 index 00000000000..6252a1c42b6 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/RuleSet/Sets/SymfonySet.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\RuleSet\Sets; + +use PhpCsFixer\RuleSet\AbstractRuleSetDescription; +/** + * @internal + */ +final class SymfonySet extends AbstractRuleSetDescription +{ + public function getRules() : array + { + return ['@PSR12' => \true, 'align_multiline_comment' => \true, 'array_syntax' => \true, 'backtick_to_shell_exec' => \true, 'binary_operator_spaces' => \true, 'blank_line_before_statement' => ['statements' => ['return']], 'cast_spaces' => \true, 'class_attributes_separation' => ['elements' => ['method' => 'one']], 'class_definition' => ['single_line' => \true], 'class_reference_name_casing' => \true, 'clean_namespace' => \true, 'concat_space' => \true, 'curly_braces_position' => ['allow_single_line_anonymous_functions' => \true, 'allow_single_line_empty_anonymous_classes' => \true], 'declare_parentheses' => \true, 'echo_tag_syntax' => \true, 'empty_loop_body' => ['style' => 'braces'], 'empty_loop_condition' => \true, 'fully_qualified_strict_types' => \true, 'general_phpdoc_tag_rename' => ['replacements' => ['inheritDocs' => 'inheritDoc']], 'global_namespace_import' => ['import_classes' => \false, 'import_constants' => \false, 'import_functions' => \false], 'include' => \true, 'increment_style' => \true, 'integer_literal_case' => \true, 'lambda_not_used_import' => \true, 'linebreak_after_opening_tag' => \true, 'magic_constant_casing' => \true, 'magic_method_casing' => \true, 'method_argument_space' => ['on_multiline' => 'ignore'], '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' => ['attribute', 'case', 'continue', 'curly_brace_block', 'default', 'extra', 'parenthesis_brace_block', 'square_brace_block', 'switch', 'throw', 'use']], 'no_leading_namespace_whitespace' => \true, 'no_mixed_echo_print' => \true, 'no_multiline_whitespace_around_double_arrow' => \true, 'no_null_property_initialization' => \true, 'no_short_bool_cast' => \true, 'no_singleline_whitespace_before_semicolons' => \true, 'no_spaces_around_offset' => \true, 'no_superfluous_phpdoc_tags' => ['remove_inheritdoc' => \true], 'no_trailing_comma_in_singleline' => \true, 'no_unneeded_control_parentheses' => ['statements' => ['break', 'clone', 'continue', 'echo_print', 'others', 'return', 'switch_case', 'yield', 'yield_from']], 'no_unneeded_curly_braces' => ['namespaces' => \true], 'no_unneeded_import_alias' => \true, 'no_unset_cast' => \true, 'no_unused_imports' => \true, 'no_useless_concat_operator' => \true, 'no_useless_nullsafe_operator' => \true, 'no_whitespace_before_comma_in_array' => \true, 'normalize_index_brace' => \true, 'nullable_type_declaration_for_default_null_value' => ['use_nullable_type_declaration' => \false], 'object_operator_without_whitespace' => \true, 'operator_linebreak' => ['only_booleans' => \true], 'ordered_imports' => ['imports_order' => ['class', 'function', 'const'], 'sort_algorithm' => 'alpha'], 'php_unit_fqcn_annotation' => \true, 'php_unit_method_casing' => \true, 'phpdoc_align' => \true, '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_order' => ['order' => ['param', 'return', 'throws']], '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, 'semicolon_after_instruction' => \true, 'simple_to_complex_string_variable' => \true, 'single_class_element_per_statement' => \true, 'single_import_per_statement' => \true, 'single_line_comment_spacing' => \true, 'single_line_comment_style' => ['comment_types' => ['hash']], 'single_line_throw' => \true, 'single_quote' => \true, 'single_space_around_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' => \true, 'trim_array_spaces' => \true, 'type_declaration_spaces' => \true, 'types_spaces' => \true, 'unary_operator_spaces' => \true, 'whitespace_after_comma_in_array' => \true, 'yoda_style' => \true]; + } + public function getDescription() : string + { + return 'Rules that follow the official `Symfony Coding Standards `_.'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php new file mode 100644 index 00000000000..9666e7dcad1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileCachingLintingIterator.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \CachingIterator> + */ +final class FileCachingLintingIterator extends \CachingIterator +{ + /** + * @var \PhpCsFixer\Linter\LinterInterface + */ + private $linter; + /** + * @var LintingResultInterface + */ + private $currentResult; + /** + * @var LintingResultInterface + */ + private $nextResult; + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + $this->linter = $linter; + } + public function currentLintingResult() : LintingResultInterface + { + return $this->currentResult; + } + public function next() : void + { + parent::next(); + $this->currentResult = $this->nextResult; + if ($this->hasNext()) { + $this->nextResult = $this->handleItem($this->getInnerIterator()->current()); + } + } + public function rewind() : void + { + 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) : LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php new file mode 100644 index 00000000000..c4813c13dfe --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileFilterIterator.php @@ -0,0 +1,82 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Cache\CacheManagerInterface; +use PhpCsFixer\FileReader; +use PhpCsFixer\FixerFileProcessedEvent; +use ECSPrefix202307\Symfony\Component\EventDispatcher\EventDispatcherInterface; +use ECSPrefix202307\Symfony\Contracts\EventDispatcher\Event; +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \FilterIterator> + */ +final class FileFilterIterator extends \FilterIterator +{ + /** + * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|null + */ + private $eventDispatcher; + /** + * @var \PhpCsFixer\Cache\CacheManagerInterface + */ + private $cacheManager; + /** + * @var array + */ + private $visitedElements = []; + /** + * @param \Traversable<\SplFileInfo> $iterator + */ + public function __construct(\Traversable $iterator, ?EventDispatcherInterface $eventDispatcher, CacheManagerInterface $cacheManager) + { + if (!$iterator instanceof \Iterator) { + $iterator = new \IteratorIterator($iterator); + } + parent::__construct($iterator); + $this->eventDispatcher = $eventDispatcher; + $this->cacheManager = $cacheManager; + } + public function accept() : bool + { + $file = $this->current(); + if (!$file instanceof \SplFileInfo) { + throw new \RuntimeException(\sprintf('Expected instance of "\\SplFileInfo", got "%s".', \get_debug_type($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); + // mark as skipped: + if ('' === $content || !$this->cacheManager->needFixing($file->getPathname(), $content)) { + $this->dispatchEvent(FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_SKIPPED)); + return \false; + } + return \true; + } + private function dispatchEvent(string $name, Event $event) : void + { + if (null === $this->eventDispatcher) { + return; + } + $this->eventDispatcher->dispatch($event, $name); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php new file mode 100644 index 00000000000..f7fc897bde2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Runner/FileLintingIterator.php @@ -0,0 +1,60 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Runner; + +use PhpCsFixer\Linter\LinterInterface; +use PhpCsFixer\Linter\LintingResultInterface; +/** + * @author Dariusz Rumiński + * + * @internal + * + * @extends \IteratorIterator> + */ +final class FileLintingIterator extends \IteratorIterator +{ + /** + * @var LintingResultInterface + */ + private $currentResult; + /** + * @var \PhpCsFixer\Linter\LinterInterface + */ + private $linter; + /** + * @param \Iterator $iterator + */ + public function __construct(\Iterator $iterator, LinterInterface $linter) + { + parent::__construct($iterator); + $this->linter = $linter; + } + public function currentLintingResult() : ?LintingResultInterface + { + return $this->currentResult; + } + public function next() : void + { + parent::next(); + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + public function rewind() : void + { + parent::rewind(); + $this->currentResult = $this->valid() ? $this->handleItem($this->current()) : null; + } + private function handleItem(\SplFileInfo $file) : LintingResultInterface + { + return $this->linter->lintFile($file->getRealPath()); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php b/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php new file mode 100644 index 00000000000..8b27a8a8d38 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Runner/Runner.php @@ -0,0 +1,213 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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\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 ECSPrefix202307\Symfony\Component\EventDispatcher\EventDispatcherInterface; +use ECSPrefix202307\Symfony\Component\Filesystem\Exception\IOException; +use ECSPrefix202307\Symfony\Contracts\EventDispatcher\Event; +/** + * @author Dariusz Rumiński + */ +final class Runner +{ + /** + * @var \PhpCsFixer\Differ\DifferInterface + */ + private $differ; + /** + * @var \PhpCsFixer\Cache\DirectoryInterface|null + */ + private $directory; + /** + * @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|null + */ + private $eventDispatcher; + /** + * @var \PhpCsFixer\Error\ErrorsManager + */ + private $errorsManager; + /** + * @var \PhpCsFixer\Cache\CacheManagerInterface + */ + private $cacheManager; + /** + * @var bool + */ + private $isDryRun; + /** + * @var \PhpCsFixer\Linter\LinterInterface + */ + private $linter; + /** + * @var \Traversable<\SplFileInfo> + */ + private $finder; + /** + * @var list + */ + private $fixers; + /** + * @var bool + */ + private $stopOnViolation; + /** + * @param \Traversable<\SplFileInfo> $finder + * @param list $fixers + */ + public function __construct(\Traversable $finder, array $fixers, DifferInterface $differ, ?EventDispatcherInterface $eventDispatcher, ErrorsManager $errorsManager, LinterInterface $linter, bool $isDryRun, CacheManagerInterface $cacheManager, ?DirectoryInterface $directory = null, bool $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; + } + /** + * @return array, diff: string}> + */ + public function fix() : array + { + $changed = []; + $finder = $this->finder; + $finderIterator = $finder instanceof \IteratorAggregate ? $finder->getIterator() : $finder; + $fileFilteredFileIterator = new \PhpCsFixer\Runner\FileFilterIterator($finderIterator, $this->eventDispatcher, $this->cacheManager); + $collection = $this->linter->isAsync() ? new \PhpCsFixer\Runner\FileCachingLintingIterator($fileFilteredFileIterator, $this->linter) : new \PhpCsFixer\Runner\FileLintingIterator($fileFilteredFileIterator, $this->linter); + foreach ($collection as $file) { + $fixInfo = $this->fixFile($file, $collection->currentLintingResult()); + // we do not need Tokens to still caching just fixed file - so clear the cache + Tokens::clearCache(); + if (null !== $fixInfo) { + $name = $this->directory->getRelativePathTo($file->__toString()); + $changed[$name] = $fixInfo; + if ($this->stopOnViolation) { + break; + } + } + } + return $changed; + } + /** + * @return null|array{appliedFixers: list, diff: string} + */ + private function fixFile(\SplFileInfo $file, LintingResultInterface $lintingResult) : ?array + { + $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 null; + } + $old = FileReader::createSingleton()->read($file->getRealPath()); + $tokens = Tokens::fromCode($old); + $oldHash = $tokens->getCodeHash(); + $newHash = $oldHash; + $new = $old; + $appliedFixers = []; + try { + foreach ($this->fixers as $fixer) { + // for custom fixers we don't know is it safe to run `->fix()` without checking `->supports()` and `->isCandidate()`, + // thus we need to check it and conditionally skip fixing + 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 (\ParseError $e) { + $this->dispatchEvent(FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_LINT)); + $this->errorsManager->report(new Error(Error::TYPE_LINT, $name, $e)); + return null; + } catch (\Throwable $e) { + $this->processException($name, $e); + return null; + } + $fixInfo = null; + if ([] !== $appliedFixers) { + $new = $tokens->generateCode(); + $newHash = $tokens->getCodeHash(); + } + // We need to check if content was changed and then applied changes. + // But we can't simply check $appliedFixers, because one fixer may revert + // work of other and both of them will mark collection as changed. + // Therefore we need to check if code hashes changed. + if ($oldHash !== $newHash) { + $fixInfo = ['appliedFixers' => $appliedFixers, 'diff' => $this->differ->diff($old, $new, $file)]; + 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 null; + } + 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, null !== $error ? $error['message'] : 'no reason available'), 0, null, $fileName); + } + } + } + $this->cacheManager->setFile($name, $new); + $this->dispatchEvent(FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(null !== $fixInfo ? FixerFileProcessedEvent::STATUS_FIXED : FixerFileProcessedEvent::STATUS_NO_CHANGES)); + return $fixInfo; + } + /** + * Process an exception that occurred. + */ + private function processException(string $name, \Throwable $e) : void + { + $this->dispatchEvent(FixerFileProcessedEvent::NAME, new FixerFileProcessedEvent(FixerFileProcessedEvent::STATUS_EXCEPTION)); + $this->errorsManager->report(new Error(Error::TYPE_EXCEPTION, $name, $e)); + } + private function dispatchEvent(string $name, Event $event) : void + { + if (null === $this->eventDispatcher) { + return; + } + $this->eventDispatcher->dispatch($event, $name); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php b/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php new file mode 100644 index 00000000000..f8e145d0a86 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/StdinFileInfo.php @@ -0,0 +1,144 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @author Davi Koscianski Vidal + * + * @internal + */ +final class StdinFileInfo extends \SplFileInfo +{ + public function __construct() + { + parent::__construct(__FILE__); + } + public function __toString() : string + { + return $this->getRealPath(); + } + public function getRealPath() : string + { + // So file_get_contents & friends will work. + // Warning - this stream is not seekable, so `file_get_contents` will work only once! Consider using `FileReader`. + return 'php://stdin'; + } + public function getATime() : int + { + return 0; + } + public function getBasename($suffix = null) : string + { + return $this->getFilename(); + } + public function getCTime() : int + { + return 0; + } + public function getExtension() : string + { + return '.php'; + } + public function getFileInfo($className = null) : \SplFileInfo + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } + public function getFilename() : string + { + /* + * Useful so fixers depending on PHP-only files still work. + * + * The idea to use STDIN is to parse PHP-only files, so we can + * assume that there will be always a PHP file out there. + */ + return 'stdin.php'; + } + public function getGroup() : int + { + return 0; + } + public function getInode() : int + { + return 0; + } + public function getLinkTarget() : string + { + return ''; + } + public function getMTime() : int + { + return 0; + } + public function getOwner() : int + { + return 0; + } + public function getPath() : string + { + return ''; + } + public function getPathInfo($className = null) : \SplFileInfo + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } + public function getPathname() : string + { + return $this->getFilename(); + } + public function getPerms() : int + { + return 0; + } + public function getSize() : int + { + return 0; + } + public function getType() : string + { + return 'file'; + } + public function isDir() : bool + { + return \false; + } + public function isExecutable() : bool + { + return \false; + } + public function isFile() : bool + { + return \true; + } + public function isLink() : bool + { + return \false; + } + public function isReadable() : bool + { + return \true; + } + public function isWritable() : bool + { + return \false; + } + public function openFile($openMode = 'r', $useIncludePath = \false, $context = null) : \SplFileObject + { + throw new \BadMethodCallException(\sprintf('Method "%s" is not implemented.', __METHOD__)); + } + public function setFileClass($className = null) : void + { + } + public function setInfoClass($className = null) : void + { + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php new file mode 100644 index 00000000000..53f0d9390b3 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTransformer.php @@ -0,0 +1,34 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Utils; +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractTransformer implements \PhpCsFixer\Tokenizer\TransformerInterface +{ + public function getName() : string + { + $nameParts = \explode('\\', static::class); + $name = \substr(\end($nameParts), 0, -\strlen('Transformer')); + return Utils::camelCaseToUnderscore($name); + } + public function getPriority() : int + { + return 0; + } + public abstract function getCustomTokens() : array; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php new file mode 100644 index 00000000000..7cb71181b68 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/AbstractTypeTransformer.php @@ -0,0 +1,76 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +abstract class AbstractTypeTransformer extends \PhpCsFixer\Tokenizer\AbstractTransformer +{ + private const TYPE_END_TOKENS = [')', [\T_CALLABLE], [\T_NS_SEPARATOR], [\T_STATIC], [\T_STRING], [\PhpCsFixer\Tokenizer\CT::T_ARRAY_TYPEHINT]]; + private const TYPE_TOKENS = [ + '|', + '&', + '(', + ')', + [\T_CALLABLE], + [\T_NS_SEPARATOR], + [\T_STATIC], + [\T_STRING], + [\PhpCsFixer\Tokenizer\CT::T_ARRAY_TYPEHINT], + [\PhpCsFixer\Tokenizer\CT::T_TYPE_ALTERNATION], + [\PhpCsFixer\Tokenizer\CT::T_TYPE_INTERSECTION], + // some siblings may already be transformed + [\T_WHITESPACE], + [\T_COMMENT], + [\T_DOC_COMMENT], + ]; + protected abstract function replaceToken(\PhpCsFixer\Tokenizer\Tokens $tokens, int $index) : void; + /** + * @param array{0: int, 1: string}|string $originalToken + */ + protected function doProcess(\PhpCsFixer\Tokenizer\Tokens $tokens, int $index, $originalToken) : void + { + if (!$tokens[$index]->equals($originalToken)) { + return; + } + if (!$this->isPartOfType($tokens, $index)) { + return; + } + $this->replaceToken($tokens, $index); + } + private function isPartOfType(\PhpCsFixer\Tokenizer\Tokens $tokens, int $index) : bool + { + // return types and non-capturing catches + $typeColonIndex = $tokens->getTokenNotOfKindSibling($index, -1, self::TYPE_TOKENS); + if ($tokens[$typeColonIndex]->isGivenKind([\T_CATCH, \PhpCsFixer\Tokenizer\CT::T_TYPE_COLON, \T_CONST])) { + return \true; + } + // for parameter there will be splat operator or variable after the type ("&" is ambiguous and can be reference or bitwise and) + $afterTypeIndex = $tokens->getTokenNotOfKindSibling($index, 1, self::TYPE_TOKENS); + if ($tokens[$afterTypeIndex]->isGivenKind(\T_ELLIPSIS)) { + return \true; + } + if (!$tokens[$afterTypeIndex]->isGivenKind(\T_VARIABLE)) { + return \false; + } + $beforeVariableIndex = $tokens->getPrevMeaningfulToken($afterTypeIndex); + if ($tokens[$beforeVariableIndex]->equals('&')) { + $prevIndex = $tokens->getPrevTokenOfKind($index, ['{', '}', ';', [\T_CLOSE_TAG], [\T_FN], [\T_FUNCTION]]); + return null !== $prevIndex && $tokens[$prevIndex]->isGivenKind([\T_FN, \T_FUNCTION]); + } + return $tokens[$beforeVariableIndex]->equalsAny(self::TYPE_END_TOKENS); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php new file mode 100644 index 00000000000..f1752b9cb88 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AlternativeSyntaxAnalyzer.php @@ -0,0 +1,77 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + * + * @TODO 4.0 remove this analyzer and move this logic into a transformer + */ +final class AlternativeSyntaxAnalyzer +{ + private const ALTERNATIVE_SYNTAX_BLOCK_EDGES = [\T_IF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], \T_ELSE => [\T_ENDIF], \T_ELSEIF => [\T_ENDIF, \T_ELSE, \T_ELSEIF], \T_FOR => [\T_ENDFOR], \T_FOREACH => [\T_ENDFOREACH], \T_WHILE => [\T_ENDWHILE], \T_SWITCH => [\T_ENDSWITCH]]; + public function belongsToAlternativeSyntax(Tokens $tokens, int $index) : bool + { + if (!$tokens[$index]->equals(':')) { + return \false; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->isGivenKind(\T_ELSE)) { + return \true; + } + if (!$tokens[$prevIndex]->equals(')')) { + return \false; + } + $openParenthesisIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex); + $beforeOpenParenthesisIndex = $tokens->getPrevMeaningfulToken($openParenthesisIndex); + return $tokens[$beforeOpenParenthesisIndex]->isGivenKind([\T_DECLARE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_IF, \T_SWITCH, \T_WHILE]); + } + public function findAlternativeSyntaxBlockEnd(Tokens $tokens, int $index) : int + { + if (!isset($tokens[$index])) { + throw new \InvalidArgumentException("There is no token at index {$index}."); + } + if (!$this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + throw new \InvalidArgumentException("Token at index {$index} is not the start of an alternative syntax block."); + } + $startTokenKind = $tokens[$index]->getId(); + $endTokenKinds = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES[$startTokenKind]; + $findKinds = [[$startTokenKind]]; + foreach ($endTokenKinds as $endTokenKind) { + $findKinds[] = [$endTokenKind]; + } + while (\true) { + $index = $tokens->getNextTokenOfKind($index, $findKinds); + if ($tokens[$index]->isGivenKind($endTokenKinds)) { + return $index; + } + if ($this->isStartOfAlternativeSyntaxBlock($tokens, $index)) { + $index = $this->findAlternativeSyntaxBlockEnd($tokens, $index); + } + } + } + private function isStartOfAlternativeSyntaxBlock(Tokens $tokens, int $index) : bool + { + $map = self::ALTERNATIVE_SYNTAX_BLOCK_EDGES; + $startTokenKind = $tokens[$index]->getId(); + if (null === $startTokenKind || !isset($map[$startTokenKind])) { + return \false; + } + $index = $tokens->getNextMeaningfulToken($index); + if ($tokens[$index]->equals('(')) { + $index = $tokens->getNextMeaningfulToken($tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index)); + } + return $tokens[$index]->equals(':'); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php new file mode 100644 index 00000000000..0bed611246b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/AbstractControlCaseStructuresAnalysis.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +abstract class AbstractControlCaseStructuresAnalysis +{ + /** + * @var int + */ + private $index; + /** + * @var int + */ + private $open; + /** + * @var int + */ + private $close; + public function __construct(int $index, int $open, int $close) + { + $this->index = $index; + $this->open = $open; + $this->close = $close; + } + public function getIndex() : int + { + return $this->index; + } + public function getOpenIndex() : int + { + return $this->open; + } + public function getCloseIndex() : int + { + return $this->close; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php new file mode 100644 index 00000000000..dc026d4caef --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/ArgumentAnalysis.php @@ -0,0 +1,71 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class ArgumentAnalysis +{ + /** + * The name of the argument. + * @var string|null + */ + private $name; + /** + * The index where the name is located in the supplied Tokens object. + * @var int|null + */ + private $nameIndex; + /** + * The default value of the argument. + * @var string|null + */ + private $default; + /** + * The type analysis of the argument. + * @var \PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis|null + */ + private $typeAnalysis; + public function __construct(?string $name, ?int $nameIndex, ?string $default, ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis $typeAnalysis = null) + { + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->default = $default ?: null; + $this->typeAnalysis = $typeAnalysis ?: null; + } + public function getDefault() : ?string + { + return $this->default; + } + public function hasDefault() : bool + { + return null !== $this->default; + } + public function getName() : ?string + { + return $this->name; + } + public function getNameIndex() : ?int + { + return $this->nameIndex; + } + public function getTypeAnalysis() : ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis + { + return $this->typeAnalysis; + } + public function hasTypeAnalysis() : bool + { + return null !== $this->typeAnalysis; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php new file mode 100644 index 00000000000..033d614166e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/CaseAnalysis.php @@ -0,0 +1,43 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @author Kuba Werłos + * + * @internal + */ +final class CaseAnalysis +{ + /** + * @var int + */ + private $index; + /** + * @var int + */ + private $colonIndex; + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + public function getIndex() : int + { + return $this->index; + } + public function getColonIndex() : int + { + return $this->colonIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php new file mode 100644 index 00000000000..cbb447ebf12 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DataProviderAnalysis.php @@ -0,0 +1,51 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +final class DataProviderAnalysis +{ + /** + * @var string + */ + private $name; + /** + * @var int + */ + private $nameIndex; + /** @var array */ + private $usageIndices; + /** + * @param array $usageIndices + */ + public function __construct(string $name, int $nameIndex, array $usageIndices) + { + $this->name = $name; + $this->nameIndex = $nameIndex; + $this->usageIndices = $usageIndices; + } + public function getName() : string + { + return $this->name; + } + public function getNameIndex() : int + { + return $this->nameIndex; + } + /** + * @return array + */ + public function getUsageIndices() : array + { + return $this->usageIndices; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php new file mode 100644 index 00000000000..6d814e4b3c4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/DefaultAnalysis.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class DefaultAnalysis +{ + /** + * @var int + */ + private $index; + /** + * @var int + */ + private $colonIndex; + public function __construct(int $index, int $colonIndex) + { + $this->index = $index; + $this->colonIndex = $colonIndex; + } + public function getIndex() : int + { + return $this->index; + } + public function getColonIndex() : int + { + return $this->colonIndex; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php new file mode 100644 index 00000000000..5a3eea4305a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/EnumAnalysis.php @@ -0,0 +1,39 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class EnumAnalysis extends \PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private $cases; + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases) + { + parent::__construct($index, $open, $close); + $this->cases = $cases; + } + /** + * @return list + */ + public function getCases() : array + { + return $this->cases; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php new file mode 100644 index 00000000000..ed1decdfd06 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/MatchAnalysis.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class MatchAnalysis extends \PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis +{ + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis|null + */ + private $defaultAnalysis; + public function __construct(int $index, int $open, int $close, ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + $this->defaultAnalysis = $defaultAnalysis; + } + public function getDefaultAnalysis() : ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php new file mode 100644 index 00000000000..250e4c8956e --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceAnalysis.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class NamespaceAnalysis implements \PhpCsFixer\Tokenizer\Analyzer\Analysis\StartEndTokenAwareAnalysis +{ + /** + * The fully qualified namespace name. + * @var string + */ + private $fullName; + /** + * The short version of the namespace. + * @var string + */ + private $shortName; + /** + * The start index of the namespace declaration in the analyzed Tokens. + * @var int + */ + private $startIndex; + /** + * The end index of the namespace declaration in the analyzed Tokens. + * @var int + */ + private $endIndex; + /** + * The start index of the scope of the namespace in the analyzed Tokens. + * @var int + */ + private $scopeStartIndex; + /** + * The end index of the scope of the namespace in the analyzed Tokens. + * @var int + */ + private $scopeEndIndex; + public function __construct(string $fullName, string $shortName, int $startIndex, int $endIndex, int $scopeStartIndex, int $scopeEndIndex) + { + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->scopeStartIndex = $scopeStartIndex; + $this->scopeEndIndex = $scopeEndIndex; + } + public function getFullName() : string + { + return $this->fullName; + } + public function getShortName() : string + { + return $this->shortName; + } + public function getStartIndex() : int + { + return $this->startIndex; + } + public function getEndIndex() : int + { + return $this->endIndex; + } + public function getScopeStartIndex() : int + { + return $this->scopeStartIndex; + } + public function getScopeEndIndex() : int + { + return $this->scopeEndIndex; + } + public function isGlobalNamespace() : bool + { + return '' === $this->getFullName(); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php new file mode 100644 index 00000000000..4ab2743c0e7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/NamespaceUseAnalysis.php @@ -0,0 +1,99 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class NamespaceUseAnalysis implements \PhpCsFixer\Tokenizer\Analyzer\Analysis\StartEndTokenAwareAnalysis +{ + public const TYPE_CLASS = 1; + // "classy" could be class, interface or trait + public const TYPE_FUNCTION = 2; + public const TYPE_CONSTANT = 3; + /** + * The fully qualified use namespace. + * @var string + */ + private $fullName; + /** + * The short version of use namespace or the alias name in case of aliased use statements. + * @var string + */ + private $shortName; + /** + * Is the use statement being aliased? + * @var bool + */ + private $isAliased; + /** + * The start index of the namespace declaration in the analyzed Tokens. + * @var int + */ + private $startIndex; + /** + * The end index of the namespace declaration in the analyzed Tokens. + * @var int + */ + private $endIndex; + /** + * The type of import: class, function or constant. + * @var int + */ + private $type; + public function __construct(string $fullName, string $shortName, bool $isAliased, int $startIndex, int $endIndex, int $type) + { + $this->fullName = $fullName; + $this->shortName = $shortName; + $this->isAliased = $isAliased; + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + $this->type = $type; + } + public function getFullName() : string + { + return $this->fullName; + } + public function getShortName() : string + { + return $this->shortName; + } + public function isAliased() : bool + { + return $this->isAliased; + } + public function getStartIndex() : int + { + return $this->startIndex; + } + public function getEndIndex() : int + { + return $this->endIndex; + } + public function getType() : int + { + return $this->type; + } + public function isClass() : bool + { + return self::TYPE_CLASS === $this->type; + } + public function isFunction() : bool + { + return self::TYPE_FUNCTION === $this->type; + } + public function isConstant() : bool + { + return self::TYPE_CONSTANT === $this->type; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php new file mode 100644 index 00000000000..ae99ad92bbc --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/StartEndTokenAwareAnalysis.php @@ -0,0 +1,25 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +interface StartEndTokenAwareAnalysis +{ + /** + * The start index of the analyzed subject inside of the Tokens. + */ + public function getStartIndex() : int; + /** + * The end index of the analyzed subject inside of the Tokens. + */ + public function getEndIndex() : int; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php new file mode 100644 index 00000000000..d212014f7a8 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/SwitchAnalysis.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class SwitchAnalysis extends \PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis +{ + /** + * @var list + */ + private $cases; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis|null + */ + private $defaultAnalysis; + /** + * @param list $cases + */ + public function __construct(int $index, int $open, int $close, array $cases, ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis $defaultAnalysis) + { + parent::__construct($index, $open, $close); + $this->cases = $cases; + $this->defaultAnalysis = $defaultAnalysis; + } + /** + * @return list + */ + public function getCases() : array + { + return $this->cases; + } + public function getDefaultAnalysis() : ?\PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis + { + return $this->defaultAnalysis; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php new file mode 100644 index 00000000000..a0d93770c01 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/Analysis/TypeAnalysis.php @@ -0,0 +1,81 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer\Analysis; + +/** + * @internal + */ +final class TypeAnalysis implements \PhpCsFixer\Tokenizer\Analyzer\Analysis\StartEndTokenAwareAnalysis +{ + /** + * This list contains soft and hard reserved types that can be used or will be used by PHP at some point. + * + * More info: + * + * @see https://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.types + * @see https://php.net/manual/en/reserved.other-reserved-words.php + * @see https://php.net/manual/en/language.pseudo-types.php + * + * @var list + */ + private static $reservedTypes = ['array', 'bool', 'callable', 'float', 'int', 'iterable', 'mixed', 'never', 'numeric', 'object', 'resource', 'self', 'string', 'void']; + /** + * @var string + */ + private $name; + /** + * @var int + */ + private $startIndex; + /** + * @var int + */ + private $endIndex; + /** + * @var bool + */ + private $nullable; + public function __construct(string $name, int $startIndex, int $endIndex) + { + $this->name = $name; + $this->nullable = \false; + if (\strncmp($name, '?', \strlen('?')) === 0) { + $this->name = \substr($name, 1); + $this->nullable = \true; + } elseif (\PHP_VERSION_ID >= 80000) { + $this->nullable = \in_array('null', \array_map('trim', \explode('|', \strtolower($name))), \true); + } + $this->startIndex = $startIndex; + $this->endIndex = $endIndex; + } + public function getName() : string + { + return $this->name; + } + public function getStartIndex() : int + { + return $this->startIndex; + } + public function getEndIndex() : int + { + return $this->endIndex; + } + public function isReservedType() : bool + { + return \in_array($this->name, self::$reservedTypes, \true); + } + public function isNullable() : bool + { + return $this->nullable; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php new file mode 100644 index 00000000000..2e7949ae6d0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ArgumentsAnalyzer.php @@ -0,0 +1,117 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\ArgumentAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\TypeAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Dariusz Rumiński + * @author Vladimir Reznichenko + * + * @internal + */ +final class ArgumentsAnalyzer +{ + /** + * Count amount of parameters in a function/method reference. + */ + public function countArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis) : int + { + return \count($this->getArguments($tokens, $openParenthesis, $closeParenthesis)); + } + /** + * Returns start and end token indices of arguments. + * + * Returns an array with each key being the first token of an + * argument and the value the last. Including non-function tokens + * such as comments and white space tokens, but without the separation + * tokens like '(', ',' and ')'. + * + * @return array + */ + public function getArguments(Tokens $tokens, int $openParenthesis, int $closeParenthesis) : array + { + $arguments = []; + $firstSensibleToken = $tokens->getNextMeaningfulToken($openParenthesis); + if ($tokens[$firstSensibleToken]->equals(')')) { + return $arguments; + } + $paramContentIndex = $openParenthesis + 1; + $argumentsStart = $paramContentIndex; + for (; $paramContentIndex < $closeParenthesis; ++$paramContentIndex) { + $token = $tokens[$paramContentIndex]; + // skip nested (), [], {} constructs + $blockDefinitionProbe = Tokens::detectBlockType($token); + if (null !== $blockDefinitionProbe && \true === $blockDefinitionProbe['isStart']) { + $paramContentIndex = $tokens->findBlockEnd($blockDefinitionProbe['type'], $paramContentIndex); + continue; + } + // if comma matched, increase arguments counter + if ($token->equals(',')) { + if ($tokens->getNextMeaningfulToken($paramContentIndex) === $closeParenthesis) { + break; + // trailing ',' in function call (PHP 7.3) + } + $arguments[$argumentsStart] = $paramContentIndex - 1; + $argumentsStart = $paramContentIndex + 1; + } + } + $arguments[$argumentsStart] = $paramContentIndex - 1; + return $arguments; + } + public function getArgumentInfo(Tokens $tokens, int $argumentStart, int $argumentEnd) : ArgumentAnalysis + { + static $skipTypes = null; + if (null === $skipTypes) { + $skipTypes = [\T_ELLIPSIS, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $skipTypes[] = \T_READONLY; + } + } + $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 (\defined('T_ATTRIBUTE') && $token->isGivenKind(\T_ATTRIBUTE)) { + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + continue; + } + if ($token->isComment() || $token->isWhitespace() || $token->isGivenKind($skipTypes) || $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(); + } + } + if (null === $info['name']) { + $info['type'] = null; + } + return new ArgumentAnalysis($info['name'], $info['name_index'], $info['default'], null !== $info['type'] ? new TypeAnalysis($info['type'], $info['type_index_start'], $info['type_index_end']) : null); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php new file mode 100644 index 00000000000..3d328c5251f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/AttributeAnalyzer.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class AttributeAnalyzer +{ + private const TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE = [';', '{', [\T_ATTRIBUTE], [\T_FUNCTION], [\T_OPEN_TAG], [\T_OPEN_TAG_WITH_ECHO], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_RETURN], [\T_VARIABLE], [CT::T_ATTRIBUTE_CLOSE]]; + /** + * Check if given index is an attribute declaration. + */ + public static function isAttribute(Tokens $tokens, int $index) : bool + { + if (!\defined('T_ATTRIBUTE') || !$tokens[$index]->isGivenKind(\T_STRING) || !$tokens->isAnyTokenKindsFound([\T_ATTRIBUTE])) { + return \false; + } + $attributeStartIndex = $tokens->getPrevTokenOfKind($index, self::TOKEN_KINDS_NOT_ALLOWED_IN_ATTRIBUTE); + if (!$tokens[$attributeStartIndex]->isGivenKind(\T_ATTRIBUTE)) { + return \false; + } + // now, between attribute start and the attribute candidate index cannot be more "(" than ")" + $count = 0; + for ($i = $attributeStartIndex + 1; $i < $index; ++$i) { + if ($tokens[$i]->equals('(')) { + ++$count; + } elseif ($tokens[$i]->equals(')')) { + --$count; + } + } + return 0 === $count; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php new file mode 100644 index 00000000000..7924bacb68a --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/BlocksAnalyzer.php @@ -0,0 +1,53 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + * + * @internal + */ +final class BlocksAnalyzer +{ + public function isBlock(Tokens $tokens, ?int $openIndex, ?int $closeIndex) : bool + { + 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); + } + /** + * @return Tokens::BLOCK_TYPE_* + */ + private function getBlockType(Token $token) : ?int + { + foreach (Tokens::getBlockEdgeDefinitions() as $blockType => $definition) { + if ($token->equals($definition['start'])) { + return $blockType; + } + } + return null; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php new file mode 100644 index 00000000000..9816d5972cb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ClassyAnalyzer.php @@ -0,0 +1,65 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class ClassyAnalyzer +{ + public function isClassyInvocation(Tokens $tokens, int $index) : bool + { + $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', 'never'], \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, CT::T_TYPE_INTERSECTION, \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_INTERSECTION, CT::T_TYPE_COLON, CT::T_USE_TRAIT])) { + return \true; + } + if (\PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer::isAttribute($tokens, $index)) { + return \true; + } + // `Foo & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = Foo & $bar; + 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]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php new file mode 100644 index 00000000000..401d865195d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/CommentsAnalyzer.php @@ -0,0 +1,230 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + * + * @internal + */ +final class CommentsAnalyzer +{ + private const TYPE_HASH = 1; + private const TYPE_DOUBLE_SLASH = 2; + private const TYPE_SLASH_ASTERISK = 3; + public function isHeaderComment(Tokens $tokens, int $index) : bool + { + 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); + } + /** + * Check if comment at given index precedes structural element. + * + * @see https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + public function isBeforeStructuralElement(Tokens $tokens, int $index) : bool + { + $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); + // @TODO: drop condition when PHP 8.0+ is required + 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; + } + if ($this->isStructuralElement($tokens, $nextIndex)) { + 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; + } + if ($tokens[$nextIndex]->isGivenKind(CT::T_USE_TRAIT)) { + return \true; + } + return \false; + } + /** + * Return array of indices that are part of a comment started at given index. + * + * @param int $index T_COMMENT index + * + * @return list + */ + public function getCommentBlockIndices(Tokens $tokens, int $index) : array + { + 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; + } + /** + * @see https://github.com/phpDocumentor/fig-standards/blob/master/proposed/phpdoc.md#3-definitions + */ + private function isStructuralElement(Tokens $tokens, int $index) : bool + { + static $skip; + if (null === $skip) { + $skip = [\T_PRIVATE, \T_PROTECTED, \T_PUBLIC, \T_VAR, \T_FUNCTION, \T_FN, \T_ABSTRACT, \T_CONST, \T_NAMESPACE, \T_REQUIRE, \T_REQUIRE_ONCE, \T_INCLUDE, \T_INCLUDE_ONCE, \T_FINAL, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $skip[] = \T_READONLY; + } + } + $token = $tokens[$index]; + if ($token->isClassy() || $token->isGivenKind($skip)) { + return \true; + } + if ($token->isGivenKind(\T_CASE) && \defined('T_ENUM')) { + $caseParent = $tokens->getPrevTokenOfKind($index, [[\T_ENUM], [\T_SWITCH]]); + return $tokens[$caseParent]->isGivenKind([\T_ENUM]); + } + if ($token->isGivenKind(\T_STATIC)) { + return !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON); + } + return \false; + } + /** + * Checks control structures (for, foreach, if, switch, while) for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $controlIndex index of control structure Token + */ + private function isValidControl(Tokens $tokens, Token $docsToken, int $controlIndex) : bool + { + 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) && \strpos($docsContent, $token->getContent()) !== \false) { + return \true; + } + } + return \false; + } + /** + * Checks variable assignments through `list()`, `print()` etc. calls for correct docblock usage. + * + * @param Token $docsToken docs Token + * @param int $languageConstructIndex index of variable Token + */ + private function isValidLanguageConstruct(Tokens $tokens, Token $docsToken, int $languageConstructIndex) : bool + { + 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) && \strpos($docsContent, $token->getContent()) !== \false) { + return \true; + } + } + return \false; + } + /** + * Checks variable assignments for correct docblock usage. + * + * @param int $index index of variable Token + */ + private function isValidVariable(Tokens $tokens, int $index) : bool + { + if (!$tokens[$index]->isGivenKind(\T_VARIABLE)) { + return \false; + } + $nextIndex = $tokens->getNextMeaningfulToken($index); + return $tokens[$nextIndex]->equals('='); + } + private function getCommentType(string $content) : int + { + if (\strncmp($content, '#', \strlen('#')) === 0) { + return self::TYPE_HASH; + } + if ('*' === $content[1]) { + return self::TYPE_SLASH_ASTERISK; + } + return self::TYPE_DOUBLE_SLASH; + } + private function getLineBreakCount(Tokens $tokens, int $whiteStart, int $whiteEnd) : int + { + $lineCount = 0; + for ($i = $whiteStart; $i < $whiteEnd; ++$i) { + $lineCount += Preg::matchAll('/\\R/u', $tokens[$i]->getContent()); + } + return $lineCount; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php new file mode 100644 index 00000000000..43947811d8f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ControlCaseStructuresAnalyzer.php @@ -0,0 +1,232 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\AbstractControlCaseStructuresAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\CaseAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DefaultAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\EnumAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\MatchAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\SwitchAnalysis; +use PhpCsFixer\Tokenizer\Tokens; +final class ControlCaseStructuresAnalyzer +{ + /** + * @param list $types Token types of interest of which analyzes must be returned + * + * @return \Generator + */ + public static function findControlStructures(Tokens $tokens, array $types) : \Generator + { + if (\count($types) < 1) { + return; + // quick skip + } + $typesWithCaseOrDefault = self::getTypesWithCaseOrDefault(); + foreach ($types as $type) { + if (!\in_array($type, $typesWithCaseOrDefault, \true)) { + throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $type)); + } + } + if (!$tokens->isAnyTokenKindsFound($types)) { + return; + // quick skip + } + $depth = -1; + /** + * @var list, + * default: array{index: int, open: int}|null, + * alternative_syntax: bool, + * }> $stack + */ + $stack = []; + $isTypeOfInterest = \false; + foreach ($tokens as $index => $token) { + if ($token->isGivenKind($typesWithCaseOrDefault)) { + ++$depth; + $stack[$depth] = ['kind' => $token->getId(), 'index' => $index, 'brace_count' => 0, 'cases' => [], 'default' => null, 'alternative_syntax' => \false]; + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, \true); + if ($token->isGivenKind(\T_SWITCH)) { + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + $stack[$depth]['alternative_syntax'] = $tokens[$stack[$depth]['open']]->equals(':'); + } elseif (\defined('T_MATCH') && $token->isGivenKind(\T_MATCH)) { + // @TODO: drop condition when PHP 8.0+ is required + $index = $tokens->getNextMeaningfulToken($index); + $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $stack[$depth]['open'] = $tokens->getNextMeaningfulToken($index); + } elseif (\defined('T_ENUM') && $token->isGivenKind(\T_ENUM)) { + $stack[$depth]['open'] = $tokens->getNextTokenOfKind($index, ['{']); + } + continue; + } + if ($depth < 0) { + continue; + } + if ($token->equals('{')) { + ++$stack[$depth]['brace_count']; + continue; + } + if ($token->equals('}')) { + --$stack[$depth]['brace_count']; + if (0 === $stack[$depth]['brace_count']) { + if ($stack[$depth]['alternative_syntax']) { + continue; + } + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + (yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth])); + } + \array_pop($stack); + --$depth; + if ($depth < -1) { + // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure.'); + } + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, \true); + } + } + continue; + } + if ($tokens[$index]->isGivenKind(\T_ENDSWITCH)) { + if (!$stack[$depth]['alternative_syntax']) { + throw new \RuntimeException('Analysis syntax failure, unexpected "T_ENDSWITCH".'); + } + if (\T_SWITCH !== $stack[$depth]['kind']) { + throw new \RuntimeException('Analysis type failure, unexpected "T_ENDSWITCH".'); + } + if (0 !== $stack[$depth]['brace_count']) { + throw new \RuntimeException('Analysis count failure, unexpected "T_ENDSWITCH".'); + } + $index = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + if ($isTypeOfInterest) { + $stack[$depth]['end'] = $index; + (yield $stack[$depth]['index'] => self::buildControlCaseStructureAnalysis($stack[$depth])); + } + \array_pop($stack); + --$depth; + if ($depth < -1) { + // @phpstan-ignore-line + throw new \RuntimeException('Analysis depth count failure ("T_ENDSWITCH").'); + } + if (isset($stack[$depth]['kind'])) { + $isTypeOfInterest = \in_array($stack[$depth]['kind'], $types, \true); + } + } + if (!$isTypeOfInterest) { + continue; + // don't bother to analyze stuff that caller is not interested in + } + if ($token->isGivenKind(\T_CASE)) { + $stack[$depth]['cases'][] = ['index' => $index, 'open' => self::findCaseOpen($tokens, $stack[$depth]['kind'], $index)]; + } elseif ($token->isGivenKind(\T_DEFAULT)) { + if (null !== $stack[$depth]['default']) { + throw new \RuntimeException('Analysis multiple "default" found.'); + } + $stack[$depth]['default'] = ['index' => $index, 'open' => self::findDefaultOpen($tokens, $stack[$depth]['kind'], $index)]; + } + } + } + /** + * @param array{ + * kind: int, + * index: int, + * open: int, + * end: int, + * cases: list, + * default: null|array{index: int, open: int}, + * } $analysis + */ + private static function buildControlCaseStructureAnalysis(array $analysis) : AbstractControlCaseStructuresAnalysis + { + $default = null === $analysis['default'] ? null : new DefaultAnalysis($analysis['default']['index'], $analysis['default']['open']); + $cases = []; + foreach ($analysis['cases'] as $case) { + $cases[$case['index']] = new CaseAnalysis($case['index'], $case['open']); + } + \sort($cases); + if (\T_SWITCH === $analysis['kind']) { + return new SwitchAnalysis($analysis['index'], $analysis['open'], $analysis['end'], $cases, $default); + } + if (\defined('T_ENUM') && \T_ENUM === $analysis['kind']) { + return new EnumAnalysis($analysis['index'], $analysis['open'], $analysis['end'], $cases); + } + if (\defined('T_MATCH') && \T_MATCH === $analysis['kind']) { + // @TODO: drop condition when PHP 8.0+ is required + return new MatchAnalysis($analysis['index'], $analysis['open'], $analysis['end'], $default); + } + throw new \InvalidArgumentException(\sprintf('Unexpected type "%d".', $analysis['kind'])); + } + private static function findCaseOpen(Tokens $tokens, int $kind, int $index) : int + { + if (\T_SWITCH === $kind) { + $ternariesCount = 0; + do { + if ($tokens[$index]->equalsAny(['(', '{'])) { + // skip constructs + $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); + return $index; + } + if (\defined('T_ENUM') && \T_ENUM === $kind) { + return $tokens->getNextTokenOfKind($index, ['=', ';']); + } + throw new \InvalidArgumentException(\sprintf('Unexpected case for type "%d".', $kind)); + } + private static function findDefaultOpen(Tokens $tokens, int $kind, int $index) : int + { + if (\T_SWITCH === $kind) { + return $tokens->getNextTokenOfKind($index, [':', ';']); + } + if (\defined('T_MATCH') && \T_MATCH === $kind) { + // @TODO: drop condition when PHP 8.0+ is required + return $tokens->getNextTokenOfKind($index, [[\T_DOUBLE_ARROW]]); + } + throw new \InvalidArgumentException(\sprintf('Unexpected default for type "%d".', $kind)); + } + /** + * @return list + */ + private static function getTypesWithCaseOrDefault() : array + { + $supportedTypes = [\T_SWITCH]; + if (\defined('T_MATCH')) { + // @TODO: drop condition when PHP 8.0+ is required + $supportedTypes[] = \T_MATCH; + } + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + $supportedTypes[] = \T_ENUM; + } + return $supportedTypes; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php new file mode 100644 index 00000000000..ef4629a6206 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/DataProviderAnalyzer.php @@ -0,0 +1,75 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\DocBlock\TypeExpression; +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\DataProviderAnalysis; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + * + * @internal + */ +final class DataProviderAnalyzer +{ + private const REGEX_CLASS = '(?:\\\\?+' . TypeExpression::REGEX_IDENTIFIER . '(\\\\' . TypeExpression::REGEX_IDENTIFIER . ')*+)'; + /** + * @return array + */ + public function getDataProviders(Tokens $tokens, int $startIndex, int $endIndex) : array + { + $methods = $this->getMethods($tokens, $startIndex, $endIndex); + $dataProviders = []; + foreach ($methods as $methodIndex) { + $docCommentIndex = $tokens->getTokenNotOfKindSibling($methodIndex, -1, [[\T_ABSTRACT], [\T_COMMENT], [\T_FINAL], [\T_FUNCTION], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_STATIC], [\T_WHITESPACE]]); + if (!$tokens[$docCommentIndex]->isGivenKind(\T_DOC_COMMENT)) { + continue; + } + Preg::matchAll('/@dataProvider\\h+((' . self::REGEX_CLASS . '::)?' . TypeExpression::REGEX_IDENTIFIER . ')/', $tokens[$docCommentIndex]->getContent(), $matches); + /** @var array $matches */ + $matches = $matches[1]; + foreach ($matches as $dataProviderName) { + $dataProviders[$dataProviderName][] = $docCommentIndex; + } + } + $dataProviderAnalyses = []; + foreach ($dataProviders as $dataProviderName => $dataProviderUsages) { + $lowercaseDataProviderName = \strtolower($dataProviderName); + if (!\array_key_exists($lowercaseDataProviderName, $methods)) { + continue; + } + $dataProviderAnalyses[$methods[$lowercaseDataProviderName]] = new DataProviderAnalysis($tokens[$methods[$lowercaseDataProviderName]]->getContent(), $methods[$lowercaseDataProviderName], $dataProviderUsages); + } + \ksort($dataProviderAnalyses); + return \array_values($dataProviderAnalyses); + } + /** + * @return array + */ + private function getMethods(Tokens $tokens, int $startIndex, int $endIndex) : array + { + $functions = []; + for ($index = $startIndex; $index < $endIndex; ++$index) { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + continue; + } + $functionNameIndex = $tokens->getNextNonWhitespace($index); + if (!$tokens[$functionNameIndex]->isGivenKind(\T_STRING)) { + continue; + } + $functions[\strtolower($tokens[$functionNameIndex]->getContent())] = $functionNameIndex; + } + return $functions; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php new file mode 100644 index 00000000000..e5b8e0f2a56 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/FunctionsAnalyzer.php @@ -0,0 +1,204 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +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; +/** + * @internal + */ +final class FunctionsAnalyzer +{ + /** + * @var array{tokens: string, imports: list, declarations: list} + */ + private $functionsAnalysis = ['tokens' => '', 'imports' => [], 'declarations' => []]; + /** + * Important: risky because of the limited (file) scope of the tool. + */ + public function isGlobalFunctionCall(Tokens $tokens, int $index) : bool + { + 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); + } + $possibleKind = \array_merge([\T_DOUBLE_COLON, \T_FUNCTION, CT::T_NAMESPACE_OPERATOR, \T_NEW, CT::T_RETURN_REF, \T_STRING], Token::getObjectOperatorKinds()); + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_ATTRIBUTE')) { + $possibleKind[] = \T_ATTRIBUTE; + } + if ($tokens[$prevIndex]->isGivenKind($possibleKind)) { + return \false; + } + if ($tokens[$tokens->getNextMeaningfulToken($nextIndex)]->isGivenKind(CT::T_FIRST_CLASS_CALLABLE)) { + return \false; + } + if ($previousIsNamespaceSeparator) { + return \true; + } + if ($tokens->isChanged() || $tokens->getCodeHash() !== $this->functionsAnalysis['tokens']) { + $this->buildFunctionsAnalysis($tokens); + } + // figure out in which namespace we are + $scopeStartIndex = 0; + $scopeEndIndex = \count($tokens) - 1; + $inGlobalNamespace = \false; + foreach ($tokens->getNamespaceDeclarations() as $declaration) { + $scopeStartIndex = $declaration->getScopeStartIndex(); + $scopeEndIndex = $declaration->getScopeEndIndex(); + if ($index >= $scopeStartIndex && $index <= $scopeEndIndex) { + $inGlobalNamespace = $declaration->isGlobalNamespace(); + break; + } + } + $call = \strtolower($tokens[$index]->getContent()); + // check if the call is to a function declared in the same namespace as the call is done, + // if the call is already in the global namespace than declared functions are in the same + // global namespace and don't need checking + if (!$inGlobalNamespace) { + /** @var int $functionNameIndex */ + foreach ($this->functionsAnalysis['declarations'] as $functionNameIndex) { + if ($functionNameIndex < $scopeStartIndex || $functionNameIndex > $scopeEndIndex) { + continue; + } + if (\strtolower($tokens[$functionNameIndex]->getContent()) === $call) { + return \false; + } + } + } + /** @var NamespaceUseAnalysis $functionUse */ + foreach ($this->functionsAnalysis['imports'] as $functionUse) { + if ($functionUse->getStartIndex() < $scopeStartIndex || $functionUse->getEndIndex() > $scopeEndIndex) { + continue; + } + if ($call !== \strtolower($functionUse->getShortName())) { + continue; + } + // global import like `use function \str_repeat;` + return $functionUse->getShortName() === \ltrim($functionUse->getFullName(), '\\'); + } + if (\PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer::isAttribute($tokens, $index)) { + return \false; + } + return \true; + } + /** + * @return array + */ + public function getFunctionArguments(Tokens $tokens, int $functionIndex) : array + { + $argumentsStart = $tokens->getNextTokenOfKind($functionIndex, ['(']); + $argumentsEnd = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $argumentsStart); + $argumentAnalyzer = new \PhpCsFixer\Tokenizer\Analyzer\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, int $methodIndex) : ?TypeAnalysis + { + $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, int $index) : bool + { + if (!$tokens->offsetExists($index)) { + return \false; + } + $operatorIndex = $tokens->getPrevMeaningfulToken($index); + if (null === $operatorIndex) { + return \false; + } + if (!$tokens[$operatorIndex]->isObjectOperator() && !$tokens[$operatorIndex]->isGivenKind(\T_DOUBLE_COLON)) { + return \false; + } + $referenceIndex = $tokens->getPrevMeaningfulToken($operatorIndex); + if (null === $referenceIndex) { + return \false; + } + return $tokens[$referenceIndex]->equalsAny([[\T_VARIABLE, '$this'], [\T_STRING, 'self'], [\T_STATIC, 'static']], \false); + } + private function buildFunctionsAnalysis(Tokens $tokens) : void + { + $this->functionsAnalysis = ['tokens' => $tokens->getCodeHash(), 'imports' => [], 'declarations' => []]; + // find declarations + if ($tokens->isTokenKindFound(\T_FUNCTION)) { + $end = \count($tokens); + for ($i = 0; $i < $end; ++$i) { + // skip classy, we are looking for functions not methods + if ($tokens[$i]->isGivenKind(Token::getClassyTokenKinds())) { + $i = $tokens->getNextTokenOfKind($i, ['(', '{']); + if ($tokens[$i]->equals('(')) { + // anonymous class + $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; + } + } + // find imported functions + $namespaceUsesAnalyzer = new \PhpCsFixer\Tokenizer\Analyzer\NamespaceUsesAnalyzer(); + if ($tokens->isTokenKindFound(CT::T_FUNCTION_IMPORT)) { + $declarations = $namespaceUsesAnalyzer->getDeclarationsFromTokens($tokens); + foreach ($declarations as $declaration) { + if ($declaration->isFunction()) { + $this->functionsAnalysis['imports'][] = $declaration; + } + } + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php new file mode 100644 index 00000000000..5fc46aae6ff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/GotoLabelAnalyzer.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class GotoLabelAnalyzer +{ + public function belongsToGoToLabel(Tokens $tokens, int $index) : bool + { + 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]]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php new file mode 100644 index 00000000000..dc217e95cb7 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespaceUsesAnalyzer.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceUseAnalysis; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +use PhpCsFixer\Tokenizer\TokensAnalyzer; +/** + * @internal + */ +final class NamespaceUsesAnalyzer +{ + /** + * @return list + */ + public function getDeclarationsFromTokens(Tokens $tokens) : array + { + $tokenAnalyzer = new TokensAnalyzer($tokens); + $useIndices = $tokenAnalyzer->getImportUseIndexes(); + return $this->getDeclarations($tokens, $useIndices); + } + /** + * @return list + */ + public function getDeclarationsInNamespace(Tokens $tokens, NamespaceAnalysis $namespace) : array + { + $namespaceUses = []; + foreach ($this->getDeclarationsFromTokens($tokens) as $namespaceUse) { + if ($namespaceUse->getStartIndex() >= $namespace->getScopeStartIndex() && $namespaceUse->getStartIndex() <= $namespace->getScopeEndIndex()) { + $namespaceUses[] = $namespaceUse; + } + } + return $namespaceUses; + } + /** + * @param list $useIndices + * + * @return list + */ + private function getDeclarations(Tokens $tokens, array $useIndices) : array + { + $uses = []; + foreach ($useIndices as $index) { + $endIndex = $tokens->getNextTokenOfKind($index, [';', [\T_CLOSE_TAG]]); + $analysis = $this->parseDeclaration($tokens, $index, $endIndex); + if (null !== $analysis) { + $uses[] = $analysis; + } + } + return $uses; + } + private function parseDeclaration(Tokens $tokens, int $startIndex, int $endIndex) : ?NamespaceUseAnalysis + { + $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)) { + // do not touch group use declarations until the logic of this is added (for example: `use some\a\{ClassD};`) + // ignore multiple use statements that should be split into few separate statements (for example: `use BarB, BarC as C;`) + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php new file mode 100644 index 00000000000..585cfff9a4f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/NamespacesAnalyzer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class NamespacesAnalyzer +{ + /** + * @return list + */ + public function getDeclarations(Tokens $tokens) : array + { + $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); + // Continue the analysis after the end of this namespace to find the next one + $index = $scopeEndIndex; + } + if (0 === \count($namespaces)) { + $namespaces[] = new NamespaceAnalysis('', '', 0, 0, 0, \count($tokens) - 1); + } + return $namespaces; + } + public function getNamespaceAt(Tokens $tokens, int $index) : NamespaceAnalysis + { + if (!$tokens->offsetExists($index)) { + throw new \InvalidArgumentException(\sprintf('Token index %d does not exist.', $index)); + } + foreach ($this->getDeclarations($tokens) as $namespace) { + if ($namespace->getScopeStartIndex() <= $index && $namespace->getScopeEndIndex() >= $index) { + return $namespace; + } + } + throw new \LogicException(\sprintf('Unable to get the namespace at index %d.', $index)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php new file mode 100644 index 00000000000..dbb94ef2cdf --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/RangeAnalyzer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class RangeAnalyzer +{ + private function __construct() + { + // cannot create instance of util. class + } + /** + * Meaningful compare of tokens within ranges. + * + * @param array{start: int, end: int} $range1 + * @param array{start: int, end: int} $range2 + */ + public static function rangeEqualsRange(Tokens $tokens, array $range1, array $range2) : bool + { + $leftStart = $range1['start']; + $leftEnd = $range1['end']; + if ($tokens[$leftStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + } + while ($tokens[$leftStart]->equals('(') && $tokens[$leftEnd]->equals(')')) { + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $leftEnd = $tokens->getPrevMeaningfulToken($leftEnd); + } + $rightStart = $range2['start']; + $rightEnd = $range2['end']; + if ($tokens[$rightStart]->isGivenKind([\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT])) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + } + while ($tokens[$rightStart]->equals('(') && $tokens[$rightEnd]->equals(')')) { + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + $rightEnd = $tokens->getPrevMeaningfulToken($rightEnd); + } + $arrayOpenTypes = ['[', [CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN]]; + $arrayCloseTypes = [']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE]]; + while (\true) { + $leftToken = $tokens[$leftStart]; + $rightToken = $tokens[$rightStart]; + if (!$leftToken->equals($rightToken) && !($leftToken->equalsAny($arrayOpenTypes) && $rightToken->equalsAny($arrayOpenTypes)) && !($leftToken->equalsAny($arrayCloseTypes) && $rightToken->equalsAny($arrayCloseTypes))) { + return \false; + } + $leftStart = $tokens->getNextMeaningfulToken($leftStart); + $rightStart = $tokens->getNextMeaningfulToken($rightStart); + $reachedLeftEnd = null === $leftStart || $leftStart > $leftEnd; + // reached end left or moved over + $reachedRightEnd = null === $rightStart || $rightStart > $rightEnd; + // reached end right or moved over + if (!$reachedLeftEnd && !$reachedRightEnd) { + continue; + } + return $reachedLeftEnd && $reachedRightEnd; + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php new file mode 100644 index 00000000000..fcd0df5d064 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/ReferenceAnalyzer.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @author Kuba Werłos + * + * @internal + */ +final class ReferenceAnalyzer +{ + public function isReference(Tokens $tokens, int $index) : bool + { + if ($tokens[$index]->isGivenKind(CT::T_RETURN_REF)) { + return \true; + } + if (!$tokens[$index]->equals('&')) { + return \false; + } + /** @var int $index */ + $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]]); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php new file mode 100644 index 00000000000..55fec970226 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Analyzer/WhitespacesAnalyzer.php @@ -0,0 +1,41 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Analyzer; + +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class WhitespacesAnalyzer +{ + public static function detectIndent(Tokens $tokens, int $index) : string + { + while (\true) { + $whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[\T_WHITESPACE]]); + if (null === $whitespaceIndex) { + return ''; + } + $whitespaceToken = $tokens[$whitespaceIndex]; + if (\strpos($whitespaceToken->getContent(), "\n") !== \false) { + 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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php new file mode 100644 index 00000000000..dfaaf168800 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CT.php @@ -0,0 +1,97 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + */ +final class CT +{ + public const T_ARRAY_INDEX_CURLY_BRACE_CLOSE = 10001; + public const T_ARRAY_INDEX_CURLY_BRACE_OPEN = 10002; + public const T_ARRAY_SQUARE_BRACE_CLOSE = 10003; + public const T_ARRAY_SQUARE_BRACE_OPEN = 10004; + public const T_ARRAY_TYPEHINT = 10005; + public const T_BRACE_CLASS_INSTANTIATION_CLOSE = 10006; + public const T_BRACE_CLASS_INSTANTIATION_OPEN = 10007; + public const T_CLASS_CONSTANT = 10008; + public const T_CONST_IMPORT = 10009; + public const T_CURLY_CLOSE = 10010; + public const T_DESTRUCTURING_SQUARE_BRACE_CLOSE = 10011; + public const T_DESTRUCTURING_SQUARE_BRACE_OPEN = 10012; + public const T_DOLLAR_CLOSE_CURLY_BRACES = 10013; + public const T_DYNAMIC_PROP_BRACE_CLOSE = 10014; + public const T_DYNAMIC_PROP_BRACE_OPEN = 10015; + public const T_DYNAMIC_VAR_BRACE_CLOSE = 10016; + public const T_DYNAMIC_VAR_BRACE_OPEN = 10017; + public const T_FUNCTION_IMPORT = 10018; + public const T_GROUP_IMPORT_BRACE_CLOSE = 10019; + public const T_GROUP_IMPORT_BRACE_OPEN = 10020; + public const T_NAMESPACE_OPERATOR = 10021; + public const T_NULLABLE_TYPE = 10022; + public const T_RETURN_REF = 10023; + public const T_TYPE_ALTERNATION = 10024; + public const T_TYPE_COLON = 10025; + public const T_USE_LAMBDA = 10026; + public const T_USE_TRAIT = 10027; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC = 10028; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED = 10029; + public const T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE = 10030; + public const T_ATTRIBUTE_CLOSE = 10031; + public const T_NAMED_ARGUMENT_NAME = 10032; + public const T_NAMED_ARGUMENT_COLON = 10033; + public const T_FIRST_CLASS_CALLABLE = 10034; + public const T_TYPE_INTERSECTION = 10035; + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN = 10036; + public const T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE = 10037; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN = 10038; + public const T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE = 10039; + private function __construct() + { + } + /** + * Get name for custom token. + * + * @param int $value custom token value + */ + public static function getName(int $value) : string + { + if (!self::has($value)) { + throw new \InvalidArgumentException(\sprintf('No custom token was found for "%s".', $value)); + } + $tokens = self::getMapById(); + return 'CT::' . $tokens[$value]; + } + /** + * Check if given custom token exists. + * + * @param int $value custom token value + */ + public static function has(int $value) : bool + { + $tokens = self::getMapById(); + return isset($tokens[$value]); + } + /** + * @return array + */ + private static function getMapById() : array + { + static $constants; + if (null === $constants) { + $reflection = new \ReflectionClass(__CLASS__); + $constants = \array_flip($reflection->getConstants()); + } + return $constants; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php new file mode 100644 index 00000000000..16ba121cc5b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/CodeHasher.php @@ -0,0 +1,33 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class CodeHasher +{ + private function __construct() + { + // cannot create instance of util. class + } + /** + * Calculate hash for code. + */ + public static function calculateCodeHash(string $code) : string + { + return \md5($code); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php new file mode 100644 index 00000000000..371081be06d --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Token.php @@ -0,0 +1,402 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +/** + * Representation of single token. + * As a token prototype you should understand a single element generated by token_get_all. + * + * @author Dariusz Rumiński + */ +final class Token +{ + /** + * Content of token prototype. + * @var string + */ + private $content; + /** + * ID of token prototype, if available. + * @var int|null + */ + private $id; + /** + * If token prototype is an array. + * @var bool + */ + private $isArray; + /** + * Flag is token was changed. + * @var bool + */ + private $changed = \false; + /** + * @param array{int, string}|string $token token prototype + */ + public function __construct($token) + { + if (\is_array($token)) { + if (!\is_int($token[0])) { + throw new \InvalidArgumentException(\sprintf('Id must be an int, got "%s".', \get_debug_type($token[0]))); + } + if (!\is_string($token[1])) { + throw new \InvalidArgumentException(\sprintf('Content must be a string, got "%s".', \get_debug_type($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]; + } 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".', \get_debug_type($token))); + } + } + /** + * @return list + */ + public static function getCastTokenKinds() : array + { + 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; + } + /** + * Get classy tokens kinds: T_CLASS, T_INTERFACE and T_TRAIT. + * + * @return list + */ + public static function getClassyTokenKinds() : array + { + static $classTokens; + if (null === $classTokens) { + $classTokens = [\T_CLASS, \T_TRAIT, \T_INTERFACE]; + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + $classTokens[] = \T_ENUM; + } + } + return $classTokens; + } + /** + * Get object operator tokens kinds: T_OBJECT_OPERATOR and (if available) T_NULLSAFE_OBJECT_OPERATOR. + * + * @return list + */ + public static function getObjectOperatorKinds() : array + { + static $objectOperators = null; + if (null === $objectOperators) { + $objectOperators = [\T_OBJECT_OPERATOR]; + if (\defined('T_NULLSAFE_OBJECT_OPERATOR')) { + $objectOperators[] = \T_NULLSAFE_OBJECT_OPERATOR; + } + } + return $objectOperators; + } + /** + * Check if token is equals to given one. + * + * If tokens are arrays, then only keys defined in parameter token are checked. + * + * @param array{0: int, 1?: string}|string|Token $other token or it's prototype + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equals($other, bool $caseSensitive = \true) : bool + { + if (\defined('T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG')) { + // @TODO: drop condition with new MAJOR release 4.0 + if ('&' === $other) { + return '&' === $this->content && (null === $this->id || $this->isGivenKind([\T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + if (null === $this->id && '&' === $this->content) { + return $other instanceof self && '&' === $other->content && (null === $other->id || $other->isGivenKind([\T_AMPERSAND_FOLLOWED_BY_VAR_OR_VARARG, \T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG])); + } + } + if ($other instanceof self) { + // Inlined getPrototype() on this very hot path. + // We access the private properties of $other directly to save function call overhead. + // This is only possible because $other is of the same class as `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; + } + } + // detect unknown keys + unset($otherPrototype[0], $otherPrototype[1]); + return [] === $otherPrototype; + } + /** + * Check if token is equals to one of given. + * + * @param list $others array of tokens or token prototypes + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function equalsAny(array $others, bool $caseSensitive = \true) : bool + { + foreach ($others as $other) { + if ($this->equals($other, $caseSensitive)) { + return \true; + } + } + return \false; + } + /** + * A helper method used to find out whether a certain input token has to be case-sensitively matched. + * + * @param bool|list $caseSensitive global case sensitiveness or an array of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * @param int $key the key of the token that has to be looked up + */ + public static function isKeyCaseSensitive($caseSensitive, int $key) : bool + { + if (\is_array($caseSensitive)) { + return $caseSensitive[$key] ?? \true; + } + return $caseSensitive; + } + /** + * @return array{int, string}|string + */ + public function getPrototype() + { + if (!$this->isArray) { + return $this->content; + } + return [$this->id, $this->content]; + } + /** + * Get token's content. + * + * It shall be used only for getting the content of token, not for checking it against excepted value. + */ + public function getContent() : string + { + return $this->content; + } + /** + * Get token's id. + * + * It shall be used only for getting the internal id of token, not for checking it against excepted value. + */ + public function getId() : ?int + { + return $this->id; + } + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|string token name + */ + public function getName() : ?string + { + if (null === $this->id) { + return null; + } + return self::getNameForId($this->id); + } + /** + * Get token's name. + * + * It shall be used only for getting the name of token, not for checking it against excepted value. + * + * @return null|string token name + */ + public static function getNameForId(int $id) : ?string + { + if (\PhpCsFixer\Tokenizer\CT::has($id)) { + return \PhpCsFixer\Tokenizer\CT::getName($id); + } + $name = \token_name($id); + return 'UNKNOWN' === $name ? null : $name; + } + /** + * Generate array containing all keywords that exists in PHP version in use. + * + * @return array + */ + public static function getKeywords() : array + { + 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', 'T_READONLY', 'T_ENUM']) + [\PhpCsFixer\Tokenizer\CT::T_ARRAY_TYPEHINT => \PhpCsFixer\Tokenizer\CT::T_ARRAY_TYPEHINT, \PhpCsFixer\Tokenizer\CT::T_CLASS_CONSTANT => \PhpCsFixer\Tokenizer\CT::T_CLASS_CONSTANT, \PhpCsFixer\Tokenizer\CT::T_CONST_IMPORT => \PhpCsFixer\Tokenizer\CT::T_CONST_IMPORT, \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE => \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE, \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED => \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC => \PhpCsFixer\Tokenizer\CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, \PhpCsFixer\Tokenizer\CT::T_FUNCTION_IMPORT => \PhpCsFixer\Tokenizer\CT::T_FUNCTION_IMPORT, \PhpCsFixer\Tokenizer\CT::T_NAMESPACE_OPERATOR => \PhpCsFixer\Tokenizer\CT::T_NAMESPACE_OPERATOR, \PhpCsFixer\Tokenizer\CT::T_USE_LAMBDA => \PhpCsFixer\Tokenizer\CT::T_USE_LAMBDA, \PhpCsFixer\Tokenizer\CT::T_USE_TRAIT => \PhpCsFixer\Tokenizer\CT::T_USE_TRAIT]; + } + return $keywords; + } + /** + * Generate array containing all predefined constants that exists in PHP version in use. + * + * @see https://php.net/manual/en/language.constants.predefined.php + * + * @return array + */ + public static function getMagicConstants() : array + { + 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; + } + /** + * Check if token prototype is an array. + * + * @return bool is array + */ + public function isArray() : bool + { + return $this->isArray; + } + /** + * Check if token is one of type cast tokens. + */ + public function isCast() : bool + { + return $this->isGivenKind(self::getCastTokenKinds()); + } + /** + * Check if token is one of classy tokens: T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM. + */ + public function isClassy() : bool + { + return $this->isGivenKind(self::getClassyTokenKinds()); + } + /** + * Check if token is one of comment tokens: T_COMMENT or T_DOC_COMMENT. + */ + public function isComment() : bool + { + static $commentTokens = [\T_COMMENT, \T_DOC_COMMENT]; + return $this->isGivenKind($commentTokens); + } + /** + * Check if token is one of object operator tokens: T_OBJECT_OPERATOR or T_NULLSAFE_OBJECT_OPERATOR. + */ + public function isObjectOperator() : bool + { + return $this->isGivenKind(self::getObjectOperatorKinds()); + } + /** + * Check if token is one of given kind. + * + * @param int|list $possibleKind kind or array of kinds + */ + public function isGivenKind($possibleKind) : bool + { + return $this->isArray && (\is_array($possibleKind) ? \in_array($this->id, $possibleKind, \true) : $this->id === $possibleKind); + } + /** + * Check if token is a keyword. + */ + public function isKeyword() : bool + { + $keywords = self::getKeywords(); + return $this->isArray && isset($keywords[$this->id]); + } + /** + * Check if token is a native PHP constant: true, false or null. + */ + public function isNativeConstant() : bool + { + static $nativeConstantStrings = ['true', 'false', 'null']; + return $this->isArray && \in_array(\strtolower($this->content), $nativeConstantStrings, \true); + } + /** + * Returns if the token is of a Magic constants type. + * + * @see https://php.net/manual/en/language.constants.predefined.php + */ + public function isMagicConstant() : bool + { + $magicConstants = self::getMagicConstants(); + return $this->isArray && isset($magicConstants[$this->id]); + } + /** + * Check if token is whitespace. + * + * @param null|string $whitespaces whitespace characters, default is " \t\n\r\0\x0B" + */ + public function isWhitespace(?string $whitespaces = " \t\n\r\x00\v") : bool + { + if (null === $whitespaces) { + $whitespaces = " \t\n\r\x00\v"; + } + if ($this->isArray && !$this->isGivenKind(\T_WHITESPACE)) { + return \false; + } + return '' === \trim($this->content, $whitespaces); + } + /** + * @return array{ + * id: int|null, + * name: string|null, + * content: string, + * isArray: bool, + * changed: bool, + * } + */ + public function toArray() : array + { + return ['id' => $this->id, 'name' => $this->getName(), 'content' => $this->content, 'isArray' => $this->isArray, 'changed' => $this->changed]; + } + public function toJson() : string + { + $jsonResult = \json_encode($this->toArray(), \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); + if (\JSON_ERROR_NONE !== \json_last_error()) { + $jsonResult = \json_encode(['errorDescription' => 'Cannot encode Tokens to JSON.', 'rawErrorMessage' => \json_last_error_msg()], \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); + } + return $jsonResult; + } + /** + * @param list $tokenNames + * + * @return array + */ + private static function getTokenKindsForNames(array $tokenNames) : array + { + $keywords = []; + foreach ($tokenNames as $keywordName) { + if (\defined($keywordName)) { + $keyword = \constant($keywordName); + $keywords[$keyword] = $keyword; + } + } + return $keywords; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php new file mode 100644 index 00000000000..925b2795127 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Tokens.php @@ -0,0 +1,1143 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Preg; +use PhpCsFixer\Tokenizer\Analyzer\Analysis\NamespaceAnalysis; +use PhpCsFixer\Tokenizer\Analyzer\NamespacesAnalyzer; +/** + * Collection of code tokens. + * + * Its role is to provide the ability to manage collection and navigate through it. + * + * As a token prototype you should understand a single element generated by token_get_all. + * + * @author Dariusz Rumiński + * + * @extends \SplFixedArray + * + * @method Token offsetGet($offset) + * + * @final + */ +class Tokens extends \SplFixedArray +{ + public const BLOCK_TYPE_PARENTHESIS_BRACE = 1; + public const BLOCK_TYPE_CURLY_BRACE = 2; + public const BLOCK_TYPE_INDEX_SQUARE_BRACE = 3; + public const BLOCK_TYPE_ARRAY_SQUARE_BRACE = 4; + public const BLOCK_TYPE_DYNAMIC_PROP_BRACE = 5; + public const BLOCK_TYPE_DYNAMIC_VAR_BRACE = 6; + public const BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE = 7; + public const BLOCK_TYPE_GROUP_IMPORT_BRACE = 8; + public const BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE = 9; + public const BLOCK_TYPE_BRACE_CLASS_INSTANTIATION = 10; + public const BLOCK_TYPE_ATTRIBUTE = 11; + public const BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS = 12; + public const BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE = 13; + /** + * Static class cache. + * + * @var array + */ + private static $cache = []; + /** + * Cache of block starts. Any change in collection will invalidate it. + * + * @var array + */ + private $blockStartCache = []; + /** + * Cache of block ends. Any change in collection will invalidate it. + * + * @var array + */ + private $blockEndCache = []; + /** + * A MD5 hash of the code string. + * @var string|null + */ + private $codeHash; + /** + * Flag is collection was changed. + * + * It doesn't know about change of collection's items. To check it run `isChanged` method. + * @var bool + */ + private $changed = \false; + /** + * Set of found token kinds. + * + * When the token kind is present in this set it means that given token kind + * was ever seen inside the collection (but may not be part of it any longer). + * The key is token kind and the value is always true. + * + * @var array + */ + private $foundTokenKinds = []; + /** + * @var null|list + */ + private $namespaceDeclarations; + /** + * Clone tokens collection. + */ + public function __clone() + { + foreach ($this as $key => $val) { + $this[$key] = clone $val; + } + } + /** + * Clear cache - one position or all of them. + * + * @param null|string $key position to clear, when null clear all + */ + public static function clearCache(?string $key = null) : void + { + if (null === $key) { + self::$cache = []; + return; + } + unset(self::$cache[$key]); + } + /** + * Detect type of block. + * + * @param Token $token token + * + * @return null|array{type: self::BLOCK_TYPE_*, isStart: bool} + */ + public static function detectBlockType(\PhpCsFixer\Tokenizer\Token $token) : ?array + { + 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; + } + /** + * Create token collection from array. + * + * @param Token[] $array the array to import + * @param ?bool $saveIndices save the numeric indices used in the original array, default is yes + */ + public static function fromArray($array, $saveIndices = null) : self + { + $tokens = new self(\count($array)); + if ($saveIndices ?? \true) { + foreach ($array as $key => $val) { + $tokens[$key] = $val; + } + } else { + $index = 0; + foreach ($array as $val) { + $tokens[$index++] = $val; + } + } + $tokens->generateCode(); + // regenerate code to calculate code hash + $tokens->clearChanged(); + return $tokens; + } + /** + * Create token collection directly from code. + * + * @param string $code PHP code + */ + public static function fromCode(string $code) : self + { + $codeHash = self::calculateCodeHash($code); + if (self::hasCache($codeHash)) { + $tokens = self::getCache($codeHash); + // generate the code to recalculate the hash + $tokens->generateCode(); + if ($codeHash === $tokens->codeHash) { + $tokens->clearEmptyTokens(); + $tokens->clearChanged(); + return $tokens; + } + } + $tokens = new self(); + $tokens->setCode($code); + $tokens->clearChanged(); + return $tokens; + } + /** + * @return array> + */ + public static function getBlockEdgeDefinitions() : array + { + $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' => [\PhpCsFixer\Tokenizer\CT::T_ARRAY_SQUARE_BRACE_OPEN, '['], 'end' => [\PhpCsFixer\Tokenizer\CT::T_ARRAY_SQUARE_BRACE_CLOSE, ']']], self::BLOCK_TYPE_DYNAMIC_PROP_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_PROP_BRACE_OPEN, '{'], 'end' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_PROP_BRACE_CLOSE, '}']], self::BLOCK_TYPE_DYNAMIC_VAR_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_VAR_BRACE_OPEN, '{'], 'end' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_VAR_BRACE_CLOSE, '}']], self::BLOCK_TYPE_ARRAY_INDEX_CURLY_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN, '{'], 'end' => [\PhpCsFixer\Tokenizer\CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, '}']], self::BLOCK_TYPE_GROUP_IMPORT_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_GROUP_IMPORT_BRACE_OPEN, '{'], 'end' => [\PhpCsFixer\Tokenizer\CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']], self::BLOCK_TYPE_DESTRUCTURING_SQUARE_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN, '['], 'end' => [\PhpCsFixer\Tokenizer\CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE, ']']], self::BLOCK_TYPE_BRACE_CLASS_INSTANTIATION => ['start' => [\PhpCsFixer\Tokenizer\CT::T_BRACE_CLASS_INSTANTIATION_OPEN, '('], 'end' => [\PhpCsFixer\Tokenizer\CT::T_BRACE_CLASS_INSTANTIATION_CLOSE, ')']], self::BLOCK_TYPE_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS => ['start' => [\PhpCsFixer\Tokenizer\CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '('], 'end' => [\PhpCsFixer\Tokenizer\CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']], self::BLOCK_TYPE_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE => ['start' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{'], 'end' => [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}']]]; + // @TODO: drop condition when PHP 8.0+ is required + if (\defined('T_ATTRIBUTE')) { + $definitions[self::BLOCK_TYPE_ATTRIBUTE] = ['start' => [\T_ATTRIBUTE, '#['], 'end' => [\PhpCsFixer\Tokenizer\CT::T_ATTRIBUTE_CLOSE, ']']]; + } + return $definitions; + } + /** + * Set new size of collection. + * + * @param int $size + */ + public function setSize($size) : bool + { + if ($this->getSize() !== $size) { + $this->changed = \true; + $this->namespaceDeclarations = null; + return parent::setSize($size); + } + return \true; + } + /** + * Unset collection item. + * + * @param int $index + */ + public function offsetUnset($index) : void + { + $this->changed = \true; + $this->namespaceDeclarations = null; + if (isset($this[$index])) { + $this->unregisterFoundToken($this[$index]); + } + parent::offsetUnset($index); + } + /** + * Set collection item. + * + * Warning! `$newval` must not be typehinted to be compatible with `ArrayAccess::offsetSet` method. + * + * @param int $index + * @param Token $newval + */ + public function offsetSet($index, $newval) : void + { + $this->blockStartCache = []; + $this->blockEndCache = []; + if (!isset($this[$index]) || !$this[$index]->equals($newval)) { + $this->changed = \true; + $this->namespaceDeclarations = null; + if (isset($this[$index])) { + $this->unregisterFoundToken($this[$index]); + } + $this->registerFoundToken($newval); + } + parent::offsetSet($index, $newval); + } + /** + * Clear internal flag if collection was changed and flag for all collection's items. + */ + public function clearChanged() : void + { + $this->changed = \false; + } + /** + * Clear empty tokens. + * + * Empty tokens can occur e.g. after calling clear on item of collection. + */ + public function clearEmptyTokens() : void + { + $limit = $this->count(); + for ($index = 0; $index < $limit; ++$index) { + if ($this->isEmptyAt($index)) { + break; + } + } + // no empty token found, therefore there is no need to override collection + if ($limit === $index) { + return; + } + for ($count = $index; $index < $limit; ++$index) { + if (!$this->isEmptyAt($index)) { + // use directly for speed, skip the register of token kinds found etc. + parent::offsetSet($count++, $this[$index]); + } + } + // we are moving the tokens, we need to clear the indices Cache + $this->blockStartCache = []; + $this->blockEndCache = []; + $this->setSize($count); + } + /** + * Ensure that on given index is a whitespace with given kind. + * + * If there is a whitespace then it's content will be modified. + * If not - the new Token will be added. + * + * @param int $index index + * @param int $indexOffset index offset for Token insertion + * @param string $whitespace whitespace to set + * + * @return bool if new Token was added + */ + public function ensureWhitespaceAtIndex(int $index, int $indexOffset, string $whitespace) : bool + { + $removeLastCommentLine = static function (self $tokens, int $index, int $indexOffset, string $whitespace) : string { + $token = $tokens[$index]; + if (1 === $indexOffset && $token->isGivenKind(\T_OPEN_TAG)) { + if (\strncmp($whitespace, "\r\n", \strlen("\r\n")) === 0) { + $tokens[$index] = new \PhpCsFixer\Tokenizer\Token([\T_OPEN_TAG, \rtrim($token->getContent()) . "\r\n"]); + return \strlen($whitespace) > 2 ? \substr($whitespace, 2) : ''; + } + $tokens[$index] = new \PhpCsFixer\Tokenizer\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 \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $whitespace]); + } + return \false; + } + $whitespace = $removeLastCommentLine($this, $index, $indexOffset, $whitespace); + if ('' === $whitespace) { + return \false; + } + $this->insertAt($index + $indexOffset, [new \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $whitespace])]); + return \true; + } + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of opening brace + * + * @return int index of closing brace + */ + public function findBlockEnd(int $type, int $searchIndex) : int + { + return $this->findOppositeBlockEdge($type, $searchIndex, \true); + } + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of closing brace + * + * @return int index of opening brace + */ + public function findBlockStart(int $type, int $searchIndex) : int + { + return $this->findOppositeBlockEdge($type, $searchIndex, \false); + } + /** + * @param int|list $possibleKind kind or array of kinds + * @param int $start optional offset + * @param null|int $end optional limit + * + * @return array>|array + */ + public function findGivenKind($possibleKind, int $start = 0, ?int $end = null) : array + { + if (null === $end) { + $end = $this->count(); + } + $elements = []; + $possibleKinds = (array) $possibleKind; + foreach ($possibleKinds as $kind) { + $elements[$kind] = []; + } + $possibleKinds = \array_filter($possibleKinds, function ($kind) : bool { + return $this->isTokenKindFound($kind); + }); + if (\count($possibleKinds) > 0) { + 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() : string + { + $code = $this->generatePartialCode(0, \count($this) - 1); + $this->changeCodeHash(self::calculateCodeHash($code)); + return $code; + } + /** + * Generate code from tokens between given indices. + * + * @param int $start start index + * @param int $end end index + */ + public function generatePartialCode(int $start, int $end) : string + { + $code = ''; + for ($i = $start; $i <= $end; ++$i) { + $code .= $this[$i]->getContent(); + } + return $code; + } + /** + * Get hash of code. + */ + public function getCodeHash() : string + { + return $this->codeHash; + } + /** + * Get index for closest next token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNextNonWhitespace(int $index, ?string $whitespaces = null) : ?int + { + return $this->getNonWhitespaceSibling($index, 1, $whitespaces); + } + /** + * Get index for closest next token of given kind. + * + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getNextTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = \true) : ?int + { + return $this->getTokenOfKindSibling($index, 1, $tokens, $caseSensitive); + } + /** + * Get index for closest sibling token which is non whitespace. + * + * @param int $index token index + * @param -1|1 $direction + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getNonWhitespaceSibling(int $index, int $direction, ?string $whitespaces = null) : ?int + { + while (\true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + if (!$this[$index]->isWhitespace($whitespaces)) { + return $index; + } + } + } + /** + * Get index for closest previous token which is non whitespace. + * + * This method is shorthand for getNonWhitespaceSibling method. + * + * @param int $index token index + * @param null|string $whitespaces whitespaces characters for Token::isWhitespace + */ + public function getPrevNonWhitespace(int $index, ?string $whitespaces = null) : ?int + { + return $this->getNonWhitespaceSibling($index, -1, $whitespaces); + } + /** + * Get index for closest previous token of given kind. + * This method is shorthand for getTokenOfKindSibling method. + * + * @param int $index token index + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getPrevTokenOfKind(int $index, array $tokens = [], bool $caseSensitive = \true) : ?int + { + return $this->getTokenOfKindSibling($index, -1, $tokens, $caseSensitive); + } + /** + * Get index for closest sibling token of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $tokens possible tokens + * @param bool $caseSensitive perform a case sensitive comparison + */ + public function getTokenOfKindSibling(int $index, int $direction, array $tokens = [], bool $caseSensitive = \true) : ?int + { + $tokens = \array_filter($tokens, function ($token) : bool { + return $this->isTokenKindFound($this->extractTokenKind($token)); + }); + if (0 === \count($tokens)) { + return null; + } + while (\true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + if ($this[$index]->equalsAny($tokens, $caseSensitive)) { + return $index; + } + } + } + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $tokens possible tokens + */ + public function getTokenNotOfKindSibling(int $index, int $direction, array $tokens = []) : ?int + { + return $this->getTokenNotOfKind($index, $direction, function (int $a) use($tokens) : bool { + return $this[$a]->equalsAny($tokens); + }); + } + /** + * Get index for closest sibling token not of given kind. + * + * @param int $index token index + * @param -1|1 $direction + * @param list $kinds possible tokens kinds + */ + public function getTokenNotOfKindsSibling(int $index, int $direction, array $kinds = []) : ?int + { + return $this->getTokenNotOfKind($index, $direction, function (int $index) use($kinds) : bool { + return $this[$index]->isGivenKind($kinds); + }); + } + /** + * Get index for closest sibling token that is not a whitespace, comment or attribute. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getMeaningfulTokenSibling(int $index, int $direction) : ?int + { + return $this->getTokenNotOfKindsSibling($index, $direction, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT]); + } + /** + * Get index for closest sibling token which is not empty. + * + * @param int $index token index + * @param -1|1 $direction + */ + public function getNonEmptySibling(int $index, int $direction) : ?int + { + while (\true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + if (!$this->isEmptyAt($index)) { + return $index; + } + } + } + /** + * Get index for closest next token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getNextMeaningfulToken(int $index) : ?int + { + return $this->getMeaningfulTokenSibling($index, 1); + } + /** + * Get index for closest previous token that is not a whitespace or comment. + * + * @param int $index token index + */ + public function getPrevMeaningfulToken(int $index) : ?int + { + return $this->getMeaningfulTokenSibling($index, -1); + } + /** + * Find a sequence of meaningful tokens and returns the array of their locations. + * + * @param list $sequence an array of token (kinds) + * @param int $start start index, defaulting to the start of the file + * @param null|int $end end index, defaulting to the end of the file + * @param array|bool $caseSensitive global case sensitiveness or a list of booleans, whose keys should match + * the ones used in $sequence. If any is missing, the default case-sensitive + * comparison is used + * + * @return null|array an array containing the tokens matching the sequence elements, indexed by their position + */ + public function findSequence(array $sequence, int $start = 0, ?int $end = null, $caseSensitive = \true) : ?array + { + $sequenceCount = \count($sequence); + if (0 === $sequenceCount) { + throw new \InvalidArgumentException('Invalid sequence.'); + } + // $end defaults to the end of the collection + $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]; + // make sure the sequence content is "meaningful" + foreach ($sequence as $key => $token) { + // if not a Token instance already, we convert it to verify the meaningfulness + if (!$token instanceof \PhpCsFixer\Tokenizer\Token) { + if (\is_array($token) && !isset($token[1])) { + // fake some content as it is required by the Token constructor, + // although optional for search purposes + $token[1] = 'DUMMY'; + } + $token = new \PhpCsFixer\Tokenizer\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)); + } + } + foreach ($sequence as $token) { + if (!$this->isTokenKindFound($this->extractTokenKind($token))) { + return null; + } + } + // remove the first token from the sequence, so we can freely iterate through the sequence after a match to + // the first one is found + $key = \key($sequence); + $firstCs = \PhpCsFixer\Tokenizer\Token::isKeyCaseSensitive($caseSensitive, $key); + $firstToken = $sequence[$key]; + unset($sequence[$key]); + // begin searching for the first token in the sequence (start included) + $index = $start - 1; + while ($index <= $end) { + $index = $this->getNextTokenOfKind($index, [$firstToken], $firstCs); + // ensure we found a match and didn't get past the end index + if (null === $index || $index > $end) { + return null; + } + // initialise the result array with the current index + $result = [$index => $this[$index]]; + // advance cursor to the current position + $currIdx = $index; + // iterate through the remaining tokens in the sequence + foreach ($sequence as $key => $token) { + $currIdx = $this->getNextMeaningfulToken($currIdx); + // ensure we didn't go too far + if (null === $currIdx || $currIdx > $end) { + return null; + } + if (!$this[$currIdx]->equals($token, \PhpCsFixer\Tokenizer\Token::isKeyCaseSensitive($caseSensitive, $key))) { + // not a match, restart the outer loop + continue 2; + } + // append index to the result array + $result[$currIdx] = $this[$currIdx]; + } + // do we have a complete match? + // hint: $result is bigger than $sequence since the first token has been removed from the latter + if (\count($sequence) < \count($result)) { + return $result; + } + } + return null; + } + /** + * Insert instances of Token inside collection. + * + * @param int $index start inserting index + * @param list|Token|Tokens $items instances of Token to insert + */ + public function insertAt(int $index, $items) : void + { + $this->insertSlices([$index => $items]); + } + /** + * Insert a slices or individual Tokens into multiple places in a single run. + * + * This approach is kind-of an experiment - it's proven to improve performance a lot for big files that needs plenty of new tickets to be inserted, + * like edge case example of 3.7h vs 4s (https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/issues/3996#issuecomment-455617637), + * yet at same time changing a logic of fixers in not-always easy way. + * + * To be discussed: + * - should we always aim to use this method? + * - should we deprecate `insertAt` method ? + * + * The `$slices` parameter is an assoc array, in which: + * - index: starting point for inserting of individual slice, with indices being relatives to original array collection before any Token inserted + * - value under index: a slice of Tokens to be inserted + * + * @internal + * + * @param array|Token|Tokens> $slices + */ + public function insertSlices(array $slices) : void + { + $itemsCount = 0; + foreach ($slices as $slice) { + $itemsCount += \is_array($slice) || $slice instanceof self ? \count($slice) : 1; + } + if (0 === $itemsCount) { + return; + } + $oldSize = \count($this); + $this->changed = \true; + $this->namespaceDeclarations = null; + $this->blockStartCache = []; + $this->blockEndCache = []; + $this->setSize($oldSize + $itemsCount); + \krsort($slices); + $farthestSliceIndex = \key($slices); + // We check only the farthest index, if it's within the size of collection, other indices will be valid too. + if (!\is_int($farthestSliceIndex) || $farthestSliceIndex > $oldSize) { + throw new \OutOfBoundsException(\sprintf('Cannot insert index "%s" outside of collection.', $farthestSliceIndex)); + } + $previousSliceIndex = $oldSize; + // since we only move already existing items around, we directly call into SplFixedArray::offset* methods. + // that way we get around additional overhead this class adds with overridden offset* methods. + foreach ($slices as $index => $slice) { + if (!\is_int($index) || $index < 0) { + throw new \OutOfBoundsException(\sprintf('Invalid index "%s".', $index)); + } + $slice = \is_array($slice) || $slice instanceof self ? $slice : [$slice]; + $sliceCount = \count($slice); + for ($i = $previousSliceIndex - 1; $i >= $index; --$i) { + parent::offsetSet($i + $itemsCount, parent::offsetGet($i)); + } + $previousSliceIndex = $index; + $itemsCount -= $sliceCount; + foreach ($slice as $indexItem => $item) { + if ('' === $item->getContent()) { + throw new \InvalidArgumentException('Must not add empty token to collection.'); + } + $this->registerFoundToken($item); + parent::offsetSet($index + $itemsCount + $indexItem, $item); + } + } + } + /** + * Check if collection was change: collection itself (like insert new tokens) or any of collection's elements. + */ + public function isChanged() : bool + { + return $this->changed; + } + public function isEmptyAt(int $index) : bool + { + $token = $this[$index]; + return null === $token->getId() && '' === $token->getContent(); + } + public function clearAt(int $index) : void + { + $this[$index] = new \PhpCsFixer\Tokenizer\Token(''); + } + /** + * Override tokens at given range. + * + * @param int $indexStart start overriding index + * @param int $indexEnd end overriding index + * @param array|Tokens $items tokens to insert + */ + public function overrideRange(int $indexStart, int $indexEnd, iterable $items) : void + { + $indexToChange = $indexEnd - $indexStart + 1; + $itemsCount = \count($items); + // If we want to add more items than passed range contains we need to + // add placeholders for overhead items. + if ($itemsCount > $indexToChange) { + $placeholders = []; + while ($itemsCount > $indexToChange) { + $placeholders[] = new \PhpCsFixer\Tokenizer\Token('__PLACEHOLDER__'); + ++$indexToChange; + } + $this->insertAt($indexEnd + 1, $placeholders); + } + // Override each items. + foreach ($items as $itemIndex => $item) { + $this[$indexStart + $itemIndex] = $item; + } + // If we want to add fewer tokens than passed range contains then clear + // not needed tokens. + if ($itemsCount < $indexToChange) { + $this->clearRange($indexStart + $itemsCount, $indexEnd); + } + } + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeLeadingWhitespace(int $index, ?string $whitespaces = null) : void + { + $this->removeWhitespaceSafely($index, -1, $whitespaces); + } + /** + * @param null|string $whitespaces optional whitespaces characters for Token::isWhitespace + */ + public function removeTrailingWhitespace(int $index, ?string $whitespaces = null) : void + { + $this->removeWhitespaceSafely($index, 1, $whitespaces); + } + /** + * Set code. Clear all current content and replace it by new Token items generated from code directly. + * + * @param string $code PHP code + */ + public function setCode(string $code) : void + { + // No need to work when the code is the same. + // That is how we avoid a lot of work and setting changed flag. + if ($code === $this->generateCode()) { + return; + } + // clear memory + $this->setSize(0); + $tokens = \token_get_all($code, \TOKEN_PARSE); + $this->setSize(\count($tokens)); + foreach ($tokens as $index => $token) { + $this[$index] = new \PhpCsFixer\Tokenizer\Token($token); + } + $this->applyTransformers(); + $this->foundTokenKinds = []; + foreach ($this as $token) { + $this->registerFoundToken($token); + } + if (\PHP_VERSION_ID < 80000) { + $this->rewind(); + } + $this->changeCodeHash(self::calculateCodeHash($code)); + $this->changed = \true; + $this->namespaceDeclarations = null; + } + public function toJson() : string + { + $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, \JSON_PRETTY_PRINT | \JSON_NUMERIC_CHECK); + } + /** + * Check if all token kinds given as argument are found. + * + * @param list $tokenKinds + */ + public function isAllTokenKindsFound(array $tokenKinds) : bool + { + foreach ($tokenKinds as $tokenKind) { + if (!isset($this->foundTokenKinds[$tokenKind])) { + return \false; + } + } + return \true; + } + /** + * Check if any token kind given as argument is found. + * + * @param list $tokenKinds + */ + public function isAnyTokenKindsFound(array $tokenKinds) : bool + { + foreach ($tokenKinds as $tokenKind) { + if (isset($this->foundTokenKinds[$tokenKind])) { + return \true; + } + } + return \false; + } + /** + * Check if token kind given as argument is found. + * + * @param int|string $tokenKind + */ + public function isTokenKindFound($tokenKind) : bool + { + return isset($this->foundTokenKinds[$tokenKind]); + } + /** + * @param int|string $tokenKind + */ + public function countTokenKind($tokenKind) : int + { + return $this->foundTokenKinds[$tokenKind] ?? 0; + } + /** + * Clear tokens in the given range. + */ + public function clearRange(int $indexStart, int $indexEnd) : void + { + for ($i = $indexStart; $i <= $indexEnd; ++$i) { + $this->clearAt($i); + } + } + /** + * Checks for monolithic PHP code. + * + * Checks that the code is pure PHP code, in a single code block, starting + * with an open tag. + */ + public function isMonolithicPhp() : bool + { + if (0 === $this->count()) { + return \false; + } + if ($this->countTokenKind(\T_INLINE_HTML) > 1) { + return \false; + } + if (1 === $this->countTokenKind(\T_INLINE_HTML)) { + return Preg::match('/^#!.+$/', $this[0]->getContent()); + } + return 1 === $this->countTokenKind(\T_OPEN_TAG) + $this->countTokenKind(\T_OPEN_TAG_WITH_ECHO); + } + /** + * @param int $start start index + * @param int $end end index + */ + public function isPartialCodeMultiline(int $start, int $end) : bool + { + for ($i = $start; $i <= $end; ++$i) { + if (\strpos($this[$i]->getContent(), "\n") !== \false) { + return \true; + } + } + return \false; + } + public function hasAlternativeSyntax() : bool + { + return $this->isAnyTokenKindsFound([\T_ENDDECLARE, \T_ENDFOR, \T_ENDFOREACH, \T_ENDIF, \T_ENDSWITCH, \T_ENDWHILE]); + } + public function clearTokenAndMergeSurroundingWhitespace(int $index) : void + { + $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 \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $this[$prevIndex]->getContent() . $this[$nextIndex]->getContent()]); + } elseif ($this->isEmptyAt($prevIndex + 1)) { + $this[$prevIndex + 1] = new \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $this[$nextIndex]->getContent()]); + } + $this->clearAt($nextIndex); + } + /** + * @internal This is performance-related workaround for lack of proper DI, may be removed at some point + * + * @return list + */ + public function getNamespaceDeclarations() : array + { + if (null === $this->namespaceDeclarations) { + $this->namespaceDeclarations = (new NamespacesAnalyzer())->getDeclarations($this); + } + return $this->namespaceDeclarations; + } + /** + * @internal + */ + protected function applyTransformers() : void + { + $transformers = \PhpCsFixer\Tokenizer\Transformers::createSingleton(); + $transformers->transform($this); + } + /** + * @param -1|1 $direction + */ + private function removeWhitespaceSafely(int $index, int $direction, ?string $whitespaces = null) : void + { + $whitespaceIndex = $this->getNonEmptySibling($index, $direction); + if (isset($this[$whitespaceIndex]) && $this[$whitespaceIndex]->isWhitespace()) { + $newContent = ''; + $tokenToCheck = $this[$whitespaceIndex]; + // if the token candidate to remove is preceded by single line comment we do not consider the new line after this comment as part of T_WHITESPACE + if (isset($this[$whitespaceIndex - 1]) && $this[$whitespaceIndex - 1]->isComment() && \strncmp($this[$whitespaceIndex - 1]->getContent(), '/*', \strlen('/*')) !== 0) { + [, $newContent, $whitespacesToCheck] = Preg::split('/^(\\R)/', $this[$whitespaceIndex]->getContent(), -1, \PREG_SPLIT_DELIM_CAPTURE); + if ('' === $whitespacesToCheck) { + return; + } + $tokenToCheck = new \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $whitespacesToCheck]); + } + if (!$tokenToCheck->isWhitespace($whitespaces)) { + return; + } + if ('' === $newContent) { + $this->clearAt($whitespaceIndex); + } else { + $this[$whitespaceIndex] = new \PhpCsFixer\Tokenizer\Token([\T_WHITESPACE, $newContent]); + } + } + } + /** + * @param self::BLOCK_TYPE_* $type type of block + * @param int $searchIndex index of starting brace + * @param bool $findEnd if method should find block's end or start + * + * @return int index of opposite brace + */ + private function findOppositeBlockEdge(int $type, int $searchIndex, bool $findEnd) : int + { + $blockEdgeDefinitions = self::getBlockEdgeDefinitions(); + if (!isset($blockEdgeDefinitions[$type])) { + throw new \InvalidArgumentException(\sprintf('Invalid param type: "%s".', $type)); + } + if ($findEnd && isset($this->blockStartCache[$searchIndex])) { + return $this->blockStartCache[$searchIndex]; + } + if (!$findEnd && 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) { + [$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; + } + } + } + if (!$this[$index]->equals($endEdge)) { + throw new \UnexpectedValueException(\sprintf('Missing block "%s".', $findEnd ? 'end' : 'start')); + } + if ($startIndex < $index) { + $this->blockStartCache[$startIndex] = $index; + $this->blockEndCache[$index] = $startIndex; + } else { + $this->blockStartCache[$index] = $startIndex; + $this->blockEndCache[$startIndex] = $index; + } + return $index; + } + /** + * Calculate hash for code. + */ + private static function calculateCodeHash(string $code) : string + { + return \PhpCsFixer\Tokenizer\CodeHasher::calculateCodeHash($code); + } + /** + * Get cache value for given key. + * + * @param string $key item key + */ + private static function getCache(string $key) : self + { + if (!self::hasCache($key)) { + throw new \OutOfBoundsException(\sprintf('Unknown cache key: "%s".', $key)); + } + return self::$cache[$key]; + } + /** + * Check if given key exists in cache. + * + * @param string $key item key + */ + private static function hasCache(string $key) : bool + { + return isset(self::$cache[$key]); + } + /** + * @param string $key item key + * @param Tokens $value item value + */ + private static function setCache(string $key, self $value) : void + { + self::$cache[$key] = $value; + } + /** + * Change code hash. + * + * Remove old cache and set new one. + * + * @param string $codeHash new code hash + */ + private function changeCodeHash(string $codeHash) : void + { + if (null !== $this->codeHash) { + self::clearCache($this->codeHash); + } + $this->codeHash = $codeHash; + self::setCache($this->codeHash, $this); + } + /** + * Register token as found. + * + * @param array{int}|string|Token $token token prototype + */ + private function registerFoundToken($token) : void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token instanceof \PhpCsFixer\Tokenizer\Token ? $token->isArray() ? $token->getId() : $token->getContent() : (\is_array($token) ? $token[0] : $token); + $this->foundTokenKinds[$tokenKind] = $this->foundTokenKinds[$tokenKind] ?? 0; + ++$this->foundTokenKinds[$tokenKind]; + } + /** + * Unregister token as not found. + * + * @param array{int}|string|Token $token token prototype + */ + private function unregisterFoundToken($token) : void + { + // inlined extractTokenKind() call on the hot path + $tokenKind = $token instanceof \PhpCsFixer\Tokenizer\Token ? $token->isArray() ? $token->getId() : $token->getContent() : (\is_array($token) ? $token[0] : $token); + if (1 === $this->foundTokenKinds[$tokenKind]) { + unset($this->foundTokenKinds[$tokenKind]); + } else { + --$this->foundTokenKinds[$tokenKind]; + } + } + /** + * @param array{int}|string|Token $token token prototype + * + * @return int|string + */ + private function extractTokenKind($token) + { + return $token instanceof \PhpCsFixer\Tokenizer\Token ? $token->isArray() ? $token->getId() : $token->getContent() : (\is_array($token) ? $token[0] : $token); + } + /** + * @param int $index token index + * @param -1|1 $direction + * @param callable(int): bool $filter + */ + private function getTokenNotOfKind(int $index, int $direction, callable $filter) : ?int + { + while (\true) { + $index += $direction; + if (!$this->offsetExists($index)) { + return null; + } + if ($this->isEmptyAt($index) || $filter($index)) { + continue; + } + return $index; + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php new file mode 100644 index 00000000000..baea02de9c4 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TokensAnalyzer.php @@ -0,0 +1,590 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +use PhpCsFixer\Tokenizer\Analyzer\AttributeAnalyzer; +use PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer; +/** + * Analyzer of Tokens collection. + * + * Its role is to provide the ability to analyze collection. + * + * @author Dariusz Rumiński + * @author Gregor Harlan + * + * @internal + */ +final class TokensAnalyzer +{ + /** + * Tokens collection instance. + * @var \PhpCsFixer\Tokenizer\Tokens + */ + private $tokens; + /** + * @var \PhpCsFixer\Tokenizer\Analyzer\GotoLabelAnalyzer|null + */ + private $gotoLabelAnalyzer; + public function __construct(\PhpCsFixer\Tokenizer\Tokens $tokens) + { + $this->tokens = $tokens; + } + /** + * Get indices of methods and properties in classy code (classes, interfaces and traits). + * + * @return array + */ + public function getClassyElements() : array + { + $elements = []; + for ($index = 1, $count = \count($this->tokens) - 2; $index < $count; ++$index) { + if ($this->tokens[$index]->isClassy()) { + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + \ksort($elements); + return $elements; + } + /** + * Get indices of modifiers of a classy code (classes, interfaces and traits). + * + * @return array{ + * final: int|null, + * abstract: int|null, + * readonly: int|null + * } + */ + public function getClassyModifiers(int $index) : array + { + if (!$this->tokens[$index]->isClassy()) { + throw new \InvalidArgumentException(\sprintf('Not an "classy" at given index %d.', $index)); + } + $readOnlyPossible = \defined('T_READONLY'); + // @TODO: drop condition when PHP 8.2+ is required + $modifiers = ['final' => null, 'abstract' => null, 'readonly' => null]; + while (\true) { + $index = $this->tokens->getPrevMeaningfulToken($index); + if ($this->tokens[$index]->isGivenKind(\T_FINAL)) { + $modifiers['final'] = $index; + } elseif ($this->tokens[$index]->isGivenKind(\T_ABSTRACT)) { + $modifiers['abstract'] = $index; + } elseif ($readOnlyPossible && $this->tokens[$index]->isGivenKind(\T_READONLY)) { + $modifiers['readonly'] = $index; + } else { + // no need to skip attributes as it is not possible on PHP8.2 + break; + } + } + return $modifiers; + } + /** + * Get indices of namespace uses. + * + * @param bool $perNamespace Return namespace uses per namespace + * + * @return ($perNamespace is true ? array> : list) + */ + public function getImportUseIndexes(bool $perNamespace = \false) : array + { + $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; + } + /** + * Check if there is an array at given index. + */ + public function isArray(int $index) : bool + { + return $this->tokens[$index]->isGivenKind([\T_ARRAY, \PhpCsFixer\Tokenizer\CT::T_ARRAY_SQUARE_BRACE_OPEN]); + } + /** + * Check if the array at index is multiline. + * + * This only checks the root-level of the array. + */ + public function isArrayMultiLine(int $index) : bool + { + if (!$this->isArray($index)) { + throw new \InvalidArgumentException(\sprintf('Not an array at given index %d.', $index)); + } + $tokens = $this->tokens; + // Skip only when it's an array, for short arrays we need the brace for correct + // level counting + if ($tokens[$index]->isGivenKind(\T_ARRAY)) { + $index = $tokens->getNextMeaningfulToken($index); + } + return $this->isBlockMultiline($tokens, $index); + } + public function isBlockMultiline(\PhpCsFixer\Tokenizer\Tokens $tokens, int $index) : bool + { + $blockType = \PhpCsFixer\Tokenizer\Tokens::detectBlockType($tokens[$index]); + if (null === $blockType || !$blockType['isStart']) { + throw new \InvalidArgumentException(\sprintf('Not an block start at given index %d.', $index)); + } + $endIndex = $tokens->findBlockEnd($blockType['type'], $index); + for (++$index; $index < $endIndex; ++$index) { + $token = $tokens[$index]; + $blockType = \PhpCsFixer\Tokenizer\Tokens::detectBlockType($token); + if (null !== $blockType && $blockType['isStart']) { + $index = $tokens->findBlockEnd($blockType['type'], $index); + continue; + } + if ($token->isWhitespace() && !$tokens[$index - 1]->isGivenKind(\T_END_HEREDOC) && \strpos($token->getContent(), "\n") !== \false) { + return \true; + } + } + return \false; + } + /** + * @param int $index Index of the T_FUNCTION token + * + * @return array{visibility: null|T_PRIVATE|T_PROTECTED|T_PUBLIC, static: bool, abstract: bool, final: bool} + */ + public function getMethodAttributes(int $index) : array + { + if (!$this->tokens[$index]->isGivenKind(\T_FUNCTION)) { + throw new \LogicException(\sprintf('No T_FUNCTION at given index %d, got "%s".', $index, $this->tokens[$index]->getName())); + } + $attributes = ['visibility' => null, 'static' => \false, 'abstract' => \false, 'final' => \false]; + for ($i = $index; $i >= 0; --$i) { + $i = $this->tokens->getPrevMeaningfulToken($i); + $token = $this->tokens[$i]; + 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; + } + // visibility + 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; + } + // found a meaningful token that is not part of + // the function signature; stop looking + break; + } + return $attributes; + } + /** + * Check if there is an anonymous class under given index. + */ + public function isAnonymousClass(int $index) : bool + { + 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; + } + $index = $this->tokens->getPrevMeaningfulToken($index); + if (\defined('T_READONLY') && $this->tokens[$index]->isGivenKind(\T_READONLY)) { + // @TODO: drop condition when PHP 8.1+ is required + $index = $this->tokens->getPrevMeaningfulToken($index); + } + while ($this->tokens[$index]->isGivenKind(\PhpCsFixer\Tokenizer\CT::T_ATTRIBUTE_CLOSE)) { + $index = $this->tokens->findBlockStart(\PhpCsFixer\Tokenizer\Tokens::BLOCK_TYPE_ATTRIBUTE, $index); + $index = $this->tokens->getPrevMeaningfulToken($index); + } + return $this->tokens[$index]->isGivenKind(\T_NEW); + } + /** + * Check if the function under given index is a lambda. + */ + public function isLambda(int $index) : bool + { + if (!$this->tokens[$index]->isGivenKind([\T_FUNCTION, \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]; + // skip & for `function & () {}` syntax + if ($startParenthesisToken->isGivenKind(\PhpCsFixer\Tokenizer\CT::T_RETURN_REF)) { + $startParenthesisIndex = $this->tokens->getNextMeaningfulToken($startParenthesisIndex); + $startParenthesisToken = $this->tokens[$startParenthesisIndex]; + } + return $startParenthesisToken->equals('('); + } + /** + * Check if the T_STRING under given index is a constant invocation. + */ + public function isConstantInvocation(int $index) : bool + { + 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, \PhpCsFixer\Tokenizer\CT::T_RETURN_REF, \PhpCsFixer\Tokenizer\CT::T_TYPE_ALTERNATION, \PhpCsFixer\Tokenizer\CT::T_TYPE_INTERSECTION, \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, \PhpCsFixer\Tokenizer\CT::T_GROUP_IMPORT_BRACE_OPEN, \T_INTERFACE, \T_TRAIT, \PhpCsFixer\Tokenizer\CT::T_TYPE_COLON, \PhpCsFixer\Tokenizer\CT::T_TYPE_ALTERNATION, \PhpCsFixer\Tokenizer\CT::T_TYPE_INTERSECTION]) || $this->tokens[$prevIndex]->isObjectOperator()) { + return \false; + } + while ($this->tokens[$prevIndex]->isGivenKind([\PhpCsFixer\Tokenizer\CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + if ($this->tokens[$prevIndex]->isGivenKind([\PhpCsFixer\Tokenizer\CT::T_CONST_IMPORT, \T_EXTENDS, \PhpCsFixer\Tokenizer\CT::T_FUNCTION_IMPORT, \T_IMPLEMENTS, \T_INSTANCEOF, \T_INSTEADOF, \T_NAMESPACE, \T_NEW, \PhpCsFixer\Tokenizer\CT::T_NULLABLE_TYPE, \PhpCsFixer\Tokenizer\CT::T_TYPE_COLON, \T_USE, \PhpCsFixer\Tokenizer\CT::T_USE_TRAIT])) { + return \false; + } + // `FOO & $bar` could be: + // - function reference parameter: function baz(Foo & $bar) {} + // - bit operator: $x = FOO & $bar; + 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; + } + } + // check for `extends`/`implements`/`use` list + if ($this->tokens[$prevIndex]->equals(',')) { + $checkIndex = $prevIndex; + while ($this->tokens[$checkIndex]->equalsAny([',', [\T_AS], [\PhpCsFixer\Tokenizer\CT::T_NAMESPACE_OPERATOR], [\T_NS_SEPARATOR], [\T_STRING]])) { + $checkIndex = $this->tokens->getPrevMeaningfulToken($checkIndex); + } + if ($this->tokens[$checkIndex]->isGivenKind([\T_EXTENDS, \PhpCsFixer\Tokenizer\CT::T_GROUP_IMPORT_BRACE_OPEN, \T_IMPLEMENTS, \T_USE, \PhpCsFixer\Tokenizer\CT::T_USE_TRAIT])) { + return \false; + } + } + // check for array in double quoted string: `"..$foo[bar].."` + 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; + } + } + // check for attribute: `#[Foo]` + if (AttributeAnalyzer::isAttribute($this->tokens, $index)) { + return \false; + } + // check for goto label + if ($this->tokens[$nextIndex]->equals(':')) { + if (null === $this->gotoLabelAnalyzer) { + $this->gotoLabelAnalyzer = new GotoLabelAnalyzer(); + } + if ($this->gotoLabelAnalyzer->belongsToGoToLabel($this->tokens, $nextIndex)) { + return \false; + } + } + // check for non-capturing catches + while ($this->tokens[$prevIndex]->isGivenKind([\PhpCsFixer\Tokenizer\CT::T_NAMESPACE_OPERATOR, \T_NS_SEPARATOR, \T_STRING, \PhpCsFixer\Tokenizer\CT::T_TYPE_ALTERNATION])) { + $prevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + } + if ($this->tokens[$prevIndex]->equals('(')) { + $prevPrevIndex = $this->tokens->getPrevMeaningfulToken($prevIndex); + if ($this->tokens[$prevPrevIndex]->isGivenKind(\T_CATCH)) { + return \false; + } + } + return \true; + } + /** + * Checks if there is a unary successor operator under given index. + */ + public function isUnarySuccessorOperator(int $index) : bool + { + static $allowedPrevToken = [']', [\T_STRING], [\T_VARIABLE], [\PhpCsFixer\Tokenizer\CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_PROP_BRACE_CLOSE], [\PhpCsFixer\Tokenizer\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); + } + /** + * Checks if there is a unary predecessor operator under given index. + */ + public function isUnaryPredecessorOperator(int $index) : bool + { + static $potentialSuccessorOperator = [\T_INC, \T_DEC]; + static $potentialBinaryOperator = ['+', '-', '&', [\PhpCsFixer\Tokenizer\CT::T_RETURN_REF]]; + static $otherOperators; + if (null === $otherOperators) { + $otherOperators = ['!', '~', '@', [\T_ELLIPSIS]]; + } + static $disallowedPrevTokens; + if (null === $disallowedPrevTokens) { + $disallowedPrevTokens = [']', '}', ')', '"', '`', [\PhpCsFixer\Tokenizer\CT::T_ARRAY_SQUARE_BRACE_CLOSE], [\PhpCsFixer\Tokenizer\CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [\PhpCsFixer\Tokenizer\CT::T_DYNAMIC_PROP_BRACE_CLOSE], [\PhpCsFixer\Tokenizer\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); + } + /** + * Checks if there is a binary operator under given index. + */ + public function isBinaryOperator(int $index) : bool + { + 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, + // and + \T_LOGICAL_OR => \true, + // or + \T_LOGICAL_XOR => \true, + // xor + \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, + // ^= + \T_SPACESHIP => \true, + // <=> + \T_COALESCE => \true, + // ?? + \T_COALESCE_EQUAL => \true, + ]; + } + $tokens = $this->tokens; + $token = $tokens[$index]; + if ($token->isGivenKind([\T_INLINE_HTML, \T_ENCAPSED_AND_WHITESPACE, \PhpCsFixer\Tokenizer\CT::T_TYPE_INTERSECTION])) { + return \false; + } + if (isset($potentialUnaryNonArrayOperators[$token->getContent()])) { + return !$this->isUnaryPredecessorOperator($index); + } + if ($token->isArray()) { + return isset($arrayOperators[$token->getId()]); + } + if (isset($nonArrayOperators[$token->getContent()])) { + return \true; + } + return \false; + } + /** + * Check if `T_WHILE` token at given index is `do { ... } while ();` syntax + * and not `while () { ...}`. + */ + public function isWhilePartOfDoWhile(int $index) : bool + { + $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(\PhpCsFixer\Tokenizer\Tokens::BLOCK_TYPE_CURLY_BRACE, $endIndex); + $beforeStartIndex = $tokens->getPrevMeaningfulToken($startIndex); + return $tokens[$beforeStartIndex]->isGivenKind(\T_DO); + } + public function isSuperGlobal(int $index) : bool + { + 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())]); + } + /** + * Find classy elements. + * + * Searches in tokens from the classy (start) index till the end (index) of the classy. + * Returns an array; first value is the index until the method has analysed (int), second the found classy elements (array). + * + * @param int $classIndex classy index + * + * @return array{int, array} + */ + private function findClassyElements(int $classIndex, int $index) : array + { + $elements = []; + $curlyBracesLevel = 0; + $bracesLevel = 0; + ++$index; + // skip the classy index itself + for ($count = \count($this->tokens); $index < $count; ++$index) { + $token = $this->tokens[$index]; + if ($token->isGivenKind(\T_ENCAPSED_AND_WHITESPACE)) { + continue; + } + if ($token->isGivenKind(\T_CLASS)) { + // anonymous class in class + // check for nested anonymous classes inside the new call of an anonymous class, + // for example `new class(function (){new class(function (){new class(function (){}){};}){};}){};` etc. + // if class(XYZ) {} skip till `(` as XYZ might contain functions etc. + $nestedClassIndex = $index; + $index = $this->tokens->getNextMeaningfulToken($index); + if ($this->tokens[$index]->equals('(')) { + ++$index; + // move after `(` + for ($nestedBracesLevel = 1; $index < $count; ++$index) { + $token = $this->tokens[$index]; + if ($token->equals('(')) { + ++$nestedBracesLevel; + continue; + } + if ($token->equals(')')) { + --$nestedBracesLevel; + if (0 === $nestedBracesLevel) { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $index); + $elements += $newElements; + break; + } + continue; + } + if ($token->isGivenKind(\T_CLASS)) { + // anonymous class in class + [$index, $newElements] = $this->findClassyElements($index, $index); + $elements += $newElements; + } + } + } else { + [$index, $newElements] = $this->findClassyElements($nestedClassIndex, $nestedClassIndex); + $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] = ['classIndex' => $classIndex, 'token' => $token, 'type' => 'property']; + continue; + } + if ($token->isGivenKind(\T_FUNCTION)) { + $elements[$index] = ['classIndex' => $classIndex, 'token' => $token, 'type' => 'method']; + } elseif ($token->isGivenKind(\T_CONST)) { + $elements[$index] = ['classIndex' => $classIndex, 'token' => $token, 'type' => 'const']; + } elseif ($token->isGivenKind(\PhpCsFixer\Tokenizer\CT::T_USE_TRAIT)) { + $elements[$index] = ['classIndex' => $classIndex, 'token' => $token, 'type' => 'trait_import']; + } elseif ($token->isGivenKind(\T_CASE)) { + $elements[$index] = ['classIndex' => $classIndex, 'token' => $token, 'type' => 'case']; + } + } + return [$index, $elements]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php new file mode 100644 index 00000000000..20cb7e701ff --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ArrayTypehintTransformer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `array` typehint from T_ARRAY into CT::T_ARRAY_TYPEHINT. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ArrayTypehintTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + 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()]); + } + } + public function getCustomTokens() : array + { + return [CT::T_ARRAY_TYPEHINT]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php new file mode 100644 index 00000000000..d42a30017d9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/AttributeTransformer.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transforms attribute related Tokens. + * + * @internal + */ +final class AttributeTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // must run before all other transformers that might touch attributes + return 200; + } + public function getRequiredPhpVersionId() : int + { + return 80000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + 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, ']']); + } + public function getCustomTokens() : array + { + return [CT::T_ATTRIBUTE_CLOSE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php new file mode 100644 index 00000000000..f5aa24b3d83 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/BraceClassInstantiationTransformer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform braced class instantiation braces in `(new Foo())` into CT::T_BRACE_CLASS_INSTANTIATION_OPEN + * and CT::T_BRACE_CLASS_INSTANTIATION_CLOSE. + * + * @author Sebastiaans Stok + * + * @internal + */ +final class BraceClassInstantiationTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // must run after CurlyBraceTransformer and SquareBraceTransformer + return -2; + } + public function getRequiredPhpVersionId() : int + { + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$tokens[$index]->equals('(') || !$tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(\T_NEW)) { + return; + } + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->equalsAny([')', ']', [CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE], [CT::T_ARRAY_SQUARE_BRACE_CLOSE], [CT::T_BRACE_CLASS_INSTANTIATION_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, ')']); + } + public function getCustomTokens() : array + { + return [CT::T_BRACE_CLASS_INSTANTIATION_OPEN, CT::T_BRACE_CLASS_INSTANTIATION_CLOSE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php new file mode 100644 index 00000000000..258e7a210c2 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ClassConstantTransformer.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `class` class' constant from T_CLASS into CT::T_CLASS_CONSTANT. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ClassConstantTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50500; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + 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()]); + } + } + public function getCustomTokens() : array + { + return [CT::T_CLASS_CONSTANT]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php new file mode 100644 index 00000000000..7b68b158af9 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ConstructorPromotionTransformer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transforms for Constructor Property Promotion. + * + * Transform T_PUBLIC, T_PROTECTED and T_PRIVATE of Constructor Property Promotion into custom tokens. + * + * @internal + */ +final class ConstructorPromotionTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 80000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$tokens[$index]->isGivenKind(\T_FUNCTION)) { + return; + } + $index = $tokens->getNextMeaningfulToken($index); + if (!$tokens[$index]->isGivenKind(\T_STRING) || '__construct' !== \strtolower($tokens[$index]->getContent())) { + return; + } + /** @var int $openIndex */ + $openIndex = $tokens->getNextMeaningfulToken($index); + // we are @ '(' now + $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()]); + } + } + } + public function getCustomTokens() : array + { + return [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED, CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php new file mode 100644 index 00000000000..c1fb1766924 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/CurlyBraceTransformer.php @@ -0,0 +1,209 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform discriminate overloaded curly braces tokens. + * + * Performed transformations: + * - closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE, + * - closing `}` for T_DOLLAR_OPEN_CURLY_BRACES into CT::T_DOLLAR_CLOSE_CURLY_BRACES, + * - in `$foo->{$bar}` into CT::T_DYNAMIC_PROP_BRACE_OPEN and CT::T_DYNAMIC_PROP_BRACE_CLOSE, + * - in `${$foo}` into CT::T_DYNAMIC_VAR_BRACE_OPEN and CT::T_DYNAMIC_VAR_BRACE_CLOSE, + * - in `$array{$index}` into CT::T_ARRAY_INDEX_CURLY_BRACE_OPEN and CT::T_ARRAY_INDEX_CURLY_BRACE_CLOSE, + * - in `use some\a\{ClassA, ClassB, ClassC as C}` into CT::T_GROUP_IMPORT_BRACE_OPEN, CT::T_GROUP_IMPORT_BRACE_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class CurlyBraceTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + $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); + $this->transformIntoGroupUseBraces($tokens, $token, $index); + $this->transformIntoDynamicClassConstantFetchBraces($tokens, $token, $index); + } + public function getCustomTokens() : array + { + 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, CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE]; + } + /** + * Transform closing `}` for T_CURLY_OPEN into CT::T_CURLY_CLOSE. + * + * This should be done at very beginning of curly braces transformations. + */ + private function transformIntoCurlyCloseBrace(Tokens $tokens, Token $token, int $index) : void + { + if (!$token->isGivenKind(\T_CURLY_OPEN)) { + return; + } + $level = 1; + do { + ++$index; + if ($tokens[$index]->equals('{') || $tokens[$index]->isGivenKind(\T_CURLY_OPEN)) { + // we count all kind of { + ++$level; + } elseif ($tokens[$index]->equals('}')) { + // we count all kind of } + --$level; + } + } while (0 < $level); + $tokens[$index] = new Token([CT::T_CURLY_CLOSE, '}']); + } + private function transformIntoDollarCloseBrace(Tokens $tokens, Token $token, int $index) : void + { + 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, int $index) : void + { + if (!$token->isObjectOperator()) { + return; + } + if (!$tokens[$index + 1]->equals('{')) { + return; + } + $openIndex = $index + 1; + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $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, int $index) : void + { + if (!$token->equals('$')) { + return; + } + $openIndex = $tokens->getNextMeaningfulToken($index); + if (null === $openIndex) { + return; + } + $openToken = $tokens[$openIndex]; + if (!$openToken->equals('{')) { + return; + } + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $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, int $index) : void + { + 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)]->isObjectOperator()) { + return; + } + if ($tokens[$prevIndex]->equals(')') && !$tokens[$tokens->getPrevMeaningfulToken($tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevIndex))]->isGivenKind(\T_ARRAY)) { + return; + } + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $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, int $index) : void + { + if (!$token->equals('{')) { + return; + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$prevIndex]->isGivenKind(\T_NS_SEPARATOR)) { + return; + } + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + $tokens[$index] = new Token([CT::T_GROUP_IMPORT_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_GROUP_IMPORT_BRACE_CLOSE, '}']); + } + private function transformIntoDynamicClassConstantFetchBraces(Tokens $tokens, Token $token, int $index) : void + { + if (\PHP_VERSION_ID < 80300) { + return; + // @TODO: drop condition when PHP 8.3+ is required or majority of the users are using 8.3+ + } + if (!$token->equals('{')) { + return; + } + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($index); + while (!$tokens[$prevMeaningfulTokenIndex]->isGivenKind(\T_DOUBLE_COLON)) { + if (!$tokens[$prevMeaningfulTokenIndex]->equals(')')) { + return; + } + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + if (!$tokens[$prevMeaningfulTokenIndex]->equals('}')) { + return; + } + $prevMeaningfulTokenIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_CURLY_BRACE, $prevMeaningfulTokenIndex); + $prevMeaningfulTokenIndex = $tokens->getPrevMeaningfulToken($prevMeaningfulTokenIndex); + } + $closeIndex = $this->naivelyFindCurlyBlockEnd($tokens, $index); + $nextMeaningfulTokenIndexAfterCloseIndex = $tokens->getNextMeaningfulToken($closeIndex); + if (!$tokens[$nextMeaningfulTokenIndexAfterCloseIndex]->equalsAny([';', [\T_CLOSE_TAG], [\T_DOUBLE_COLON]])) { + return; + } + $tokens[$index] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_OPEN, '{']); + $tokens[$closeIndex] = new Token([CT::T_DYNAMIC_CLASS_CONSTANT_FETCH_CURLY_BRACE_CLOSE, '}']); + } + /** + * We do not want to rely on `$tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $index)` here, + * as it relies on block types that are assuming that `}` tokens are already transformed to Custom Tokens that are allowing to distinguish different block types. + * As we are just about to transform `{` and `}` into Custom Tokens by this transformer, thus we need to compare those tokens manually by content without using `Tokens::findBlockEnd`. + */ + private function naivelyFindCurlyBlockEnd(Tokens $tokens, int $startIndex) : int + { + if (!$tokens->offsetExists($startIndex)) { + throw new \OutOfBoundsException(\sprintf('Unavailable index: "%s".', $startIndex)); + } + if ('{' !== $tokens[$startIndex]->getContent()) { + throw new \InvalidArgumentException(\sprintf('Wrong start index: "%s".', $startIndex)); + } + $blockLevel = 1; + $endIndex = $tokens->count() - 1; + for ($index = $startIndex + 1; $index !== $endIndex; ++$index) { + $token = $tokens[$index]; + if ('{' === $token->getContent()) { + ++$blockLevel; + continue; + } + if ('}' === $token->getContent()) { + --$blockLevel; + if (0 === $blockLevel) { + if (!$token->equals('}')) { + throw new \UnexpectedValueException(\sprintf('Detected block end for index: "%s" was already transformed into other token type: "%s".', $startIndex, $token->getName())); + } + return $index; + } + } + } + throw new \UnexpectedValueException(\sprintf('Missing block end for index: "%s".', $startIndex)); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php new file mode 100644 index 00000000000..e85b49917c0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/DisjunctiveNormalFormTypeParenthesisTransformer.php @@ -0,0 +1,55 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform DNF parentheses into CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN and CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE. + * + * @see https://wiki.php.net/rfc/dnf_types + * + * @internal + */ +final class DisjunctiveNormalFormTypeParenthesisTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // needs to run after TypeAlternationTransformer + return -16; + } + public function getRequiredPhpVersionId() : int + { + return 80200; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($token->equals('(') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $index; + $closeIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + } elseif ($token->equals(')') && $tokens[$tokens->getNextMeaningfulToken($index)]->isGivenKind(CT::T_TYPE_ALTERNATION)) { + $openIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $index); + $closeIndex = $index; + } else { + return; + } + $tokens[$openIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, '(']); + $tokens[$closeIndex] = new Token([CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE, ')']); + } + public function getCustomTokens() : array + { + return [CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_OPEN, CT::T_DISJUNCTIVE_NORMAL_FORM_TYPE_PARENTHESIS_CLOSE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php new file mode 100644 index 00000000000..7ff17149eb0 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/FirstClassCallableTransformer.php @@ -0,0 +1,38 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * @internal + */ +final class FirstClassCallableTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 80100; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($token->isGivenKind(\T_ELLIPSIS) && $tokens[$tokens->getPrevMeaningfulToken($index)]->equals('(') && $tokens[$tokens->getNextMeaningfulToken($index)]->equals(')')) { + $tokens[$index] = new Token([CT::T_FIRST_CLASS_CALLABLE, '...']); + } + } + public function getCustomTokens() : array + { + return [CT::T_FIRST_CLASS_CALLABLE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php new file mode 100644 index 00000000000..d241963c5db --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ImportTransformer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform const/function import tokens. + * + * Performed transformations: + * - T_CONST into CT::T_CONST_IMPORT + * - T_FUNCTION into CT::T_FUNCTION_IMPORT + * + * @author Gregor Harlan + * + * @internal + */ +final class ImportTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // Should run after CurlyBraceTransformer and ReturnRefTransformer + return -1; + } + public function getRequiredPhpVersionId() : int + { + return 50600; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$token->isGivenKind([\T_CONST, \T_FUNCTION])) { + return; + } + $prevToken = $tokens[$tokens->getPrevMeaningfulToken($index)]; + if (!$prevToken->isGivenKind(\T_USE)) { + $nextToken = $tokens[$tokens->getNextTokenOfKind($index, ['=', '(', [CT::T_RETURN_REF], [CT::T_GROUP_IMPORT_BRACE_CLOSE]])]; + if (!$nextToken->isGivenKind(CT::T_GROUP_IMPORT_BRACE_CLOSE)) { + return; + } + } + $tokens[$index] = new Token([$token->isGivenKind(\T_FUNCTION) ? CT::T_FUNCTION_IMPORT : CT::T_CONST_IMPORT, $token->getContent()]); + } + public function getCustomTokens() : array + { + return [CT::T_CONST_IMPORT, CT::T_FUNCTION_IMPORT]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php new file mode 100644 index 00000000000..3a9ab018a3b --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NameQualifiedTransformer.php @@ -0,0 +1,72 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform NAME_QUALIFIED, T_NAME_FULLY_QUALIFIED and T_NAME_RELATIVE into T_NAMESPACE T_NS_SEPARATOR T_STRING. + * + * @internal + */ +final class NameQualifiedTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + return 1; + // must run before NamespaceOperatorTransformer + } + public function getRequiredPhpVersionId() : int + { + return 80000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($token->isGivenKind([\T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED])) { + $this->transformQualified($tokens, $token, $index); + } elseif ($token->isGivenKind(\T_NAME_RELATIVE)) { + $this->transformRelative($tokens, $token, $index); + } + } + public function getCustomTokens() : array + { + return []; + } + private function transformQualified(Tokens $tokens, Token $token, int $index) : void + { + $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, int $index) : void + { + $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); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php new file mode 100644 index 00000000000..292519709cb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamedArgumentTransformer.php @@ -0,0 +1,58 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform named argument tokens. + * + * @internal + */ +final class NamedArgumentTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // needs to run after TypeColonTransformer + return -15; + } + public function getRequiredPhpVersionId() : int + { + return 80000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$tokens[$index]->equals(':')) { + return; + } + $stringIndex = $tokens->getPrevMeaningfulToken($index); + if (!$tokens[$stringIndex]->isGivenKind(\T_STRING)) { + return; + } + $preStringIndex = $tokens->getPrevMeaningfulToken($stringIndex); + // if equals any [';', '{', '}', [T_OPEN_TAG]] than it is a goto label + // if equals ')' than likely it is a type colon, but sure not a name argument + // if equals '?' than it is part of ternary statement + 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, ':']); + } + public function getCustomTokens() : array + { + return [CT::T_NAMED_ARGUMENT_COLON, CT::T_NAMED_ARGUMENT_NAME]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php new file mode 100644 index 00000000000..689a7302e1c --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NamespaceOperatorTransformer.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `namespace` operator from T_NAMESPACE into CT::T_NAMESPACE_OPERATOR. + * + * @author Gregor Harlan + * + * @internal + */ +final class NamespaceOperatorTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50300; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + 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()]); + } + } + public function getCustomTokens() : array + { + return [CT::T_NAMESPACE_OPERATOR]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php new file mode 100644 index 00000000000..55da11a2e43 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/NullableTypeTransformer.php @@ -0,0 +1,59 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `?` operator into CT::T_NULLABLE_TYPE in `function foo(?Bar $b) {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class NullableTypeTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // needs to run after TypeColonTransformer + return -20; + } + public function getRequiredPhpVersionId() : int + { + return 70100; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$token->equals('?')) { + return; + } + static $types; + if (null === $types) { + $types = ['(', ',', [CT::T_TYPE_COLON], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PUBLIC], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PROTECTED], [CT::T_CONSTRUCTOR_PROPERTY_PROMOTION_PRIVATE], [CT::T_ATTRIBUTE_CLOSE], [\T_PRIVATE], [\T_PROTECTED], [\T_PUBLIC], [\T_VAR], [\T_STATIC], [\T_CONST]]; + if (\defined('T_READONLY')) { + // @TODO: drop condition when PHP 8.1+ is required + $types[] = [\T_READONLY]; + } + } + $prevIndex = $tokens->getPrevMeaningfulToken($index); + if ($tokens[$prevIndex]->equalsAny($types)) { + $tokens[$index] = new Token([CT::T_NULLABLE_TYPE, '?']); + } + } + public function getCustomTokens() : array + { + return [CT::T_NULLABLE_TYPE]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php new file mode 100644 index 00000000000..dfc19dbd059 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/ReturnRefTransformer.php @@ -0,0 +1,42 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `&` operator into CT::T_RETURN_REF in `function & foo() {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ReturnRefTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($token->equals('&') && $tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind([\T_FUNCTION, \T_FN])) { + $tokens[$index] = new Token([CT::T_RETURN_REF, '&']); + } + } + public function getCustomTokens() : array + { + return [CT::T_RETURN_REF]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php new file mode 100644 index 00000000000..3f497f50bda --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/SquareBraceTransformer.php @@ -0,0 +1,128 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform discriminate overloaded square braces tokens. + * + * Performed transformations: + * - in `[1, 2, 3]` into CT::T_ARRAY_SQUARE_BRACE_OPEN and CT::T_ARRAY_SQUARE_BRACE_CLOSE, + * - in `[$a, &$b, [$c]] = array(1, 2, array(3))` into CT::T_DESTRUCTURING_SQUARE_BRACE_OPEN and CT::T_DESTRUCTURING_SQUARE_BRACE_CLOSE. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class SquareBraceTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // must run after CurlyBraceTransformer and AttributeTransformer + return -1; + } + public function getRequiredPhpVersionId() : int + { + // Short array syntax was introduced in PHP 5.4, but the fixer is smart + // enough to handle it even before 5.4. + // Same for array destructing syntax sugar `[` introduced in PHP 7.1. + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($this->isArrayDestructing($tokens, $index)) { + $this->transformIntoDestructuringSquareBrace($tokens, $index); + return; + } + if ($this->isShortArray($tokens, $index)) { + $this->transformIntoArraySquareBrace($tokens, $index); + } + } + public function getCustomTokens() : array + { + 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, int $index) : void + { + $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, int $index) : void + { + $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); + } + } + /** + * Check if token under given index is short array opening. + */ + private function isShortArray(Tokens $tokens, int $index) : bool + { + 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, int $index) : bool + { + 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]]; + $prevIndex = $tokens->getPrevMeaningfulToken($index); + $prevToken = $tokens[$prevIndex]; + if ($prevToken->equalsAny($disallowedPrevTokens)) { + return \false; + } + if ($prevToken->isGivenKind(\T_AS)) { + return \true; + } + if ($prevToken->isGivenKind(\T_DOUBLE_ARROW)) { + $variableIndex = $tokens->getPrevMeaningfulToken($prevIndex); + if (!$tokens[$variableIndex]->isGivenKind(\T_VARIABLE)) { + return \false; + } + $prevVariableIndex = $tokens->getPrevMeaningfulToken($variableIndex); + if ($tokens[$prevVariableIndex]->isGivenKind(\T_AS)) { + return \true; + } + } + $type = Tokens::detectBlockType($tokens[$index]); + $end = $tokens->findBlockEnd($type['type'], $index); + $nextToken = $tokens[$tokens->getNextMeaningfulToken($end)]; + return $nextToken->equals('='); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php new file mode 100644 index 00000000000..9ff5fa6b158 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeAlternationTransformer.php @@ -0,0 +1,50 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `|` operator into CT::T_TYPE_ALTERNATION in `function foo(Type1 | Type2 $x) {` + * or `} catch (ExceptionType1 | ExceptionType2 $e) {`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TypeAlternationTransformer extends AbstractTypeTransformer +{ + public function getPriority() : int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + public function getRequiredPhpVersionId() : int + { + return 70100; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + $this->doProcess($tokens, $index, '|'); + } + public function getCustomTokens() : array + { + return [CT::T_TYPE_ALTERNATION]; + } + protected function replaceToken(Tokens $tokens, int $index) : void + { + $tokens[$index] = new Token([CT::T_TYPE_ALTERNATION, '|']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php new file mode 100644 index 00000000000..db533c873f1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeColonTransformer.php @@ -0,0 +1,67 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `:` operator into CT::T_TYPE_COLON in `function foo() : int {}`. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class TypeColonTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // needs to run after ReturnRefTransformer and UseTransformer + // and before TypeAlternationTransformer + return -10; + } + public function getRequiredPhpVersionId() : int + { + return 70000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$token->equals(':')) { + return; + } + $endIndex = $tokens->getPrevMeaningfulToken($index); + if (\defined('T_ENUM') && $tokens[$tokens->getPrevMeaningfulToken($endIndex)]->isGivenKind(\T_ENUM)) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + return; + } + if (!$tokens[$endIndex]->equals(')')) { + return; + } + $startIndex = $tokens->findBlockStart(Tokens::BLOCK_TYPE_PARENTHESIS_BRACE, $endIndex); + $prevIndex = $tokens->getPrevMeaningfulToken($startIndex); + $prevToken = $tokens[$prevIndex]; + // if this could be a function name we need to take one more step + if ($prevToken->isGivenKind(\T_STRING)) { + $prevIndex = $tokens->getPrevMeaningfulToken($prevIndex); + $prevToken = $tokens[$prevIndex]; + } + if ($prevToken->isGivenKind([\T_FUNCTION, CT::T_RETURN_REF, CT::T_USE_LAMBDA, \T_FN])) { + $tokens[$index] = new Token([CT::T_TYPE_COLON, ':']); + } + } + public function getCustomTokens() : array + { + return [CT::T_TYPE_COLON]; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php new file mode 100644 index 00000000000..369315b38cb --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/TypeIntersectionTransformer.php @@ -0,0 +1,48 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTypeTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform `&` operator into CT::T_TYPE_INTERSECTION in `function foo(Type1 & Type2 $x) {` + * or `} catch (ExceptionType1 & ExceptionType2 $e) {`. + * + * @internal + */ +final class TypeIntersectionTransformer extends AbstractTypeTransformer +{ + public function getPriority() : int + { + // needs to run after ArrayTypehintTransformer, TypeColonTransformer and AttributeTransformer + return -15; + } + public function getRequiredPhpVersionId() : int + { + return 80100; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + $this->doProcess($tokens, $index, [\T_AMPERSAND_NOT_FOLLOWED_BY_VAR_OR_VARARG, '&']); + } + public function getCustomTokens() : array + { + return [CT::T_TYPE_INTERSECTION]; + } + protected function replaceToken(Tokens $tokens, int $index) : void + { + $tokens[$index] = new Token([CT::T_TYPE_INTERSECTION, '&']); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php new file mode 100644 index 00000000000..21d657332b1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/UseTransformer.php @@ -0,0 +1,86 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\CT; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Transform T_USE into: + * - CT::T_USE_TRAIT for imports, + * - CT::T_USE_LAMBDA for lambda variable uses. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class UseTransformer extends AbstractTransformer +{ + public function getPriority() : int + { + // Should run after CurlyBraceTransformer and before TypeColonTransformer + return -5; + } + public function getRequiredPhpVersionId() : int + { + return 50300; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if ($token->isGivenKind(\T_USE) && $this->isUseForLambda($tokens, $index)) { + $tokens[$index] = new Token([CT::T_USE_LAMBDA, $token->getContent()]); + return; + } + // Only search inside class/trait body for `T_USE` for traits. + // Cannot import traits inside interfaces or anywhere else + $classTypes = [\T_TRAIT]; + if (\defined('T_ENUM')) { + // @TODO: drop condition when PHP 8.1+ is required + $classTypes[] = \T_ENUM; + } + if ($token->isGivenKind(\T_CLASS)) { + if ($tokens[$tokens->getPrevMeaningfulToken($index)]->isGivenKind(\T_DOUBLE_COLON)) { + return; + } + } elseif (!$token->isGivenKind($classTypes)) { + 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()]); + } + } + } + public function getCustomTokens() : array + { + return [CT::T_USE_TRAIT, CT::T_USE_LAMBDA]; + } + /** + * Check if token under given index is `use` statement for lambda function. + */ + private function isUseForLambda(Tokens $tokens, int $index) : bool + { + $nextToken = $tokens[$tokens->getNextMeaningfulToken($index)]; + // test `function () use ($foo) {}` case + return $nextToken->equals('('); + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php new file mode 100644 index 00000000000..3a6e5b04b92 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/Transformer/WhitespacyCommentTransformer.php @@ -0,0 +1,54 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer\Transformer; + +use PhpCsFixer\Tokenizer\AbstractTransformer; +use PhpCsFixer\Tokenizer\Token; +use PhpCsFixer\Tokenizer\Tokens; +/** + * Move trailing whitespaces from comments and docs into following T_WHITESPACE token. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class WhitespacyCommentTransformer extends AbstractTransformer +{ + public function getRequiredPhpVersionId() : int + { + return 50000; + } + public function process(Tokens $tokens, Token $token, int $index) : void + { + if (!$token->isComment()) { + return; + } + $content = $token->getContent(); + $trimmedContent = \rtrim($content); + // nothing trimmed, nothing to do + 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])); + } + } + public function getCustomTokens() : array + { + return []; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php new file mode 100644 index 00000000000..e39011bda21 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Tokenizer/TransformerInterface.php @@ -0,0 +1,62 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +/** + * Interface for Transformer class. + * + * Transformer role is to register custom tokens and transform Tokens collection to use them. + * + * Custom token is a user defined token type and is used to separate different meaning of original token type. + * For example T_ARRAY is a token for both creating new array and typehinting a parameter. This two meaning should have two token types. + * + * @author Dariusz Rumiński + * + * @internal + */ +interface TransformerInterface +{ + /** + * Get tokens created by Transformer. + * + * @return list + */ + public function getCustomTokens() : array; + /** + * Return the name of the transformer. + * + * The name must be all lowercase and without any spaces. + * + * @return string The name of the fixer + */ + public function getName() : string; + /** + * Returns the priority of the transformer. + * + * The default priority is 0 and higher priorities are executed first. + */ + public function getPriority() : int; + /** + * Return minimal required PHP version id to transform the code. + * + * Custom Token kinds from Transformers are always registered, but sometimes + * there is no need to analyse the Tokens if for sure we cannot find examined + * token kind, e.g. transforming `T_FUNCTION` in ` + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer\Tokenizer; + +use ECSPrefix202307\Symfony\Component\Finder\Finder; +use ECSPrefix202307\Symfony\Component\Finder\SplFileInfo; +/** + * Collection of Transformer classes. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class Transformers +{ + /** + * The registered transformers. + * + * @var list + */ + private $items = []; + /** + * Register built in Transformers. + */ + private function __construct() + { + $this->registerBuiltInTransformers(); + \usort($this->items, static function (\PhpCsFixer\Tokenizer\TransformerInterface $a, \PhpCsFixer\Tokenizer\TransformerInterface $b) : int { + return $b->getPriority() <=> $a->getPriority(); + }); + } + public static function createSingleton() : self + { + static $instance = null; + if (!$instance) { + $instance = new self(); + } + return $instance; + } + /** + * Transform given Tokens collection through all Transformer classes. + * + * @param Tokens $tokens Tokens collection + */ + public function transform(\PhpCsFixer\Tokenizer\Tokens $tokens) : void + { + foreach ($this->items as $transformer) { + foreach ($tokens as $index => $token) { + $transformer->process($tokens, $token, $index); + } + } + } + /** + * @param TransformerInterface $transformer Transformer + */ + private function registerTransformer(\PhpCsFixer\Tokenizer\TransformerInterface $transformer) : void + { + if (\PHP_VERSION_ID >= $transformer->getRequiredPhpVersionId()) { + $this->items[] = $transformer; + } + } + private function registerBuiltInTransformers() : void + { + static $registered = \false; + if ($registered) { + return; + } + $registered = \true; + foreach ($this->findBuiltInTransformers() as $transformer) { + $this->registerTransformer($transformer); + } + } + /** + * @return \Generator + */ + private function findBuiltInTransformers() : iterable + { + /** @var SplFileInfo $file */ + foreach (Finder::create()->files()->in(__DIR__ . '/Transformer') as $file) { + $relativeNamespace = $file->getRelativePath(); + $class = __NAMESPACE__ . '\\Transformer\\' . ('' !== $relativeNamespace ? $relativeNamespace . '\\' : '') . $file->getBasename('.php'); + (yield new $class()); + } + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php b/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php new file mode 100644 index 00000000000..64a2d5d5f6f --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ToolInfo.php @@ -0,0 +1,87 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Console\Application; +/** + * Obtain information about using version of tool. + * + * @author Dariusz Rumiński + * + * @internal + */ +final class ToolInfo implements \PhpCsFixer\ToolInfoInterface +{ + public const COMPOSER_PACKAGE_NAME = 'friendsofphp/php-cs-fixer'; + public const COMPOSER_LEGACY_PACKAGE_NAME = 'fabpot/php-cs-fixer'; + /** + * @var null|array{name: string, version: string, dist: array{reference?: string}} + */ + private $composerInstallationDetails; + /** + * @var null|bool + */ + private $isInstalledByComposer; + public function getComposerInstallationDetails() : array + { + 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 = $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() : string + { + $package = $this->getComposerInstallationDetails(); + $versionSuffix = ''; + if (isset($package['dist']['reference'])) { + $versionSuffix = '#' . $package['dist']['reference']; + } + return $package['version'] . $versionSuffix; + } + public function getVersion() : string + { + if ($this->isInstalledByComposer()) { + return Application::VERSION . ':' . $this->getComposerVersion(); + } + return Application::VERSION; + } + public function isInstalledAsPhar() : bool + { + return \strncmp(__DIR__, 'phar://', \strlen('phar://')) === 0; + } + public function isInstalledByComposer() : bool + { + if (null === $this->isInstalledByComposer) { + $this->isInstalledByComposer = !$this->isInstalledAsPhar() && \file_exists($this->getComposerInstalledFile()); + } + return $this->isInstalledByComposer; + } + public function getPharDownloadUri(string $version) : string + { + return \sprintf('https://github.com/PHP-CS-Fixer/PHP-CS-Fixer/releases/download/%s/php-cs-fixer.phar', $version); + } + private function getComposerInstalledFile() : string + { + return __DIR__ . '/../../../composer/installed.json'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php b/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php new file mode 100644 index 00000000000..b18c8526433 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/ToolInfoInterface.php @@ -0,0 +1,29 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @internal + */ +interface ToolInfoInterface +{ + /** + * @return array{name: string, version: string, dist: array{reference?: string}} + */ + public function getComposerInstallationDetails() : array; + public function getComposerVersion() : string; + public function getVersion() : string; + public function isInstalledAsPhar() : bool; + public function isInstalledByComposer() : bool; + public function getPharDownloadUri(string $version) : string; +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/Utils.php b/vendor/friendsofphp/php-cs-fixer/src/Utils.php new file mode 100644 index 00000000000..4ee08b80c43 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/Utils.php @@ -0,0 +1,205 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +use PhpCsFixer\Fixer\FixerInterface; +use PhpCsFixer\Tokenizer\Token; +/** + * @author Dariusz Rumiński + * @author Graham Campbell + * @author Odín del Río + * + * @internal + * + * @deprecated This is a God Class anti-pattern. Don't expand it. It is fine to use logic that is already here (that's why we don't trigger deprecation warnings), but over time logic should be moved to dedicated, single-responsibility classes. + */ +final class Utils +{ + /** + * @var array + */ + private static $deprecations = []; + private function __construct() + { + // cannot create instance of util. class + } + /** + * Converts a camel cased string to a snake cased string. + */ + public static function camelCaseToUnderscore(string $string) : string + { + return \mb_strtolower(\PhpCsFixer\Preg::replace('/(?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"); + } + /** + * Perform stable sorting using provided comparison function. + * + * Stability is ensured by using Schwartzian transform. + * + * @param mixed[] $elements + * @param callable $getComparedValue a callable that takes a single element and returns the value to compare + * @param callable $compareValues a callable that compares two values + * + * @return mixed[] + */ + public static function stableSort(array $elements, callable $getComparedValue, callable $compareValues) : array + { + \array_walk($elements, static function (&$element, int $index) use($getComparedValue) : void { + $element = [$element, $index, $getComparedValue($element)]; + }); + \usort($elements, static function ($a, $b) use($compareValues) : int { + $comparison = $compareValues($a[2], $b[2]); + if (0 !== $comparison) { + return $comparison; + } + return $a[1] <=> $b[1]; + }); + return \array_map(static function (array $item) { + return $item[0]; + }, $elements); + } + /** + * Sort fixers by their priorities. + * + * @param FixerInterface[] $fixers + * + * @return FixerInterface[] + */ + public static function sortFixers(array $fixers) : array + { + // Schwartzian transform is used to improve the efficiency and avoid + // `usort(): Array was modified by the user comparison function` warning for mocked objects. + return self::stableSort($fixers, static function (FixerInterface $fixer) : int { + return $fixer->getPriority(); + }, static function (int $a, int $b) : int { + return $b <=> $a; + }); + } + /** + * Join names in natural language using specified wrapper (double quote by default). + * + * @param string[] $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoin(array $names, string $wrapper = '"') : string + { + if (0 === \count($names)) { + throw new \InvalidArgumentException('Array of names cannot be empty.'); + } + if (\strlen($wrapper) > 1) { + throw new \InvalidArgumentException('Wrapper should be a single-char string or empty.'); + } + $names = \array_map(static function (string $name) use($wrapper) : string { + return \sprintf('%2$s%1$s%2$s', $name, $wrapper); + }, $names); + $last = \array_pop($names); + if (\count($names) > 0) { + return \implode(', ', $names) . ' and ' . $last; + } + return $last; + } + /** + * Join names in natural language wrapped in backticks, e.g. `a`, `b` and `c`. + * + * @param string[] $names + * + * @throws \InvalidArgumentException + */ + public static function naturalLanguageJoinWithBackticks(array $names) : string + { + return self::naturalLanguageJoin($names, '`'); + } + public static function triggerDeprecation(\Exception $futureException) : void + { + if (\getenv('PHP_CS_FIXER_FUTURE_MODE')) { + throw new \RuntimeException('Your are using something deprecated, see previous exception. Aborting execution because `PHP_CS_FIXER_FUTURE_MODE` environment variable is set.', 0, $futureException); + } + $message = $futureException->getMessage(); + self::$deprecations[$message] = \true; + @\trigger_error($message, \E_USER_DEPRECATED); + } + /** + * @return list + */ + public static function getTriggeredDeprecations() : array + { + $triggeredDeprecations = \array_keys(self::$deprecations); + \sort($triggeredDeprecations); + return $triggeredDeprecations; + } + /** + * @param mixed $value + */ + public static function toString($value) : string + { + return \is_array($value) ? self::arrayToString($value) : self::scalarToString($value); + } + /** + * @param mixed $value + */ + private static function scalarToString($value) : string + { + $str = \var_export($value, \true); + return \PhpCsFixer\Preg::replace('/\\bNULL\\b/', 'null', $str); + } + /** + * @param array $value + */ + private static function arrayToString(array $value) : string + { + if (0 === \count($value)) { + return '[]'; + } + $arrayIsList = function (array $array) : bool { + if (\function_exists('array_is_list')) { + return \array_is_list($array); + } + if ($array === []) { + return \true; + } + $current_key = 0; + foreach ($array as $key => $noop) { + if ($key !== $current_key) { + return \false; + } + ++$current_key; + } + return \true; + }; + $isHash = !$arrayIsList($value); + $str = '['; + foreach ($value as $k => $v) { + if ($isHash) { + $str .= self::scalarToString($k) . ' => '; + } + $str .= \is_array($v) ? self::arrayToString($v) . ', ' : self::scalarToString($v) . ', '; + } + return \substr($str, 0, -2) . ']'; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php b/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php new file mode 100644 index 00000000000..a81a97db1e1 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/WhitespacesFixerConfig.php @@ -0,0 +1,47 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + */ +final class WhitespacesFixerConfig +{ + /** + * @var string + */ + private $indent; + /** + * @var string + */ + private $lineEnding; + public function __construct(string $indent = ' ', string $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() : string + { + return $this->indent; + } + public function getLineEnding() : string + { + return $this->lineEnding; + } +} diff --git a/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php b/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php new file mode 100644 index 00000000000..5c105a70351 --- /dev/null +++ b/vendor/friendsofphp/php-cs-fixer/src/WordMatcher.php @@ -0,0 +1,46 @@ + + * Dariusz Rumiński + * + * This source file is subject to the MIT license that is bundled + * with this source code in the file LICENSE. + */ +namespace PhpCsFixer; + +/** + * @author Dariusz Rumiński + * + * @internal + */ +final class WordMatcher +{ + /** + * @var string[] + */ + private $candidates; + /** + * @param string[] $candidates + */ + public function __construct(array $candidates) + { + $this->candidates = $candidates; + } + public function match(string $needle) : ?string + { + $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; + } +} diff --git a/vendor/illuminate/container/BoundMethod.php b/vendor/illuminate/container/BoundMethod.php new file mode 100644 index 00000000000..c6d921d202b --- /dev/null +++ b/vendor/illuminate/container/BoundMethod.php @@ -0,0 +1,170 @@ +make($segments[0]), $method], $parameters); + } + /** + * Call a method that has been bound to the container. + * + * @param \Illuminate\Container\Container $container + * @param callable $callback + * @param mixed $default + * @return mixed + */ + protected static function callBoundMethod($container, $callback, $default) + { + if (!\is_array($callback)) { + return Util::unwrapIfClosure($default); + } + // Here we need to turn the array callable into a Class@method string we can use to + // examine the container and see if there are any method bindings for this given + // method. If there are, we can call this method binding callback immediately. + $method = static::normalizeMethod($callback); + if ($container->hasMethodBinding($method)) { + return $container->callMethodBinding($method, $callback[0]); + } + return Util::unwrapIfClosure($default); + } + /** + * Normalize the given callback into a Class@method string. + * + * @param callable $callback + * @return string + */ + protected static function normalizeMethod($callback) + { + $class = \is_string($callback[0]) ? $callback[0] : \get_class($callback[0]); + return "{$class}@{$callback[1]}"; + } + /** + * Get all dependencies for a given method. + * + * @param \Illuminate\Container\Container $container + * @param callable|string $callback + * @param array $parameters + * @return array + * + * @throws \ReflectionException + */ + protected static function getMethodDependencies($container, $callback, array $parameters = []) + { + $dependencies = []; + foreach (static::getCallReflector($callback)->getParameters() as $parameter) { + static::addDependencyForCallParameter($container, $parameter, $parameters, $dependencies); + } + return \array_merge($dependencies, \array_values($parameters)); + } + /** + * Get the proper reflection instance for the given callback. + * + * @param callable|string $callback + * @return \ReflectionFunctionAbstract + * + * @throws \ReflectionException + */ + protected static function getCallReflector($callback) + { + if (\is_string($callback) && \strpos($callback, '::') !== \false) { + $callback = \explode('::', $callback); + } elseif (\is_object($callback) && !$callback instanceof Closure) { + $callback = [$callback, '__invoke']; + } + return \is_array($callback) ? new ReflectionMethod($callback[0], $callback[1]) : new ReflectionFunction($callback); + } + /** + * Get the dependency for the given call parameter. + * + * @param \Illuminate\Container\Container $container + * @param \ReflectionParameter $parameter + * @param array $parameters + * @param array $dependencies + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected static function addDependencyForCallParameter($container, $parameter, array &$parameters, &$dependencies) + { + if (\array_key_exists($paramName = $parameter->getName(), $parameters)) { + $dependencies[] = $parameters[$paramName]; + unset($parameters[$paramName]); + } elseif (!\is_null($className = Util::getParameterClassName($parameter))) { + if (\array_key_exists($className, $parameters)) { + $dependencies[] = $parameters[$className]; + unset($parameters[$className]); + } elseif ($parameter->isVariadic()) { + $variadicDependencies = $container->make($className); + $dependencies = \array_merge($dependencies, \is_array($variadicDependencies) ? $variadicDependencies : [$variadicDependencies]); + } else { + $dependencies[] = $container->make($className); + } + } elseif ($parameter->isDefaultValueAvailable()) { + $dependencies[] = $parameter->getDefaultValue(); + } elseif (!$parameter->isOptional() && !\array_key_exists($paramName, $parameters)) { + $message = "Unable to resolve dependency [{$parameter}] in class {$parameter->getDeclaringClass()->getName()}"; + throw new BindingResolutionException($message); + } + } + /** + * Determine if the given string is in Class@method syntax. + * + * @param mixed $callback + * @return bool + */ + protected static function isCallableWithAtSign($callback) + { + return \is_string($callback) && \strpos($callback, '@') !== \false; + } +} diff --git a/vendor/illuminate/container/Container.php b/vendor/illuminate/container/Container.php new file mode 100644 index 00000000000..3285c7e4973 --- /dev/null +++ b/vendor/illuminate/container/Container.php @@ -0,0 +1,1293 @@ +getAlias($c); + } + return new ContextualBindingBuilder($this, $aliases); + } + /** + * Determine if the given abstract type has been bound. + * + * @param string $abstract + * @return bool + */ + public function bound($abstract) + { + return isset($this->bindings[$abstract]) || isset($this->instances[$abstract]) || $this->isAlias($abstract); + } + /** + * {@inheritdoc} + * + * @return bool + */ + public function has(string $id) : bool + { + return $this->bound($id); + } + /** + * Determine if the given abstract type has been resolved. + * + * @param string $abstract + * @return bool + */ + public function resolved($abstract) + { + if ($this->isAlias($abstract)) { + $abstract = $this->getAlias($abstract); + } + return isset($this->resolved[$abstract]) || isset($this->instances[$abstract]); + } + /** + * Determine if a given type is shared. + * + * @param string $abstract + * @return bool + */ + public function isShared($abstract) + { + return isset($this->instances[$abstract]) || isset($this->bindings[$abstract]['shared']) && $this->bindings[$abstract]['shared'] === \true; + } + /** + * Determine if a given string is an alias. + * + * @param string $name + * @return bool + */ + public function isAlias($name) + { + return isset($this->aliases[$name]); + } + /** + * Register a binding with the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + * + * @throws \TypeError + */ + public function bind($abstract, $concrete = null, $shared = \false) + { + $this->dropStaleInstances($abstract); + // If no concrete type was given, we will simply set the concrete type to the + // abstract type. After that, the concrete type to be registered as shared + // without being forced to state their classes in both of the parameters. + if (\is_null($concrete)) { + $concrete = $abstract; + } + // If the factory is not a Closure, it means it is just a class name which is + // bound into this container to the abstract type and we will just wrap it + // up inside its own Closure to give us more convenience when extending. + if (!$concrete instanceof Closure) { + if (!\is_string($concrete)) { + throw new TypeError(self::class . '::bind(): Argument #2 ($concrete) must be of type Closure|string|null'); + } + $concrete = $this->getClosure($abstract, $concrete); + } + $this->bindings[$abstract] = \compact('concrete', 'shared'); + // If the abstract type was already resolved in this container we'll fire the + // rebound listener so that any objects which have already gotten resolved + // can have their copy of the object updated via the listener callbacks. + if ($this->resolved($abstract)) { + $this->rebound($abstract); + } + } + /** + * Get the Closure to be used when building a type. + * + * @param string $abstract + * @param string $concrete + * @return \Closure + */ + protected function getClosure($abstract, $concrete) + { + return function ($container, $parameters = []) use($abstract, $concrete) { + if ($abstract == $concrete) { + return $container->build($concrete); + } + return $container->resolve($concrete, $parameters, $raiseEvents = \false); + }; + } + /** + * Determine if the container has a method binding. + * + * @param string $method + * @return bool + */ + public function hasMethodBinding($method) + { + return isset($this->methodBindings[$method]); + } + /** + * Bind a callback to resolve with Container::call. + * + * @param array|string $method + * @param \Closure $callback + * @return void + */ + public function bindMethod($method, $callback) + { + $this->methodBindings[$this->parseBindMethod($method)] = $callback; + } + /** + * Get the method to be bound in class@method format. + * + * @param array|string $method + * @return string + */ + protected function parseBindMethod($method) + { + if (\is_array($method)) { + return $method[0] . '@' . $method[1]; + } + return $method; + } + /** + * Get the method binding for the given method. + * + * @param string $method + * @param mixed $instance + * @return mixed + */ + public function callMethodBinding($method, $instance) + { + return \call_user_func($this->methodBindings[$method], $instance, $this); + } + /** + * Add a contextual binding to the container. + * + * @param string $concrete + * @param string $abstract + * @param \Closure|string $implementation + * @return void + */ + public function addContextualBinding($concrete, $abstract, $implementation) + { + $this->contextual[$concrete][$this->getAlias($abstract)] = $implementation; + } + /** + * Register a binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @param bool $shared + * @return void + */ + public function bindIf($abstract, $concrete = null, $shared = \false) + { + if (!$this->bound($abstract)) { + $this->bind($abstract, $concrete, $shared); + } + } + /** + * Register a shared binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function singleton($abstract, $concrete = null) + { + $this->bind($abstract, $concrete, \true); + } + /** + * Register a shared binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function singletonIf($abstract, $concrete = null) + { + if (!$this->bound($abstract)) { + $this->singleton($abstract, $concrete); + } + } + /** + * Register a scoped binding in the container. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function scoped($abstract, $concrete = null) + { + $this->scopedInstances[] = $abstract; + $this->singleton($abstract, $concrete); + } + /** + * Register a scoped binding if it hasn't already been registered. + * + * @param string $abstract + * @param \Closure|string|null $concrete + * @return void + */ + public function scopedIf($abstract, $concrete = null) + { + if (!$this->bound($abstract)) { + $this->scoped($abstract, $concrete); + } + } + /** + * "Extend" an abstract type in the container. + * + * @param string $abstract + * @param \Closure $closure + * @return void + * + * @throws \InvalidArgumentException + */ + public function extend($abstract, Closure $closure) + { + $abstract = $this->getAlias($abstract); + if (isset($this->instances[$abstract])) { + $this->instances[$abstract] = $closure($this->instances[$abstract], $this); + $this->rebound($abstract); + } else { + $this->extenders[$abstract][] = $closure; + if ($this->resolved($abstract)) { + $this->rebound($abstract); + } + } + } + /** + * Register an existing instance as shared in the container. + * + * @param string $abstract + * @param mixed $instance + * @return mixed + */ + public function instance($abstract, $instance) + { + $this->removeAbstractAlias($abstract); + $isBound = $this->bound($abstract); + unset($this->aliases[$abstract]); + // We'll check to determine if this type has been bound before, and if it has + // we will fire the rebound callbacks registered with the container and it + // can be updated with consuming classes that have gotten resolved here. + $this->instances[$abstract] = $instance; + if ($isBound) { + $this->rebound($abstract); + } + return $instance; + } + /** + * Remove an alias from the contextual binding alias cache. + * + * @param string $searched + * @return void + */ + protected function removeAbstractAlias($searched) + { + if (!isset($this->aliases[$searched])) { + return; + } + foreach ($this->abstractAliases as $abstract => $aliases) { + foreach ($aliases as $index => $alias) { + if ($alias == $searched) { + unset($this->abstractAliases[$abstract][$index]); + } + } + } + } + /** + * Assign a set of tags to a given binding. + * + * @param array|string $abstracts + * @param array|mixed ...$tags + * @return void + */ + public function tag($abstracts, $tags) + { + $tags = \is_array($tags) ? $tags : \array_slice(\func_get_args(), 1); + foreach ($tags as $tag) { + if (!isset($this->tags[$tag])) { + $this->tags[$tag] = []; + } + foreach ((array) $abstracts as $abstract) { + $this->tags[$tag][] = $abstract; + } + } + } + /** + * Resolve all of the bindings for a given tag. + * + * @param string $tag + * @return iterable + */ + public function tagged($tag) + { + if (!isset($this->tags[$tag])) { + return []; + } + return new RewindableGenerator(function () use($tag) { + foreach ($this->tags[$tag] as $abstract) { + (yield $this->make($abstract)); + } + }, \count($this->tags[$tag])); + } + /** + * Alias a type to a different name. + * + * @param string $abstract + * @param string $alias + * @return void + * + * @throws \LogicException + */ + public function alias($abstract, $alias) + { + if ($alias === $abstract) { + throw new LogicException("[{$abstract}] is aliased to itself."); + } + $this->aliases[$alias] = $abstract; + $this->abstractAliases[$abstract][] = $alias; + } + /** + * Bind a new callback to an abstract's rebind event. + * + * @param string $abstract + * @param \Closure $callback + * @return mixed + */ + public function rebinding($abstract, Closure $callback) + { + $this->reboundCallbacks[$abstract = $this->getAlias($abstract)][] = $callback; + if ($this->bound($abstract)) { + return $this->make($abstract); + } + } + /** + * Refresh an instance on the given target and method. + * + * @param string $abstract + * @param mixed $target + * @param string $method + * @return mixed + */ + public function refresh($abstract, $target, $method) + { + return $this->rebinding($abstract, function ($app, $instance) use($target, $method) { + $target->{$method}($instance); + }); + } + /** + * Fire the "rebound" callbacks for the given abstract type. + * + * @param string $abstract + * @return void + */ + protected function rebound($abstract) + { + $instance = $this->make($abstract); + foreach ($this->getReboundCallbacks($abstract) as $callback) { + $callback($this, $instance); + } + } + /** + * Get the rebound callbacks for a given type. + * + * @param string $abstract + * @return array + */ + protected function getReboundCallbacks($abstract) + { + return $this->reboundCallbacks[$abstract] ?? []; + } + /** + * Wrap the given closure such that its dependencies will be injected when executed. + * + * @param \Closure $callback + * @param array $parameters + * @return \Closure + */ + public function wrap(Closure $callback, array $parameters = []) + { + return function () use($callback, $parameters) { + return $this->call($callback, $parameters); + }; + } + /** + * Call the given Closure / class@method and inject its dependencies. + * + * @param callable|string $callback + * @param array $parameters + * @param string|null $defaultMethod + * @return mixed + * + * @throws \InvalidArgumentException + */ + public function call($callback, array $parameters = [], $defaultMethod = null) + { + $pushedToBuildStack = \false; + if (($className = $this->getClassForCallable($callback)) && !\in_array($className, $this->buildStack, \true)) { + $this->buildStack[] = $className; + $pushedToBuildStack = \true; + } + $result = BoundMethod::call($this, $callback, $parameters, $defaultMethod); + if ($pushedToBuildStack) { + \array_pop($this->buildStack); + } + return $result; + } + /** + * Get the class name for the given callback, if one can be determined. + * + * @param callable|string $callback + * @return string|false + */ + protected function getClassForCallable($callback) + { + if (\PHP_VERSION_ID >= 80200) { + if (\is_callable($callback) && !($reflector = new ReflectionFunction(\Closure::fromCallable($callback)))->isAnonymous()) { + return $reflector->getClosureScopeClass()->name ?? \false; + } + return \false; + } + if (!\is_array($callback)) { + return \false; + } + return \is_string($callback[0]) ? $callback[0] : \get_class($callback[0]); + } + /** + * Get a closure to resolve the given type from the container. + * + * @param string $abstract + * @return \Closure + */ + public function factory($abstract) + { + return function () use($abstract) { + return $this->make($abstract); + }; + } + /** + * An alias function name for make(). + * + * @param string|callable $abstract + * @param array $parameters + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function makeWith($abstract, array $parameters = []) + { + return $this->make($abstract, $parameters); + } + /** + * Resolve the given type from the container. + * + * @param string|callable $abstract + * @param array $parameters + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + public function make($abstract, array $parameters = []) + { + return $this->resolve($abstract, $parameters); + } + /** + * {@inheritdoc} + * + * @return mixed + */ + public function get(string $id) + { + try { + return $this->resolve($id); + } catch (Exception $e) { + if ($this->has($id) || $e instanceof CircularDependencyException) { + throw $e; + } + throw new EntryNotFoundException($id, \is_int($e->getCode()) ? $e->getCode() : 0, $e); + } + } + /** + * Resolve the given type from the container. + * + * @param string|callable $abstract + * @param array $parameters + * @param bool $raiseEvents + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @throws \Illuminate\Contracts\Container\CircularDependencyException + */ + protected function resolve($abstract, $parameters = [], $raiseEvents = \true) + { + $abstract = $this->getAlias($abstract); + // First we'll fire any event handlers which handle the "before" resolving of + // specific types. This gives some hooks the chance to add various extends + // calls to change the resolution of objects that they're interested in. + if ($raiseEvents) { + $this->fireBeforeResolvingCallbacks($abstract, $parameters); + } + $concrete = $this->getContextualConcrete($abstract); + $needsContextualBuild = !empty($parameters) || !\is_null($concrete); + // If an instance of the type is currently being managed as a singleton we'll + // just return an existing instance instead of instantiating new instances + // so the developer can keep using the same objects instance every time. + if (isset($this->instances[$abstract]) && !$needsContextualBuild) { + return $this->instances[$abstract]; + } + $this->with[] = $parameters; + if (\is_null($concrete)) { + $concrete = $this->getConcrete($abstract); + } + // We're ready to instantiate an instance of the concrete type registered for + // the binding. This will instantiate the types, as well as resolve any of + // its "nested" dependencies recursively until all have gotten resolved. + $object = $this->isBuildable($concrete, $abstract) ? $this->build($concrete) : $this->make($concrete); + // If we defined any extenders for this type, we'll need to spin through them + // and apply them to the object being built. This allows for the extension + // of services, such as changing configuration or decorating the object. + foreach ($this->getExtenders($abstract) as $extender) { + $object = $extender($object, $this); + } + // If the requested type is registered as a singleton we'll want to cache off + // the instances in "memory" so we can return it later without creating an + // entirely new instance of an object on each subsequent request for it. + if ($this->isShared($abstract) && !$needsContextualBuild) { + $this->instances[$abstract] = $object; + } + if ($raiseEvents) { + $this->fireResolvingCallbacks($abstract, $object); + } + // Before returning, we will also set the resolved flag to "true" and pop off + // the parameter overrides for this build. After those two things are done + // we will be ready to return back the fully constructed class instance. + $this->resolved[$abstract] = \true; + \array_pop($this->with); + return $object; + } + /** + * Get the concrete type for a given abstract. + * + * @param string|callable $abstract + * @return mixed + */ + protected function getConcrete($abstract) + { + // If we don't have a registered resolver or concrete for the type, we'll just + // assume each type is a concrete name and will attempt to resolve it as is + // since the container should be able to resolve concretes automatically. + if (isset($this->bindings[$abstract])) { + return $this->bindings[$abstract]['concrete']; + } + return $abstract; + } + /** + * Get the contextual concrete binding for the given abstract. + * + * @param string|callable $abstract + * @return \Closure|string|array|null + */ + protected function getContextualConcrete($abstract) + { + if (!\is_null($binding = $this->findInContextualBindings($abstract))) { + return $binding; + } + // Next we need to see if a contextual binding might be bound under an alias of the + // given abstract type. So, we will need to check if any aliases exist with this + // type and then spin through them and check for contextual bindings on these. + if (empty($this->abstractAliases[$abstract])) { + return; + } + foreach ($this->abstractAliases[$abstract] as $alias) { + if (!\is_null($binding = $this->findInContextualBindings($alias))) { + return $binding; + } + } + } + /** + * Find the concrete binding for the given abstract in the contextual binding array. + * + * @param string|callable $abstract + * @return \Closure|string|null + */ + protected function findInContextualBindings($abstract) + { + return $this->contextual[\end($this->buildStack)][$abstract] ?? null; + } + /** + * Determine if the given concrete is buildable. + * + * @param mixed $concrete + * @param string $abstract + * @return bool + */ + protected function isBuildable($concrete, $abstract) + { + return $concrete === $abstract || $concrete instanceof Closure; + } + /** + * Instantiate a concrete instance of the given type. + * + * @param \Closure|string $concrete + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + * @throws \Illuminate\Contracts\Container\CircularDependencyException + */ + public function build($concrete) + { + // If the concrete type is actually a Closure, we will just execute it and + // hand back the results of the functions, which allows functions to be + // used as resolvers for more fine-tuned resolution of these objects. + if ($concrete instanceof Closure) { + return $concrete($this, $this->getLastParameterOverride()); + } + try { + $reflector = new ReflectionClass($concrete); + } catch (ReflectionException $e) { + throw new BindingResolutionException("Target class [{$concrete}] does not exist.", 0, $e); + } + // If the type is not instantiable, the developer is attempting to resolve + // an abstract type such as an Interface or Abstract Class and there is + // no binding registered for the abstractions so we need to bail out. + if (!$reflector->isInstantiable()) { + return $this->notInstantiable($concrete); + } + $this->buildStack[] = $concrete; + $constructor = $reflector->getConstructor(); + // If there are no constructors, that means there are no dependencies then + // we can just resolve the instances of the objects right away, without + // resolving any other types or dependencies out of these containers. + if (\is_null($constructor)) { + \array_pop($this->buildStack); + return new $concrete(); + } + $dependencies = $constructor->getParameters(); + // Once we have all the constructor's parameters we can create each of the + // dependency instances and then use the reflection instances to make a + // new instance of this class, injecting the created dependencies in. + try { + $instances = $this->resolveDependencies($dependencies); + } catch (BindingResolutionException $e) { + \array_pop($this->buildStack); + throw $e; + } + \array_pop($this->buildStack); + return $reflector->newInstanceArgs($instances); + } + /** + * Resolve all of the dependencies from the ReflectionParameters. + * + * @param \ReflectionParameter[] $dependencies + * @return array + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolveDependencies(array $dependencies) + { + $results = []; + foreach ($dependencies as $dependency) { + // If the dependency has an override for this particular build we will use + // that instead as the value. Otherwise, we will continue with this run + // of resolutions and let reflection attempt to determine the result. + if ($this->hasParameterOverride($dependency)) { + $results[] = $this->getParameterOverride($dependency); + continue; + } + // If the class is null, it means the dependency is a string or some other + // primitive type which we can not resolve since it is not a class and + // we will just bomb out with an error since we have no-where to go. + $result = \is_null(Util::getParameterClassName($dependency)) ? $this->resolvePrimitive($dependency) : $this->resolveClass($dependency); + if ($dependency->isVariadic()) { + $results = \array_merge($results, $result); + } else { + $results[] = $result; + } + } + return $results; + } + /** + * Determine if the given dependency has a parameter override. + * + * @param \ReflectionParameter $dependency + * @return bool + */ + protected function hasParameterOverride($dependency) + { + return \array_key_exists($dependency->name, $this->getLastParameterOverride()); + } + /** + * Get a parameter override for a dependency. + * + * @param \ReflectionParameter $dependency + * @return mixed + */ + protected function getParameterOverride($dependency) + { + return $this->getLastParameterOverride()[$dependency->name]; + } + /** + * Get the last parameter override. + * + * @return array + */ + protected function getLastParameterOverride() + { + return \count($this->with) ? \end($this->with) : []; + } + /** + * Resolve a non-class hinted primitive dependency. + * + * @param \ReflectionParameter $parameter + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolvePrimitive(ReflectionParameter $parameter) + { + if (!\is_null($concrete = $this->getContextualConcrete('$' . $parameter->getName()))) { + return Util::unwrapIfClosure($concrete, $this); + } + if ($parameter->isDefaultValueAvailable()) { + return $parameter->getDefaultValue(); + } + if ($parameter->isVariadic()) { + return []; + } + $this->unresolvablePrimitive($parameter); + } + /** + * Resolve a class based dependency from the container. + * + * @param \ReflectionParameter $parameter + * @return mixed + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function resolveClass(ReflectionParameter $parameter) + { + try { + return $parameter->isVariadic() ? $this->resolveVariadicClass($parameter) : $this->make(Util::getParameterClassName($parameter)); + } catch (BindingResolutionException $e) { + if ($parameter->isDefaultValueAvailable()) { + \array_pop($this->with); + return $parameter->getDefaultValue(); + } + if ($parameter->isVariadic()) { + \array_pop($this->with); + return []; + } + throw $e; + } + } + /** + * Resolve a class based variadic dependency from the container. + * + * @param \ReflectionParameter $parameter + * @return mixed + */ + protected function resolveVariadicClass(ReflectionParameter $parameter) + { + $className = Util::getParameterClassName($parameter); + $abstract = $this->getAlias($className); + if (!\is_array($concrete = $this->getContextualConcrete($abstract))) { + return $this->make($className); + } + return \array_map(function ($abstract) { + return $this->resolve($abstract); + }, $concrete); + } + /** + * Throw an exception that the concrete is not instantiable. + * + * @param string $concrete + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function notInstantiable($concrete) + { + if (!empty($this->buildStack)) { + $previous = \implode(', ', $this->buildStack); + $message = "Target [{$concrete}] is not instantiable while building [{$previous}]."; + } else { + $message = "Target [{$concrete}] is not instantiable."; + } + throw new BindingResolutionException($message); + } + /** + * Throw an exception for an unresolvable primitive. + * + * @param \ReflectionParameter $parameter + * @return void + * + * @throws \Illuminate\Contracts\Container\BindingResolutionException + */ + protected function unresolvablePrimitive(ReflectionParameter $parameter) + { + $message = "Unresolvable dependency resolving [{$parameter}] in class {$parameter->getDeclaringClass()->getName()}"; + throw new BindingResolutionException($message); + } + /** + * Register a new before resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function beforeResolving($abstract, Closure $callback = null) + { + if (\is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + if ($abstract instanceof Closure && \is_null($callback)) { + $this->globalBeforeResolvingCallbacks[] = $abstract; + } else { + $this->beforeResolvingCallbacks[$abstract][] = $callback; + } + } + /** + * Register a new resolving callback. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function resolving($abstract, Closure $callback = null) + { + if (\is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + if (\is_null($callback) && $abstract instanceof Closure) { + $this->globalResolvingCallbacks[] = $abstract; + } else { + $this->resolvingCallbacks[$abstract][] = $callback; + } + } + /** + * Register a new after resolving callback for all types. + * + * @param \Closure|string $abstract + * @param \Closure|null $callback + * @return void + */ + public function afterResolving($abstract, Closure $callback = null) + { + if (\is_string($abstract)) { + $abstract = $this->getAlias($abstract); + } + if ($abstract instanceof Closure && \is_null($callback)) { + $this->globalAfterResolvingCallbacks[] = $abstract; + } else { + $this->afterResolvingCallbacks[$abstract][] = $callback; + } + } + /** + * Fire all of the before resolving callbacks. + * + * @param string $abstract + * @param array $parameters + * @return void + */ + protected function fireBeforeResolvingCallbacks($abstract, $parameters = []) + { + $this->fireBeforeCallbackArray($abstract, $parameters, $this->globalBeforeResolvingCallbacks); + foreach ($this->beforeResolvingCallbacks as $type => $callbacks) { + if ($type === $abstract || \is_subclass_of($abstract, $type)) { + $this->fireBeforeCallbackArray($abstract, $parameters, $callbacks); + } + } + } + /** + * Fire an array of callbacks with an object. + * + * @param string $abstract + * @param array $parameters + * @param array $callbacks + * @return void + */ + protected function fireBeforeCallbackArray($abstract, $parameters, array $callbacks) + { + foreach ($callbacks as $callback) { + $callback($abstract, $parameters, $this); + } + } + /** + * Fire all of the resolving callbacks. + * + * @param string $abstract + * @param mixed $object + * @return void + */ + protected function fireResolvingCallbacks($abstract, $object) + { + $this->fireCallbackArray($object, $this->globalResolvingCallbacks); + $this->fireCallbackArray($object, $this->getCallbacksForType($abstract, $object, $this->resolvingCallbacks)); + $this->fireAfterResolvingCallbacks($abstract, $object); + } + /** + * Fire all of the after resolving callbacks. + * + * @param string $abstract + * @param mixed $object + * @return void + */ + protected function fireAfterResolvingCallbacks($abstract, $object) + { + $this->fireCallbackArray($object, $this->globalAfterResolvingCallbacks); + $this->fireCallbackArray($object, $this->getCallbacksForType($abstract, $object, $this->afterResolvingCallbacks)); + } + /** + * Get all callbacks for a given type. + * + * @param string $abstract + * @param object $object + * @param array $callbacksPerType + * @return array + */ + protected function getCallbacksForType($abstract, $object, array $callbacksPerType) + { + $results = []; + foreach ($callbacksPerType as $type => $callbacks) { + if ($type === $abstract || $object instanceof $type) { + $results = \array_merge($results, $callbacks); + } + } + return $results; + } + /** + * Fire an array of callbacks with an object. + * + * @param mixed $object + * @param array $callbacks + * @return void + */ + protected function fireCallbackArray($object, array $callbacks) + { + foreach ($callbacks as $callback) { + $callback($object, $this); + } + } + /** + * Get the container's bindings. + * + * @return array + */ + public function getBindings() + { + return $this->bindings; + } + /** + * Get the alias for an abstract if available. + * + * @param string $abstract + * @return string + */ + public function getAlias($abstract) + { + return isset($this->aliases[$abstract]) ? $this->getAlias($this->aliases[$abstract]) : $abstract; + } + /** + * Get the extender callbacks for a given type. + * + * @param string $abstract + * @return array + */ + protected function getExtenders($abstract) + { + return $this->extenders[$this->getAlias($abstract)] ?? []; + } + /** + * Remove all of the extender callbacks for a given type. + * + * @param string $abstract + * @return void + */ + public function forgetExtenders($abstract) + { + unset($this->extenders[$this->getAlias($abstract)]); + } + /** + * Drop all of the stale instances and aliases. + * + * @param string $abstract + * @return void + */ + protected function dropStaleInstances($abstract) + { + unset($this->instances[$abstract], $this->aliases[$abstract]); + } + /** + * Remove a resolved instance from the instance cache. + * + * @param string $abstract + * @return void + */ + public function forgetInstance($abstract) + { + unset($this->instances[$abstract]); + } + /** + * Clear all of the instances from the container. + * + * @return void + */ + public function forgetInstances() + { + $this->instances = []; + } + /** + * Clear all of the scoped instances from the container. + * + * @return void + */ + public function forgetScopedInstances() + { + foreach ($this->scopedInstances as $scoped) { + unset($this->instances[$scoped]); + } + } + /** + * Flush the container of all bindings and resolved instances. + * + * @return void + */ + public function flush() + { + $this->aliases = []; + $this->resolved = []; + $this->bindings = []; + $this->instances = []; + $this->abstractAliases = []; + $this->scopedInstances = []; + } + /** + * Get the globally available instance of the container. + * + * @return static + */ + public static function getInstance() + { + if (\is_null(static::$instance)) { + static::$instance = new static(); + } + return static::$instance; + } + /** + * Set the shared instance of the container. + * + * @param \Illuminate\Contracts\Container\Container|null $container + * @return \Illuminate\Contracts\Container\Container|static + */ + public static function setInstance(ContainerContract $container = null) + { + return static::$instance = $container; + } + /** + * Determine if a given offset exists. + * + * @param string $key + * @return bool + */ + public function offsetExists($key) : bool + { + return $this->bound($key); + } + /** + * Get the value at a given offset. + * + * @param string $key + * @return mixed + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->make($key); + } + /** + * Set the value at a given offset. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function offsetSet($key, $value) : void + { + $this->bind($key, $value instanceof Closure ? $value : function () use($value) { + return $value; + }); + } + /** + * Unset the value at a given offset. + * + * @param string $key + * @return void + */ + public function offsetUnset($key) : void + { + unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]); + } + /** + * Dynamically access container services. + * + * @param string $key + * @return mixed + */ + public function __get($key) + { + return $this[$key]; + } + /** + * Dynamically set container services. + * + * @param string $key + * @param mixed $value + * @return void + */ + public function __set($key, $value) + { + $this[$key] = $value; + } +} diff --git a/vendor/illuminate/container/ContextualBindingBuilder.php b/vendor/illuminate/container/ContextualBindingBuilder.php new file mode 100644 index 00000000000..6c6a44551a6 --- /dev/null +++ b/vendor/illuminate/container/ContextualBindingBuilder.php @@ -0,0 +1,88 @@ +concrete = $concrete; + $this->container = $container; + } + /** + * Define the abstract target that depends on the context. + * + * @param string $abstract + * @return $this + */ + public function needs($abstract) + { + $this->needs = $abstract; + return $this; + } + /** + * Define the implementation for the contextual binding. + * + * @param \Closure|string|array $implementation + * @return void + */ + public function give($implementation) + { + foreach (Util::arrayWrap($this->concrete) as $concrete) { + $this->container->addContextualBinding($concrete, $this->needs, $implementation); + } + } + /** + * Define tagged services to be used as the implementation for the contextual binding. + * + * @param string $tag + * @return void + */ + public function giveTagged($tag) + { + $this->give(function ($container) use($tag) { + $taggedServices = $container->tagged($tag); + return \is_array($taggedServices) ? $taggedServices : \iterator_to_array($taggedServices); + }); + } + /** + * Specify the configuration item to bind as a primitive. + * + * @param string $key + * @param mixed $default + * @return void + */ + public function giveConfig($key, $default = null) + { + $this->give(function ($container) use($key, $default) { + return $container->get('config')->get($key, $default); + }); + } +} diff --git a/vendor/illuminate/container/EntryNotFoundException.php b/vendor/illuminate/container/EntryNotFoundException.php new file mode 100644 index 00000000000..7332e389e77 --- /dev/null +++ b/vendor/illuminate/container/EntryNotFoundException.php @@ -0,0 +1,10 @@ +count = $count; + $this->generator = $generator; + } + /** + * Get an iterator from the generator. + * + * @return \Traversable + */ + public function getIterator() : Traversable + { + return ($this->generator)(); + } + /** + * Get the total number of tagged services. + * + * @return int + */ + public function count() : int + { + if (\is_callable($count = $this->count)) { + $this->count = $count(); + } + return $this->count; + } +} diff --git a/vendor/illuminate/container/Util.php b/vendor/illuminate/container/Util.php new file mode 100644 index 00000000000..e7299137998 --- /dev/null +++ b/vendor/illuminate/container/Util.php @@ -0,0 +1,65 @@ +getType(); + if (!$type instanceof ReflectionNamedType || $type->isBuiltin()) { + return null; + } + $name = $type->getName(); + if (!\is_null($class = $parameter->getDeclaringClass())) { + if ($name === 'self') { + return $class->getName(); + } + if ($name === 'parent' && ($parent = $class->getParentClass())) { + return $parent->getName(); + } + } + return $name; + } +} diff --git a/vendor/illuminate/container/composer.json b/vendor/illuminate/container/composer.json new file mode 100644 index 00000000000..f33a35fbbc2 --- /dev/null +++ b/vendor/illuminate/container/composer.json @@ -0,0 +1,38 @@ +{ + "name": "illuminate\/container", + "description": "The Illuminate Container package.", + "license": "MIT", + "homepage": "https:\/\/laravel.com", + "support": { + "issues": "https:\/\/github.com\/laravel\/framework\/issues", + "source": "https:\/\/github.com\/laravel\/framework" + }, + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + } + ], + "require": { + "php": "^8.1", + "illuminate\/contracts": "^10.0", + "psr\/container": "^1.1.1|^2.0.1" + }, + "provide": { + "psr\/container-implementation": "1.1|2.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Illuminate\\Container\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-master": "10.x-dev" + } + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev" +} \ No newline at end of file diff --git a/vendor/illuminate/contracts/Auth/Access/Authorizable.php b/vendor/illuminate/contracts/Auth/Access/Authorizable.php new file mode 100644 index 00000000000..f219b944451 --- /dev/null +++ b/vendor/illuminate/contracts/Auth/Access/Authorizable.php @@ -0,0 +1,15 @@ +|CastsAttributes|CastsInboundAttributes + */ + public static function castUsing(array $arguments); +} diff --git a/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php b/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php new file mode 100644 index 00000000000..5b07ed770dd --- /dev/null +++ b/vendor/illuminate/contracts/Database/Eloquent/CastsAttributes.php @@ -0,0 +1,32 @@ + $attributes + * @return TGet|null + */ + public function get(Model $model, string $key, $value, array $attributes); + /** + * Transform the attribute to its underlying model values. + * + * @param \Illuminate\Database\Eloquent\Model $model + * @param string $key + * @param mixed $value + * @param array $attributes + * @return mixed + */ + public function set(Model $model, string $key, $value, array $attributes); +} diff --git a/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php b/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php new file mode 100644 index 00000000000..dad5d68f7f9 --- /dev/null +++ b/vendor/illuminate/contracts/Database/Eloquent/CastsInboundAttributes.php @@ -0,0 +1,18 @@ +id = $id; + $this->class = $class; + $this->relations = $relations; + $this->connection = $connection; + } + /** + * Specify the collection class that should be used when serializing / restoring collections. + * + * @param string|null $collectionClass + * @return $this + */ + public function useCollectionClass(?string $collectionClass) + { + $this->collectionClass = $collectionClass; + return $this; + } +} diff --git a/vendor/illuminate/contracts/Database/Query/Builder.php b/vendor/illuminate/contracts/Database/Query/Builder.php new file mode 100644 index 00000000000..0365d7a63cd --- /dev/null +++ b/vendor/illuminate/contracts/Database/Query/Builder.php @@ -0,0 +1,12 @@ + + */ + public function getQueueableIds(); + /** + * Get the relationships of the entities being queued. + * + * @return array + */ + public function getQueueableRelations(); + /** + * Get the connection of the entities being queued. + * + * @return string|null + */ + public function getQueueableConnection(); +} diff --git a/vendor/illuminate/contracts/Queue/QueueableEntity.php b/vendor/illuminate/contracts/Queue/QueueableEntity.php new file mode 100644 index 00000000000..bd19e3f9adc --- /dev/null +++ b/vendor/illuminate/contracts/Queue/QueueableEntity.php @@ -0,0 +1,25 @@ + + */ + public function toArray(); +} diff --git a/vendor/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php b/vendor/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php new file mode 100644 index 00000000000..61983b48ac6 --- /dev/null +++ b/vendor/illuminate/contracts/Support/CanBeEscapedWhenCastToString.php @@ -0,0 +1,14 @@ +=7.2 <8.3" + }, + "require-dev": { + "nette\/tester": "~2.0", + "tracy\/tracy": "^2.3", + "phpstan\/phpstan": "^1.0", + "jetbrains\/phpstorm-attributes": "dev-master" + }, + "conflict": { + "nette\/di": "<3.0.6" + }, + "suggest": { + "ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()", + "ext-json": "to use Nette\\Utils\\Json", + "ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()", + "ext-mbstring": "to use Strings::lower() etc...", + "ext-xml": "to use Strings::length() etc. when mbstring is not available", + "ext-gd": "to use Image", + "ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()" + }, + "autoload": { + "classmap": [ + "src\/" + ] + }, + "minimum-stability": "dev", + "scripts": { + "phpstan": "phpstan analyse", + "tester": "tester tests -s" + }, + "extra": { + "branch-alias": { + "dev-master": "3.2-dev" + } + } +} \ No newline at end of file diff --git a/vendor/nette/utils/license.md b/vendor/nette/utils/license.md new file mode 100644 index 00000000000..cf741bd05fb --- /dev/null +++ b/vendor/nette/utils/license.md @@ -0,0 +1,60 @@ +Licenses +======== + +Good news! You may use Nette Framework under the terms of either +the New BSD License or the GNU General Public License (GPL) version 2 or 3. + +The BSD License is recommended for most projects. It is easy to understand and it +places almost no restrictions on what you can do with the framework. If the GPL +fits better to your project, you can use the framework under this license. + +You don't have to notify anyone which license you are using. You can freely +use Nette Framework in commercial projects as long as the copyright header +remains intact. + +Please be advised that the name "Nette Framework" is a protected trademark and its +usage has some limitations. So please do not use word "Nette" in the name of your +project or top-level domain, and choose a name that stands on its own merits. +If your stuff is good, it will not take long to establish a reputation for yourselves. + + +New BSD License +--------------- + +Copyright (c) 2004, 2014 David Grudl (https://davidgrudl.com) +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + * Neither the name of "Nette Framework" nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as is" and +any express or implied warranties, including, but not limited to, the implied +warranties of merchantability and fitness for a particular purpose are +disclaimed. In no event shall the copyright owner or contributors be liable for +any direct, indirect, incidental, special, exemplary, or consequential damages +(including, but not limited to, procurement of substitute goods or services; +loss of use, data, or profits; or business interruption) however caused and on +any theory of liability, whether in contract, strict liability, or tort +(including negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + + +GNU General Public License +-------------------------- + +GPL licenses are very very long, so instead of including them here we offer +you URLs with full text: + +- [GPL version 2](http://www.gnu.org/licenses/gpl-2.0.html) +- [GPL version 3](http://www.gnu.org/licenses/gpl-3.0.html) diff --git a/vendor/nette/utils/readme.md b/vendor/nette/utils/readme.md new file mode 100644 index 00000000000..430cc735913 --- /dev/null +++ b/vendor/nette/utils/readme.md @@ -0,0 +1,54 @@ +Nette Utility Classes +===================== + +[![Downloads this Month](https://img.shields.io/packagist/dm/nette/utils.svg)](https://packagist.org/packages/nette/utils) +[![Tests](https://github.com/nette/utils/workflows/Tests/badge.svg?branch=master)](https://github.com/nette/utils/actions) +[![Coverage Status](https://coveralls.io/repos/github/nette/utils/badge.svg?branch=master)](https://coveralls.io/github/nette/utils?branch=master) +[![Latest Stable Version](https://poser.pugx.org/nette/utils/v/stable)](https://github.com/nette/utils/releases) +[![License](https://img.shields.io/badge/license-New%20BSD-blue.svg)](https://github.com/nette/utils/blob/master/license.md) + + +Introduction +------------ + +In package nette/utils you will find a set of [useful classes](https://doc.nette.org/utils) for everyday use: + +- [Arrays](https://doc.nette.org/utils/arrays) - manipulate arrays +- [Callback](https://doc.nette.org/utils/callback) - PHP callbacks +- [Date and Time](https://doc.nette.org/utils/datetime) - modify times and dates +- [Filesystem](https://doc.nette.org/utils/filesystem) - copying, renaming, … +- [Helper Functions](https://doc.nette.org/utils/helpers) +- [HTML elements](https://doc.nette.org/utils/html-elements) - generate HTML +- [Images](https://doc.nette.org/utils/images) - crop, resize, rotate images +- [JSON](https://doc.nette.org/utils/json) - encoding and decoding +- [Generating Random Strings](https://doc.nette.org/utils/random) +- [Paginator](https://doc.nette.org/utils/paginator) - pagination math +- [PHP Reflection](https://doc.nette.org/utils/reflection) +- [Strings](https://doc.nette.org/utils/strings) - useful text functions +- [SmartObject](https://doc.nette.org/utils/smartobject) - PHP object enhancements +- [Validation](https://doc.nette.org/utils/validators) - validate inputs +- [Type](https://doc.nette.org/utils/type) - PHP data type + + +Installation +------------ + +The recommended way to install is via Composer: + +``` +composer require nette/utils +``` + +- Nette Utils 3.2 is compatible with PHP 7.2 to 8.2 +- Nette Utils 3.1 is compatible with PHP 7.1 to 8.0 +- Nette Utils 3.0 is compatible with PHP 7.1 to 8.0 +- Nette Utils 2.5 is compatible with PHP 5.6 to 8.0 + +[Support Me](https://github.com/sponsors/dg) +-------------------------------------------- + +Do you like Nette Utils? Are you looking forward to the new features? + +[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg) + +Thank you! diff --git a/vendor/nette/utils/src/HtmlStringable.php b/vendor/nette/utils/src/HtmlStringable.php new file mode 100644 index 00000000000..1738d9d808a --- /dev/null +++ b/vendor/nette/utils/src/HtmlStringable.php @@ -0,0 +1,17 @@ +getIterator(); + } while ($iterator instanceof \IteratorAggregate); + \assert($iterator instanceof \Iterator); + } elseif ($iterator instanceof \Iterator) { + } elseif ($iterator instanceof \Traversable) { + $iterator = new \IteratorIterator($iterator); + } else { + throw new Nette\InvalidArgumentException(\sprintf('Invalid argument passed to %s; array or Traversable expected, %s given.', self::class, \is_object($iterator) ? \get_class($iterator) : \gettype($iterator))); + } + parent::__construct($iterator, 0); + } + /** + * Is the current element the first one? + */ + public function isFirst(?int $gridWidth = null) : bool + { + return $this->counter === 1 || $gridWidth && $this->counter !== 0 && ($this->counter - 1) % $gridWidth === 0; + } + /** + * Is the current element the last one? + */ + public function isLast(?int $gridWidth = null) : bool + { + return !$this->hasNext() || $gridWidth && $this->counter % $gridWidth === 0; + } + /** + * Is the iterator empty? + */ + public function isEmpty() : bool + { + return $this->counter === 0; + } + /** + * Is the counter odd? + */ + public function isOdd() : bool + { + return $this->counter % 2 === 1; + } + /** + * Is the counter even? + */ + public function isEven() : bool + { + return $this->counter % 2 === 0; + } + /** + * Returns the counter. + */ + public function getCounter() : int + { + return $this->counter; + } + /** + * Returns the count of elements. + */ + public function count() : int + { + $inner = $this->getInnerIterator(); + if ($inner instanceof \Countable) { + return $inner->count(); + } else { + throw new Nette\NotSupportedException('Iterator is not countable.'); + } + } + /** + * Forwards to the next element. + */ + public function next() : void + { + parent::next(); + if (parent::valid()) { + $this->counter++; + } + } + /** + * Rewinds the Iterator. + */ + public function rewind() : void + { + parent::rewind(); + $this->counter = parent::valid() ? 1 : 0; + } + /** + * Returns the next key. + * @return mixed + */ + public function getNextKey() + { + return $this->getInnerIterator()->key(); + } + /** + * Returns the next element. + * @return mixed + */ + public function getNextValue() + { + return $this->getInnerIterator()->current(); + } +} diff --git a/vendor/nette/utils/src/Iterators/Mapper.php b/vendor/nette/utils/src/Iterators/Mapper.php new file mode 100644 index 00000000000..c0a112707aa --- /dev/null +++ b/vendor/nette/utils/src/Iterators/Mapper.php @@ -0,0 +1,27 @@ +callback = $callback; + } + #[\ReturnTypeWillChange] + public function current() + { + return ($this->callback)(parent::current(), parent::key()); + } +} diff --git a/vendor/nette/utils/src/SmartObject.php b/vendor/nette/utils/src/SmartObject.php new file mode 100644 index 00000000000..528f4d439f8 --- /dev/null +++ b/vendor/nette/utils/src/SmartObject.php @@ -0,0 +1,120 @@ +{$name} ?? null; + if (\is_iterable($handlers)) { + foreach ($handlers as $handler) { + $handler(...$args); + } + } elseif ($handlers !== null) { + throw new UnexpectedValueException("Property {$class}::\${$name} must be iterable or null, " . \gettype($handlers) . ' given.'); + } + } else { + ObjectHelpers::strictCall($class, $name); + } + } + /** + * @throws MemberAccessException + */ + public static function __callStatic(string $name, array $args) + { + ObjectHelpers::strictStaticCall(static::class, $name); + } + /** + * @return mixed + * @throws MemberAccessException if the property is not defined. + */ + public function &__get(string $name) + { + $class = static::class; + if ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { + // property getter + if (!($prop & 0b1)) { + throw new MemberAccessException("Cannot read a write-only property {$class}::\${$name}."); + } + $m = ($prop & 0b10 ? 'get' : 'is') . \ucfirst($name); + if ($prop & 0b10000) { + $trace = \debug_backtrace(0, 1)[0]; + // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) ? " in {$trace['file']} on line {$trace['line']}" : ''; + \trigger_error("Property {$class}::\${$name} is deprecated, use {$class}::{$m}() method{$loc}.", \E_USER_DEPRECATED); + } + if ($prop & 0b100) { + // return by reference + return $this->{$m}(); + } else { + $val = $this->{$m}(); + return $val; + } + } else { + ObjectHelpers::strictGet($class, $name); + } + } + /** + * @param mixed $value + * @return void + * @throws MemberAccessException if the property is not defined or is read-only + */ + public function __set(string $name, $value) + { + $class = static::class; + if (ObjectHelpers::hasProperty($class, $name)) { + // unsetted property + $this->{$name} = $value; + } elseif ($prop = ObjectHelpers::getMagicProperties($class)[$name] ?? null) { + // property setter + if (!($prop & 0b1000)) { + throw new MemberAccessException("Cannot write to a read-only property {$class}::\${$name}."); + } + $m = 'set' . \ucfirst($name); + if ($prop & 0b10000) { + $trace = \debug_backtrace(0, 1)[0]; + // suppose this method is called from __call() + $loc = isset($trace['file'], $trace['line']) ? " in {$trace['file']} on line {$trace['line']}" : ''; + \trigger_error("Property {$class}::\${$name} is deprecated, use {$class}::{$m}() method{$loc}.", \E_USER_DEPRECATED); + } + $this->{$m}($value); + } else { + ObjectHelpers::strictSet($class, $name); + } + } + /** + * @return void + * @throws MemberAccessException + */ + public function __unset(string $name) + { + $class = static::class; + if (!ObjectHelpers::hasProperty($class, $name)) { + throw new MemberAccessException("Cannot unset the property {$class}::\${$name}."); + } + } + public function __isset(string $name) : bool + { + return isset(ObjectHelpers::getMagicProperties(static::class)[$name]); + } +} diff --git a/vendor/nette/utils/src/StaticClass.php b/vendor/nette/utils/src/StaticClass.php new file mode 100644 index 00000000000..c5a09f6e45a --- /dev/null +++ b/vendor/nette/utils/src/StaticClass.php @@ -0,0 +1,32 @@ + $array + * @return static + */ + public static function from(array $array, bool $recursive = \true) + { + $obj = new static(); + foreach ($array as $key => $value) { + $obj->{$key} = $recursive && \is_array($value) ? static::from($value, \true) : $value; + } + return $obj; + } + /** + * Returns an iterator over all items. + * @return \RecursiveArrayIterator + */ + public function getIterator() : \RecursiveArrayIterator + { + return new \RecursiveArrayIterator((array) $this); + } + /** + * Returns items count. + */ + public function count() : int + { + return \count((array) $this); + } + /** + * Replaces or appends a item. + * @param string|int $key + * @param T $value + */ + public function offsetSet($key, $value) : void + { + if (!\is_scalar($key)) { + // prevents null + throw new Nette\InvalidArgumentException(\sprintf('Key must be either a string or an integer, %s given.', \gettype($key))); + } + $this->{$key} = $value; + } + /** + * Returns a item. + * @param string|int $key + * @return T + */ + #[\ReturnTypeWillChange] + public function offsetGet($key) + { + return $this->{$key}; + } + /** + * Determines whether a item exists. + * @param string|int $key + */ + public function offsetExists($key) : bool + { + return isset($this->{$key}); + } + /** + * Removes the element from this list. + * @param string|int $key + */ + public function offsetUnset($key) : void + { + unset($this->{$key}); + } +} diff --git a/vendor/nette/utils/src/Utils/ArrayList.php b/vendor/nette/utils/src/Utils/ArrayList.php new file mode 100644 index 00000000000..504c6572c92 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ArrayList.php @@ -0,0 +1,109 @@ + $array + * @return static + */ + public static function from(array $array) + { + if (!Arrays::isList($array)) { + throw new Nette\InvalidArgumentException('Array is not valid list.'); + } + $obj = new static(); + $obj->list = $array; + return $obj; + } + /** + * Returns an iterator over all items. + * @return \ArrayIterator + */ + public function getIterator() : \ArrayIterator + { + return new \ArrayIterator($this->list); + } + /** + * Returns items count. + */ + public function count() : int + { + return \count($this->list); + } + /** + * Replaces or appends a item. + * @param int|null $index + * @param T $value + * @throws Nette\OutOfRangeException + */ + public function offsetSet($index, $value) : void + { + if ($index === null) { + $this->list[] = $value; + } elseif (!\is_int($index) || $index < 0 || $index >= \count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } else { + $this->list[$index] = $value; + } + } + /** + * Returns a item. + * @param int $index + * @return T + * @throws Nette\OutOfRangeException + */ + #[\ReturnTypeWillChange] + public function offsetGet($index) + { + if (!\is_int($index) || $index < 0 || $index >= \count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + return $this->list[$index]; + } + /** + * Determines whether a item exists. + * @param int $index + */ + public function offsetExists($index) : bool + { + return \is_int($index) && $index >= 0 && $index < \count($this->list); + } + /** + * Removes the element at the specified position in this list. + * @param int $index + * @throws Nette\OutOfRangeException + */ + public function offsetUnset($index) : void + { + if (!\is_int($index) || $index < 0 || $index >= \count($this->list)) { + throw new Nette\OutOfRangeException('Offset invalid or out of range'); + } + \array_splice($this->list, $index, 1); + } + /** + * Prepends a item. + * @param T $value + */ + public function prepend($value) : void + { + $first = \array_slice($this->list, 0, 1); + $this->offsetSet(0, $value); + \array_splice($this->list, 1, 0, $first); + } +} diff --git a/vendor/nette/utils/src/Utils/Arrays.php b/vendor/nette/utils/src/Utils/Arrays.php new file mode 100644 index 00000000000..9c63dfa929b --- /dev/null +++ b/vendor/nette/utils/src/Utils/Arrays.php @@ -0,0 +1,394 @@ + $array + * @param array-key|array-key[] $key + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function get(array $array, $key, $default = null) + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) && \array_key_exists($k, $array)) { + $array = $array[$k]; + } else { + if (\func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '{$k}'."); + } + return $default; + } + } + return $array; + } + /** + * Returns reference to array item. If the index does not exist, new one is created with value null. + * @template T + * @param array $array + * @param array-key|array-key[] $key + * @return ?T + * @throws Nette\InvalidArgumentException if traversed item is not an array + */ + public static function &getRef(array &$array, $key) + { + foreach (is_array($key) ? $key : [$key] as $k) { + if (is_array($array) || $array === null) { + $array =& $array[$k]; + } else { + throw new Nette\InvalidArgumentException('Traversed item is not an array.'); + } + } + return $array; + } + /** + * Recursively merges two fields. It is useful, for example, for merging tree structures. It behaves as + * the + operator for array, ie. it adds a key/value pair from the second array to the first one and retains + * the value from the first array in the case of a key collision. + * @template T1 + * @template T2 + * @param array $array1 + * @param array $array2 + * @return array + */ + public static function mergeTree(array $array1, array $array2) : array + { + $res = $array1 + $array2; + foreach (\array_intersect_key($array1, $array2) as $k => $v) { + if (is_array($v) && is_array($array2[$k])) { + $res[$k] = self::mergeTree($v, $array2[$k]); + } + } + return $res; + } + /** + * Returns zero-indexed position of given array key. Returns null if key is not found. + * @param array-key $key + * @return int|null offset if it is found, null otherwise + */ + public static function getKeyOffset(array $array, $key) : ?int + { + return Helpers::falseToNull(\array_search(self::toKey($key), \array_keys($array), \true)); + } + /** + * @deprecated use getKeyOffset() + */ + public static function searchKey(array $array, $key) : ?int + { + return self::getKeyOffset($array, $key); + } + /** + * Tests an array for the presence of value. + * @param mixed $value + */ + public static function contains(array $array, $value) : bool + { + return \in_array($value, $array, \true); + } + /** + * Returns the first item from the array or null if array is empty. + * @template T + * @param array $array + * @return ?T + */ + public static function first(array $array) + { + return count($array) ? \reset($array) : null; + } + /** + * Returns the last item from the array or null if array is empty. + * @template T + * @param array $array + * @return ?T + */ + public static function last(array $array) + { + return count($array) ? \end($array) : null; + } + /** + * Inserts the contents of the $inserted array into the $array immediately after the $key. + * If $key is null (or does not exist), it is inserted at the beginning. + * @param array-key|null $key + */ + public static function insertBefore(array &$array, $key, array $inserted) : void + { + $offset = $key === null ? 0 : (int) self::getKeyOffset($array, $key); + $array = \array_slice($array, 0, $offset, \true) + $inserted + \array_slice($array, $offset, count($array), \true); + } + /** + * Inserts the contents of the $inserted array into the $array before the $key. + * If $key is null (or does not exist), it is inserted at the end. + * @param array-key|null $key + */ + public static function insertAfter(array &$array, $key, array $inserted) : void + { + if ($key === null || ($offset = self::getKeyOffset($array, $key)) === null) { + $offset = count($array) - 1; + } + $array = \array_slice($array, 0, $offset + 1, \true) + $inserted + \array_slice($array, $offset + 1, count($array), \true); + } + /** + * Renames key in array. + * @param array-key $oldKey + * @param array-key $newKey + */ + public static function renameKey(array &$array, $oldKey, $newKey) : bool + { + $offset = self::getKeyOffset($array, $oldKey); + if ($offset === null) { + return \false; + } + $val =& $array[$oldKey]; + $keys = \array_keys($array); + $keys[$offset] = $newKey; + $array = \array_combine($keys, $array); + $array[$newKey] =& $val; + return \true; + } + /** + * Returns only those array items, which matches a regular expression $pattern. + * @param string[] $array + * @return string[] + */ + public static function grep( + array $array, + /** + * @language + */ + string $pattern, + int $flags = 0 + ) : array + { + return Strings::pcre('preg_grep', [$pattern, $array, $flags]); + } + /** + * Transforms multidimensional array to flat array. + */ + public static function flatten(array $array, bool $preserveKeys = \false) : array + { + $res = []; + $cb = $preserveKeys ? function ($v, $k) use(&$res) : void { + $res[$k] = $v; + } : function ($v) use(&$res) : void { + $res[] = $v; + }; + \array_walk_recursive($array, $cb); + return $res; + } + /** + * Checks if the array is indexed in ascending order of numeric keys from zero, a.k.a list. + * @param mixed $value + */ + public static function isList($value) : bool + { + $arrayIsList = function (array $array) : bool { + if (\function_exists('array_is_list')) { + return \array_is_list($array); + } + if ($array === []) { + return \true; + } + $current_key = 0; + foreach ($array as $key => $noop) { + if ($key !== $current_key) { + return \false; + } + ++$current_key; + } + return \true; + }; + return is_array($value) && (\PHP_VERSION_ID < 80100 ? !$value || \array_keys($value) === \range(0, count($value) - 1) : $arrayIsList($value)); + } + /** + * Reformats table to associative tree. Path looks like 'field|field[]field->field=field'. + * @param string|string[] $path + * @return array|\stdClass + */ + public static function associate(array $array, $path) + { + $parts = is_array($path) ? $path : \preg_split('#(\\[\\]|->|=|\\|)#', $path, -1, \PREG_SPLIT_DELIM_CAPTURE | \PREG_SPLIT_NO_EMPTY); + if (!$parts || $parts === ['->'] || $parts[0] === '=' || $parts[0] === '|') { + throw new Nette\InvalidArgumentException("Invalid path '{$path}'."); + } + $res = $parts[0] === '->' ? new \stdClass() : []; + foreach ($array as $rowOrig) { + $row = (array) $rowOrig; + $x =& $res; + for ($i = 0; $i < count($parts); $i++) { + $part = $parts[$i]; + if ($part === '[]') { + $x =& $x[]; + } elseif ($part === '=') { + if (isset($parts[++$i])) { + $x = $row[$parts[$i]]; + $row = null; + } + } elseif ($part === '->') { + if (isset($parts[++$i])) { + if ($x === null) { + $x = new \stdClass(); + } + $x =& $x->{$row[$parts[$i]]}; + } else { + $row = is_object($rowOrig) ? $rowOrig : (object) $row; + } + } elseif ($part !== '|') { + $x =& $x[(string) $row[$part]]; + } + } + if ($x === null) { + $x = $row; + } + } + return $res; + } + /** + * Normalizes array to associative array. Replace numeric keys with their values, the new value will be $filling. + * @param mixed $filling + */ + public static function normalize(array $array, $filling = null) : array + { + $res = []; + foreach ($array as $k => $v) { + $res[is_int($k) ? $v : $k] = is_int($k) ? $filling : $v; + } + return $res; + } + /** + * Returns and removes the value of an item from an array. If it does not exist, it throws an exception, + * or returns $default, if provided. + * @template T + * @param array $array + * @param array-key $key + * @param ?T $default + * @return ?T + * @throws Nette\InvalidArgumentException if item does not exist and default value is not provided + */ + public static function pick(array &$array, $key, $default = null) + { + if (\array_key_exists($key, $array)) { + $value = $array[$key]; + unset($array[$key]); + return $value; + } elseif (\func_num_args() < 3) { + throw new Nette\InvalidArgumentException("Missing item '{$key}'."); + } else { + return $default; + } + } + /** + * Tests whether at least one element in the array passes the test implemented by the + * provided callback with signature `function ($value, $key, array $array): bool`. + */ + public static function some(iterable $array, callable $callback) : bool + { + foreach ($array as $k => $v) { + if ($callback($v, $k, $array)) { + return \true; + } + } + return \false; + } + /** + * Tests whether all elements in the array pass the test implemented by the provided function, + * which has the signature `function ($value, $key, array $array): bool`. + */ + public static function every(iterable $array, callable $callback) : bool + { + foreach ($array as $k => $v) { + if (!$callback($v, $k, $array)) { + return \false; + } + } + return \true; + } + /** + * Calls $callback on all elements in the array and returns the array of return values. + * The callback has the signature `function ($value, $key, array $array): bool`. + */ + public static function map(iterable $array, callable $callback) : array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $callback($v, $k, $array); + } + return $res; + } + /** + * Invokes all callbacks and returns array of results. + * @param callable[] $callbacks + */ + public static function invoke(iterable $callbacks, ...$args) : array + { + $res = []; + foreach ($callbacks as $k => $cb) { + $res[$k] = $cb(...$args); + } + return $res; + } + /** + * Invokes method on every object in an array and returns array of results. + * @param object[] $objects + */ + public static function invokeMethod(iterable $objects, string $method, ...$args) : array + { + $res = []; + foreach ($objects as $k => $obj) { + $res[$k] = $obj->{$method}(...$args); + } + return $res; + } + /** + * Copies the elements of the $array array to the $object object and then returns it. + * @template T of object + * @param T $object + * @return T + */ + public static function toObject(iterable $array, $object) + { + foreach ($array as $k => $v) { + $object->{$k} = $v; + } + return $object; + } + /** + * Converts value to array key. + * @param mixed $value + * @return array-key + */ + public static function toKey($value) + { + return \key([$value => null]); + } + /** + * Returns copy of the $array where every item is converted to string + * and prefixed by $prefix and suffixed by $suffix. + * @param string[] $array + * @return string[] + */ + public static function wrap(array $array, string $prefix = '', string $suffix = '') : array + { + $res = []; + foreach ($array as $k => $v) { + $res[$k] = $prefix . $v . $suffix; + } + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Callback.php b/vendor/nette/utils/src/Utils/Callback.php new file mode 100644 index 00000000000..798c03073c4 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Callback.php @@ -0,0 +1,150 @@ +getMessage()); + } + } + /** + * Invokes callback. + * @return mixed + * @deprecated + */ + public static function invoke($callable, ...$args) + { + \trigger_error(__METHOD__ . '() is deprecated, use native invoking.', \E_USER_DEPRECATED); + self::check($callable); + return $callable(...$args); + } + /** + * Invokes callback with an array of parameters. + * @return mixed + * @deprecated + */ + public static function invokeArgs($callable, array $args = []) + { + \trigger_error(__METHOD__ . '() is deprecated, use native invoking.', \E_USER_DEPRECATED); + self::check($callable); + return $callable(...$args); + } + /** + * Invokes internal PHP function with own error handler. + * @return mixed + */ + public static function invokeSafe(string $function, array $args, callable $onError) + { + $prev = \set_error_handler(function ($severity, $message, $file) use($onError, &$prev, $function) : ?bool { + if ($file === __FILE__) { + $msg = \ini_get('html_errors') ? Html::htmlToText($message) : $message; + $msg = \preg_replace("#^{$function}\\(.*?\\): #", '', $msg); + if ($onError($msg, $severity) !== \false) { + return null; + } + } + return $prev ? $prev(...\func_get_args()) : \false; + }); + try { + return $function(...$args); + } finally { + \restore_error_handler(); + } + } + /** + * Checks that $callable is valid PHP callback. Otherwise throws exception. If the $syntax is set to true, only verifies + * that $callable has a valid structure to be used as a callback, but does not verify if the class or method actually exists. + * @param mixed $callable + * @return callable + * @throws Nette\InvalidArgumentException + */ + public static function check($callable, bool $syntax = \false) + { + if (!\is_callable($callable, $syntax)) { + throw new Nette\InvalidArgumentException($syntax ? 'Given value is not a callable type.' : \sprintf("Callback '%s' is not callable.", self::toString($callable))); + } + return $callable; + } + /** + * Converts PHP callback to textual form. Class or method may not exists. + * @param mixed $callable + */ + public static function toString($callable) : string + { + if ($callable instanceof \Closure) { + $inner = self::unwrap($callable); + return '{closure' . ($inner instanceof \Closure ? '}' : ' ' . self::toString($inner) . '}'); + } elseif (is_string($callable) && $callable[0] === "\x00") { + return '{lambda}'; + } else { + \is_callable(is_object($callable) ? [$callable, '__invoke'] : $callable, \true, $textual); + return $textual; + } + } + /** + * Returns reflection for method or function used in PHP callback. + * @param callable $callable type check is escalated to ReflectionException + * @return \ReflectionMethod|\ReflectionFunction + * @throws \ReflectionException if callback is not valid + */ + public static function toReflection($callable) : \ReflectionFunctionAbstract + { + if ($callable instanceof \Closure) { + $callable = self::unwrap($callable); + } + if (is_string($callable) && \strpos($callable, '::')) { + return new \ReflectionMethod($callable); + } elseif (is_array($callable)) { + return new \ReflectionMethod($callable[0], $callable[1]); + } elseif (is_object($callable) && !$callable instanceof \Closure) { + return new \ReflectionMethod($callable, '__invoke'); + } else { + return new \ReflectionFunction($callable); + } + } + /** + * Checks whether PHP callback is function or static method. + */ + public static function isStatic(callable $callable) : bool + { + return is_string(is_array($callable) ? $callable[0] : $callable); + } + /** + * Unwraps closure created by Closure::fromCallable(). + * @return callable|array + */ + public static function unwrap(\Closure $closure) + { + $r = new \ReflectionFunction($closure); + if (\substr($r->name, -1) === '}') { + return $closure; + } elseif ($obj = $r->getClosureThis()) { + return [$obj, $r->name]; + } elseif ($class = $r->getClosureScopeClass()) { + return [$class->name, $r->name]; + } else { + return $r->name; + } + } +} diff --git a/vendor/nette/utils/src/Utils/DateTime.php b/vendor/nette/utils/src/Utils/DateTime.php new file mode 100644 index 00000000000..6dee7710e48 --- /dev/null +++ b/vendor/nette/utils/src/Utils/DateTime.php @@ -0,0 +1,105 @@ +format('Y-m-d H:i:s.u'), $time->getTimezone()); + } elseif (\is_numeric($time)) { + if ($time <= self::YEAR) { + $time += \time(); + } + return (new static('@' . $time))->setTimezone(new \DateTimeZone(\date_default_timezone_get())); + } else { + // textual or null + return new static((string) $time); + } + } + /** + * Creates DateTime object. + * @return static + * @throws Nette\InvalidArgumentException if the date and time are not valid. + */ + public static function fromParts(int $year, int $month, int $day, int $hour = 0, int $minute = 0, float $second = 0.0) + { + $s = \sprintf('%04d-%02d-%02d %02d:%02d:%02.5F', $year, $month, $day, $hour, $minute, $second); + if (!\checkdate($month, $day, $year) || $hour < 0 || $hour > 23 || $minute < 0 || $minute > 59 || $second < 0 || $second >= 60) { + throw new Nette\InvalidArgumentException("Invalid date '{$s}'"); + } + return new static($s); + } + /** + * Returns new DateTime object formatted according to the specified format. + * @param string $format The format the $time parameter should be in + * @param string $time + * @param string|\DateTimeZone $timezone (default timezone is used if null is passed) + * @return static|false + */ + #[\ReturnTypeWillChange] + public static function createFromFormat($format, $time, $timezone = null) + { + if ($timezone === null) { + $timezone = new \DateTimeZone(\date_default_timezone_get()); + } elseif (\is_string($timezone)) { + $timezone = new \DateTimeZone($timezone); + } elseif (!$timezone instanceof \DateTimeZone) { + throw new Nette\InvalidArgumentException('Invalid timezone given'); + } + $date = parent::createFromFormat($format, $time, $timezone); + return $date ? static::from($date) : \false; + } + /** + * Returns JSON representation in ISO 8601 (used by JavaScript). + */ + public function jsonSerialize() : string + { + return $this->format('c'); + } + /** + * Returns the date and time in the format 'Y-m-d H:i:s'. + */ + public function __toString() : string + { + return $this->format('Y-m-d H:i:s'); + } + /** + * Creates a copy with a modified time. + * @return static + */ + public function modifyClone(string $modify = '') + { + $dolly = clone $this; + return $modify ? $dolly->modify($modify) : $dolly; + } +} diff --git a/vendor/nette/utils/src/Utils/FileSystem.php b/vendor/nette/utils/src/Utils/FileSystem.php new file mode 100644 index 00000000000..298a6a75843 --- /dev/null +++ b/vendor/nette/utils/src/Utils/FileSystem.php @@ -0,0 +1,185 @@ +getPathname()); + } + foreach ($iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($origin, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $item) { + if ($item->isDir()) { + static::createDir($target . '/' . $iterator->getSubPathName()); + } else { + static::copy($item->getPathname(), $target . '/' . $iterator->getSubPathName()); + } + } + } else { + static::createDir(\dirname($target)); + if (($s = @\fopen($origin, 'rb')) && ($d = @\fopen($target, 'wb')) && @\stream_copy_to_stream($s, $d) === \false) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to copy file '%s' to '%s'. %s", self::normalizePath($origin), self::normalizePath($target), Helpers::getLastError())); + } + } + } + /** + * Deletes a file or directory if exists. + * @throws Nette\IOException on error occurred + */ + public static function delete(string $path) : void + { + if (\is_file($path) || \is_link($path)) { + $func = \DIRECTORY_SEPARATOR === '\\' && \is_dir($path) ? 'rmdir' : 'unlink'; + if (!@$func($path)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to delete '%s'. %s", self::normalizePath($path), Helpers::getLastError())); + } + } elseif (\is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + static::delete($item->getPathname()); + } + if (!@\rmdir($path)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to delete directory '%s'. %s", self::normalizePath($path), Helpers::getLastError())); + } + } + } + /** + * Renames or moves a file or a directory. Overwrites existing files and directories by default. + * @throws Nette\IOException on error occurred + * @throws Nette\InvalidStateException if $overwrite is set to false and destination already exists + */ + public static function rename(string $origin, string $target, bool $overwrite = \true) : void + { + if (!$overwrite && \file_exists($target)) { + throw new Nette\InvalidStateException(\sprintf("File or directory '%s' already exists.", self::normalizePath($target))); + } elseif (!\file_exists($origin)) { + throw new Nette\IOException(\sprintf("File or directory '%s' not found.", self::normalizePath($origin))); + } else { + static::createDir(\dirname($target)); + if (\realpath($origin) !== \realpath($target)) { + static::delete($target); + } + if (!@\rename($origin, $target)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to rename file or directory '%s' to '%s'. %s", self::normalizePath($origin), self::normalizePath($target), Helpers::getLastError())); + } + } + } + /** + * Reads the content of a file. + * @throws Nette\IOException on error occurred + */ + public static function read(string $file) : string + { + $content = @\file_get_contents($file); + // @ is escalated to exception + if ($content === \false) { + throw new Nette\IOException(\sprintf("Unable to read file '%s'. %s", self::normalizePath($file), Helpers::getLastError())); + } + return $content; + } + /** + * Writes the string to a file. + * @throws Nette\IOException on error occurred + */ + public static function write(string $file, string $content, ?int $mode = 0666) : void + { + static::createDir(\dirname($file)); + if (@\file_put_contents($file, $content) === \false) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to write file '%s'. %s", self::normalizePath($file), Helpers::getLastError())); + } + if ($mode !== null && !@\chmod($file, $mode)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to chmod file '%s' to mode %s. %s", self::normalizePath($file), \decoct($mode), Helpers::getLastError())); + } + } + /** + * Fixes permissions to a specific file or directory. Directories can be fixed recursively. + * @throws Nette\IOException on error occurred + */ + public static function makeWritable(string $path, int $dirMode = 0777, int $fileMode = 0666) : void + { + if (\is_file($path)) { + if (!@\chmod($path, $fileMode)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to chmod file '%s' to mode %s. %s", self::normalizePath($path), \decoct($fileMode), Helpers::getLastError())); + } + } elseif (\is_dir($path)) { + foreach (new \FilesystemIterator($path) as $item) { + static::makeWritable($item->getPathname(), $dirMode, $fileMode); + } + if (!@\chmod($path, $dirMode)) { + // @ is escalated to exception + throw new Nette\IOException(\sprintf("Unable to chmod directory '%s' to mode %s. %s", self::normalizePath($path), \decoct($dirMode), Helpers::getLastError())); + } + } else { + throw new Nette\IOException(\sprintf("File or directory '%s' not found.", self::normalizePath($path))); + } + } + /** + * Determines if the path is absolute. + */ + public static function isAbsolute(string $path) : bool + { + return (bool) \preg_match('#([a-z]:)?[/\\\\]|[a-z][a-z0-9+.-]*://#Ai', $path); + } + /** + * Normalizes `..` and `.` and directory separators in path. + */ + public static function normalizePath(string $path) : string + { + $parts = $path === '' ? [] : \preg_split('~[/\\\\]+~', $path); + $res = []; + foreach ($parts as $part) { + if ($part === '..' && $res && \end($res) !== '..' && \end($res) !== '') { + \array_pop($res); + } elseif ($part !== '.') { + $res[] = $part; + } + } + return $res === [''] ? \DIRECTORY_SEPARATOR : \implode(\DIRECTORY_SEPARATOR, $res); + } + /** + * Joins all segments of the path and normalizes the result. + */ + public static function joinPaths(string ...$paths) : string + { + return self::normalizePath(\implode('/', $paths)); + } +} diff --git a/vendor/nette/utils/src/Utils/Floats.php b/vendor/nette/utils/src/Utils/Floats.php new file mode 100644 index 00000000000..fb9069812aa --- /dev/null +++ b/vendor/nette/utils/src/Utils/Floats.php @@ -0,0 +1,83 @@ + $b it returns 1 + * @throws \LogicException if one of parameters is NAN + */ + public static function compare(float $a, float $b) : int + { + if (\is_nan($a) || \is_nan($b)) { + throw new \LogicException('Trying to compare NAN'); + } elseif (!\is_finite($a) && !\is_finite($b) && $a === $b) { + return 0; + } + $diff = \abs($a - $b); + if ($diff < self::Epsilon || $diff / \max(\abs($a), \abs($b)) < self::Epsilon) { + return 0; + } + return $a < $b ? -1 : 1; + } + /** + * Returns true if $a = $b + * @throws \LogicException if one of parameters is NAN + */ + public static function areEqual(float $a, float $b) : bool + { + return self::compare($a, $b) === 0; + } + /** + * Returns true if $a < $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThan(float $a, float $b) : bool + { + return self::compare($a, $b) < 0; + } + /** + * Returns true if $a <= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isLessThanOrEqualTo(float $a, float $b) : bool + { + return self::compare($a, $b) <= 0; + } + /** + * Returns true if $a > $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThan(float $a, float $b) : bool + { + return self::compare($a, $b) > 0; + } + /** + * Returns true if $a >= $b + * @throws \LogicException if one of parameters is NAN + */ + public static function isGreaterThanOrEqualTo(float $a, float $b) : bool + { + return self::compare($a, $b) >= 0; + } +} diff --git a/vendor/nette/utils/src/Utils/Helpers.php b/vendor/nette/utils/src/Utils/Helpers.php new file mode 100644 index 00000000000..b5a1d1c8fc9 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Helpers.php @@ -0,0 +1,78 @@ + $max) { + throw new Nette\InvalidArgumentException("Minimum ({$min}) is not less than maximum ({$max})."); + } + return \min(\max($value, $min), $max); + } + /** + * Looks for a string from possibilities that is most similar to value, but not the same (for 8-bit encoding). + * @param string[] $possibilities + */ + public static function getSuggestion(array $possibilities, string $value) : ?string + { + $best = null; + $min = (\strlen($value) / 4 + 1) * 10 + 0.1; + foreach (\array_unique($possibilities) as $item) { + if ($item !== $value && ($len = \levenshtein($item, $value, 10, 11, 10)) < $min) { + $min = $len; + $best = $item; + } + } + return $best; + } +} diff --git a/vendor/nette/utils/src/Utils/Html.php b/vendor/nette/utils/src/Utils/Html.php new file mode 100644 index 00000000000..348380d772f --- /dev/null +++ b/vendor/nette/utils/src/Utils/Html.php @@ -0,0 +1,744 @@ + element's attributes */ + public $attrs = []; + /** @var bool use XHTML syntax? */ + public static $xhtml = \false; + /** @var array void elements */ + public static $emptyElements = ['img' => 1, 'hr' => 1, 'br' => 1, 'input' => 1, 'meta' => 1, 'area' => 1, 'embed' => 1, 'keygen' => 1, 'source' => 1, 'base' => 1, 'col' => 1, 'link' => 1, 'param' => 1, 'basefont' => 1, 'frame' => 1, 'isindex' => 1, 'wbr' => 1, 'command' => 1, 'track' => 1]; + /** @var array nodes */ + protected $children = []; + /** @var string element's name */ + private $name; + /** @var bool is element empty? */ + private $isEmpty; + /** + * Constructs new HTML element. + * @param array|string $attrs element's attributes or plain text content + * @return static + */ + public static function el(?string $name = null, $attrs = null) + { + $el = new static(); + $parts = \explode(' ', (string) $name, 2); + $el->setName($parts[0]); + if (is_array($attrs)) { + $el->attrs = $attrs; + } elseif ($attrs !== null) { + $el->setText($attrs); + } + if (isset($parts[1])) { + foreach (Strings::matchAll($parts[1] . ' ', '#([a-z0-9:-]+)(?:=(["\'])?(.*?)(?(2)\\2|\\s))?#i') as $m) { + $el->attrs[$m[1]] = $m[3] ?? \true; + } + } + return $el; + } + /** + * Returns an object representing HTML text. + */ + public static function fromHtml(string $html) : self + { + return (new static())->setHtml($html); + } + /** + * Returns an object representing plain text. + */ + public static function fromText(string $text) : self + { + return (new static())->setText($text); + } + /** + * Converts to HTML. + */ + public final function toHtml() : string + { + return $this->render(); + } + /** + * Converts to plain text. + */ + public final function toText() : string + { + return $this->getText(); + } + /** + * Converts given HTML code to plain text. + */ + public static function htmlToText(string $html) : string + { + return \html_entity_decode(\strip_tags($html), \ENT_QUOTES | \ENT_HTML5, 'UTF-8'); + } + /** + * Changes element's name. + * @return static + */ + public final function setName(string $name, ?bool $isEmpty = null) + { + $this->name = $name; + $this->isEmpty = $isEmpty ?? isset(static::$emptyElements[$name]); + return $this; + } + /** + * Returns element's name. + */ + public final function getName() : string + { + return $this->name; + } + /** + * Is element empty? + */ + public final function isEmpty() : bool + { + return $this->isEmpty; + } + /** + * Sets multiple attributes. + * @return static + */ + public function addAttributes(array $attrs) + { + $this->attrs = \array_merge($this->attrs, $attrs); + return $this; + } + /** + * Appends value to element's attribute. + * @param mixed $value + * @param mixed $option + * @return static + */ + public function appendAttribute(string $name, $value, $option = \true) + { + if (is_array($value)) { + $prev = isset($this->attrs[$name]) ? (array) $this->attrs[$name] : []; + $this->attrs[$name] = $value + $prev; + } elseif ((string) $value === '') { + $tmp =& $this->attrs[$name]; + // appending empty value? -> ignore, but ensure it exists + } elseif (!isset($this->attrs[$name]) || is_array($this->attrs[$name])) { + // needs array + $this->attrs[$name][$value] = $option; + } else { + $this->attrs[$name] = [$this->attrs[$name] => \true, $value => $option]; + } + return $this; + } + /** + * Sets element's attribute. + * @param mixed $value + * @return static + */ + public function setAttribute(string $name, $value) + { + $this->attrs[$name] = $value; + return $this; + } + /** + * Returns element's attribute. + * @return mixed + */ + public function getAttribute(string $name) + { + return $this->attrs[$name] ?? null; + } + /** + * Unsets element's attribute. + * @return static + */ + public function removeAttribute(string $name) + { + unset($this->attrs[$name]); + return $this; + } + /** + * Unsets element's attributes. + * @return static + */ + public function removeAttributes(array $attributes) + { + foreach ($attributes as $name) { + unset($this->attrs[$name]); + } + return $this; + } + /** + * Overloaded setter for element's attribute. + * @param mixed $value + */ + public final function __set(string $name, $value) : void + { + $this->attrs[$name] = $value; + } + /** + * Overloaded getter for element's attribute. + * @return mixed + */ + public final function &__get(string $name) + { + return $this->attrs[$name]; + } + /** + * Overloaded tester for element's attribute. + */ + public final function __isset(string $name) : bool + { + return isset($this->attrs[$name]); + } + /** + * Overloaded unsetter for element's attribute. + */ + public final function __unset(string $name) : void + { + unset($this->attrs[$name]); + } + /** + * Overloaded setter for element's attribute. + * @return mixed + */ + public final function __call(string $m, array $args) + { + $p = \substr($m, 0, 3); + if ($p === 'get' || $p === 'set' || $p === 'add') { + $m = \substr($m, 3); + $m[0] = $m[0] | " "; + if ($p === 'get') { + return $this->attrs[$m] ?? null; + } elseif ($p === 'add') { + $args[] = \true; + } + } + if (\count($args) === 0) { + // invalid + } elseif (\count($args) === 1) { + // set + $this->attrs[$m] = $args[0]; + } else { + // add + $this->appendAttribute($m, $args[0], $args[1]); + } + return $this; + } + /** + * Special setter for element's attribute. + * @return static + */ + public final function href(string $path, ?array $query = null) + { + if ($query) { + $query = \http_build_query($query, '', '&'); + if ($query !== '') { + $path .= '?' . $query; + } + } + $this->attrs['href'] = $path; + return $this; + } + /** + * Setter for data-* attributes. Booleans are converted to 'true' resp. 'false'. + * @param mixed $value + * @return static + */ + public function data(string $name, $value = null) + { + if (\func_num_args() === 1) { + $this->attrs['data'] = $name; + } else { + $this->attrs["data-{$name}"] = \is_bool($value) ? \json_encode($value) : $value; + } + return $this; + } + /** + * Sets element's HTML content. + * @param HtmlStringable|string $html + * @return static + */ + public final function setHtml($html) + { + $this->children = [(string) $html]; + return $this; + } + /** + * Returns element's HTML content. + */ + public final function getHtml() : string + { + return \implode('', $this->children); + } + /** + * Sets element's textual content. + * @param HtmlStringable|string|int|float $text + * @return static + */ + public final function setText($text) + { + if (!$text instanceof HtmlStringable) { + $text = \htmlspecialchars((string) $text, \ENT_NOQUOTES, 'UTF-8'); + } + $this->children = [(string) $text]; + return $this; + } + /** + * Returns element's textual content. + */ + public final function getText() : string + { + return self::htmlToText($this->getHtml()); + } + /** + * Adds new element's child. + * @param HtmlStringable|string $child Html node or raw HTML string + * @return static + */ + public final function addHtml($child) + { + return $this->insert(null, $child); + } + /** + * Appends plain-text string to element content. + * @param HtmlStringable|string|int|float $text + * @return static + */ + public function addText($text) + { + if (!$text instanceof HtmlStringable) { + $text = \htmlspecialchars((string) $text, \ENT_NOQUOTES, 'UTF-8'); + } + return $this->insert(null, $text); + } + /** + * Creates and adds a new Html child. + * @param array|string $attrs element's attributes or raw HTML string + * @return static created element + */ + public final function create(string $name, $attrs = null) + { + $this->insert(null, $child = static::el($name, $attrs)); + return $child; + } + /** + * Inserts child node. + * @param HtmlStringable|string $child Html node or raw HTML string + * @return static + */ + public function insert(?int $index, $child, bool $replace = \false) + { + $child = $child instanceof self ? $child : (string) $child; + if ($index === null) { + // append + $this->children[] = $child; + } else { + // insert or replace + \array_splice($this->children, $index, $replace ? 1 : 0, [$child]); + } + return $this; + } + /** + * Inserts (replaces) child node (\ArrayAccess implementation). + * @param int|null $index position or null for appending + * @param Html|string $child Html node or raw HTML string + */ + public final function offsetSet($index, $child) : void + { + $this->insert($index, $child, \true); + } + /** + * Returns child node (\ArrayAccess implementation). + * @param int $index + * @return HtmlStringable|string + */ + #[\ReturnTypeWillChange] + public final function offsetGet($index) + { + return $this->children[$index]; + } + /** + * Exists child node? (\ArrayAccess implementation). + * @param int $index + */ + public final function offsetExists($index) : bool + { + return isset($this->children[$index]); + } + /** + * Removes child node (\ArrayAccess implementation). + * @param int $index + */ + public function offsetUnset($index) : void + { + if (isset($this->children[$index])) { + \array_splice($this->children, $index, 1); + } + } + /** + * Returns children count. + */ + public final function count() : int + { + return \count($this->children); + } + /** + * Removes all children. + */ + public function removeChildren() : void + { + $this->children = []; + } + /** + * Iterates over elements. + * @return \ArrayIterator + */ + public final function getIterator() : \ArrayIterator + { + return new \ArrayIterator($this->children); + } + /** + * Returns all children. + */ + public final function getChildren() : array + { + return $this->children; + } + /** + * Renders element's start tag, content and end tag. + */ + public final function render(?int $indent = null) : string + { + $s = $this->startTag(); + if (!$this->isEmpty) { + // add content + if ($indent !== null) { + $indent++; + } + foreach ($this->children as $child) { + if ($child instanceof self) { + $s .= $child->render($indent); + } else { + $s .= $child; + } + } + // add end tag + $s .= $this->endTag(); + } + if ($indent !== null) { + return "\n" . \str_repeat("\t", $indent - 1) . $s . "\n" . \str_repeat("\t", \max(0, $indent - 2)); + } + return $s; + } + public final function __toString() : string + { + try { + return $this->render(); + } catch (\Throwable $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + \trigger_error('Exception in ' . __METHOD__ . "(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", \E_USER_ERROR); + return ''; + } + } + /** + * Returns element's start tag. + */ + public final function startTag() : string + { + return $this->name ? '<' . $this->name . $this->attributes() . (static::$xhtml && $this->isEmpty ? ' />' : '>') : ''; + } + /** + * Returns element's end tag. + */ + public final function endTag() : string + { + return $this->name && !$this->isEmpty ? 'name . '>' : ''; + } + /** + * Returns element's attributes. + * @internal + */ + public final function attributes() : string + { + if (!is_array($this->attrs)) { + return ''; + } + $s = ''; + $attrs = $this->attrs; + foreach ($attrs as $key => $value) { + if ($value === null || $value === \false) { + continue; + } elseif ($value === \true) { + if (static::$xhtml) { + $s .= ' ' . $key . '="' . $key . '"'; + } else { + $s .= ' ' . $key; + } + continue; + } elseif (is_array($value)) { + if (\strncmp($key, 'data-', 5) === 0) { + $value = Json::encode($value); + } else { + $tmp = null; + foreach ($value as $k => $v) { + if ($v != null) { + // intentionally ==, skip nulls & empty string + // composite 'style' vs. 'others' + $tmp[] = $v === \true ? $k : (is_string($k) ? $k . ':' . $v : $v); + } + } + if ($tmp === null) { + continue; + } + $value = \implode($key === 'style' || !\strncmp($key, 'on', 2) ? ';' : ' ', $tmp); + } + } elseif (is_float($value)) { + $value = \rtrim(\rtrim(\number_format($value, 10, '.', ''), '0'), '.'); + } else { + $value = (string) $value; + } + $q = \strpos($value, '"') === \false ? '"' : "'"; + $s .= ' ' . $key . '=' . $q . \str_replace(['&', $q, '<'], ['&', $q === '"' ? '"' : ''', self::$xhtml ? '<' : '<'], $value) . (\strpos($value, '`') !== \false && \strpbrk($value, ' <>"\'') === \false ? ' ' : '') . $q; + } + $s = \str_replace('@', '@', $s); + return $s; + } + /** + * Clones all children too. + */ + public function __clone() + { + foreach ($this->children as $key => $value) { + if (is_object($value)) { + $this->children[$key] = clone $value; + } + } + } +} diff --git a/vendor/nette/utils/src/Utils/Image.php b/vendor/nette/utils/src/Utils/Image.php new file mode 100644 index 00000000000..6b322820161 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Image.php @@ -0,0 +1,607 @@ + + * $image = Image::fromFile('nette.jpg'); + * $image->resize(150, 100); + * $image->sharpen(); + * $image->send(); + * + * + * @method Image affine(array $affine, array $clip = null) + * @method array affineMatrixConcat(array $m1, array $m2) + * @method array affineMatrixGet(int $type, mixed $options = null) + * @method void alphaBlending(bool $on) + * @method void antialias(bool $on) + * @method void arc($x, $y, $w, $h, $start, $end, $color) + * @method void char(int $font, $x, $y, string $char, $color) + * @method void charUp(int $font, $x, $y, string $char, $color) + * @method int colorAllocate($red, $green, $blue) + * @method int colorAllocateAlpha($red, $green, $blue, $alpha) + * @method int colorAt($x, $y) + * @method int colorClosest($red, $green, $blue) + * @method int colorClosestAlpha($red, $green, $blue, $alpha) + * @method int colorClosestHWB($red, $green, $blue) + * @method void colorDeallocate($color) + * @method int colorExact($red, $green, $blue) + * @method int colorExactAlpha($red, $green, $blue, $alpha) + * @method void colorMatch(Image $image2) + * @method int colorResolve($red, $green, $blue) + * @method int colorResolveAlpha($red, $green, $blue, $alpha) + * @method void colorSet($index, $red, $green, $blue) + * @method array colorsForIndex($index) + * @method int colorsTotal() + * @method int colorTransparent($color = null) + * @method void convolution(array $matrix, float $div, float $offset) + * @method void copy(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH) + * @method void copyMerge(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity) + * @method void copyMergeGray(Image $src, $dstX, $dstY, $srcX, $srcY, $srcW, $srcH, $opacity) + * @method void copyResampled(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) + * @method void copyResized(Image $src, $dstX, $dstY, $srcX, $srcY, $dstW, $dstH, $srcW, $srcH) + * @method Image cropAuto(int $mode = -1, float $threshold = .5, int $color = -1) + * @method void ellipse($cx, $cy, $w, $h, $color) + * @method void fill($x, $y, $color) + * @method void filledArc($cx, $cy, $w, $h, $s, $e, $color, $style) + * @method void filledEllipse($cx, $cy, $w, $h, $color) + * @method void filledPolygon(array $points, $numPoints, $color) + * @method void filledRectangle($x1, $y1, $x2, $y2, $color) + * @method void fillToBorder($x, $y, $border, $color) + * @method void filter($filtertype) + * @method void flip(int $mode) + * @method array ftText($size, $angle, $x, $y, $col, string $fontFile, string $text, array $extrainfo = null) + * @method void gammaCorrect(float $inputgamma, float $outputgamma) + * @method array getClip() + * @method int interlace($interlace = null) + * @method bool isTrueColor() + * @method void layerEffect($effect) + * @method void line($x1, $y1, $x2, $y2, $color) + * @method void openPolygon(array $points, int $num_points, int $color) + * @method void paletteCopy(Image $source) + * @method void paletteToTrueColor() + * @method void polygon(array $points, $numPoints, $color) + * @method array psText(string $text, $font, $size, $color, $backgroundColor, $x, $y, $space = null, $tightness = null, float $angle = null, $antialiasSteps = null) + * @method void rectangle($x1, $y1, $x2, $y2, $col) + * @method mixed resolution(int $res_x = null, int $res_y = null) + * @method Image rotate(float $angle, $backgroundColor) + * @method void saveAlpha(bool $saveflag) + * @method Image scale(int $newWidth, int $newHeight = -1, int $mode = IMG_BILINEAR_FIXED) + * @method void setBrush(Image $brush) + * @method void setClip(int $x1, int $y1, int $x2, int $y2) + * @method void setInterpolation(int $method = IMG_BILINEAR_FIXED) + * @method void setPixel($x, $y, $color) + * @method void setStyle(array $style) + * @method void setThickness($thickness) + * @method void setTile(Image $tile) + * @method void string($font, $x, $y, string $s, $col) + * @method void stringUp($font, $x, $y, string $s, $col) + * @method void trueColorToPalette(bool $dither, $ncolors) + * @method array ttfText($size, $angle, $x, $y, $color, string $fontfile, string $text) + * @property-read int $width + * @property-read int $height + * @property-read resource|\GdImage $imageResource + */ +class Image +{ + use Nette\SmartObject; + /** {@link resize()} only shrinks images */ + public const SHRINK_ONLY = 0b1; + /** {@link resize()} will ignore aspect ratio */ + public const STRETCH = 0b10; + /** {@link resize()} fits in given area so its dimensions are less than or equal to the required dimensions */ + public const FIT = 0b0; + /** {@link resize()} fills given area so its dimensions are greater than or equal to the required dimensions */ + public const FILL = 0b100; + /** {@link resize()} fills given area exactly */ + public const EXACT = 0b1000; + /** image types */ + public const JPEG = \IMAGETYPE_JPEG, PNG = \IMAGETYPE_PNG, GIF = \IMAGETYPE_GIF, WEBP = \IMAGETYPE_WEBP, AVIF = 19, BMP = \IMAGETYPE_BMP; + public const EMPTY_GIF = "GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\x00\x00\x00!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;"; + private const Formats = [self::JPEG => 'jpeg', self::PNG => 'png', self::GIF => 'gif', self::WEBP => 'webp', self::AVIF => 'avif', self::BMP => 'bmp']; + /** @var resource|\GdImage */ + private $image; + /** + * Returns RGB color (0..255) and transparency (0..127). + */ + public static function rgb(int $red, int $green, int $blue, int $transparency = 0) : array + { + return ['red' => \max(0, \min(255, $red)), 'green' => \max(0, \min(255, $green)), 'blue' => \max(0, \min(255, $blue)), 'alpha' => \max(0, \min(127, $transparency))]; + } + /** + * Reads an image from a file and returns its type in $type. + * @throws Nette\NotSupportedException if gd extension is not loaded + * @throws UnknownImageFileException if file not found or file type is not known + * @return static + */ + public static function fromFile(string $file, ?int &$type = null) + { + if (!\extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + $type = self::detectTypeFromFile($file); + if (!$type) { + throw new UnknownImageFileException(\is_file($file) ? "Unknown type of file '{$file}'." : "File '{$file}' not found."); + } + return self::invokeSafe('imagecreatefrom' . self::Formats[$type], $file, "Unable to open file '{$file}'.", __METHOD__); + } + /** + * Reads an image from a string and returns its type in $type. + * @return static + * @throws Nette\NotSupportedException if gd extension is not loaded + * @throws ImageException + */ + public static function fromString(string $s, ?int &$type = null) + { + if (!\extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + $type = self::detectTypeFromString($s); + if (!$type) { + throw new UnknownImageFileException('Unknown type of image.'); + } + return self::invokeSafe('imagecreatefromstring', $s, 'Unable to open image from string.', __METHOD__); + } + private static function invokeSafe(string $func, string $arg, string $message, string $callee) : self + { + $errors = []; + $res = Callback::invokeSafe($func, [$arg], function (string $message) use(&$errors) : void { + $errors[] = $message; + }); + if (!$res) { + throw new ImageException($message . ' Errors: ' . \implode(', ', $errors)); + } elseif ($errors) { + \trigger_error($callee . '(): ' . \implode(', ', $errors), \E_USER_WARNING); + } + return new static($res); + } + /** + * Creates a new true color image of the given dimensions. The default color is black. + * @return static + * @throws Nette\NotSupportedException if gd extension is not loaded + */ + public static function fromBlank(int $width, int $height, ?array $color = null) + { + if (!\extension_loaded('gd')) { + throw new Nette\NotSupportedException('PHP extension GD is not loaded.'); + } + if ($width < 1 || $height < 1) { + throw new Nette\InvalidArgumentException('Image width and height must be greater than zero.'); + } + $image = \imagecreatetruecolor($width, $height); + if ($color) { + $color += ['alpha' => 0]; + $color = \imagecolorresolvealpha($image, $color['red'], $color['green'], $color['blue'], $color['alpha']); + \imagealphablending($image, \false); + \imagefilledrectangle($image, 0, 0, $width - 1, $height - 1, $color); + \imagealphablending($image, \true); + } + return new static($image); + } + /** + * Returns the type of image from file. + */ + public static function detectTypeFromFile(string $file, &$width = null, &$height = null) : ?int + { + [$width, $height, $type] = @\getimagesize($file); + // @ - files smaller than 12 bytes causes read error + return isset(self::Formats[$type]) ? $type : null; + } + /** + * Returns the type of image from string. + */ + public static function detectTypeFromString(string $s, &$width = null, &$height = null) : ?int + { + [$width, $height, $type] = @\getimagesizefromstring($s); + // @ - strings smaller than 12 bytes causes read error + return isset(self::Formats[$type]) ? $type : null; + } + /** + * Returns the file extension for the given `Image::XXX` constant. + */ + public static function typeToExtension(int $type) : string + { + if (!isset(self::Formats[$type])) { + throw new Nette\InvalidArgumentException("Unsupported image type '{$type}'."); + } + return self::Formats[$type]; + } + /** + * Returns the `Image::XXX` constant for given file extension. + */ + public static function extensionToType(string $extension) : int + { + $extensions = \array_flip(self::Formats) + ['jpg' => self::JPEG]; + $extension = \strtolower($extension); + if (!isset($extensions[$extension])) { + throw new Nette\InvalidArgumentException("Unsupported file extension '{$extension}'."); + } + return $extensions[$extension]; + } + /** + * Returns the mime type for the given `Image::XXX` constant. + */ + public static function typeToMimeType(int $type) : string + { + return 'image/' . self::typeToExtension($type); + } + /** + * Wraps GD image. + * @param resource|\GdImage $image + */ + public function __construct($image) + { + $this->setImageResource($image); + \imagesavealpha($image, \true); + } + /** + * Returns image width. + */ + public function getWidth() : int + { + return \imagesx($this->image); + } + /** + * Returns image height. + */ + public function getHeight() : int + { + return \imagesy($this->image); + } + /** + * Sets image resource. + * @param resource|\GdImage $image + * @return static + */ + protected function setImageResource($image) + { + if (!$image instanceof \GdImage && !(\is_resource($image) && \get_resource_type($image) === 'gd')) { + throw new Nette\InvalidArgumentException('Image is not valid.'); + } + $this->image = $image; + return $this; + } + /** + * Returns image GD resource. + * @return resource|\GdImage + */ + public function getImageResource() + { + return $this->image; + } + /** + * Scales an image. + * @param int|string|null $width in pixels or percent + * @param int|string|null $height in pixels or percent + * @return static + */ + public function resize($width, $height, int $flags = self::FIT) + { + if ($flags & self::EXACT) { + return $this->resize($width, $height, self::FILL)->crop('50%', '50%', $width, $height); + } + [$newWidth, $newHeight] = static::calculateSize($this->getWidth(), $this->getHeight(), $width, $height, $flags); + if ($newWidth !== $this->getWidth() || $newHeight !== $this->getHeight()) { + // resize + $newImage = static::fromBlank($newWidth, $newHeight, self::rgb(0, 0, 0, 127))->getImageResource(); + \imagecopyresampled($newImage, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $this->getWidth(), $this->getHeight()); + $this->image = $newImage; + } + if ($width < 0 || $height < 0) { + \imageflip($this->image, $width < 0 ? $height < 0 ? \IMG_FLIP_BOTH : \IMG_FLIP_HORIZONTAL : \IMG_FLIP_VERTICAL); + } + return $this; + } + /** + * Calculates dimensions of resized image. + * @param int|string|null $newWidth in pixels or percent + * @param int|string|null $newHeight in pixels or percent + */ + public static function calculateSize(int $srcWidth, int $srcHeight, $newWidth, $newHeight, int $flags = self::FIT) : array + { + if ($newWidth === null) { + } elseif (self::isPercent($newWidth)) { + $newWidth = (int) \round($srcWidth / 100 * \abs($newWidth)); + $percents = \true; + } else { + $newWidth = \abs($newWidth); + } + if ($newHeight === null) { + } elseif (self::isPercent($newHeight)) { + $newHeight = (int) \round($srcHeight / 100 * \abs($newHeight)); + $flags |= empty($percents) ? 0 : self::STRETCH; + } else { + $newHeight = \abs($newHeight); + } + if ($flags & self::STRETCH) { + // non-proportional + if (!$newWidth || !$newHeight) { + throw new Nette\InvalidArgumentException('For stretching must be both width and height specified.'); + } + if ($flags & self::SHRINK_ONLY) { + $newWidth = (int) \round($srcWidth * \min(1, $newWidth / $srcWidth)); + $newHeight = (int) \round($srcHeight * \min(1, $newHeight / $srcHeight)); + } + } else { + // proportional + if (!$newWidth && !$newHeight) { + throw new Nette\InvalidArgumentException('At least width or height must be specified.'); + } + $scale = []; + if ($newWidth > 0) { + // fit width + $scale[] = $newWidth / $srcWidth; + } + if ($newHeight > 0) { + // fit height + $scale[] = $newHeight / $srcHeight; + } + if ($flags & self::FILL) { + $scale = [\max($scale)]; + } + if ($flags & self::SHRINK_ONLY) { + $scale[] = 1; + } + $scale = \min($scale); + $newWidth = (int) \round($srcWidth * $scale); + $newHeight = (int) \round($srcHeight * $scale); + } + return [\max($newWidth, 1), \max($newHeight, 1)]; + } + /** + * Crops image. + * @param int|string $left in pixels or percent + * @param int|string $top in pixels or percent + * @param int|string $width in pixels or percent + * @param int|string $height in pixels or percent + * @return static + */ + public function crop($left, $top, $width, $height) + { + [$r['x'], $r['y'], $r['width'], $r['height']] = static::calculateCutout($this->getWidth(), $this->getHeight(), $left, $top, $width, $height); + if (\gd_info()['GD Version'] === 'bundled (2.1.0 compatible)') { + $this->image = \imagecrop($this->image, $r); + \imagesavealpha($this->image, \true); + } else { + $newImage = static::fromBlank($r['width'], $r['height'], self::RGB(0, 0, 0, 127))->getImageResource(); + \imagecopy($newImage, $this->image, 0, 0, $r['x'], $r['y'], $r['width'], $r['height']); + $this->image = $newImage; + } + return $this; + } + /** + * Calculates dimensions of cutout in image. + * @param int|string $left in pixels or percent + * @param int|string $top in pixels or percent + * @param int|string $newWidth in pixels or percent + * @param int|string $newHeight in pixels or percent + */ + public static function calculateCutout(int $srcWidth, int $srcHeight, $left, $top, $newWidth, $newHeight) : array + { + if (self::isPercent($newWidth)) { + $newWidth = (int) \round($srcWidth / 100 * $newWidth); + } + if (self::isPercent($newHeight)) { + $newHeight = (int) \round($srcHeight / 100 * $newHeight); + } + if (self::isPercent($left)) { + $left = (int) \round(($srcWidth - $newWidth) / 100 * $left); + } + if (self::isPercent($top)) { + $top = (int) \round(($srcHeight - $newHeight) / 100 * $top); + } + if ($left < 0) { + $newWidth += $left; + $left = 0; + } + if ($top < 0) { + $newHeight += $top; + $top = 0; + } + $newWidth = \min($newWidth, $srcWidth - $left); + $newHeight = \min($newHeight, $srcHeight - $top); + return [$left, $top, $newWidth, $newHeight]; + } + /** + * Sharpens image a little bit. + * @return static + */ + public function sharpen() + { + \imageconvolution($this->image, [ + // my magic numbers ;) + [-1, -1, -1], + [-1, 24, -1], + [-1, -1, -1], + ], 16, 0); + return $this; + } + /** + * Puts another image into this image. + * @param int|string $left in pixels or percent + * @param int|string $top in pixels or percent + * @param int $opacity 0..100 + * @return static + */ + public function place(self $image, $left = 0, $top = 0, int $opacity = 100) + { + $opacity = \max(0, \min(100, $opacity)); + if ($opacity === 0) { + return $this; + } + $width = $image->getWidth(); + $height = $image->getHeight(); + if (self::isPercent($left)) { + $left = (int) \round(($this->getWidth() - $width) / 100 * $left); + } + if (self::isPercent($top)) { + $top = (int) \round(($this->getHeight() - $height) / 100 * $top); + } + $output = $input = $image->image; + if ($opacity < 100) { + $tbl = []; + for ($i = 0; $i < 128; $i++) { + $tbl[$i] = \round(127 - (127 - $i) * $opacity / 100); + } + $output = \imagecreatetruecolor($width, $height); + \imagealphablending($output, \false); + if (!$image->isTrueColor()) { + $input = $output; + \imagefilledrectangle($output, 0, 0, $width, $height, \imagecolorallocatealpha($output, 0, 0, 0, 127)); + \imagecopy($output, $image->image, 0, 0, 0, 0, $width, $height); + } + for ($x = 0; $x < $width; $x++) { + for ($y = 0; $y < $height; $y++) { + $c = \imagecolorat($input, $x, $y); + $c = ($c & 0xffffff) + ($tbl[$c >> 24] << 24); + \imagesetpixel($output, $x, $y, $c); + } + } + \imagealphablending($output, \true); + } + \imagecopy($this->image, $output, $left, $top, 0, 0, $width, $height); + return $this; + } + /** + * Saves image to the file. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * @throws ImageException + */ + public function save(string $file, ?int $quality = null, ?int $type = null) : void + { + $type = $type ?? self::extensionToType(\pathinfo($file, \PATHINFO_EXTENSION)); + $this->output($type, $quality, $file); + } + /** + * Outputs image to string. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + */ + public function toString(int $type = self::JPEG, ?int $quality = null) : string + { + return Helpers::capture(function () use($type, $quality) { + $this->output($type, $quality); + }); + } + /** + * Outputs image to string. + */ + public function __toString() : string + { + try { + return $this->toString(); + } catch (\Throwable $e) { + if (\func_num_args() || \PHP_VERSION_ID >= 70400) { + throw $e; + } + \trigger_error('Exception in ' . __METHOD__ . "(): {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}", \E_USER_ERROR); + return ''; + } + } + /** + * Outputs image to browser. Quality is in the range 0..100 for JPEG (default 85), WEBP (default 80) and AVIF (default 30) and 0..9 for PNG (default 9). + * @throws ImageException + */ + public function send(int $type = self::JPEG, ?int $quality = null) : void + { + \header('Content-Type: ' . self::typeToMimeType($type)); + $this->output($type, $quality); + } + /** + * Outputs image to browser or file. + * @throws ImageException + */ + private function output(int $type, ?int $quality, ?string $file = null) : void + { + switch ($type) { + case self::JPEG: + $quality = $quality === null ? 85 : \max(0, \min(100, $quality)); + $success = @\imagejpeg($this->image, $file, $quality); + // @ is escalated to exception + break; + case self::PNG: + $quality = $quality === null ? 9 : \max(0, \min(9, $quality)); + $success = @\imagepng($this->image, $file, $quality); + // @ is escalated to exception + break; + case self::GIF: + $success = @\imagegif($this->image, $file); + // @ is escalated to exception + break; + case self::WEBP: + $quality = $quality === null ? 80 : \max(0, \min(100, $quality)); + $success = @\imagewebp($this->image, $file, $quality); + // @ is escalated to exception + break; + case self::AVIF: + $quality = $quality === null ? 30 : \max(0, \min(100, $quality)); + $success = @imageavif($this->image, $file, $quality); + // @ is escalated to exception + break; + case self::BMP: + $success = @\imagebmp($this->image, $file); + // @ is escalated to exception + break; + default: + throw new Nette\InvalidArgumentException("Unsupported image type '{$type}'."); + } + if (!$success) { + throw new ImageException(Helpers::getLastError() ?: 'Unknown error'); + } + } + /** + * Call to undefined method. + * @return mixed + * @throws Nette\MemberAccessException + */ + public function __call(string $name, array $args) + { + $function = 'image' . $name; + if (!\function_exists($function)) { + ObjectHelpers::strictCall(static::class, $name); + } + foreach ($args as $key => $value) { + if ($value instanceof self) { + $args[$key] = $value->getImageResource(); + } elseif (\is_array($value) && isset($value['red'])) { + // rgb + $args[$key] = \imagecolorallocatealpha($this->image, $value['red'], $value['green'], $value['blue'], $value['alpha']) ?: \imagecolorresolvealpha($this->image, $value['red'], $value['green'], $value['blue'], $value['alpha']); + } + } + $res = $function($this->image, ...$args); + return $res instanceof \GdImage || \is_resource($res) && \get_resource_type($res) === 'gd' ? $this->setImageResource($res) : $res; + } + public function __clone() + { + \ob_start(function () { + }); + \imagepng($this->image, null, 0); + $this->setImageResource(\imagecreatefromstring(\ob_get_clean())); + } + /** + * @param int|string $num in pixels or percent + */ + private static function isPercent(&$num) : bool + { + if (\is_string($num) && \substr($num, -1) === '%') { + $num = (float) \substr($num, 0, -1); + return \true; + } elseif (\is_int($num) || $num === (string) (int) $num) { + $num = (int) $num; + return \false; + } + throw new Nette\InvalidArgumentException("Expected dimension in int|string, '{$num}' given."); + } + /** + * Prevents serialization. + */ + public function __sleep() : array + { + throw new Nette\NotSupportedException('You cannot serialize or unserialize ' . self::class . ' instances.'); + } +} diff --git a/vendor/nette/utils/src/Utils/Json.php b/vendor/nette/utils/src/Utils/Json.php new file mode 100644 index 00000000000..d0427f35f18 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Json.php @@ -0,0 +1,49 @@ +getProperties(\ReflectionProperty::IS_PUBLIC), function ($p) { + return !$p->isStatic(); + }), self::parseFullDoc($rc, '~^[ \\t*]*@property(?:-read)?[ \\t]+(?:\\S+[ \\t]+)??\\$(\\w+)~m')), $name); + throw new MemberAccessException("Cannot read an undeclared property {$class}::\${$name}" . ($hint ? ", did you mean \${$hint}?" : '.')); + } + /** + * @return never + * @throws MemberAccessException + */ + public static function strictSet(string $class, string $name) : void + { + $rc = new \ReflectionClass($class); + $hint = self::getSuggestion(\array_merge(\array_filter($rc->getProperties(\ReflectionProperty::IS_PUBLIC), function ($p) { + return !$p->isStatic(); + }), self::parseFullDoc($rc, '~^[ \\t*]*@property(?:-write)?[ \\t]+(?:\\S+[ \\t]+)??\\$(\\w+)~m')), $name); + throw new MemberAccessException("Cannot write to an undeclared property {$class}::\${$name}" . ($hint ? ", did you mean \${$hint}?" : '.')); + } + /** + * @return never + * @throws MemberAccessException + */ + public static function strictCall(string $class, string $method, array $additionalMethods = []) : void + { + $trace = \debug_backtrace(0, 3); + // suppose this method is called from __call() + $context = ($trace[1]['function'] ?? null) === '__call' ? $trace[2]['class'] ?? null : null; + if ($context && \is_a($class, $context, \true) && \method_exists($context, $method)) { + // called parent::$method() + $class = \get_parent_class($context); + } + if (\method_exists($class, $method)) { + // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() ? 'private ' : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method {$class}::{$method}() from " . ($context ? "scope {$context}." : 'global scope.')); + } else { + $hint = self::getSuggestion(\array_merge(\get_class_methods($class), self::parseFullDoc(new \ReflectionClass($class), '~^[ \\t*]*@method[ \\t]+(?:static[ \\t]+)?(?:\\S+[ \\t]+)??(\\w+)\\(~m'), $additionalMethods), $method); + throw new MemberAccessException("Call to undefined method {$class}::{$method}()" . ($hint ? ", did you mean {$hint}()?" : '.')); + } + } + /** + * @return never + * @throws MemberAccessException + */ + public static function strictStaticCall(string $class, string $method) : void + { + $trace = \debug_backtrace(0, 3); + // suppose this method is called from __callStatic() + $context = ($trace[1]['function'] ?? null) === '__callStatic' ? $trace[2]['class'] ?? null : null; + if ($context && \is_a($class, $context, \true) && \method_exists($context, $method)) { + // called parent::$method() + $class = \get_parent_class($context); + } + if (\method_exists($class, $method)) { + // insufficient visibility + $rm = new \ReflectionMethod($class, $method); + $visibility = $rm->isPrivate() ? 'private ' : ($rm->isProtected() ? 'protected ' : ''); + throw new MemberAccessException("Call to {$visibility}method {$class}::{$method}() from " . ($context ? "scope {$context}." : 'global scope.')); + } else { + $hint = self::getSuggestion(\array_filter((new \ReflectionClass($class))->getMethods(\ReflectionMethod::IS_PUBLIC), function ($m) { + return $m->isStatic(); + }), $method); + throw new MemberAccessException("Call to undefined static method {$class}::{$method}()" . ($hint ? ", did you mean {$hint}()?" : '.')); + } + } + /** + * Returns array of magic properties defined by annotation @property. + * @return array of [name => bit mask] + * @internal + */ + public static function getMagicProperties(string $class) : array + { + static $cache; + $props =& $cache[$class]; + if ($props !== null) { + return $props; + } + $rc = new \ReflectionClass($class); + \preg_match_all('~^ [ \\t*]* @property(|-read|-write|-deprecated) [ \\t]+ [^\\s$]+ [ \\t]+ \\$ (\\w+) ()~mx', (string) $rc->getDocComment(), $matches, \PREG_SET_ORDER); + $props = []; + foreach ($matches as [, $type, $name]) { + $uname = \ucfirst($name); + $write = $type !== '-read' && $rc->hasMethod($nm = 'set' . $uname) && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); + $read = $type !== '-write' && ($rc->hasMethod($nm = 'get' . $uname) || $rc->hasMethod($nm = 'is' . $uname)) && ($rm = $rc->getMethod($nm))->name === $nm && !$rm->isPrivate() && !$rm->isStatic(); + if ($read || $write) { + $props[$name] = $read << 0 | ($nm[0] === 'g') << 1 | $rm->returnsReference() << 2 | $write << 3 | ($type === '-deprecated') << 4; + } + } + foreach ($rc->getTraits() as $trait) { + $props += self::getMagicProperties($trait->name); + } + if ($parent = \get_parent_class($class)) { + $props += self::getMagicProperties($parent); + } + return $props; + } + /** + * Finds the best suggestion (for 8-bit encoding). + * @param (\ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionClass|\ReflectionProperty|string)[] $possibilities + * @internal + */ + public static function getSuggestion(array $possibilities, string $value) : ?string + { + $norm = \preg_replace($re = '#^(get|set|has|is|add)(?=[A-Z])#', '+', $value); + $best = null; + $min = (\strlen($value) / 4 + 1) * 10 + 0.1; + foreach (\array_unique($possibilities, \SORT_REGULAR) as $item) { + $item = $item instanceof \Reflector ? $item->name : $item; + if ($item !== $value && (($len = \levenshtein($item, $value, 10, 11, 10)) < $min || ($len = \levenshtein(\preg_replace($re, '*', $item), $norm, 10, 11, 10)) < $min)) { + $min = $len; + $best = $item; + } + } + return $best; + } + private static function parseFullDoc(\ReflectionClass $rc, string $pattern) : array + { + do { + $doc[] = $rc->getDocComment(); + $traits = $rc->getTraits(); + while ($trait = \array_pop($traits)) { + $doc[] = $trait->getDocComment(); + $traits += $trait->getTraits(); + } + } while ($rc = $rc->getParentClass()); + return \preg_match_all($pattern, \implode($doc), $m) ? $m[1] : []; + } + /** + * Checks if the public non-static property exists. + * @return bool|string returns 'event' if the property exists and has event like name + * @internal + */ + public static function hasProperty(string $class, string $name) + { + static $cache; + $prop =& $cache[$class][$name]; + if ($prop === null) { + $prop = \false; + try { + $rp = new \ReflectionProperty($class, $name); + if ($rp->isPublic() && !$rp->isStatic()) { + $prop = $name >= 'onA' && $name < 'on_' ? 'event' : \true; + } + } catch (\ReflectionException $e) { + } + } + return $prop; + } +} diff --git a/vendor/nette/utils/src/Utils/ObjectMixin.php b/vendor/nette/utils/src/Utils/ObjectMixin.php new file mode 100644 index 00000000000..21cf40d9c21 --- /dev/null +++ b/vendor/nette/utils/src/Utils/ObjectMixin.php @@ -0,0 +1,32 @@ +page = $page; + return $this; + } + /** + * Returns current page number. + */ + public function getPage() : int + { + return $this->base + $this->getPageIndex(); + } + /** + * Returns first page number. + */ + public function getFirstPage() : int + { + return $this->base; + } + /** + * Returns last page number. + */ + public function getLastPage() : ?int + { + return $this->itemCount === null ? null : $this->base + \max(0, $this->getPageCount() - 1); + } + /** + * Returns the sequence number of the first element on the page + */ + public function getFirstItemOnPage() : int + { + return $this->itemCount !== 0 ? $this->offset + 1 : 0; + } + /** + * Returns the sequence number of the last element on the page + */ + public function getLastItemOnPage() : int + { + return $this->offset + $this->length; + } + /** + * Sets first page (base) number. + * @return static + */ + public function setBase(int $base) + { + $this->base = $base; + return $this; + } + /** + * Returns first page (base) number. + */ + public function getBase() : int + { + return $this->base; + } + /** + * Returns zero-based page number. + */ + protected function getPageIndex() : int + { + $index = \max(0, $this->page - $this->base); + return $this->itemCount === null ? $index : \min($index, \max(0, $this->getPageCount() - 1)); + } + /** + * Is the current page the first one? + */ + public function isFirst() : bool + { + return $this->getPageIndex() === 0; + } + /** + * Is the current page the last one? + */ + public function isLast() : bool + { + return $this->itemCount === null ? \false : $this->getPageIndex() >= $this->getPageCount() - 1; + } + /** + * Returns the total number of pages. + */ + public function getPageCount() : ?int + { + return $this->itemCount === null ? null : (int) \ceil($this->itemCount / $this->itemsPerPage); + } + /** + * Sets the number of items to display on a single page. + * @return static + */ + public function setItemsPerPage(int $itemsPerPage) + { + $this->itemsPerPage = \max(1, $itemsPerPage); + return $this; + } + /** + * Returns the number of items to display on a single page. + */ + public function getItemsPerPage() : int + { + return $this->itemsPerPage; + } + /** + * Sets the total number of items. + * @return static + */ + public function setItemCount(?int $itemCount = null) + { + $this->itemCount = $itemCount === null ? null : \max(0, $itemCount); + return $this; + } + /** + * Returns the total number of items. + */ + public function getItemCount() : ?int + { + return $this->itemCount; + } + /** + * Returns the absolute index of the first item on current page. + */ + public function getOffset() : int + { + return $this->getPageIndex() * $this->itemsPerPage; + } + /** + * Returns the absolute index of the first item on current page in countdown paging. + */ + public function getCountdownOffset() : ?int + { + return $this->itemCount === null ? null : \max(0, $this->itemCount - ($this->getPageIndex() + 1) * $this->itemsPerPage); + } + /** + * Returns the number of items on current page. + */ + public function getLength() : int + { + return $this->itemCount === null ? $this->itemsPerPage : \min($this->itemsPerPage, $this->itemCount - $this->getPageIndex() * $this->itemsPerPage); + } +} diff --git a/vendor/nette/utils/src/Utils/Random.php b/vendor/nette/utils/src/Utils/Random.php new file mode 100644 index 00000000000..0362edcd49b --- /dev/null +++ b/vendor/nette/utils/src/Utils/Random.php @@ -0,0 +1,38 @@ +getReturnType() ?? (\PHP_VERSION_ID >= 80100 && $func instanceof \ReflectionMethod ? $func->getTentativeReturnType() : null); + return self::getType($func, $type); + } + /** + * @deprecated + */ + public static function getReturnTypes(\ReflectionFunctionAbstract $func) : array + { + $type = Type::fromReflection($func); + return $type ? $type->getNames() : []; + } + /** + * Returns the type of given parameter and normalizes `self` and `parent` to the actual class names. + * If the parameter does not have a type, it returns null. + * If the parameter has union or intersection type, it throws Nette\InvalidStateException. + */ + public static function getParameterType(\ReflectionParameter $param) : ?string + { + return self::getType($param, $param->getType()); + } + /** + * @deprecated + */ + public static function getParameterTypes(\ReflectionParameter $param) : array + { + $type = Type::fromReflection($param); + return $type ? $type->getNames() : []; + } + /** + * Returns the type of given property and normalizes `self` and `parent` to the actual class names. + * If the property does not have a type, it returns null. + * If the property has union or intersection type, it throws Nette\InvalidStateException. + */ + public static function getPropertyType(\ReflectionProperty $prop) : ?string + { + return self::getType($prop, \PHP_VERSION_ID >= 70400 ? \method_exists($prop, 'getType') ? $prop->getType() : null : null); + } + /** + * @deprecated + */ + public static function getPropertyTypes(\ReflectionProperty $prop) : array + { + $type = Type::fromReflection($prop); + return $type ? $type->getNames() : []; + } + /** + * @param \ReflectionFunction|\ReflectionMethod|\ReflectionParameter|\ReflectionProperty $reflection + */ + private static function getType($reflection, ?\ReflectionType $type) : ?string + { + if ($type === null) { + return null; + } elseif ($type instanceof \ReflectionNamedType) { + return Type::resolve($type->getName(), $reflection); + } elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { + throw new Nette\InvalidStateException('The ' . self::toString($reflection) . ' is not expected to have a union or intersection type.'); + } else { + throw new Nette\InvalidStateException('Unexpected type of ' . self::toString($reflection)); + } + } + /** + * Returns the default value of parameter. If it is a constant, it returns its value. + * @return mixed + * @throws \ReflectionException If the parameter does not have a default value or the constant cannot be resolved + */ + public static function getParameterDefaultValue(\ReflectionParameter $param) + { + if ($param->isDefaultValueConstant()) { + $const = $orig = $param->getDefaultValueConstantName(); + $pair = \explode('::', $const); + if (isset($pair[1])) { + $pair[0] = Type::resolve($pair[0], $param); + try { + $rcc = new \ReflectionClassConstant($pair[0], $pair[1]); + } catch (\ReflectionException $e) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant {$orig} used as default value of {$name}.", 0, $e); + } + return $rcc->getValue(); + } elseif (!\defined($const)) { + $const = \substr((string) \strrchr($const, '\\'), 1); + if (!\defined($const)) { + $name = self::toString($param); + throw new \ReflectionException("Unable to resolve constant {$orig} used as default value of {$name}."); + } + } + return \constant($const); + } + return $param->getDefaultValue(); + } + /** + * Returns a reflection of a class or trait that contains a declaration of given property. Property can also be declared in the trait. + */ + public static function getPropertyDeclaringClass(\ReflectionProperty $prop) : \ReflectionClass + { + foreach ($prop->getDeclaringClass()->getTraits() as $trait) { + if ($trait->hasProperty($prop->name) && $trait->getProperty($prop->name)->getDocComment() === $prop->getDocComment()) { + return self::getPropertyDeclaringClass($trait->getProperty($prop->name)); + } + } + return $prop->getDeclaringClass(); + } + /** + * Returns a reflection of a method that contains a declaration of $method. + * Usually, each method is its own declaration, but the body of the method can also be in the trait and under a different name. + */ + public static function getMethodDeclaringMethod(\ReflectionMethod $method) : \ReflectionMethod + { + // file & line guessing as workaround for insufficient PHP reflection + $decl = $method->getDeclaringClass(); + if ($decl->getFileName() === $method->getFileName() && $decl->getStartLine() <= $method->getStartLine() && $decl->getEndLine() >= $method->getEndLine()) { + return $method; + } + $hash = [$method->getFileName(), $method->getStartLine(), $method->getEndLine()]; + if (($alias = $decl->getTraitAliases()[$method->name] ?? null) && ($m = new \ReflectionMethod($alias)) && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]) { + return self::getMethodDeclaringMethod($m); + } + foreach ($decl->getTraits() as $trait) { + if ($trait->hasMethod($method->name) && ($m = $trait->getMethod($method->name)) && $hash === [$m->getFileName(), $m->getStartLine(), $m->getEndLine()]) { + return self::getMethodDeclaringMethod($m); + } + } + return $method; + } + /** + * Finds out if reflection has access to PHPdoc comments. Comments may not be available due to the opcode cache. + */ + public static function areCommentsAvailable() : bool + { + static $res; + return $res ?? ($res = (bool) (new \ReflectionMethod(__METHOD__))->getDocComment()); + } + public static function toString(\Reflector $ref) : string + { + if ($ref instanceof \ReflectionClass) { + return $ref->name; + } elseif ($ref instanceof \ReflectionMethod) { + return $ref->getDeclaringClass()->name . '::' . $ref->name . '()'; + } elseif ($ref instanceof \ReflectionFunction) { + return $ref->name . '()'; + } elseif ($ref instanceof \ReflectionProperty) { + return self::getPropertyDeclaringClass($ref)->name . '::$' . $ref->name; + } elseif ($ref instanceof \ReflectionParameter) { + return '$' . $ref->name . ' in ' . self::toString($ref->getDeclaringFunction()); + } else { + throw new Nette\InvalidArgumentException(); + } + } + /** + * Expands the name of the class to full name in the given context of given class. + * Thus, it returns how the PHP parser would understand $name if it were written in the body of the class $context. + * @throws Nette\InvalidArgumentException + */ + public static function expandClassName(string $name, \ReflectionClass $context) : string + { + $lower = \strtolower($name); + if (empty($name)) { + throw new Nette\InvalidArgumentException('Class name must not be empty.'); + } elseif (Validators::isBuiltinType($lower)) { + return $lower; + } elseif ($lower === 'self' || $lower === 'static') { + return $context->name; + } elseif ($lower === 'parent') { + return $context->getParentClass() ? $context->getParentClass()->name : 'parent'; + } elseif ($name[0] === '\\') { + // fully qualified name + return \ltrim($name, '\\'); + } + $uses = self::getUseStatements($context); + $parts = \explode('\\', $name, 2); + if (isset($uses[$parts[0]])) { + $parts[0] = $uses[$parts[0]]; + return \implode('\\', $parts); + } elseif ($context->inNamespace()) { + return $context->getNamespaceName() . '\\' . $name; + } else { + return $name; + } + } + /** @return array of [alias => class] */ + public static function getUseStatements(\ReflectionClass $class) : array + { + if ($class->isAnonymous()) { + throw new Nette\NotImplementedException('Anonymous classes are not supported.'); + } + static $cache = []; + if (!isset($cache[$name = $class->name])) { + if ($class->isInternal()) { + $cache[$name] = []; + } else { + $code = \file_get_contents($class->getFileName()); + $cache = self::parseUseStatements($code, $name) + $cache; + } + } + return $cache[$name]; + } + /** + * Parses PHP code to [class => [alias => class, ...]] + */ + private static function parseUseStatements(string $code, ?string $forClass = null) : array + { + try { + $tokens = \token_get_all($code, \TOKEN_PARSE); + } catch (\ParseError $e) { + \trigger_error($e->getMessage(), \E_USER_NOTICE); + $tokens = []; + } + $namespace = $class = $classLevel = $level = null; + $res = $uses = []; + $nameTokens = \PHP_VERSION_ID < 80000 ? [\T_STRING, \T_NS_SEPARATOR] : [\T_STRING, \T_NS_SEPARATOR, \T_NAME_QUALIFIED, \T_NAME_FULLY_QUALIFIED]; + while ($token = \current($tokens)) { + \next($tokens); + switch (\is_array($token) ? $token[0] : $token) { + case \T_NAMESPACE: + $namespace = \ltrim(self::fetch($tokens, $nameTokens) . '\\', '\\'); + $uses = []; + break; + case \T_CLASS: + case \T_INTERFACE: + case \T_TRAIT: + case \PHP_VERSION_ID < 80100 ? \T_CLASS : \T_ENUM: + if ($name = self::fetch($tokens, \T_STRING)) { + $class = $namespace . $name; + $classLevel = $level + 1; + $res[$class] = $uses; + if ($class === $forClass) { + return $res; + } + } + break; + case \T_USE: + while (!$class && ($name = self::fetch($tokens, $nameTokens))) { + $name = \ltrim($name, '\\'); + if (self::fetch($tokens, '{')) { + while ($suffix = self::fetch($tokens, $nameTokens)) { + if (self::fetch($tokens, \T_AS)) { + $uses[self::fetch($tokens, \T_STRING)] = $name . $suffix; + } else { + $tmp = \explode('\\', $suffix); + $uses[\end($tmp)] = $name . $suffix; + } + if (!self::fetch($tokens, ',')) { + break; + } + } + } elseif (self::fetch($tokens, \T_AS)) { + $uses[self::fetch($tokens, \T_STRING)] = $name; + } else { + $tmp = \explode('\\', $name); + $uses[\end($tmp)] = $name; + } + if (!self::fetch($tokens, ',')) { + break; + } + } + break; + case \T_CURLY_OPEN: + case \T_DOLLAR_OPEN_CURLY_BRACES: + case '{': + $level++; + break; + case '}': + if ($level === $classLevel) { + $class = $classLevel = null; + } + $level--; + } + } + return $res; + } + private static function fetch(array &$tokens, $take) : ?string + { + $res = null; + while ($token = \current($tokens)) { + [$token, $s] = \is_array($token) ? $token : [$token, $token]; + if (\in_array($token, (array) $take, \true)) { + $res .= $s; + } elseif (!\in_array($token, [\T_DOC_COMMENT, \T_WHITESPACE, \T_COMMENT], \true)) { + break; + } + \next($tokens); + } + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Strings.php b/vendor/nette/utils/src/Utils/Strings.php new file mode 100644 index 00000000000..3e5f25e9a5a --- /dev/null +++ b/vendor/nette/utils/src/Utils/Strings.php @@ -0,0 +1,486 @@ += 0xd800 && $code <= 0xdfff || $code > 0x10ffff) { + throw new Nette\InvalidArgumentException('Code point must be in range 0x0 to 0xD7FF or 0xE000 to 0x10FFFF.'); + } elseif (!\extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + return \iconv('UTF-32BE', 'UTF-8//IGNORE', \pack('N', $code)); + } + /** + * Starts the $haystack string with the prefix $needle? + */ + public static function startsWith(string $haystack, string $needle) : bool + { + return \strncmp($haystack, $needle, strlen($needle)) === 0; + } + /** + * Ends the $haystack string with the suffix $needle? + */ + public static function endsWith(string $haystack, string $needle) : bool + { + return $needle === '' || \substr($haystack, -strlen($needle)) === $needle; + } + /** + * Does $haystack contain $needle? + */ + public static function contains(string $haystack, string $needle) : bool + { + return \strpos($haystack, $needle) !== \false; + } + /** + * Returns a part of UTF-8 string specified by starting position and length. If start is negative, + * the returned string will start at the start'th character from the end of string. + */ + public static function substring(string $s, int $start, ?int $length = null) : string + { + if (\function_exists('mb_substr')) { + return \mb_substr($s, $start, $length, 'UTF-8'); + // MB is much faster + } elseif (!\extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires extension ICONV or MBSTRING, neither is loaded.'); + } elseif ($length === null) { + $length = self::length($s); + } elseif ($start < 0 && $length < 0) { + $start += self::length($s); + // unifies iconv_substr behavior with mb_substr + } + return \iconv_substr($s, $start, $length, 'UTF-8'); + } + /** + * Removes control characters, normalizes line breaks to `\n`, removes leading and trailing blank lines, + * trims end spaces on lines, normalizes UTF-8 to the normal form of NFC. + */ + public static function normalize(string $s) : string + { + // convert to compressed normal form (NFC) + if (\class_exists('Normalizer', \false) && ($n = \Normalizer::normalize($s, \Normalizer::FORM_C)) !== \false) { + $s = $n; + } + $s = self::normalizeNewLines($s); + // remove control characters; leave \t + \n + $s = self::pcre('preg_replace', ['#[\\x00-\\x08\\x0B-\\x1F\\x7F-\\x9F]+#u', '', $s]); + // right trim + $s = self::pcre('preg_replace', ['#[\\t ]+$#m', '', $s]); + // leading and trailing blank lines + $s = \trim($s, "\n"); + return $s; + } + /** + * Standardize line endings to unix-like. + */ + public static function normalizeNewLines(string $s) : string + { + return \str_replace(["\r\n", "\r"], "\n", $s); + } + /** + * Converts UTF-8 string to ASCII, ie removes diacritics etc. + */ + public static function toAscii(string $s) : string + { + $iconv = \defined('ICONV_IMPL') ? \trim(\ICONV_IMPL, '"\'') : null; + static $transliterator = null; + if ($transliterator === null) { + if (\class_exists('Transliterator', \false)) { + $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII'); + } else { + \trigger_error(__METHOD__ . "(): it is recommended to enable PHP extensions 'intl'.", \E_USER_NOTICE); + $transliterator = \false; + } + } + // remove control characters and check UTF-8 validity + $s = self::pcre('preg_replace', ['#[^\\x09\\x0A\\x0D\\x20-\\x7E\\xA0-\\x{2FF}\\x{370}-\\x{10FFFF}]#u', '', $s]); + // transliteration (by Transliterator and iconv) is not optimal, replace some characters directly + $s = \strtr($s, ["„" => '"', "“" => '"', "”" => '"', "‚" => "'", "‘" => "'", "’" => "'", "°" => '^', "Я" => 'Ya', "я" => 'ya', "Ю" => 'Yu', "ю" => 'yu', "Ä" => 'Ae', "Ö" => 'Oe', "Ü" => 'Ue', "ẞ" => 'Ss', "ä" => 'ae', "ö" => 'oe', "ü" => 'ue', "ß" => 'ss']); + // „ “ ” ‚ ‘ ’ ° Я я Ю ю Ä Ö Ü ẞ ä ö ü ß + if ($iconv !== 'libiconv') { + $s = \strtr($s, ["®" => '(R)', "©" => '(c)', "…" => '...', "«" => '<<', "»" => '>>', "£" => 'lb', "¥" => 'yen', "²" => '^2', "³" => '^3', "µ" => 'u', "¹" => '^1', "º" => 'o', "¿" => '?', "ˊ" => "'", "ˍ" => '_', "˝" => '"', "`" => '', "€" => 'EUR', "™" => 'TM', "℮" => 'e', "←" => '<-', "↑" => '^', "→" => '->', "↓" => 'V', "↔" => '<->']); + // ® © … « » £ ¥ ² ³ µ ¹ º ¿ ˊ ˍ ˝ ` € ™ ℮ ← ↑ → ↓ ↔ + } + if ($transliterator) { + $s = $transliterator->transliterate($s); + // use iconv because The transliterator leaves some characters out of ASCII, eg → ʾ + if ($iconv === 'glibc') { + $s = \strtr($s, '?', "\x01"); + // temporarily hide ? to distinguish them from the garbage that iconv creates + $s = \iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + $s = \str_replace(['?', "\x01"], ['', '?'], $s); + // remove garbage and restore ? characters + } elseif ($iconv === 'libiconv') { + $s = \iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + } else { + // null or 'unknown' (#216) + $s = self::pcre('preg_replace', ['#[^\\x00-\\x7F]++#', '', $s]); + // remove non-ascii chars + } + } elseif ($iconv === 'glibc' || $iconv === 'libiconv') { + // temporarily hide these characters to distinguish them from the garbage that iconv creates + $s = \strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06"); + if ($iconv === 'glibc') { + // glibc implementation is very limited. transliterate into Windows-1250 and then into ASCII, so most Eastern European characters are preserved + $s = \iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); + $s = \strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe\x96\xa0\x8b\x97\x9b\xa6\xad\xb7", 'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.'); + $s = self::pcre('preg_replace', ['#[^\\x00-\\x7F]++#', '', $s]); + } else { + $s = \iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); + } + // remove garbage that iconv creates during transliteration (eg Ý -> Y') + $s = \str_replace(['`', "'", '"', '^', '~', '?'], '', $s); + // restore temporarily hidden characters + $s = \strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?'); + } else { + $s = self::pcre('preg_replace', ['#[^\\x00-\\x7F]++#', '', $s]); + // remove non-ascii chars + } + return $s; + } + /** + * Modifies the UTF-8 string to the form used in the URL, ie removes diacritics and replaces all characters + * except letters of the English alphabet and numbers with a hyphens. + */ + public static function webalize(string $s, ?string $charlist = null, bool $lower = \true) : string + { + $s = self::toAscii($s); + if ($lower) { + $s = \strtolower($s); + } + $s = self::pcre('preg_replace', ['#[^a-z0-9' . ($charlist !== null ? \preg_quote($charlist, '#') : '') . ']+#i', '-', $s]); + $s = \trim($s, '-'); + return $s; + } + /** + * Truncates a UTF-8 string to given maximal length, while trying not to split whole words. Only if the string is truncated, + * an ellipsis (or something else set with third argument) is appended to the string. + */ + public static function truncate(string $s, int $maxLen, string $append = "…") : string + { + if (self::length($s) > $maxLen) { + $maxLen -= self::length($append); + if ($maxLen < 1) { + return $append; + } elseif ($matches = self::match($s, '#^.{1,' . $maxLen . '}(?=[\\s\\x00-/:-@\\[-`{-~])#us')) { + return $matches[0] . $append; + } else { + return self::substring($s, 0, $maxLen) . $append; + } + } + return $s; + } + /** + * Indents a multiline text from the left. Second argument sets how many indentation chars should be used, + * while the indent itself is the third argument (*tab* by default). + */ + public static function indent(string $s, int $level = 1, string $chars = "\t") : string + { + if ($level > 0) { + $s = self::replace($s, '#(?:^|[\\r\\n]+)(?=[^\\r\\n])#', '$0' . \str_repeat($chars, $level)); + } + return $s; + } + /** + * Converts all characters of UTF-8 string to lower case. + */ + public static function lower(string $s) : string + { + return \mb_strtolower($s, 'UTF-8'); + } + /** + * Converts the first character of a UTF-8 string to lower case and leaves the other characters unchanged. + */ + public static function firstLower(string $s) : string + { + return self::lower(self::substring($s, 0, 1)) . self::substring($s, 1); + } + /** + * Converts all characters of a UTF-8 string to upper case. + */ + public static function upper(string $s) : string + { + return \mb_strtoupper($s, 'UTF-8'); + } + /** + * Converts the first character of a UTF-8 string to upper case and leaves the other characters unchanged. + */ + public static function firstUpper(string $s) : string + { + return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1); + } + /** + * Converts the first character of every word of a UTF-8 string to upper case and the others to lower case. + */ + public static function capitalize(string $s) : string + { + return \mb_convert_case($s, \MB_CASE_TITLE, 'UTF-8'); + } + /** + * Compares two UTF-8 strings or their parts, without taking character case into account. If length is null, whole strings are compared, + * if it is negative, the corresponding number of characters from the end of the strings is compared, + * otherwise the appropriate number of characters from the beginning is compared. + */ + public static function compare(string $left, string $right, ?int $length = null) : bool + { + if (\class_exists('Normalizer', \false)) { + $left = \Normalizer::normalize($left, \Normalizer::FORM_D); + // form NFD is faster + $right = \Normalizer::normalize($right, \Normalizer::FORM_D); + // form NFD is faster + } + if ($length < 0) { + $left = self::substring($left, $length, -$length); + $right = self::substring($right, $length, -$length); + } elseif ($length !== null) { + $left = self::substring($left, 0, $length); + $right = self::substring($right, 0, $length); + } + return self::lower($left) === self::lower($right); + } + /** + * Finds the common prefix of strings or returns empty string if the prefix was not found. + * @param string[] $strings + */ + public static function findPrefix(array $strings) : string + { + $first = \array_shift($strings); + for ($i = 0; $i < strlen($first); $i++) { + foreach ($strings as $s) { + if (!isset($s[$i]) || $first[$i] !== $s[$i]) { + while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xc0") { + $i--; + } + return \substr($first, 0, $i); + } + } + } + return $first; + } + /** + * Returns number of characters (not bytes) in UTF-8 string. + * That is the number of Unicode code points which may differ from the number of graphemes. + */ + public static function length(string $s) : int + { + return \function_exists('mb_strlen') ? \mb_strlen($s, 'UTF-8') : strlen(\utf8_decode($s)); + } + /** + * Removes all left and right side spaces (or the characters passed as second argument) from a UTF-8 encoded string. + */ + public static function trim(string $s, string $charlist = self::TRIM_CHARACTERS) : string + { + $charlist = \preg_quote($charlist, '#'); + return self::replace($s, '#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', ''); + } + /** + * Pads a UTF-8 string to given length by prepending the $pad string to the beginning. + */ + public static function padLeft(string $s, int $length, string $pad = ' ') : string + { + $length = \max(0, $length - self::length($s)); + $padLen = self::length($pad); + return \str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s; + } + /** + * Pads UTF-8 string to given length by appending the $pad string to the end. + */ + public static function padRight(string $s, int $length, string $pad = ' ') : string + { + $length = \max(0, $length - self::length($s)); + $padLen = self::length($pad); + return $s . \str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen); + } + /** + * Reverses UTF-8 string. + */ + public static function reverse(string $s) : string + { + if (!\extension_loaded('iconv')) { + throw new Nette\NotSupportedException(__METHOD__ . '() requires ICONV extension that is not loaded.'); + } + return \iconv('UTF-32LE', 'UTF-8', \strrev(\iconv('UTF-8', 'UTF-32BE', $s))); + } + /** + * Returns part of $haystack before $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function before(string $haystack, string $needle, int $nth = 1) : ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null ? null : \substr($haystack, 0, $pos); + } + /** + * Returns part of $haystack after $nth occurence of $needle or returns null if the needle was not found. + * Negative value means searching from the end. + */ + public static function after(string $haystack, string $needle, int $nth = 1) : ?string + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null ? null : \substr($haystack, $pos + strlen($needle)); + } + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the $needle was not found. + * Negative value of `$nth` means searching from the end. + */ + public static function indexOf(string $haystack, string $needle, int $nth = 1) : ?int + { + $pos = self::pos($haystack, $needle, $nth); + return $pos === null ? null : self::length(\substr($haystack, 0, $pos)); + } + /** + * Returns position in characters of $nth occurence of $needle in $haystack or null if the needle was not found. + */ + private static function pos(string $haystack, string $needle, int $nth = 1) : ?int + { + if (!$nth) { + return null; + } elseif ($nth > 0) { + if ($needle === '') { + return 0; + } + $pos = 0; + while (($pos = \strpos($haystack, $needle, $pos)) !== \false && --$nth) { + $pos++; + } + } else { + $len = strlen($haystack); + if ($needle === '') { + return $len; + } elseif ($len === 0) { + return null; + } + $pos = $len - 1; + while (($pos = \strrpos($haystack, $needle, $pos - $len)) !== \false && ++$nth) { + $pos--; + } + } + return Helpers::falseToNull($pos); + } + /** + * Splits a string into array by the regular expression. Parenthesized expression in the delimiter are captured. + * Parameter $flags can be any combination of PREG_SPLIT_NO_EMPTY and PREG_OFFSET_CAPTURE flags. + */ + public static function split( + string $subject, + /** + * @language + */ + string $pattern, + int $flags = 0 + ) : array + { + return self::pcre('preg_split', [$pattern, $subject, -1, $flags | \PREG_SPLIT_DELIM_CAPTURE]); + } + /** + * Checks if given string matches a regular expression pattern and returns an array with first found match and each subpattern. + * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE and PREG_UNMATCHED_AS_NULL flags. + */ + public static function match( + string $subject, + /** + * @language + */ + string $pattern, + int $flags = 0, + int $offset = 0 + ) : ?array + { + if ($offset > strlen($subject)) { + return null; + } + return self::pcre('preg_match', [$pattern, $subject, &$m, $flags, $offset]) ? $m : null; + } + /** + * Finds all occurrences matching regular expression pattern and returns a two-dimensional array. Result is array of matches (ie uses by default PREG_SET_ORDER). + * Parameter $flags can be any combination of PREG_OFFSET_CAPTURE, PREG_UNMATCHED_AS_NULL and PREG_PATTERN_ORDER flags. + */ + public static function matchAll( + string $subject, + /** + * @language + */ + string $pattern, + int $flags = 0, + int $offset = 0 + ) : array + { + if ($offset > strlen($subject)) { + return []; + } + self::pcre('preg_match_all', [$pattern, $subject, &$m, $flags & \PREG_PATTERN_ORDER ? $flags : $flags | \PREG_SET_ORDER, $offset]); + return $m; + } + /** + * Replaces all occurrences matching regular expression $pattern which can be string or array in the form `pattern => replacement`. + * @param string|array $pattern + * @param string|callable $replacement + */ + public static function replace( + string $subject, + /** + * @language + */ + $pattern, + $replacement = '', + int $limit = -1 + ) : string + { + if (is_object($replacement) || is_array($replacement)) { + if (!\is_callable($replacement, \false, $textual)) { + throw new Nette\InvalidStateException("Callback '{$textual}' is not callable."); + } + return self::pcre('preg_replace_callback', [$pattern, $replacement, $subject, $limit]); + } elseif (is_array($pattern) && \is_string(\key($pattern))) { + $replacement = \array_values($pattern); + $pattern = \array_keys($pattern); + } + return self::pcre('preg_replace', [$pattern, $replacement, $subject, $limit]); + } + /** @internal */ + public static function pcre(string $func, array $args) + { + $res = Callback::invokeSafe($func, $args, function (string $message) use($args) : void { + // compile-time error, not detectable by preg_last_error + throw new RegexpException($message . ' in pattern: ' . \implode(' or ', (array) $args[0])); + }); + if (($code = \preg_last_error()) && ($res === null || !\in_array($func, ['preg_filter', 'preg_replace_callback', 'preg_replace'], \true))) { + throw new RegexpException((RegexpException::MESSAGES[$code] ?? 'Unknown error') . ' (pattern: ' . \implode(' or ', (array) $args[0]) . ')', $code); + } + return $res; + } +} diff --git a/vendor/nette/utils/src/Utils/Type.php b/vendor/nette/utils/src/Utils/Type.php new file mode 100644 index 00000000000..17299db2d6d --- /dev/null +++ b/vendor/nette/utils/src/Utils/Type.php @@ -0,0 +1,212 @@ + */ + private $types; + /** @var bool */ + private $simple; + /** @var string |, & */ + private $kind; + /** + * Creates a Type object based on reflection. Resolves self, static and parent to the actual class name. + * If the subject has no type, it returns null. + * @param \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $reflection + */ + public static function fromReflection($reflection) : ?self + { + if ($reflection instanceof \ReflectionProperty && \PHP_VERSION_ID < 70400) { + return null; + } elseif ($reflection instanceof \ReflectionMethod) { + $type = $reflection->getReturnType() ?? (\PHP_VERSION_ID >= 80100 ? $reflection->getTentativeReturnType() : null); + } else { + $type = $reflection instanceof \ReflectionFunctionAbstract ? $reflection->getReturnType() : $reflection->getType(); + } + return $type ? self::fromReflectionType($type, $reflection, \true) : null; + } + private static function fromReflectionType(\ReflectionType $type, $of, bool $asObject) + { + if ($type instanceof \ReflectionNamedType) { + $name = self::resolve($type->getName(), $of); + return $asObject ? new self($type->allowsNull() && $name !== 'mixed' ? [$name, 'null'] : [$name]) : $name; + } elseif ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) { + return new self(\array_map(function ($t) use($of) { + return self::fromReflectionType($t, $of, \false); + }, $type->getTypes()), $type instanceof \ReflectionUnionType ? '|' : '&'); + } else { + throw new Nette\InvalidStateException('Unexpected type of ' . Reflection::toString($of)); + } + } + /** + * Creates the Type object according to the text notation. + */ + public static function fromString(string $type) : self + { + if (!Validators::isTypeDeclaration($type)) { + throw new Nette\InvalidArgumentException("Invalid type '{$type}'."); + } + if ($type[0] === '?') { + return new self([\substr($type, 1), 'null']); + } + $unions = []; + foreach (\explode('|', $type) as $part) { + $part = \explode('&', \trim($part, '()')); + $unions[] = \count($part) === 1 ? $part[0] : new self($part, '&'); + } + return \count($unions) === 1 && $unions[0] instanceof self ? $unions[0] : new self($unions); + } + /** + * Resolves 'self', 'static' and 'parent' to the actual class name. + * @param \ReflectionFunctionAbstract|\ReflectionParameter|\ReflectionProperty $of + */ + public static function resolve(string $type, $of) : string + { + $lower = \strtolower($type); + if ($of instanceof \ReflectionFunction) { + return $type; + } elseif ($lower === 'self' || $lower === 'static') { + return $of->getDeclaringClass()->name; + } elseif ($lower === 'parent' && $of->getDeclaringClass()->getParentClass()) { + return $of->getDeclaringClass()->getParentClass()->name; + } else { + return $type; + } + } + private function __construct(array $types, string $kind = '|') + { + $o = \array_search('null', $types, \true); + if ($o !== \false) { + // null as last + \array_splice($types, $o, 1); + $types[] = 'null'; + } + $this->types = $types; + $this->simple = \is_string($types[0]) && ($types[1] ?? 'null') === 'null'; + $this->kind = \count($types) > 1 ? $kind : ''; + } + public function __toString() : string + { + $multi = \count($this->types) > 1; + if ($this->simple) { + return ($multi ? '?' : '') . $this->types[0]; + } + $res = []; + foreach ($this->types as $type) { + $res[] = $type instanceof self && $multi ? "({$type})" : $type; + } + return \implode($this->kind, $res); + } + /** + * Returns the array of subtypes that make up the compound type as strings. + * @return array + */ + public function getNames() : array + { + return \array_map(function ($t) { + return $t instanceof self ? $t->getNames() : $t; + }, $this->types); + } + /** + * Returns the array of subtypes that make up the compound type as Type objects: + * @return self[] + */ + public function getTypes() : array + { + return \array_map(function ($t) { + return $t instanceof self ? $t : new self([$t]); + }, $this->types); + } + /** + * Returns the type name for simple types, otherwise null. + */ + public function getSingleName() : ?string + { + return $this->simple ? $this->types[0] : null; + } + /** + * Returns true whether it is a union type. + */ + public function isUnion() : bool + { + return $this->kind === '|'; + } + /** + * Returns true whether it is an intersection type. + */ + public function isIntersection() : bool + { + return $this->kind === '&'; + } + /** + * Returns true whether it is a simple type. Single nullable types are also considered to be simple types. + */ + public function isSimple() : bool + { + return $this->simple; + } + /** @deprecated use isSimple() */ + public function isSingle() : bool + { + return $this->simple; + } + /** + * Returns true whether the type is both a simple and a PHP built-in type. + */ + public function isBuiltin() : bool + { + return $this->simple && Validators::isBuiltinType($this->types[0]); + } + /** + * Returns true whether the type is both a simple and a class name. + */ + public function isClass() : bool + { + return $this->simple && !Validators::isBuiltinType($this->types[0]); + } + /** + * Determines if type is special class name self/parent/static. + */ + public function isClassKeyword() : bool + { + return $this->simple && Validators::isClassKeyword($this->types[0]); + } + /** + * Verifies type compatibility. For example, it checks if a value of a certain type could be passed as a parameter. + */ + public function allows(string $subtype) : bool + { + if ($this->types === ['mixed']) { + return \true; + } + $subtype = self::fromString($subtype); + return $subtype->isUnion() ? Arrays::every($subtype->types, function ($t) { + return $this->allows2($t instanceof self ? $t->types : [$t]); + }) : $this->allows2($subtype->types); + } + private function allows2(array $subtypes) : bool + { + return $this->isUnion() ? Arrays::some($this->types, function ($t) use($subtypes) { + return $this->allows3($t instanceof self ? $t->types : [$t], $subtypes); + }) : $this->allows3($this->types, $subtypes); + } + private function allows3(array $types, array $subtypes) : bool + { + return Arrays::every($types, function ($type) use($subtypes) { + $builtin = Validators::isBuiltinType($type); + return Arrays::some($subtypes, function ($subtype) use($type, $builtin) { + return $builtin ? \strcasecmp($type, $subtype) === 0 : \is_a($subtype, $type, \true); + }); + }); + } +} diff --git a/vendor/nette/utils/src/Utils/Validators.php b/vendor/nette/utils/src/Utils/Validators.php new file mode 100644 index 00000000000..47900698074 --- /dev/null +++ b/vendor/nette/utils/src/Utils/Validators.php @@ -0,0 +1,340 @@ + 1, 'int' => 1, 'float' => 1, 'bool' => 1, 'array' => 1, 'object' => 1, 'callable' => 1, 'iterable' => 1, 'void' => 1, 'null' => 1, 'mixed' => 1, 'false' => 1, 'never' => 1, 'true' => 1]; + /** @var array */ + protected static $validators = [ + // PHP types + 'array' => 'is_array', + 'bool' => 'is_bool', + 'boolean' => 'is_bool', + 'float' => 'is_float', + 'int' => 'is_int', + 'integer' => 'is_int', + 'null' => 'is_null', + 'object' => 'is_object', + 'resource' => 'is_resource', + 'scalar' => 'is_scalar', + 'string' => 'is_string', + // pseudo-types + 'callable' => [self::class, 'isCallable'], + 'iterable' => 'is_iterable', + 'list' => [Arrays::class, 'isList'], + 'mixed' => [self::class, 'isMixed'], + 'none' => [self::class, 'isNone'], + 'number' => [self::class, 'isNumber'], + 'numeric' => [self::class, 'isNumeric'], + 'numericint' => [self::class, 'isNumericInt'], + // string patterns + 'alnum' => 'ctype_alnum', + 'alpha' => 'ctype_alpha', + 'digit' => 'ctype_digit', + 'lower' => 'ctype_lower', + 'pattern' => null, + 'space' => 'ctype_space', + 'unicode' => [self::class, 'isUnicode'], + 'upper' => 'ctype_upper', + 'xdigit' => 'ctype_xdigit', + // syntax validation + 'email' => [self::class, 'isEmail'], + 'identifier' => [self::class, 'isPhpIdentifier'], + 'uri' => [self::class, 'isUri'], + 'url' => [self::class, 'isUrl'], + // environment validation + 'class' => 'class_exists', + 'interface' => 'interface_exists', + 'directory' => 'is_dir', + 'file' => 'is_file', + 'type' => [self::class, 'isType'], + ]; + /** @var array */ + protected static $counters = ['string' => 'strlen', 'unicode' => [Strings::class, 'length'], 'array' => 'count', 'list' => 'count', 'alnum' => 'strlen', 'alpha' => 'strlen', 'digit' => 'strlen', 'lower' => 'strlen', 'space' => 'strlen', 'upper' => 'strlen', 'xdigit' => 'strlen']; + /** + * Verifies that the value is of expected types separated by pipe. + * @param mixed $value + * @throws AssertionException + */ + public static function assert($value, string $expected, string $label = 'variable') : void + { + if (!static::is($value, $expected)) { + $expected = \str_replace(['|', ':'], [' or ', ' in range '], $expected); + $translate = ['boolean' => 'bool', 'integer' => 'int', 'double' => 'float', 'NULL' => 'null']; + $type = $translate[\gettype($value)] ?? \gettype($value); + if (\is_int($value) || \is_float($value) || \is_string($value) && \strlen($value) < 40) { + $type .= ' ' . \var_export($value, \true); + } elseif (\is_object($value)) { + $type .= ' ' . \get_class($value); + } + throw new AssertionException("The {$label} expects to be {$expected}, {$type} given."); + } + } + /** + * Verifies that element $key in array is of expected types separated by pipe. + * @param mixed[] $array + * @param int|string $key + * @throws AssertionException + */ + public static function assertField(array $array, $key, ?string $expected = null, string $label = "item '%' in array") : void + { + if (!\array_key_exists($key, $array)) { + throw new AssertionException('Missing ' . \str_replace('%', $key, $label) . '.'); + } elseif ($expected) { + static::assert($array[$key], $expected, \str_replace('%', $key, $label)); + } + } + /** + * Verifies that the value is of expected types separated by pipe. + * @param mixed $value + */ + public static function is($value, string $expected) : bool + { + foreach (\explode('|', $expected) as $item) { + if (\substr($item, -2) === '[]') { + if (\is_iterable($value) && self::everyIs($value, \substr($item, 0, -2))) { + return \true; + } + continue; + } elseif (\substr($item, 0, 1) === '?') { + $item = \substr($item, 1); + if ($value === null) { + return \true; + } + } + [$type] = $item = \explode(':', $item, 2); + if (isset(static::$validators[$type])) { + try { + if (!static::$validators[$type]($value)) { + continue; + } + } catch (\TypeError $e) { + continue; + } + } elseif ($type === 'pattern') { + if (Strings::match($value, '|^' . ($item[1] ?? '') . '$|D')) { + return \true; + } + continue; + } elseif (!$value instanceof $type) { + continue; + } + if (isset($item[1])) { + $length = $value; + if (isset(static::$counters[$type])) { + $length = static::$counters[$type]($value); + } + $range = \explode('..', $item[1]); + if (!isset($range[1])) { + $range[1] = $range[0]; + } + if ($range[0] !== '' && $length < $range[0] || $range[1] !== '' && $length > $range[1]) { + continue; + } + } + return \true; + } + return \false; + } + /** + * Finds whether all values are of expected types separated by pipe. + * @param mixed[] $values + */ + public static function everyIs(iterable $values, string $expected) : bool + { + foreach ($values as $value) { + if (!static::is($value, $expected)) { + return \false; + } + } + return \true; + } + /** + * Checks if the value is an integer or a float. + * @param mixed $value + */ + public static function isNumber($value) : bool + { + return \is_int($value) || \is_float($value); + } + /** + * Checks if the value is an integer or a integer written in a string. + * @param mixed $value + */ + public static function isNumericInt($value) : bool + { + return \is_int($value) || \is_string($value) && \preg_match('#^[+-]?[0-9]+$#D', $value); + } + /** + * Checks if the value is a number or a number written in a string. + * @param mixed $value + */ + public static function isNumeric($value) : bool + { + return \is_float($value) || \is_int($value) || \is_string($value) && \preg_match('#^[+-]?([0-9]++\\.?[0-9]*|\\.[0-9]+)$#D', $value); + } + /** + * Checks if the value is a syntactically correct callback. + * @param mixed $value + */ + public static function isCallable($value) : bool + { + return $value && \is_callable($value, \true); + } + /** + * Checks if the value is a valid UTF-8 string. + * @param mixed $value + */ + public static function isUnicode($value) : bool + { + return \is_string($value) && \preg_match('##u', $value); + } + /** + * Checks if the value is 0, '', false or null. + * @param mixed $value + */ + public static function isNone($value) : bool + { + return $value == null; + // intentionally == + } + /** @internal */ + public static function isMixed() : bool + { + return \true; + } + /** + * Checks if a variable is a zero-based integer indexed array. + * @param mixed $value + * @deprecated use Nette\Utils\Arrays::isList + */ + public static function isList($value) : bool + { + return Arrays::isList($value); + } + /** + * Checks if the value is in the given range [min, max], where the upper or lower limit can be omitted (null). + * Numbers, strings and DateTime objects can be compared. + * @param mixed $value + */ + public static function isInRange($value, array $range) : bool + { + if ($value === null || !(isset($range[0]) || isset($range[1]))) { + return \false; + } + $limit = $range[0] ?? $range[1]; + if (\is_string($limit)) { + $value = (string) $value; + } elseif ($limit instanceof \DateTimeInterface) { + if (!$value instanceof \DateTimeInterface) { + return \false; + } + } elseif (\is_numeric($value)) { + $value *= 1; + } else { + return \false; + } + return (!isset($range[0]) || $value >= $range[0]) && (!isset($range[1]) || $value <= $range[1]); + } + /** + * Checks if the value is a valid email address. It does not verify that the domain actually exists, only the syntax is verified. + */ + public static function isEmail(string $value) : bool + { + $atom = "[-a-z0-9!#\$%&'*+/=?^_`{|}~]"; + // RFC 5322 unquoted characters in local-part + $alpha = "a-z\x80-\xff"; + // superset of IDN + return (bool) \preg_match(<< \\? (? [a-zA-Z_\x7f-\xff][\w\x7f-\xff]*) (\\ (?&name))* ) | + (? (?&type) (& (?&type))+ ) | + (? (?&type) | \( (?&intersection) \) ) (\| (?&upart))+ + )$~xAD +XX +, $type); + } +} diff --git a/vendor/nette/utils/src/Utils/exceptions.php b/vendor/nette/utils/src/Utils/exceptions.php new file mode 100644 index 00000000000..79fe208439d --- /dev/null +++ b/vendor/nette/utils/src/Utils/exceptions.php @@ -0,0 +1,40 @@ + 'Internal error', \PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted', \PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted', \PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data', \PREG_BAD_UTF8_OFFSET_ERROR => 'Offset didn\'t correspond to the begin of a valid UTF-8 code point', 6 => 'Failed due to limited JIT stack space']; +} +/** + * The exception that indicates assertion error. + */ +class AssertionException extends \Exception +{ +} diff --git a/vendor/nette/utils/src/compatibility.php b/vendor/nette/utils/src/compatibility.php new file mode 100644 index 00000000000..baeeeb5e697 --- /dev/null +++ b/vendor/nette/utils/src/compatibility.php @@ -0,0 +1,28 @@ +=8.0.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Cache\\": "src\/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + } +} \ No newline at end of file diff --git a/vendor/psr/cache/src/CacheException.php b/vendor/psr/cache/src/CacheException.php new file mode 100644 index 00000000000..dba5d064e11 --- /dev/null +++ b/vendor/psr/cache/src/CacheException.php @@ -0,0 +1,10 @@ +=7.4.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Container\\": "src\/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + } +} \ No newline at end of file diff --git a/vendor/psr/container/src/ContainerExceptionInterface.php b/vendor/psr/container/src/ContainerExceptionInterface.php new file mode 100644 index 00000000000..92291639e7d --- /dev/null +++ b/vendor/psr/container/src/ContainerExceptionInterface.php @@ -0,0 +1,11 @@ +logger = $logger; + } + + public function doSomething() + { + if ($this->logger) { + $this->logger->info('Doing work'); + } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } + + // do something useful + } +} +``` + +You can then pick one of the implementations of the interface to get a logger. + +If you want to implement the interface, you can require this package and +implement `Psr\Log\LoggerInterface` in your code. Please read the +[specification text](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md) +for details. diff --git a/vendor/psr/log/composer.json b/vendor/psr/log/composer.json new file mode 100644 index 00000000000..344ddba6b14 --- /dev/null +++ b/vendor/psr/log/composer.json @@ -0,0 +1,30 @@ +{ + "name": "psr\/log", + "description": "Common interface for logging libraries", + "keywords": [ + "psr", + "psr-3", + "log" + ], + "homepage": "https:\/\/github.com\/php-fig\/log", + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\Log\\": "src" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + } +} \ No newline at end of file diff --git a/vendor/psr/log/src/AbstractLogger.php b/vendor/psr/log/src/AbstractLogger.php new file mode 100644 index 00000000000..313a524f5f3 --- /dev/null +++ b/vendor/psr/log/src/AbstractLogger.php @@ -0,0 +1,15 @@ +logger = $logger; + } +} diff --git a/vendor/psr/log/src/LoggerInterface.php b/vendor/psr/log/src/LoggerInterface.php new file mode 100644 index 00000000000..936bfd108e7 --- /dev/null +++ b/vendor/psr/log/src/LoggerInterface.php @@ -0,0 +1,117 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function alert($message, array $context = []) : void + { + $this->log(LogLevel::ALERT, $message, $context); + } + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function critical($message, array $context = []) : void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function error($message, array $context = []) : void + { + $this->log(LogLevel::ERROR, $message, $context); + } + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function warning($message, array $context = []) : void + { + $this->log(LogLevel::WARNING, $message, $context); + } + /** + * Normal but significant events. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function notice($message, array $context = []) : void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function info($message, array $context = []) : void + { + $this->log(LogLevel::INFO, $message, $context); + } + /** + * Detailed debug information. + * + * @param string|\Stringable $message + * @param array $context + * + * @return void + */ + public function debug($message, array $context = []) : void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public abstract function log($level, $message, array $context = []) : void; +} diff --git a/vendor/psr/log/src/NullLogger.php b/vendor/psr/log/src/NullLogger.php new file mode 100644 index 00000000000..fad18d1acea --- /dev/null +++ b/vendor/psr/log/src/NullLogger.php @@ -0,0 +1,30 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string|\Stringable $message + * @param array $context + * + * @return void + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, $message, array $context = []) : void + { + // noop + } +} diff --git a/vendor/psr/simple-cache/LICENSE.md b/vendor/psr/simple-cache/LICENSE.md new file mode 100644 index 00000000000..e49a7c85a10 --- /dev/null +++ b/vendor/psr/simple-cache/LICENSE.md @@ -0,0 +1,21 @@ +# The MIT License (MIT) + +Copyright (c) 2016 PHP Framework Interoperability Group + +> 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. diff --git a/vendor/psr/simple-cache/README.md b/vendor/psr/simple-cache/README.md new file mode 100644 index 00000000000..43641d175cc --- /dev/null +++ b/vendor/psr/simple-cache/README.md @@ -0,0 +1,8 @@ +PHP FIG Simple Cache PSR +======================== + +This repository holds all interfaces related to PSR-16. + +Note that this is not a cache implementation of its own. It is merely an interface that describes a cache implementation. See [the specification](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-16-simple-cache.md) for more details. + +You can find implementations of the specification by looking for packages providing the [psr/simple-cache-implementation](https://packagist.org/providers/psr/simple-cache-implementation) virtual package. diff --git a/vendor/psr/simple-cache/composer.json b/vendor/psr/simple-cache/composer.json new file mode 100644 index 00000000000..3102e13e713 --- /dev/null +++ b/vendor/psr/simple-cache/composer.json @@ -0,0 +1,31 @@ +{ + "name": "psr\/simple-cache", + "description": "Common interfaces for simple caching", + "keywords": [ + "psr", + "psr-16", + "cache", + "simple-cache", + "caching" + ], + "license": "MIT", + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https:\/\/www.php-fig.org\/" + } + ], + "require": { + "php": ">=8.0.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\Psr\\SimpleCache\\": "src\/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "3.0.x-dev" + } + } +} \ No newline at end of file diff --git a/vendor/psr/simple-cache/src/CacheException.php b/vendor/psr/simple-cache/src/CacheException.php new file mode 100644 index 00000000000..1afab20fde2 --- /dev/null +++ b/vendor/psr/simple-cache/src/CacheException.php @@ -0,0 +1,10 @@ + $keys A list of keys that can be obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * + * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + */ + public function getMultiple(iterable $keys, $default = null) : iterable; + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * @param iterable $values A list of key => value pairs for a multiple-set operation. + * @param null|int|\DateInterval $ttl Optional. The TTL value of this item. If no value is sent and + * the driver supports TTL then the library may set a default value + * for it or let the driver take care of that. + * + * @return bool True on success and false on failure. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $values is neither an array nor a Traversable, + * or if any of the $values are not a legal value. + */ + public function setMultiple(iterable $values, $ttl = null) : bool; + /** + * Deletes multiple cache items in a single operation. + * + * @param iterable $keys A list of string-based keys to be deleted. + * + * @return bool True if the items were successfully removed. False if there was an error. + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if $keys is neither an array nor a Traversable, + * or if any of the $keys are not a legal value. + */ + public function deleteMultiple(iterable $keys) : bool; + /** + * Determines whether an item is present in the cache. + * + * NOTE: It is recommended that has() is only to be used for cache warming type purposes + * and not to be used within your live applications operations for get/set, as this method + * is subject to a race condition where your has() will return true and immediately after, + * another script can remove it making the state of your app out of date. + * + * @param string $key The cache item key. + * + * @return bool + * + * @throws \Psr\SimpleCache\InvalidArgumentException + * MUST be thrown if the $key string is not a legal value. + */ + public function has(string $key) : bool; +} diff --git a/vendor/psr/simple-cache/src/InvalidArgumentException.php b/vendor/psr/simple-cache/src/InvalidArgumentException.php new file mode 100644 index 00000000000..374c5fbc3da --- /dev/null +++ b/vendor/psr/simple-cache/src/InvalidArgumentException.php @@ -0,0 +1,13 @@ + Contains no other changes, so it's actually fully compatible with the v0.6.0 release. + +## 0.6.0 (2019-07-04) + +* Feature / BC break: Add support for `getMultiple()`, `setMultiple()`, `deleteMultiple()`, `clear()` and `has()` + supporting multiple cache items (inspired by PSR-16). + (#32 by @krlv and #37 by @clue) + +* Documentation for TTL precision with millisecond accuracy or below and + use high-resolution timer for cache TTL on PHP 7.3+. + (#35 and #38 by @clue) + +* Improve API documentation and allow legacy HHVM to fail in Travis CI config. + (#34 and #36 by @clue) + +* Prefix all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#31 by @WyriHaximus) + +## 0.5.0 (2018-06-25) + +* Improve documentation by describing what is expected of a class implementing `CacheInterface`. + (#21, #22, #23, #27 by @WyriHaximus) + +* Implemented (optional) Least Recently Used (LRU) cache algorithm for `ArrayCache`. + (#26 by @clue) + +* Added support for cache expiration (TTL). + (#29 by @clue and @WyriHaximus) + +* Renamed `remove` to `delete` making it more in line with `PSR-16`. + (#30 by @clue) + +## 0.4.2 (2017-12-20) + +* Improve documentation with usage and installation instructions + (#10 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` and + add forward compatibility with PHPUnit 5 and PHPUnit 6 and + sanitize Composer autoload paths + (#14 by @shaunbramley and #12 and #18 by @clue) + +## 0.4.1 (2016-02-25) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#9 by @clue) +* Adjust compatibility to 5.3 (#7 by @clue) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.0 (2013-04-14) + +* Version bump + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS diff --git a/vendor/react/cache/LICENSE b/vendor/react/cache/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/cache/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/cache/README.md b/vendor/react/cache/README.md new file mode 100644 index 00000000000..7a86be9cf3e --- /dev/null +++ b/vendor/react/cache/README.md @@ -0,0 +1,367 @@ +# Cache + +[![CI status](https://github.com/reactphp/cache/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/cache/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/cache?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/cache) + +Async, [Promise](https://github.com/reactphp/promise)-based cache interface +for [ReactPHP](https://reactphp.org/). + +The cache component provides a +[Promise](https://github.com/reactphp/promise)-based +[`CacheInterface`](#cacheinterface) and an in-memory [`ArrayCache`](#arraycache) +implementation of that. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. +This project is heavily inspired by +[PSR-16: Common Interface for Caching Libraries](https://www.php-fig.org/psr/psr-16/), +but uses an interface more suited for async, non-blocking applications. + +**Table of Contents** + +* [Usage](#usage) + * [CacheInterface](#cacheinterface) + * [get()](#get) + * [set()](#set) + * [delete()](#delete) + * [getMultiple()](#getmultiple) + * [setMultiple()](#setmultiple) + * [deleteMultiple()](#deletemultiple) + * [clear()](#clear) + * [has()](#has) + * [ArrayCache](#arraycache) +* [Common usage](#common-usage) + * [Fallback get](#fallback-get) + * [Fallback-get-and-set](#fallback-get-and-set) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Usage + +### CacheInterface + +The `CacheInterface` describes the main interface of this component. +This allows consumers to type hint against the interface and third parties to +provide alternate implementations. + +#### get() + +The `get(string $key, mixed $default = null): PromiseInterface` method can be used to +retrieve an item from the cache. + +This method will resolve with the cached value on success or with the +given `$default` value when no item can be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache + ->get('foo') + ->then('var_dump'); +``` + +This example fetches the value of the key `foo` and passes it to the +`var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +#### set() + +The `set(string $key, mixed $value, ?float $ttl = null): PromiseInterface` method can be used to +store an item in the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for this cache item. If this parameter is omitted (or `null`), the item +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache item results in a cache miss, +see also [`get()`](#get). + +```php +$cache->set('foo', 'bar', 60); +``` + +This example eventually sets the value of the key `foo` to `bar`. If it +already exists, it is overridden. + +This interface does not enforce any particular TTL resolution, so special +care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Cache implementations SHOULD work on a +best effort basis and SHOULD provide at least second accuracy unless +otherwise noted. Many existing cache implementations are known to provide +microsecond or millisecond accuracy, but it's generally not recommended +to rely on this high precision. + +This interface suggests that cache implementations SHOULD use a monotonic +time source if available. Given that a monotonic time source is only +available as of PHP 7.3 by default, cache implementations MAY fall back +to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s and then +adjust your system time forward by 20s, the cache item SHOULD still +expire in 30s. + +#### delete() + +The `delete(string $key): PromiseInterface` method can be used to +delete an item from the cache. + +This method will resolve with `true` on success or `false` when an error +occurs. When no item for `$key` is found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->delete('foo'); +``` + +This example eventually deletes the key `foo` from the cache. As with +`set()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### getMultiple() + +The `getMultiple(string[] $keys, mixed $default = null): PromiseInterface` method can be used to +retrieve multiple cache items by their unique keys. + +This method will resolve with an array of cached values on success or with the +given `$default` value when an item can not be found or when an error occurs. +Similarly, an expired cache item (once the time-to-live is expired) is +considered a cache miss. + +```php +$cache->getMultiple(array('name', 'age'))->then(function (array $values) { + $name = $values['name'] ?? 'User'; + $age = $values['age'] ?? 'n/a'; + + echo $name . ' is ' . $age . PHP_EOL; +}); +``` + +This example fetches the cache items for the `name` and `age` keys and +prints some example output. You can use any of the composition provided +by [promises](https://github.com/reactphp/promise). + +#### setMultiple() + +The `setMultiple(array $values, ?float $ttl = null): PromiseInterface` method can be used to +persist a set of key => value pairs in the cache, with an optional TTL. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to store +it, it may take a while. + +The optional `$ttl` parameter sets the maximum time-to-live in seconds +for these cache items. If this parameter is omitted (or `null`), these items +will stay in the cache for as long as the underlying implementation +supports. Trying to access an expired cache items results in a cache miss, +see also [`getMultiple()`](#getmultiple). + +```php +$cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); +``` + +This example eventually sets the list of values - the key `foo` to `1` value +and the key `bar` to `2`. If some of the keys already exist, they are overridden. + +#### deleteMultiple() + +The `setMultiple(string[] $keys): PromiseInterface` method can be used to +delete multiple cache items in a single operation. + +This method will resolve with `true` on success or `false` when an error +occurs. When no items for `$keys` are found in the cache, it also resolves +to `true`. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->deleteMultiple(array('foo', 'bar, 'baz')); +``` + +This example eventually deletes keys `foo`, `bar` and `baz` from the cache. +As with `setMultiple()`, this may not happen instantly and a promise is returned to +provide guarantees whether or not the item has been removed from cache. + +#### clear() + +The `clear(): PromiseInterface` method can be used to +wipe clean the entire cache. + +This method will resolve with `true` on success or `false` when an error +occurs. If the cache implementation has to go over the network to +delete it, it may take a while. + +```php +$cache->clear(); +``` + +This example eventually deletes all keys from the cache. As with `deleteMultiple()`, +this may not happen instantly and a promise is returned to provide guarantees +whether or not all the items have been removed from cache. + +#### has() + +The `has(string $key): PromiseInterface` method can be used to +determine whether an item is present in the cache. + +This method will resolve with `true` on success or `false` when no item can be found +or when an error occurs. Similarly, an expired cache item (once the time-to-live +is expired) is considered a cache miss. + +```php +$cache + ->has('foo') + ->then('var_dump'); +``` + +This example checks if the value of the key `foo` is set in the cache and passes +the result to the `var_dump` function. You can use any of the composition provided by +[promises](https://github.com/reactphp/promise). + +NOTE: It is recommended that has() is only to be used for cache warming type purposes +and not to be used within your live applications operations for get/set, as this method +is subject to a race condition where your has() will return true and immediately after, +another script can remove it making the state of your app out of date. + +### ArrayCache + +The `ArrayCache` provides an in-memory implementation of the [`CacheInterface`](#cacheinterface). + +```php +$cache = new ArrayCache(); + +$cache->set('foo', 'bar'); +``` + +Its constructor accepts an optional `?int $limit` parameter to limit the +maximum number of entries to store in the LRU cache. If you add more +entries to this instance, it will automatically take care of removing +the one that was least recently used (LRU). + +For example, this snippet will overwrite the first value and only store +the last two entries: + +```php +$cache = new ArrayCache(2); + +$cache->set('foo', '1'); +$cache->set('bar', '2'); +$cache->set('baz', '3'); +``` + +This cache implementation is known to rely on wall-clock time to schedule +future cache expiration times when using any version before PHP 7.3, +because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you store a cache item with a TTL of 30s on PHP < 7.3 +and then adjust your system time forward by 20s, the cache item may +expire in 10s. See also [`set()`](#set) for more details. + +## Common usage + +### Fallback get + +A common use case of caches is to attempt fetching a cached value and as a +fallback retrieve it from the original data source if not found. Here is an +example of that: + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return getFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); +``` + +First an attempt is made to retrieve the value of `foo`. A callback function is +registered that will call `getFooFromDb` when the resulting value is null. +`getFooFromDb` is a function (can be any PHP callable) that will be called if the +key does not exist in the cache. + +`getFooFromDb` can handle the missing key by returning a promise for the +actual value from the database (or any other data source). As a result, this +chain will correctly fall back, and provide the value in both cases. + +### Fallback get and set + +To expand on the fallback get example, often you want to set the value on the +cache after fetching it from the data source. + +```php +$cache + ->get('foo') + ->then(function ($result) { + if ($result === null) { + return $this->getAndCacheFooFromDb(); + } + + return $result; + }) + ->then('var_dump'); + +public function getAndCacheFooFromDb() +{ + return $this->db + ->get('foo') + ->then(array($this, 'cacheFooFromDb')); +} + +public function cacheFooFromDb($foo) +{ + $this->cache->set('foo', $foo); + + return $foo; +} +``` + +By using chaining you can easily conditionally cache the value if it is +fetched from the database. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/cache:^1.2 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use PHP 7+* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/vendor/react/cache/composer.json b/vendor/react/cache/composer.json new file mode 100644 index 00000000000..c8748d9d902 --- /dev/null +++ b/vendor/react/cache/composer.json @@ -0,0 +1,50 @@ +{ + "name": "react\/cache", + "description": "Async, Promise-based cache interface for ReactPHP", + "keywords": [ + "cache", + "caching", + "promise", + "ReactPHP" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react\/promise": "^3.0 || ^2.0 || ^1.1" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Cache\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\Cache\\": "tests\/" + } + } +} \ No newline at end of file diff --git a/vendor/react/cache/src/ArrayCache.php b/vendor/react/cache/src/ArrayCache.php new file mode 100644 index 00000000000..3e51bbb6cde --- /dev/null +++ b/vendor/react/cache/src/ArrayCache.php @@ -0,0 +1,153 @@ +set('foo', 'bar'); + * ``` + * + * Its constructor accepts an optional `?int $limit` parameter to limit the + * maximum number of entries to store in the LRU cache. If you add more + * entries to this instance, it will automatically take care of removing + * the one that was least recently used (LRU). + * + * For example, this snippet will overwrite the first value and only store + * the last two entries: + * + * ```php + * $cache = new ArrayCache(2); + * + * $cache->set('foo', '1'); + * $cache->set('bar', '2'); + * $cache->set('baz', '3'); + * ``` + * + * This cache implementation is known to rely on wall-clock time to schedule + * future cache expiration times when using any version before PHP 7.3, + * because a monotonic time source is only available as of PHP 7.3 (`hrtime()`). + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s on PHP < 7.3 + * and then adjust your system time forward by 20s, the cache item may + * expire in 10s. See also [`set()`](#set) for more details. + * + * @param int|null $limit maximum number of entries to store in the LRU cache + */ + public function __construct($limit = null) + { + $this->limit = $limit; + // prefer high-resolution timer, available as of PHP 7.3+ + $this->supportsHighResolution = \function_exists('hrtime'); + } + public function get($key, $default = null) + { + // delete key if it is already expired => below will detect this as a cache miss + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve($default); + } + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + return Promise\resolve($value); + } + public function set($key, $value, $ttl = null) + { + // unset before setting to ensure this entry will be added to end of array (LRU info) + unset($this->data[$key]); + $this->data[$key] = $value; + // sort expiration times if TTL is given (first will expire first) + unset($this->expires[$key]); + if ($ttl !== null) { + $this->expires[$key] = $this->now() + $ttl; + \asort($this->expires); + } + // ensure size limit is not exceeded or remove first entry from array + if ($this->limit !== null && \count($this->data) > $this->limit) { + // first try to check if there's any expired entry + // expiration times are sorted, so we can simply look at the first one + \reset($this->expires); + $key = \key($this->expires); + // check to see if the first in the list of expiring keys is already expired + // if the first key is not expired, we have to overwrite by using LRU info + if ($key === null || $this->now() - $this->expires[$key] < 0) { + \reset($this->data); + $key = \key($this->data); + } + unset($this->data[$key], $this->expires[$key]); + } + return Promise\resolve(\true); + } + public function delete($key) + { + unset($this->data[$key], $this->expires[$key]); + return Promise\resolve(\true); + } + public function getMultiple(array $keys, $default = null) + { + $values = array(); + foreach ($keys as $key) { + $values[$key] = $this->get($key, $default); + } + return Promise\all($values); + } + public function setMultiple(array $values, $ttl = null) + { + foreach ($values as $key => $value) { + $this->set($key, $value, $ttl); + } + return Promise\resolve(\true); + } + public function deleteMultiple(array $keys) + { + foreach ($keys as $key) { + unset($this->data[$key], $this->expires[$key]); + } + return Promise\resolve(\true); + } + public function clear() + { + $this->data = array(); + $this->expires = array(); + return Promise\resolve(\true); + } + public function has($key) + { + // delete key if it is already expired + if (isset($this->expires[$key]) && $this->now() - $this->expires[$key] > 0) { + unset($this->data[$key], $this->expires[$key]); + } + if (!\array_key_exists($key, $this->data)) { + return Promise\resolve(\false); + } + // remove and append to end of array to keep track of LRU info + $value = $this->data[$key]; + unset($this->data[$key]); + $this->data[$key] = $value; + return Promise\resolve(\true); + } + /** + * @return float + */ + private function now() + { + return $this->supportsHighResolution ? \hrtime(\true) * 1.0E-9 : \microtime(\true); + } +} diff --git a/vendor/react/cache/src/CacheInterface.php b/vendor/react/cache/src/CacheInterface.php new file mode 100644 index 00000000000..a26a3432b68 --- /dev/null +++ b/vendor/react/cache/src/CacheInterface.php @@ -0,0 +1,186 @@ +get('foo') + * ->then('var_dump'); + * ``` + * + * This example fetches the value of the key `foo` and passes it to the + * `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * @param string $key + * @param mixed $default Default value to return for cache miss or null if not given. + * @return PromiseInterface + */ + public function get($key, $default = null); + /** + * Stores an item in the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for this cache item. If this parameter is omitted (or `null`), the item + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache item results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->set('foo', 'bar', 60); + * ``` + * + * This example eventually sets the value of the key `foo` to `bar`. If it + * already exists, it is overridden. + * + * This interface does not enforce any particular TTL resolution, so special + * care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Cache implementations SHOULD work on a + * best effort basis and SHOULD provide at least second accuracy unless + * otherwise noted. Many existing cache implementations are known to provide + * microsecond or millisecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * This interface suggests that cache implementations SHOULD use a monotonic + * time source if available. Given that a monotonic time source is only + * available as of PHP 7.3 by default, cache implementations MAY fall back + * to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you store a cache item with a TTL of 30s and then + * adjust your system time forward by 20s, the cache item SHOULD still + * expire in 30s. + * + * @param string $key + * @param mixed $value + * @param ?float $ttl + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function set($key, $value, $ttl = null); + /** + * Deletes an item from the cache. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. When no item for `$key` is found in the cache, it also resolves + * to `true`. If the cache implementation has to go over the network to + * delete it, it may take a while. + * + * ```php + * $cache->delete('foo'); + * ``` + * + * This example eventually deletes the key `foo` from the cache. As with + * `set()`, this may not happen instantly and a promise is returned to + * provide guarantees whether or not the item has been removed from cache. + * + * @param string $key + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function delete($key); + /** + * Retrieves multiple cache items by their unique keys. + * + * This method will resolve with an array of cached values on success or with the + * given `$default` value when an item can not be found or when an error occurs. + * Similarly, an expired cache item (once the time-to-live is expired) is + * considered a cache miss. + * + * ```php + * $cache->getMultiple(array('name', 'age'))->then(function (array $values) { + * $name = $values['name'] ?? 'User'; + * $age = $values['age'] ?? 'n/a'; + * + * echo $name . ' is ' . $age . PHP_EOL; + * }); + * ``` + * + * This example fetches the cache items for the `name` and `age` keys and + * prints some example output. You can use any of the composition provided + * by [promises](https://github.com/reactphp/promise). + * + * @param string[] $keys A list of keys that can obtained in a single operation. + * @param mixed $default Default value to return for keys that do not exist. + * @return PromiseInterface Returns a promise which resolves to an `array` of cached values + */ + public function getMultiple(array $keys, $default = null); + /** + * Persists a set of key => value pairs in the cache, with an optional TTL. + * + * This method will resolve with `true` on success or `false` when an error + * occurs. If the cache implementation has to go over the network to store + * it, it may take a while. + * + * The optional `$ttl` parameter sets the maximum time-to-live in seconds + * for these cache items. If this parameter is omitted (or `null`), these items + * will stay in the cache for as long as the underlying implementation + * supports. Trying to access an expired cache items results in a cache miss, + * see also [`get()`](#get). + * + * ```php + * $cache->setMultiple(array('foo' => 1, 'bar' => 2), 60); + * ``` + * + * This example eventually sets the list of values - the key `foo` to 1 value + * and the key `bar` to 2. If some of the keys already exist, they are overridden. + * + * @param array $values A list of key => value pairs for a multiple-set operation. + * @param ?float $ttl Optional. The TTL value of this item. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function setMultiple(array $values, $ttl = null); + /** + * Deletes multiple cache items in a single operation. + * + * @param string[] $keys A list of string-based keys to be deleted. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function deleteMultiple(array $keys); + /** + * Wipes clean the entire cache. + * + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function clear(); + /** + * Determines whether an item is present in the cache. + * + * This method will resolve with `true` on success or `false` when no item can be found + * or when an error occurs. Similarly, an expired cache item (once the time-to-live + * is expired) is considered a cache miss. + * + * ```php + * $cache + * ->has('foo') + * ->then('var_dump'); + * ``` + * + * This example checks if the value of the key `foo` is set in the cache and passes + * the result to the `var_dump` function. You can use any of the composition provided by + * [promises](https://github.com/reactphp/promise). + * + * NOTE: It is recommended that has() is only to be used for cache warming type purposes + * and not to be used within your live applications operations for get/set, as this method + * is subject to a race condition where your has() will return true and immediately after, + * another script can remove it making the state of your app out of date. + * + * @param string $key The cache item key. + * @return PromiseInterface Returns a promise which resolves to `true` on success or `false` on error + */ + public function has($key); +} diff --git a/vendor/react/child-process/CHANGELOG.md b/vendor/react/child-process/CHANGELOG.md new file mode 100644 index 00000000000..81bf50c5784 --- /dev/null +++ b/vendor/react/child-process/CHANGELOG.md @@ -0,0 +1,165 @@ +# Changelog + +## 0.6.5 (2022-09-16) + +* Feature: Full support for PHP 8.1 and PHP 8.2 release. + (#91 by @SimonFrings and #99 by @WyriHaximus) + +* Feature / Fix: Improve error reporting when custom error handler is used. + (#94 by @clue) + +* Minor documentation improvements. + (#92 by @SimonFrings and #95 by @nhedger) + +* Improve test suite, skip failing tests on bugged versions and fix legacy HHVM build. + (#96 and #98 by @clue and #93 by @SimonFrings) + +## 0.6.4 (2021-10-12) + +* Feature / Fix: Skip sigchild check if `phpinfo()` has been disabled. + (#89 by @clue) + +* Fix: Fix detecting closed socket pipes on PHP 8. + (#90 by @clue) + +## 0.6.3 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#87 by @clue) + + ```php + // old (still supported) + $process = new React\ChildProcess\Process($command); + $process->start($loop); + + // new (using default loop) + $process = new React\ChildProcess\Process($command); + $process->start(); + ``` + +## 0.6.2 (2021-02-05) + +* Feature: Support PHP 8 and add non-blocking I/O support on Windows with PHP 8. + (#85 by @clue) + +* Minor documentation improvements. + (#78 by @WyriHaximus and #80 by @gdejong) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9, switch to GitHub actions and clean up test suite. + (#75 by @reedy, #81 by @gdejong, #82 by @SimonFrings and #84 by @clue) + +## 0.6.1 (2019-02-15) + +* Feature / Fix: Improve error reporting when spawning child process fails. + (#73 by @clue) + +## 0.6.0 (2019-01-14) + +A major feature release with some minor API improvements! +This project now has limited Windows support and supports passing custom pipes +and file descriptors to the child process. + +This update involves a few minor BC breaks. We've tried hard to avoid BC breaks +where possible and minimize impact otherwise. We expect that most consumers of +this package will actually not be affected by any BC breaks, see below for more +details. + +* Feature / BC break: Support passing custom pipes and file descriptors to child process, + expose all standard I/O pipes in an array and remove unused Windows-only options. + (#62, #64 and #65 by @clue) + + > BC note: The optional `$options` parameter in the `Process` constructor + has been removed and a new `$fds` parameter has been added instead. The + previous `$options` parameter was Windows-only, available options were not + documented or referenced anywhere else in this library, so its actual + impact is expected to be relatively small. See the documentation and the + following changelog entry if you're looking for Windows support. + +* Feature: Support spawning child process on Windows without process I/O pipes. + (#67 by @clue) + +* Feature / BC break: Improve sigchild compatibility and support explicit configuration. + (#63 by @clue) + + ```php + // advanced: not recommended by default + Process::setSigchildEnabled(true); + ``` + + > BC note: The old public sigchild methods have been removed, but its + practical impact is believed to be relatively small due to the automatic detection. + +* Improve performance by prefixing all global functions calls with \ to skip + the look up and resolve process and go straight to the global function. + (#68 by @WyriHaximus) + +* Minor documentation improvements and docblock updates. + (#59 by @iamluc and #69 by @CharlotteDunois) + +* Improve test suite to test against PHP7.2 and PHP 7.3, improve HHVM compatibility, + add forward compatibility with PHPUnit 7 and run tests on Windows via Travis CI. + (#66 and #71 by @clue) + +## 0.5.2 (2018-01-18) + +* Feature: Detect "exit" immediately if last process pipe is closed + (#58 by @clue) + + This introduces a simple check to see if the program is already known to be + closed when the last process pipe is closed instead of relying on a periodic + timer. This simple change improves "exit" detection significantly for most + programs and does not cause a noticeable penalty for more advanced use cases. + +* Fix forward compatibility with upcoming EventLoop releases + (#56 by @clue) + +## 0.5.1 (2017-12-22) + +* Fix: Update Stream dependency to work around SEGFAULT in legacy PHP < 5.4.28 + and PHP < 5.5.12 + (#50 and #52 by @clue) + +* Improve test suite by simplifying test bootstrapping logic via Composer and + adding forward compatibility with PHPUnit 6 + (#53, #54 and #55 by @clue) + +## 0.5.0 (2017-08-15) + +* Forward compatibility: react/event-loop 1.0 and 0.5, react/stream 0.7.2 and 1.0, and Événement 3.0 + (#38 and #44 by @WyriHaximus, and #46 by @clue) +* Windows compatibility: Documentate that windows isn't supported in 0.5 unless used from within WSL + (#41 and #47 by @WyriHaximus) +* Documentation: Termination examples + (#42 by @clue) +* BC: Throw LogicException in Process instanciating when on Windows or when proc_open is missing (was `RuntimeException`) + (#49 by @mdrost) + +## 0.4.3 (2017-03-14) + +* Ease getting started by improving documentation and adding examples + (#33 and #34 by @clue) + +* First class support for PHP 5.3 through PHP 7.1 and HHVM + (#29 by @clue and #32 by @WyriHaximus) + +## 0.4.2 (2017-03-10) + +* Feature: Forward compatibility with Stream v0.5 + (#26 by @clue) + +* Improve test suite by removing AppVeyor and adding PHPUnit to `require-dev` + (#27 and #28 by @clue) + +## 0.4.1 (2016-08-01) + +* Standalone component +* Test against PHP 7 and HHVM, report test coverage, AppVeyor tests +* Wait for stdout and stderr to close before watching for process exit + (#18 by @mbonneau) + +## 0.4.0 (2014-02-02) + +* Feature: Added ChildProcess to run async child processes within the event loop (@jmikola) diff --git a/vendor/react/child-process/LICENSE b/vendor/react/child-process/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/child-process/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/child-process/README.md b/vendor/react/child-process/README.md new file mode 100644 index 00000000000..2dc8aab7976 --- /dev/null +++ b/vendor/react/child-process/README.md @@ -0,0 +1,619 @@ +# ChildProcess + +[![CI status](https://github.com/reactphp/child-process/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/child-process/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/child-process?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/child-process) + +Event-driven library for executing child processes with +[ReactPHP](https://reactphp.org/). + +This library integrates [Program Execution](http://php.net/manual/en/book.exec.php) +with the [EventLoop](https://github.com/reactphp/event-loop). +Child processes launched may be signaled and will emit an +`exit` event upon termination. +Additionally, process I/O streams (i.e. STDIN, STDOUT, STDERR) are exposed +as [Streams](https://github.com/reactphp/stream). + +**Table of contents** + +* [Quickstart example](#quickstart-example) +* [Process](#process) + * [Stream Properties](#stream-properties) + * [Command](#command) + * [Termination](#termination) + * [Custom pipes](#custom-pipes) + * [Sigchild Compatibility](#sigchild-compatibility) + * [Windows Compatibility](#windows-compatibility) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +```php +$process = new React\ChildProcess\Process('echo foo'); +$process->start(); + +$process->stdout->on('data', function ($chunk) { + echo $chunk; +}); + +$process->on('exit', function($exitCode, $termSignal) { + echo 'Process exited with code ' . $exitCode . PHP_EOL; +}); +``` + +See also the [examples](examples). + +## Process + +### Stream Properties + +Once a process is started, its I/O streams will be constructed as instances of +`React\Stream\ReadableStreamInterface` and `React\Stream\WritableStreamInterface`. +Before `start()` is called, these properties are not set. Once a process terminates, +the streams will become closed but not unset. + +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams as given below by default. +You can use the named references for common use cases or access these as an +array with all three pipes. + +* `$stdin` or `$pipes[0]` is a `WritableStreamInterface` +* `$stdout` or `$pipes[1]` is a `ReadableStreamInterface` +* `$stderr` or `$pipes[2]` is a `ReadableStreamInterface` + +Note that this default configuration may be overridden by explicitly passing +[custom pipes](#custom-pipes), in which case they may not be set or be assigned +different values. In particular, note that [Windows support](#windows-compatibility) +is limited in that it doesn't support non-blocking STDIO pipes. The `$pipes` +array will always contain references to all pipes as configured and the standard +I/O references will always be set to reference the pipes matching the above +conventions. See [custom pipes](#custom-pipes) for more details. + +Because each of these implement the underlying +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) or +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface), +you can use any of their events and methods as usual: + +```php +$process = new Process($command); +$process->start(); + +$process->stdout->on('data', function ($chunk) { + echo $chunk; +}); + +$process->stdout->on('end', function () { + echo 'ended'; +}); + +$process->stdout->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage(); +}); + +$process->stdout->on('close', function () { + echo 'closed'; +}); + +$process->stdin->write($data); +$process->stdin->end($data = null); +// … +``` + +For more details, see the +[`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) and +[`WritableStreamInterface`](https://github.com/reactphp/stream#writablestreaminterface). + +### Command + +The `Process` class allows you to pass any kind of command line string: + +```php +$process = new Process('echo test'); +$process->start(); +``` + +The command line string usually consists of a whitespace-separated list with +your main executable bin and any number of arguments. Special care should be +taken to escape or quote any arguments, escpecially if you pass any user input +along. Likewise, keep in mind that especially on Windows, it is rather common to +have path names containing spaces and other special characters. If you want to +run a binary like this, you will have to ensure this is quoted as a single +argument using `escapeshellarg()` like this: + +```php +$bin = 'C:\\Program files (x86)\\PHP\\php.exe'; +$file = 'C:\\Users\\me\\Desktop\\Application\\main.php'; + +$process = new Process(escapeshellarg($bin) . ' ' . escapeshellarg($file)); +$process->start(); +``` + +By default, PHP will launch processes by wrapping the given command line string +in a `sh` command on Unix, so that the first example will actually execute +`sh -c echo test` under the hood on Unix. On Windows, it will not launch +processes by wrapping them in a shell. + +This is a very useful feature because it does not only allow you to pass single +commands, but actually allows you to pass any kind of shell command line and +launch multiple sub-commands using command chains (with `&&`, `||`, `;` and +others) and allows you to redirect STDIO streams (with `2>&1` and family). +This can be used to pass complete command lines and receive the resulting STDIO +streams from the wrapping shell command like this: + +```php +$process = new Process('echo run && demo || echo failed'); +$process->start(); +``` + +> Note that [Windows support](#windows-compatibility) is limited in that it + doesn't support STDIO streams at all and also that processes will not be run + in a wrapping shell by default. If you want to run a shell built-in function + such as `echo hello` or `sleep 10`, you may have to prefix your command line + with an explicit shell like `cmd /c echo hello`. + +In other words, the underlying shell is responsible for managing this command +line and launching the individual sub-commands and connecting their STDIO +streams as appropriate. +This implies that the `Process` class will only receive the resulting STDIO +streams from the wrapping shell, which will thus contain the complete +input/output with no way to discern the input/output of single sub-commands. + +If you want to discern the output of single sub-commands, you may want to +implement some higher-level protocol logic, such as printing an explicit +boundary between each sub-command like this: + +```php +$process = new Process('cat first && echo --- && cat second'); +$process->start(); +``` + +As an alternative, considering launching one process at a time and listening on +its `exit` event to conditionally start the next process in the chain. +This will give you an opportunity to configure the subsequent process I/O streams: + +```php +$first = new Process('cat first'); +$first->start(); + +$first->on('exit', function () { + $second = new Process('cat second'); + $second->start(); +}); +``` + +Keep in mind that PHP uses the shell wrapper for ALL command lines on Unix. +While this may seem reasonable for more complex command lines, this actually +also applies to running the most simple single command: + +```php +$process = new Process('yes'); +$process->start(); +``` + +This will actually spawn a command hierarchy similar to this on Unix: + +``` +5480 … \_ php example.php +5481 … \_ sh -c yes +5482 … \_ yes +``` + +This means that trying to get the underlying process PID or sending signals +will actually target the wrapping shell, which may not be the desired result +in many cases. + +If you do not want this wrapping shell process to show up, you can simply +prepend the command string with `exec` on Unix platforms, which will cause the +wrapping shell process to be replaced by our process: + +```php +$process = new Process('exec yes'); +$process->start(); +``` + +This will show a resulting command hierarchy similar to this: + +``` +5480 … \_ php example.php +5481 … \_ yes +``` + +This means that trying to get the underlying process PID and sending signals +will now target the actual command as expected. + +Note that in this case, the command line will not be run in a wrapping shell. +This implies that when using `exec`, there's no way to pass command lines such +as those containing command chains or redirected STDIO streams. + +As a rule of thumb, most commands will likely run just fine with the wrapping +shell. +If you pass a complete command line (or are unsure), you SHOULD most likely keep +the wrapping shell. +If you're running on Unix and you want to pass an invidual command only, you MAY +want to consider prepending the command string with `exec` to avoid the wrapping shell. + +### Termination + +The `exit` event will be emitted whenever the process is no longer running. +Event listeners will receive the exit code and termination signal as two +arguments: + +```php +$process = new Process('sleep 10'); +$process->start(); + +$process->on('exit', function ($code, $term) { + if ($term === null) { + echo 'exit with code ' . $code . PHP_EOL; + } else { + echo 'terminated with signal ' . $term . PHP_EOL; + } +}); +``` + +Note that `$code` is `null` if the process has terminated, but the exit +code could not be determined (for example +[sigchild compatibility](#sigchild-compatibility) was disabled). +Similarly, `$term` is `null` unless the process has terminated in response to +an uncaught signal sent to it. +This is not a limitation of this project, but actual how exit codes and signals +are exposed on POSIX systems, for more details see also +[here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). + +It's also worth noting that process termination depends on all file descriptors +being closed beforehand. +This means that all [process pipes](#stream-properties) will emit a `close` +event before the `exit` event and that no more `data` events will arrive after +the `exit` event. +Accordingly, if either of these pipes is in a paused state (`pause()` method +or internally due to a `pipe()` call), this detection may not trigger. + +The `terminate(?int $signal = null): bool` method can be used to send the +process a signal (SIGTERM by default). +Depending on which signal you send to the process and whether it has a signal +handler registered, this can be used to either merely signal a process or even +forcefully terminate it. + +```php +$process->terminate(SIGUSR1); +``` + +Keep the above section in mind if you want to forcefully terminate a process. +If your process spawn sub-processes or implicitly uses the +[wrapping shell mentioned above](#command), its file descriptors may be +inherited to child processes and terminating the main process may not +necessarily terminate the whole process tree. +It is highly suggested that you explicitly `close()` all process pipes +accordingly when terminating a process: + +```php +$process = new Process('sleep 10'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + foreach ($process->pipes as $pipe) { + $pipe->close(); + } + $process->terminate(); +}); +``` + +For many simple programs these seamingly complicated steps can also be avoided +by prefixing the command line with `exec` to avoid the wrapping shell and its +inherited process pipes as [mentioned above](#command). + +```php +$process = new Process('exec sleep 10'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + $process->terminate(); +}); +``` + +Many command line programs also wait for data on `STDIN` and terminate cleanly +when this pipe is closed. +For example, the following can be used to "soft-close" a `cat` process: + +```php +$process = new Process('cat'); +$process->start(); + +Loop::addTimer(2.0, function () use ($process) { + $process->stdin->end(); +}); +``` + +While process pipes and termination may seem confusing to newcomers, the above +properties actually allow some fine grained control over process termination, +such as first trying a soft-close and then applying a force-close after a +timeout. + +### Custom pipes + +Following common Unix conventions, this library will start each child process +with the three pipes matching the standard I/O streams by default. For more +advanced use cases it may be useful to pass in custom pipes, such as explicitly +passing additional file descriptors (FDs) or overriding default process pipes. + +Note that passing custom pipes is considered advanced usage and requires a +more in-depth understanding of Unix file descriptors and how they are inherited +to child processes and shared in multi-processing applications. + +If you do not want to use the default standard I/O pipes, you can explicitly +pass an array containing the file descriptor specification to the constructor +like this: + +```php +$fds = array( + // standard I/O pipes for stdin/stdout/stderr + 0 => array('pipe', 'r'), + 1 => array('pipe', 'w'), + 2 => array('pipe', 'w'), + + // example FDs for files or open resources + 4 => array('file', '/dev/null', 'r'), + 6 => fopen('log.txt','a'), + 8 => STDERR, + + // example FDs for sockets + 10 => fsockopen('localhost', 8080), + 12 => stream_socket_server('tcp://0.0.0.0:4711') +); + +$process = new Process($cmd, null, null, $fds); +$process->start(); +``` + +Unless your use case has special requirements that demand otherwise, you're +highly recommended to (at least) pass in the standard I/O pipes as given above. +The file descriptor specification accepts arguments in the exact same format +as the underlying [`proc_open()`](http://php.net/proc_open) function. + +Once the process is started, the `$pipes` array will always contain references to +all pipes as configured and the standard I/O references will always be set to +reference the pipes matching common Unix conventions. This library supports any +number of pipes and additional file descriptors, but many common applications +being run as a child process will expect that the parent process properly +assigns these file descriptors. + +### Sigchild Compatibility + +Internally, this project uses a work-around to improve compatibility when PHP +has been compiled with the `--enable-sigchild` option. This should not affect most +installations as this configure option is not used by default and many +distributions (such as Debian and Ubuntu) are known to not use this by default. +Some installations that use [Oracle OCI8](http://php.net/manual/en/book.oci8.php) +may use this configure option to circumvent `defunct` processes. + +When PHP has been compiled with the `--enable-sigchild` option, a child process' +exit code cannot be reliably determined via `proc_close()` or `proc_get_status()`. +To work around this, we execute the child process with an additional pipe and +use that to retrieve its exit code. + +This work-around incurs some overhead, so we only trigger this when necessary +and when we detect that PHP has been compiled with the `--enable-sigchild` option. +Because PHP does not provide a way to reliably detect this option, we try to +inspect output of PHP's configure options from the `phpinfo()` function. + +The static `setSigchildEnabled(bool $sigchild): void` method can be used to +explicitly enable or disable this behavior like this: + +```php +// advanced: not recommended by default +Process::setSigchildEnabled(true); +``` + +Note that all processes instantiated after this method call will be affected. +If this work-around is disabled on an affected PHP installation, the `exit` +event may receive `null` instead of the actual exit code as described above. +Similarly, some distributions are known to omit the configure options from +`phpinfo()`, so automatic detection may fail to enable this work-around in some +cases. You may then enable this explicitly as given above. + +**Note:** The original functionality was taken from Symfony's +[Process](https://github.com/symfony/process) compoment. + +### Windows Compatibility + +Due to platform constraints, this library provides only limited support for +spawning child processes on Windows. In particular, PHP does not allow accessing +standard I/O pipes on Windows without blocking. As such, this project will not +allow constructing a child process with the default process pipes and will +instead throw a `LogicException` on Windows by default: + +```php +// throws LogicException on Windows +$process = new Process('ping example.com'); +$process->start(); +``` + +There are a number of alternatives and workarounds as detailed below if you want +to run a child process on Windows, each with its own set of pros and cons: + +* As of PHP 8, you can start the child process with `socket` pair descriptors + in place of normal standard I/O pipes like this: + + ```php + $process = new Process( + 'ping example.com', + null, + null, + [ + ['socket'], + ['socket'], + ['socket'] + ] + ); + $process->start(); + + $process->stdout->on('data', function ($chunk) { + echo $chunk; + }); + ``` + + These `socket` pairs support non-blocking process I/O on any platform, + including Windows. However, not all programs accept stdio sockets. + +* This package does work on + [`Windows Subsystem for Linux`](https://en.wikipedia.org/wiki/Windows_Subsystem_for_Linux) + (or WSL) without issues. When you are in control over how your application is + deployed, we recommend [installing WSL](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide) + when you want to run this package on Windows. + +* If you only care about the exit code of a child process to check if its + execution was successful, you can use [custom pipes](#custom-pipes) to omit + any standard I/O pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array()); + $process->start(); + + $process->on('exit', function ($exitcode) { + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Similarly, this is also useful if your child process communicates over + sockets with remote servers or even your parent process using the + [Socket component](https://github.com/reactphp/socket). This is usually + considered the best alternative if you have control over how your child + process communicates with the parent process. + +* If you only care about command output after the child process has been + executed, you can use [custom pipes](#custom-pipes) to configure file + handles to be passed to the child process instead of pipes like this: + + ```php + $process = new Process('ping example.com', null, null, array( + array('file', 'nul', 'r'), + $stdout = tmpfile(), + array('file', 'nul', 'w') + )); + $process->start(); + + $process->on('exit', function ($exitcode) use ($stdout) { + echo 'exit with ' . $exitcode . PHP_EOL; + + // rewind to start and then read full file (demo only, this is blocking). + // reading from shared file is only safe if you have some synchronization in place + // or after the child process has terminated. + rewind($stdout); + echo stream_get_contents($stdout); + fclose($stdout); + }); + ``` + + Note that this example uses `tmpfile()`/`fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also the [Filesystem component](https://github.com/reactphp/filesystem) as an + alternative. + +* If you want to access command output as it happens in a streaming fashion, + you can use redirection to spawn an additional process to forward your + standard I/O streams to a socket and use [custom pipes](#custom-pipes) to + omit any actual standard I/O pipes like this: + + ```php + $server = new React\Socket\Server('127.0.0.1:0'); + $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->on('data', function ($chunk) { + echo $chunk; + }); + }); + + $command = 'ping example.com | foobar ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start(); + + $process->on('exit', function ($exitcode) use ($server) { + $server->close(); + echo 'exit with ' . $exitcode . PHP_EOL; + }); + ``` + + Note how this will spawn another fictional `foobar` helper program to consume + the standard output from the actual child process. This is in fact similar + to the above recommendation of using socket connections in the child process, + but in this case does not require modification of the actual child process. + + In this example, the fictional `foobar` helper program can be implemented by + simply consuming all data from standard input and forwarding it to a socket + connection like this: + + ```php + $socket = stream_socket_client($argv[1]); + do { + fwrite($socket, $data = fread(STDIN, 8192)); + } while (isset($data[0])); + ``` + + Accordingly, this example can also be run with plain PHP without having to + rely on any external helper program like this: + + ```php + $code = '$s=stream_socket_client($argv[1]);do{fwrite($s,$d=fread(STDIN, 8192));}while(isset($d[0]));'; + $command = 'ping example.com | php -r ' . escapeshellarg($code) . ' ' . escapeshellarg($server->getAddress()); + $process = new Process($command, null, null, array()); + $process->start(); + ``` + + See also [example #23](examples/23-forward-socket.php). + + Note that this is for illustration purposes only and you may want to implement + some proper error checks and/or socket verification in actual production use + if you do not want to risk other processes connecting to the server socket. + In this case, we suggest looking at the excellent + [createprocess-windows](https://github.com/cubiclesoft/createprocess-windows). + +Additionally, note that the [command](#command) given to the `Process` will be +passed to the underlying Windows-API +([`CreateProcess`](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-createprocessa)) +as-is and the process will not be launched in a wrapping shell by default. In +particular, this means that shell built-in functions such as `echo hello` or +`sleep 10` may have to be prefixed with an explicit shell command like this: + +```php +$process = new Process('cmd /c echo hello', null, null, $pipes); +$process->start(); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This will install the latest supported version: + +```bash +composer require react/child-process:^0.6.5 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +See above note for limited [Windows Compatibility](#windows-compatibility). + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/vendor/react/child-process/composer.json b/vendor/react/child-process/composer.json new file mode 100644 index 00000000000..604fe58f507 --- /dev/null +++ b/vendor/react/child-process/composer.json @@ -0,0 +1,53 @@ +{ + "name": "react\/child-process", + "description": "Event-driven library for executing child processes with ReactPHP.", + "keywords": [ + "process", + "event-driven", + "ReactPHP" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0", + "react\/event-loop": "^1.2", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.3 || ^5.7 || ^4.8.35", + "react\/socket": "^1.8", + "sebastian\/environment": "^5.0 || ^3.0 || ^2.0 || ^1.0" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\ChildProcess\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\ChildProcess\\": "tests" + } + } +} \ No newline at end of file diff --git a/vendor/react/child-process/src/Process.php b/vendor/react/child-process/src/Process.php new file mode 100644 index 00000000000..fbc74aa38e0 --- /dev/null +++ b/vendor/react/child-process/src/Process.php @@ -0,0 +1,500 @@ +start(); + * + * $process->on('exit', function ($code, $term) { + * if ($term === null) { + * echo 'exit with code ' . $code . PHP_EOL; + * } else { + * echo 'terminated with signal ' . $term . PHP_EOL; + * } + * }); + * ``` + * + * Note that `$code` is `null` if the process has terminated, but the exit + * code could not be determined (for example + * [sigchild compatibility](#sigchild-compatibility) was disabled). + * Similarly, `$term` is `null` unless the process has terminated in response to + * an uncaught signal sent to it. + * This is not a limitation of this project, but actual how exit codes and signals + * are exposed on POSIX systems, for more details see also + * [here](https://unix.stackexchange.com/questions/99112/default-exit-code-when-process-is-terminated). + * + * It's also worth noting that process termination depends on all file descriptors + * being closed beforehand. + * This means that all [process pipes](#stream-properties) will emit a `close` + * event before the `exit` event and that no more `data` events will arrive after + * the `exit` event. + * Accordingly, if either of these pipes is in a paused state (`pause()` method + * or internally due to a `pipe()` call), this detection may not trigger. + */ +class Process extends EventEmitter +{ + /** + * @var WritableStreamInterface|null|DuplexStreamInterface|ReadableStreamInterface + */ + public $stdin; + /** + * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface + */ + public $stdout; + /** + * @var ReadableStreamInterface|null|DuplexStreamInterface|WritableStreamInterface + */ + public $stderr; + /** + * Array with all process pipes (once started) + * + * Unless explicitly configured otherwise during construction, the following + * standard I/O pipes will be assigned by default: + * - 0: STDIN (`WritableStreamInterface`) + * - 1: STDOUT (`ReadableStreamInterface`) + * - 2: STDERR (`ReadableStreamInterface`) + * + * @var array + */ + public $pipes = array(); + private $cmd; + private $cwd; + private $env; + private $fds; + private $enhanceSigchildCompatibility; + private $sigchildPipe; + private $process; + private $status; + private $exitCode; + private $fallbackExitCode; + private $stopSignal; + private $termSignal; + private static $sigchild; + /** + * Constructor. + * + * @param string $cmd Command line to run + * @param null|string $cwd Current working directory or null to inherit + * @param null|array $env Environment variables or null to inherit + * @param null|array $fds File descriptors to allocate for this process (or null = default STDIO streams) + * @throws \LogicException On windows or when proc_open() is not installed + */ + public function __construct($cmd, $cwd = null, array $env = null, array $fds = null) + { + if (!\function_exists('proc_open')) { + throw new \LogicException('The Process class relies on proc_open(), which is not available on your PHP installation.'); + } + $this->cmd = $cmd; + $this->cwd = $cwd; + if (null !== $env) { + $this->env = array(); + foreach ($env as $key => $value) { + $this->env[(string) $key] = (string) $value; + } + } + if ($fds === null) { + $fds = array( + array('pipe', 'r'), + // stdin + array('pipe', 'w'), + // stdout + array('pipe', 'w'), + ); + } + if (\DIRECTORY_SEPARATOR === '\\') { + foreach ($fds as $fd) { + if (isset($fd[0]) && $fd[0] === 'pipe') { + throw new \LogicException('Process pipes are not supported on Windows due to their blocking nature on Windows'); + } + } + } + $this->fds = $fds; + $this->enhanceSigchildCompatibility = self::isSigchildEnabled(); + } + /** + * Start the process. + * + * After the process is started, the standard I/O streams will be constructed + * and available via public properties. + * + * This method takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this process. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * @param ?LoopInterface $loop Loop interface for stream construction + * @param float $interval Interval to periodically monitor process state (seconds) + * @throws \RuntimeException If the process is already running or fails to start + */ + public function start(LoopInterface $loop = null, $interval = 0.1) + { + if ($this->isRunning()) { + throw new \RuntimeException('Process is already running'); + } + $loop = $loop ?: Loop::get(); + $cmd = $this->cmd; + $fdSpec = $this->fds; + $sigchild = null; + // Read exit code through fourth pipe to work around --enable-sigchild + if ($this->enhanceSigchildCompatibility) { + $fdSpec[] = array('pipe', 'w'); + \end($fdSpec); + $sigchild = \key($fdSpec); + // make sure this is fourth or higher (do not mess with STDIO) + if ($sigchild < 3) { + $fdSpec[3] = $fdSpec[$sigchild]; + unset($fdSpec[$sigchild]); + $sigchild = 3; + } + $cmd = \sprintf('(%s) ' . $sigchild . '>/dev/null; code=$?; echo $code >&' . $sigchild . '; exit $code', $cmd); + } + // on Windows, we do not launch the given command line in a shell (cmd.exe) by default and omit any error dialogs + // the cmd.exe shell can explicitly be given as part of the command as detailed in both documentation and tests + $options = array(); + if (\DIRECTORY_SEPARATOR === '\\') { + $options['bypass_shell'] = \true; + $options['suppress_errors'] = \true; + } + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errstr) { + // Match errstr from PHP's warning message. + // proc_open(/dev/does-not-exist): Failed to open stream: No such file or directory + $errstr = $error; + }); + $pipes = array(); + $this->process = @\proc_open($cmd, $fdSpec, $pipes, $this->cwd, $this->env, $options); + \restore_error_handler(); + if (!\is_resource($this->process)) { + throw new \RuntimeException('Unable to launch a new process: ' . $errstr); + } + // count open process pipes and await close event for each to drain buffers before detecting exit + $that = $this; + $closeCount = 0; + $streamCloseHandler = function () use(&$closeCount, $loop, $interval, $that) { + $closeCount--; + if ($closeCount > 0) { + return; + } + // process already closed => report immediately + if (!$that->isRunning()) { + $that->close(); + $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); + return; + } + // close not detected immediately => check regularly + $loop->addPeriodicTimer($interval, function ($timer) use($that, $loop) { + if (!$that->isRunning()) { + $loop->cancelTimer($timer); + $that->close(); + $that->emit('exit', array($that->getExitCode(), $that->getTermSignal())); + } + }); + }; + if ($sigchild !== null) { + $this->sigchildPipe = $pipes[$sigchild]; + unset($pipes[$sigchild]); + } + foreach ($pipes as $n => $fd) { + // use open mode from stream meta data or fall back to pipe open mode for legacy HHVM + $meta = \stream_get_meta_data($fd); + $mode = $meta['mode'] === '' ? $this->fds[$n][1] === 'r' ? 'w' : 'r' : $meta['mode']; + if ($mode === 'r+') { + $stream = new DuplexResourceStream($fd, $loop); + $stream->on('close', $streamCloseHandler); + $closeCount++; + } elseif ($mode === 'w') { + $stream = new WritableResourceStream($fd, $loop); + } else { + $stream = new ReadableResourceStream($fd, $loop); + $stream->on('close', $streamCloseHandler); + $closeCount++; + } + $this->pipes[$n] = $stream; + } + $this->stdin = isset($this->pipes[0]) ? $this->pipes[0] : null; + $this->stdout = isset($this->pipes[1]) ? $this->pipes[1] : null; + $this->stderr = isset($this->pipes[2]) ? $this->pipes[2] : null; + // immediately start checking for process exit when started without any I/O pipes + if (!$closeCount) { + $streamCloseHandler(); + } + } + /** + * Close the process. + * + * This method should only be invoked via the periodic timer that monitors + * the process state. + */ + public function close() + { + if ($this->process === null) { + return; + } + foreach ($this->pipes as $pipe) { + $pipe->close(); + } + if ($this->enhanceSigchildCompatibility) { + $this->pollExitCodePipe(); + $this->closeExitCodePipe(); + } + $exitCode = \proc_close($this->process); + $this->process = null; + if ($this->exitCode === null && $exitCode !== -1) { + $this->exitCode = $exitCode; + } + if ($this->exitCode === null && $this->status['exitcode'] !== -1) { + $this->exitCode = $this->status['exitcode']; + } + if ($this->exitCode === null && $this->fallbackExitCode !== null) { + $this->exitCode = $this->fallbackExitCode; + $this->fallbackExitCode = null; + } + } + /** + * Terminate the process with an optional signal. + * + * @param int $signal Optional signal (default: SIGTERM) + * @return bool Whether the signal was sent successfully + */ + public function terminate($signal = null) + { + if ($this->process === null) { + return \false; + } + if ($signal !== null) { + return \proc_terminate($this->process, $signal); + } + return \proc_terminate($this->process); + } + /** + * Get the command string used to launch the process. + * + * @return string + */ + public function getCommand() + { + return $this->cmd; + } + /** + * Get the exit code returned by the process. + * + * This value is only meaningful if isRunning() has returned false. Null + * will be returned if the process is still running. + * + * Null may also be returned if the process has terminated, but the exit + * code could not be determined (e.g. sigchild compatibility was disabled). + * + * @return int|null + */ + public function getExitCode() + { + return $this->exitCode; + } + /** + * Get the process ID. + * + * @return int|null + */ + public function getPid() + { + $status = $this->getCachedStatus(); + return $status !== null ? $status['pid'] : null; + } + /** + * Get the signal that caused the process to stop its execution. + * + * This value is only meaningful if isStopped() has returned true. Null will + * be returned if the process was never stopped. + * + * @return int|null + */ + public function getStopSignal() + { + return $this->stopSignal; + } + /** + * Get the signal that caused the process to terminate its execution. + * + * This value is only meaningful if isTerminated() has returned true. Null + * will be returned if the process was never terminated. + * + * @return int|null + */ + public function getTermSignal() + { + return $this->termSignal; + } + /** + * Return whether the process is still running. + * + * @return bool + */ + public function isRunning() + { + if ($this->process === null) { + return \false; + } + $status = $this->getFreshStatus(); + return $status !== null ? $status['running'] : \false; + } + /** + * Return whether the process has been stopped by a signal. + * + * @return bool + */ + public function isStopped() + { + $status = $this->getFreshStatus(); + return $status !== null ? $status['stopped'] : \false; + } + /** + * Return whether the process has been terminated by an uncaught signal. + * + * @return bool + */ + public function isTerminated() + { + $status = $this->getFreshStatus(); + return $status !== null ? $status['signaled'] : \false; + } + /** + * Return whether PHP has been compiled with the '--enable-sigchild' option. + * + * @see \Symfony\Component\Process\Process::isSigchildEnabled() + * @return bool + */ + public static final function isSigchildEnabled() + { + if (null !== self::$sigchild) { + return self::$sigchild; + } + if (!\function_exists('phpinfo')) { + return self::$sigchild = \false; + // @codeCoverageIgnore + } + \ob_start(); + \phpinfo(\INFO_GENERAL); + return self::$sigchild = \false !== \strpos(\ob_get_clean(), '--enable-sigchild'); + } + /** + * Enable or disable sigchild compatibility mode. + * + * Sigchild compatibility mode is required to get the exit code and + * determine the success of a process when PHP has been compiled with + * the --enable-sigchild option. + * + * @param bool $sigchild + * @return void + */ + public static final function setSigchildEnabled($sigchild) + { + self::$sigchild = (bool) $sigchild; + } + /** + * Check the fourth pipe for an exit code. + * + * This should only be used if --enable-sigchild compatibility was enabled. + */ + private function pollExitCodePipe() + { + if ($this->sigchildPipe === null) { + return; + } + $r = array($this->sigchildPipe); + $w = $e = null; + $n = @\stream_select($r, $w, $e, 0); + if (1 !== $n) { + return; + } + $data = \fread($r[0], 8192); + if (\strlen($data) > 0) { + $this->fallbackExitCode = (int) $data; + } + } + /** + * Close the fourth pipe used to relay an exit code. + * + * This should only be used if --enable-sigchild compatibility was enabled. + */ + private function closeExitCodePipe() + { + if ($this->sigchildPipe === null) { + return; + } + \fclose($this->sigchildPipe); + $this->sigchildPipe = null; + } + /** + * Return the cached process status. + * + * @return array + */ + private function getCachedStatus() + { + if ($this->status === null) { + $this->updateStatus(); + } + return $this->status; + } + /** + * Return the updated process status. + * + * @return array + */ + private function getFreshStatus() + { + $this->updateStatus(); + return $this->status; + } + /** + * Update the process status, stop/term signals, and exit code. + * + * Stop/term signals are only updated if the process is currently stopped or + * signaled, respectively. Otherwise, signal values will remain as-is so the + * corresponding getter methods may be used at a later point in time. + */ + private function updateStatus() + { + if ($this->process === null) { + return; + } + $this->status = \proc_get_status($this->process); + if ($this->status === \false) { + throw new \UnexpectedValueException('proc_get_status() failed'); + } + if ($this->status['stopped']) { + $this->stopSignal = $this->status['stopsig']; + } + if ($this->status['signaled']) { + $this->termSignal = $this->status['termsig']; + } + if (!$this->status['running'] && -1 !== $this->status['exitcode']) { + $this->exitCode = $this->status['exitcode']; + } + } +} diff --git a/vendor/react/dns/CHANGELOG.md b/vendor/react/dns/CHANGELOG.md new file mode 100644 index 00000000000..ca60df323c8 --- /dev/null +++ b/vendor/react/dns/CHANGELOG.md @@ -0,0 +1,439 @@ +# Changelog + +## 1.11.0 (2023-06-02) + +* Feature: Include timeout logic to avoid dependency on reactphp/promise-timer. + (#213 by @clue) + +* Improve test suite and project setup and report failed assertions. + (#210 by @clue, #212 by @WyriHaximus and #209 and #211 by @SimonFrings) + +## 1.10.0 (2022-09-08) + +* Feature: Full support for PHP 8.2 release. + (#201 by @clue and #207 by @WyriHaximus) + +* Feature: Optimize forward compatibility with Promise v3, avoid hitting autoloader. + (#202 by @clue) + +* Feature / Fix: Improve error reporting when custom error handler is used. + (#197 by @clue) + +* Fix: Fix invalid references in exception stack trace. + (#191 by @clue) + +* Minor documentation improvements. + (#195 by @SimonFrings and #203 by @nhedger) + +* Improve test suite, update to use default loop and new reactphp/async package. + (#204, #205 and #206 by @clue and #196 by @SimonFrings) + +## 1.9.0 (2021-12-20) + +* Feature: Full support for PHP 8.1 release and prepare PHP 8.2 compatibility + by refactoring `Parser` to avoid assigning dynamic properties. + (#188 and #186 by @clue and #184 by @SimonFrings) + +* Feature: Avoid dependency on `ext-filter`. + (#185 by @clue) + +* Feature / Fix: Skip invalid nameserver entries from `resolv.conf` and ignore IPv6 zone IDs. + (#187 by @clue) + +* Feature / Fix: Reduce socket read chunk size for queries over TCP/IP. + (#189 by @clue) + +## 1.8.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#182 by @clue) + + ```php + // old (still supported) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config, $loop); + + // new (using default loop) + $factory = new React\Dns\Resolver\Factory(); + $resolver = $factory->create($config); + ``` + +## 1.7.0 (2021-06-25) + +* Feature: Update DNS `Factory` to accept complete `Config` object. + Add new `FallbackExecutor` and use fallback DNS servers when `Config` lists multiple servers. + (#179 and #180 by @clue) + + ```php + // old (still supported) + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + $resolver = $factory->create($server, $loop); + + // new + $config = React\Dns\Config\Config::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; + } + $resolver = $factory->create($config, $loop); + ``` + +## 1.6.0 (2021-06-21) + +* Feature: Add support for legacy `SPF` record type. + (#178 by @akondas and @clue) + +* Fix: Fix integer overflow for TCP/IP chunk size on 32 bit platforms. + (#177 by @clue) + +## 1.5.0 (2021-03-05) + +* Feature: Improve error reporting when query fails, include domain and query type and DNS server address where applicable. + (#174 by @clue) + +* Feature: Improve error handling when sending data to DNS server fails (macOS). + (#171 and #172 by @clue) + +* Fix: Improve DNS response parser to limit recursion for compressed labels. + (#169 by @clue) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#170 by @SimonFrings) + +## 1.4.0 (2020-09-18) + +* Feature: Support upcoming PHP 8. + (#168 by @clue) + +* Improve test suite and update to PHPUnit 9.3. + (#164 by @clue, #165 and #166 by @SimonFrings and #167 by @WyriHaximus) + +## 1.3.0 (2020-07-10) + +* Feature: Forward compatibility with react/promise v3. + (#153 by @WyriHaximus) + +* Feature: Support parsing `OPT` records (EDNS0). + (#157 by @clue) + +* Fix: Avoid PHP warnings due to lack of args in exception trace on PHP 7.4. + (#160 by @clue) + +* Improve test suite and add `.gitattributes` to exclude dev files from exports. + Run tests on PHPUnit 9 and PHP 7.4 and clean up test suite. + (#154 by @reedy, #156 by @clue and #163 by @SimonFrings) + +## 1.2.0 (2019-08-15) + +* Feature: Add `TcpTransportExecutor` to send DNS queries over TCP/IP connection, + add `SelectiveTransportExecutor` to retry with TCP if UDP is truncated and + automatically select transport protocol when no explicit `udp://` or `tcp://` scheme is given in `Factory`. + (#145, #146, #147 and #148 by @clue) + +* Feature: Support escaping literal dots and special characters in domain names. + (#144 by @clue) + +## 1.1.0 (2019-07-18) + +* Feature: Support parsing `CAA` and `SSHFP` records. + (#141 and #142 by @clue) + +* Feature: Add `ResolverInterface` as common interface for `Resolver` class. + (#139 by @clue) + +* Fix: Add missing private property definitions and + remove unneeded dependency on `react/stream`. + (#140 and #143 by @clue) + +## 1.0.0 (2019-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +This update involves a number of BC breaks due to dropped support for +deprecated functionality and some internal API cleanup. We've tried hard to +avoid BC breaks where possible and minimize impact otherwise. We expect that +most consumers of this package will actually not be affected by any BC +breaks, see below for more details: + +* BC break: Delete all deprecated APIs, use `Query` objects for `Message` questions + instead of nested arrays and increase code coverage to 100%. + (#130 by @clue) + +* BC break: Move `$nameserver` from `ExecutorInterface` to `UdpTransportExecutor`, + remove advanced/internal `UdpTransportExecutor` args for `Parser`/`BinaryDumper` and + add API documentation for `ExecutorInterface`. + (#135, #137 and #138 by @clue) + +* BC break: Replace `HeaderBag` attributes with simple `Message` properties. + (#132 by @clue) + +* BC break: Mark all `Record` attributes as required, add documentation vs `Query`. + (#136 by @clue) + +* BC break: Mark all classes as final to discourage inheritance + (#134 by @WyriHaximus) + +## 0.4.19 (2019-07-10) + +* Feature: Avoid garbage references when DNS resolution rejects on legacy PHP <= 5.6. + (#133 by @clue) + +## 0.4.18 (2019-09-07) + +* Feature / Fix: Implement `CachingExecutor` using cache TTL, deprecate old `CachedExecutor`, + respect TTL from response records when caching and do not cache truncated responses. + (#129 by @clue) + +* Feature: Limit cache size to 256 last responses by default. + (#127 by @clue) + +* Feature: Cooperatively resolve hosts to avoid running same query concurrently. + (#125 by @clue) + +## 0.4.17 (2019-04-01) + +* Feature: Support parsing `authority` and `additional` records from DNS response. + (#123 by @clue) + +* Feature: Support dumping records as part of outgoing binary DNS message. + (#124 by @clue) + +* Feature: Forward compatibility with upcoming Cache v0.6 and Cache v1.0 + (#121 by @clue) + +* Improve test suite to add forward compatibility with PHPUnit 7, + test against PHP 7.3 and use legacy PHPUnit 5 on legacy HHVM. + (#122 by @clue) + +## 0.4.16 (2018-11-11) + +* Feature: Improve promise cancellation for DNS lookup retries and clean up any garbage references. + (#118 by @clue) + +* Fix: Reject parsing malformed DNS response messages such as incomplete DNS response messages, + malformed record data or malformed compressed domain name labels. + (#115 and #117 by @clue) + +* Fix: Fix interpretation of TTL as UINT32 with most significant bit unset. + (#116 by @clue) + +* Fix: Fix caching advanced MX/SRV/TXT/SOA structures. + (#112 by @clue) + +## 0.4.15 (2018-07-02) + +* Feature: Add `resolveAll()` method to support custom query types in `Resolver`. + (#110 by @clue and @WyriHaximus) + + ```php + $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + }); + ``` + +* Feature: Support parsing `NS`, `TXT`, `MX`, `SOA` and `SRV` records. + (#104, #105, #106, #107 and #108 by @clue) + +* Feature: Add support for `Message::TYPE_ANY` and parse unknown types as binary data. + (#104 by @clue) + +* Feature: Improve error messages for failed queries and improve documentation. + (#109 by @clue) + +* Feature: Add reverse DNS lookup example. + (#111 by @clue) + +## 0.4.14 (2018-06-26) + +* Feature: Add `UdpTransportExecutor`, validate incoming DNS response messages + to avoid cache poisoning attacks and deprecate legacy `Executor`. + (#101 and #103 by @clue) + +* Feature: Forward compatibility with Cache 0.5 + (#102 by @clue) + +* Deprecate legacy `Query::$currentTime` and binary parser data attributes to clean up and simplify API. + (#99 by @clue) + +## 0.4.13 (2018-02-27) + +* Add `Config::loadSystemConfigBlocking()` to load default system config + and support parsing DNS config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac and WMIC on Windows) + (#92, #93, #94 and #95 by @clue) + + ```php + $config = Config::loadSystemConfigBlocking(); + $server = $config->nameservers ? reset($config->nameservers) : '8.8.8.8'; + ``` + +* Remove unneeded cyclic dependency on react/socket + (#96 by @clue) + +## 0.4.12 (2018-01-14) + +* Improve test suite by adding forward compatibility with PHPUnit 6, + test against PHP 7.2, fix forward compatibility with upcoming EventLoop releases, + add test group to skip integration tests relying on internet connection + and add minor documentation improvements. + (#85 and #87 by @carusogabriel, #88 and #89 by @clue and #83 by @jsor) + +## 0.4.11 (2017-08-25) + +* Feature: Support resolving from default hosts file + (#75, #76 and #77 by @clue) + + This means that resolving hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $resolver->resolve('localhost')->then(function ($ip) { + echo 'IP: ' . $ip; + }); + ``` + + The new `HostsExecutor` exists for advanced usage and is otherwise used + internally for this feature. + +## 0.4.10 (2017-08-10) + +* Feature: Forward compatibility with EventLoop v1.0 and v0.5 and + lock minimum dependencies and work around circular dependency for tests + (#70 and #71 by @clue) + +* Fix: Work around DNS timeout issues for Windows users + (#74 by @clue) + +* Documentation and examples for advanced usage + (#66 by @WyriHaximus) + +* Remove broken TCP code, do not retry with invalid TCP query + (#73 by @clue) + +* Improve test suite by fixing HHVM build for now again and ignore future HHVM build errors and + lock Travis distro so new defaults will not break the build and + fix failing tests for PHP 7.1 + (#68 by @WyriHaximus and #69 and #72 by @clue) + +## 0.4.9 (2017-05-01) + +* Feature: Forward compatibility with upcoming Socket v1.0 and v0.8 + (#61 by @clue) + +## 0.4.8 (2017-04-16) + +* Feature: Add support for the AAAA record type to the protocol parser + (#58 by @othillo) + +* Feature: Add support for the PTR record type to the protocol parser + (#59 by @othillo) + +## 0.4.7 (2017-03-31) + +* Feature: Forward compatibility with upcoming Socket v0.6 and v0.7 component + (#57 by @clue) + +## 0.4.6 (2017-03-11) + +* Fix: Fix DNS timeout issues for Windows users and add forward compatibility + with Stream v0.5 and upcoming v0.6 + (#53 by @clue) + +* Improve test suite by adding PHPUnit to `require-dev` + (#54 by @clue) + +## 0.4.5 (2017-03-02) + +* Fix: Ensure we ignore the case of the answer + (#51 by @WyriHaximus) + +* Feature: Add `TimeoutExecutor` and simplify internal APIs to allow internal + code re-use for upcoming versions. + (#48 and #49 by @clue) + +## 0.4.4 (2017-02-13) + +* Fix: Fix handling connection and stream errors + (#45 by @clue) + +* Feature: Add examples and forward compatibility with upcoming Socket v0.5 component + (#46 and #47 by @clue) + +## 0.4.3 (2016-07-31) + +* Feature: Allow for cache adapter injection (#38 by @WyriHaximus) + + ```php + $factory = new React\Dns\Resolver\Factory(); + + $cache = new MyCustomCacheInstance(); + $resolver = $factory->createCached('8.8.8.8', $loop, $cache); + ``` + +* Feature: Support Promise cancellation (#35 by @clue) + + ```php + $promise = $resolver->resolve('reactphp.org'); + + $promise->cancel(); + ``` + +## 0.4.2 (2016-02-24) + +* Repository maintenance, split off from main repo, improve test suite and documentation +* First class support for PHP7 and HHVM (#34 by @clue) +* Adjust compatibility to 5.3 (#30 by @clue) + +## 0.4.1 (2014-04-13) + +* Bug fix: Fixed PSR-4 autoload path (@marcj/WyriHaximus) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* Bug fix: Properly resolve CNAME aliases +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.2 (2013-05-10) + +* Feature: Support default port for IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Feature: New cache component, used by DNS + +## 0.2.5 (2012-11-26) + +* Version bump + +## 0.2.4 (2012-11-18) + +* Feature: Change to promise-based API (@jsor) + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Feature: DNS executor timeout handling (@arnaud-lb) +* Feature: DNS retry executor (@arnaud-lb) + +## 0.2.1 (2012-10-14) + +* Minor adjustments to DNS parser + +## 0.2.0 (2012-09-10) + +* Feature: DNS resolver diff --git a/vendor/react/dns/LICENSE b/vendor/react/dns/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/dns/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/dns/README.md b/vendor/react/dns/README.md new file mode 100644 index 00000000000..06dc20eb55c --- /dev/null +++ b/vendor/react/dns/README.md @@ -0,0 +1,453 @@ +# DNS + +[![CI status](https://github.com/reactphp/dns/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/dns/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/dns?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/dns) + +Async DNS resolver for [ReactPHP](https://reactphp.org/). + +The main point of the DNS component is to provide async DNS resolution. +However, it is really a toolkit for working with DNS messages, and could +easily be used to create a DNS server. + +**Table of contents** + +* [Basic usage](#basic-usage) +* [Caching](#caching) + * [Custom cache adapter](#custom-cache-adapter) +* [ResolverInterface](#resolverinterface) + * [resolve()](#resolve) + * [resolveAll()](#resolveall) +* [Advanced usage](#advanced-usage) + * [UdpTransportExecutor](#udptransportexecutor) + * [TcpTransportExecutor](#tcptransportexecutor) + * [SelectiveTransportExecutor](#selectivetransportexecutor) + * [HostsFileExecutor](#hostsfileexecutor) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [References](#references) + +## Basic usage + +The most basic usage is to just create a resolver through the resolver +factory. All you need to give it is a nameserver, then you can start resolving +names, baby! + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->create($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +See also the [first example](examples). + +The `Config` class can be used to load the system default config. This is an +operation that may access the filesystem and block. Ideally, this method should +thus be executed only once before the loop starts and not repeatedly while it is +running. +Note that this class may return an *empty* configuration if the system config +can not be loaded. As such, you'll likely want to apply a default nameserver +as above if none can be found. + +> Note that the factory loads the hosts file from the filesystem once when + creating the resolver instance. + Ideally, this method should thus be executed only once before the loop starts + and not repeatedly while it is running. + +But there's more. + +## Caching + +You can cache results by configuring the resolver to use a `CachedExecutor`: + +```php +$config = React\Dns\Config\Config::loadSystemConfigBlocking(); +if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; +} + +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached($config); + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); + +... + +$dns->resolve('igor.io')->then(function ($ip) { + echo "Host: $ip\n"; +}); +``` + +If the first call returns before the second, only one query will be executed. +The second result will be served from an in memory cache. +This is particularly useful for long running scripts where the same hostnames +have to be looked up multiple times. + +See also the [third example](examples). + +### Custom cache adapter + +By default, the above will use an in memory cache. + +You can also specify a custom cache implementing [`CacheInterface`](https://github.com/reactphp/cache) to handle the record cache instead: + +```php +$cache = new React\Cache\ArrayCache(); +$factory = new React\Dns\Resolver\Factory(); +$dns = $factory->createCached('8.8.8.8', null, $cache); +``` + +See also the wiki for possible [cache implementations](https://github.com/reactphp/react/wiki/Users#cache-implementations). + +## ResolverInterface + + + +### resolve() + +The `resolve(string $domain): PromiseInterface` method can be used to +resolve the given $domain name to a single IPv4 address (type `A` query). + +```php +$resolver->resolve('reactphp.org')->then(function ($ip) { + echo 'IP for reactphp.org is ' . $ip . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a single IP +address on success. + +If the DNS server sends a DNS response message that contains more than +one IP address for this query, it will randomly pick one of the IP +addresses from the response. If you want the full list of IP addresses +or want to send a different type of query, you should use the +[`resolveAll()`](#resolveall) method instead. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolve('reactphp.org'); + +$promise->cancel(); +``` + +### resolveAll() + +The `resolveAll(string $host, int $type): PromiseInterface` method can be used to +resolve all record values for the given $domain name and query $type. + +```php +$resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); + +$resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; +}); +``` + +This is one of the main methods in this package. It sends a DNS query +for the given $domain name to your DNS server and returns a list with all +record values on success. + +If the DNS server sends a DNS response message that contains one or more +records for this query, it will return a list with all record values +from the response. You can use the `Message::TYPE_*` constants to control +which type of query will be sent. Note that this method always returns a +list of record values, but each record value type depends on the query +type. For example, it returns the IPv4 addresses for type `A` queries, +the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, +`CNAME` and `PTR` queries and structured data for other queries. See also +the `Record` documentation for more details. + +If the DNS server sends a DNS response message that indicates an error +code, this method will reject with a `RecordNotFoundException`. Its +message and code can be used to check for the response code. + +If the DNS communication fails and the server does not respond with a +valid response message, this message will reject with an `Exception`. + +Pending DNS queries can be cancelled by cancelling its pending promise like so: + +```php +$promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + +$promise->cancel(); +``` + +## Advanced Usage + +### UdpTransportExecutor + +The `UdpTransportExecutor` can be used to +send DNS queries over a UDP transport. + +This is the main class that sends a DNS query to your DNS server and is used +internally by the `Resolver` for the actual message transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `igor.io`. + +```php +$executor = new UdpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also the [fourth example](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 +); +``` + +Also note that this executor uses an unreliable UDP transport and that it +does not implement any retry logic, so you will likely want to use this in +combination with a `RetryExecutor` like this: + +```php +$executor = new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new RetryExecutor( + new TimeoutExecutor( + new UdpTransportExecutor($nameserver), + 3.0 + ) + ) +); +``` + +> Internally, this class uses PHP's UDP sockets and does not take advantage + of [react/datagram](https://github.com/reactphp/datagram) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Datagram + component instead of reimplementing this socket logic from scratch. + +### TcpTransportExecutor + +The `TcpTransportExecutor` class can be used to +send DNS queries over a TCP/IP stream transport. + +This is one of the main classes that send a DNS query to your DNS server. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new TcpTransportExecutor('8.8.8.8:53'); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +See also [example #92](examples). + +Note that this executor does not implement a timeout, so you will very likely +want to use this in combination with a `TimeoutExecutor` like this: + +```php +$executor = new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 +); +``` + +Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP +transport, so you do not necessarily have to implement any retry logic. + +Note that this executor is entirely async and as such allows you to execute +queries concurrently. The first query will establish a TCP/IP socket +connection to the DNS server which will be kept open for a short period. +Additional queries will automatically reuse this existing socket connection +to the DNS server, will pipeline multiple requests over this single +connection and will keep an idle connection open for a short period. The +initial TCP/IP connection overhead may incur a slight delay if you only send +occasional queries – when sending a larger number of concurrent queries over +an existing connection, it becomes increasingly more efficient and avoids +creating many concurrent sockets like the UDP-based executor. You may still +want to limit the number of (concurrent) queries in your application or you +may be facing rate limitations and bans on the resolver end. For many common +applications, you may want to avoid sending the same query multiple times +when the first one is still pending, so you will likely want to use this in +combination with a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new TimeoutExecutor( + new TcpTransportExecutor($nameserver), + 3.0 + ) +); +``` + +> Internally, this class uses PHP's TCP/IP sockets and does not take advantage + of [react/socket](https://github.com/reactphp/socket) purely for + organizational reasons to avoid a cyclic dependency between the two + packages. Higher-level components should take advantage of the Socket + component instead of reimplementing this socket logic from scratch. + +### SelectiveTransportExecutor + +The `SelectiveTransportExecutor` class can be used to +Send DNS queries over a UDP or TCP/IP stream transport. + +This class will automatically choose the correct transport protocol to send +a DNS query to your DNS server. It will always try to send it over the more +efficient UDP transport first. If this query yields a size related issue +(truncated messages), it will retry over a streaming TCP/IP transport. + +For more advanced usages one can utilize this class directly. +The following example looks up the `IPv6` address for `reactphp.org`. + +```php +$executor = new SelectiveTransportExecutor($udpExecutor, $tcpExecutor); + +$executor->query( + new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) +)->then(function (Message $message) { + foreach ($message->answers as $answer) { + echo 'IPv6: ' . $answer->data . PHP_EOL; + } +}, 'printf'); +``` + +Note that this executor only implements the logic to select the correct +transport for the given DNS query. Implementing the correct transport logic, +implementing timeouts and any retry logic is left up to the given executors, +see also [`UdpTransportExecutor`](#udptransportexecutor) and +[`TcpTransportExecutor`](#tcptransportexecutor) for more details. + +Note that this executor is entirely async and as such allows you to execute +any number of queries concurrently. You should probably limit the number of +concurrent queries in your application or you're very likely going to face +rate limitations and bans on the resolver end. For many common applications, +you may want to avoid sending the same query multiple times when the first +one is still pending, so you will likely want to use this in combination with +a `CoopExecutor` like this: + +```php +$executor = new CoopExecutor( + new SelectiveTransportExecutor( + $datagramExecutor, + $streamExecutor + ) +); +``` + +### HostsFileExecutor + +Note that the above `UdpTransportExecutor` class always performs an actual DNS query. +If you also want to take entries from your hosts file into account, you may +use this code: + +```php +$hosts = \React\Dns\Config\HostsFile::loadFromPathBlocking(); + +$executor = new UdpTransportExecutor('8.8.8.8:53'); +$executor = new HostsFileExecutor($hosts, $executor); + +$executor->query( + new Query('localhost', Message::TYPE_A, Message::CLASS_IN) +); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/dns:^1.11 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## References + +* [RFC 1034](https://tools.ietf.org/html/rfc1034) Domain Names - Concepts and Facilities +* [RFC 1035](https://tools.ietf.org/html/rfc1035) Domain Names - Implementation and Specification diff --git a/vendor/react/dns/composer.json b/vendor/react/dns/composer.json new file mode 100644 index 00000000000..46bd8fbc262 --- /dev/null +++ b/vendor/react/dns/composer.json @@ -0,0 +1,54 @@ +{ + "name": "react\/dns", + "description": "Async DNS resolver for ReactPHP", + "keywords": [ + "dns", + "dns-resolver", + "ReactPHP", + "async" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "react\/cache": "^1.0 || ^0.6 || ^0.5", + "react\/event-loop": "^1.2", + "react\/promise": "^3.0 || ^2.7 || ^1.2.1" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^4.8.35", + "react\/async": "^4 || ^3 || ^2", + "react\/promise-timer": "^1.9" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Dns\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\Dns\\": "tests\/" + } + } +} \ No newline at end of file diff --git a/vendor/react/dns/src/BadServerException.php b/vendor/react/dns/src/BadServerException.php new file mode 100644 index 00000000000..f5daccbf5fd --- /dev/null +++ b/vendor/react/dns/src/BadServerException.php @@ -0,0 +1,7 @@ + `fe80:1`) + if (\strpos($ip, ':') !== \false && ($pos = \strpos($ip, '%')) !== \false) { + $ip = \substr($ip, 0, $pos); + } + if (@\inet_pton($ip) !== \false) { + $config->nameservers[] = $ip; + } + } + return $config; + } + /** + * Loads the DNS configurations from Windows's WMIC (from the given command or default command) + * + * Note that this method blocks while loading the given command and should + * thus be used with care! While this should be relatively fast for normal + * WMIC commands, it remains unknown if this may block under certain + * circumstances. In particular, this method should only be executed before + * the loop starts, not while it is running. + * + * Note that this method will only try to execute the given command try to + * parse its output, irrespective of whether this command exists. In + * particular, this command is only available on Windows. Currently, this + * will only parse valid nameserver entries from the command output and will + * ignore all other output without complaining. + * + * Note that the previous section implies that this may return an empty + * `Config` object if no valid nameserver entries can be found. + * + * @param ?string $command (advanced) should not be given (NULL) unless you know what you're doing + * @return self + * @link https://ss64.com/nt/wmic.html + */ + public static function loadWmicBlocking($command = null) + { + $contents = \shell_exec($command === null ? 'wmic NICCONFIG get "DNSServerSearchOrder" /format:CSV' : $command); + \preg_match_all('/(?<=[{;,"])([\\da-f.:]{4,})(?=[};,"])/i', $contents, $matches); + $config = new self(); + $config->nameservers = $matches[1]; + return $config; + } + public $nameservers = array(); +} diff --git a/vendor/react/dns/src/Config/HostsFile.php b/vendor/react/dns/src/Config/HostsFile.php new file mode 100644 index 00000000000..99e7e86dca7 --- /dev/null +++ b/vendor/react/dns/src/Config/HostsFile.php @@ -0,0 +1,134 @@ +contents = $contents; + } + /** + * Returns all IPs for the given hostname + * + * @param string $name + * @return string[] + */ + public function getIpsForHost($name) + { + $name = \strtolower($name); + $ips = array(); + foreach (\preg_split('/\\r?\\n/', $this->contents) as $line) { + $parts = \preg_split('/\\s+/', $line); + $ip = \array_shift($parts); + if ($parts && \array_search($name, $parts) !== \false) { + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (\strpos($ip, ':') !== \false && ($pos = \strpos($ip, '%')) !== \false) { + $ip = \substr($ip, 0, $pos); + } + if (@\inet_pton($ip) !== \false) { + $ips[] = $ip; + } + } + } + return $ips; + } + /** + * Returns all hostnames for the given IPv4 or IPv6 address + * + * @param string $ip + * @return string[] + */ + public function getHostsForIp($ip) + { + // check binary representation of IP to avoid string case and short notation + $ip = @\inet_pton($ip); + if ($ip === \false) { + return array(); + } + $names = array(); + foreach (\preg_split('/\\r?\\n/', $this->contents) as $line) { + $parts = \preg_split('/\\s+/', $line, -1, \PREG_SPLIT_NO_EMPTY); + $addr = (string) \array_shift($parts); + // remove IPv6 zone ID (`fe80::1%lo0` => `fe80:1`) + if (\strpos($addr, ':') !== \false && ($pos = \strpos($addr, '%')) !== \false) { + $addr = \substr($addr, 0, $pos); + } + if (@\inet_pton($addr) === $ip) { + foreach ($parts as $part) { + $names[] = $part; + } + } + } + return $names; + } +} diff --git a/vendor/react/dns/src/Model/Message.php b/vendor/react/dns/src/Model/Message.php new file mode 100644 index 00000000000..26e280d82a5 --- /dev/null +++ b/vendor/react/dns/src/Model/Message.php @@ -0,0 +1,203 @@ +id = self::generateId(); + $request->rd = \true; + $request->questions[] = $query; + return $request; + } + /** + * Creates a new response message for the given query with the given answer records + * + * @param Query $query + * @param Record[] $answers + * @return self + */ + public static function createResponseWithAnswersForQuery(Query $query, array $answers) + { + $response = new Message(); + $response->id = self::generateId(); + $response->qr = \true; + $response->rd = \true; + $response->questions[] = $query; + foreach ($answers as $record) { + $response->answers[] = $record; + } + return $response; + } + /** + * generates a random 16 bit message ID + * + * This uses a CSPRNG so that an outside attacker that is sending spoofed + * DNS response messages can not guess the message ID to avoid possible + * cache poisoning attacks. + * + * The `random_int()` function is only available on PHP 7+ or when + * https://github.com/paragonie/random_compat is installed. As such, using + * the latest supported PHP version is highly recommended. This currently + * falls back to a less secure random number generator on older PHP versions + * in the hope that this system is properly protected against outside + * attackers, for example by using one of the common local DNS proxy stubs. + * + * @return int + * @see self::getId() + * @codeCoverageIgnore + */ + private static function generateId() + { + if (\function_exists('random_int')) { + return \random_int(0, 0xffff); + } + return \mt_rand(0, 0xffff); + } + /** + * The 16 bit message ID + * + * The response message ID has to match the request message ID. This allows + * the receiver to verify this is the correct response message. An outside + * attacker may try to inject fake responses by "guessing" the message ID, + * so this should use a proper CSPRNG to avoid possible cache poisoning. + * + * @var int 16 bit message ID + * @see self::generateId() + */ + public $id = 0; + /** + * @var bool Query/Response flag, query=false or response=true + */ + public $qr = \false; + /** + * @var int specifies the kind of query (4 bit), see self::OPCODE_* constants + * @see self::OPCODE_QUERY + */ + public $opcode = self::OPCODE_QUERY; + /** + * + * @var bool Authoritative Answer + */ + public $aa = \false; + /** + * @var bool TrunCation + */ + public $tc = \false; + /** + * @var bool Recursion Desired + */ + public $rd = \false; + /** + * @var bool Recursion Available + */ + public $ra = \false; + /** + * @var int response code (4 bit), see self::RCODE_* constants + * @see self::RCODE_OK + */ + public $rcode = Message::RCODE_OK; + /** + * An array of Query objects + * + * ```php + * $questions = array( + * new Query( + * 'reactphp.org', + * Message::TYPE_A, + * Message::CLASS_IN + * ) + * ); + * ``` + * + * @var Query[] + */ + public $questions = array(); + /** + * @var Record[] + */ + public $answers = array(); + /** + * @var Record[] + */ + public $authority = array(); + /** + * @var Record[] + */ + public $additional = array(); +} diff --git a/vendor/react/dns/src/Model/Record.php b/vendor/react/dns/src/Model/Record.php new file mode 100644 index 00000000000..22779799dfc --- /dev/null +++ b/vendor/react/dns/src/Model/Record.php @@ -0,0 +1,148 @@ +name = $name; + $this->type = $type; + $this->class = $class; + $this->ttl = $ttl; + $this->data = $data; + } +} diff --git a/vendor/react/dns/src/Protocol/BinaryDumper.php b/vendor/react/dns/src/Protocol/BinaryDumper.php new file mode 100644 index 00000000000..fe40701081f --- /dev/null +++ b/vendor/react/dns/src/Protocol/BinaryDumper.php @@ -0,0 +1,149 @@ +headerToBinary($message); + $data .= $this->questionToBinary($message->questions); + $data .= $this->recordsToBinary($message->answers); + $data .= $this->recordsToBinary($message->authority); + $data .= $this->recordsToBinary($message->additional); + return $data; + } + /** + * @param Message $message + * @return string + */ + private function headerToBinary(Message $message) + { + $data = ''; + $data .= \pack('n', $message->id); + $flags = 0x0; + $flags = $flags << 1 | ($message->qr ? 1 : 0); + $flags = $flags << 4 | $message->opcode; + $flags = $flags << 1 | ($message->aa ? 1 : 0); + $flags = $flags << 1 | ($message->tc ? 1 : 0); + $flags = $flags << 1 | ($message->rd ? 1 : 0); + $flags = $flags << 1 | ($message->ra ? 1 : 0); + $flags = $flags << 3 | 0; + // skip unused zero bit + $flags = $flags << 4 | $message->rcode; + $data .= \pack('n', $flags); + $data .= \pack('n', \count($message->questions)); + $data .= \pack('n', \count($message->answers)); + $data .= \pack('n', \count($message->authority)); + $data .= \pack('n', \count($message->additional)); + return $data; + } + /** + * @param Query[] $questions + * @return string + */ + private function questionToBinary(array $questions) + { + $data = ''; + foreach ($questions as $question) { + $data .= $this->domainNameToBinary($question->name); + $data .= \pack('n*', $question->type, $question->class); + } + return $data; + } + /** + * @param Record[] $records + * @return string + */ + private function recordsToBinary(array $records) + { + $data = ''; + foreach ($records as $record) { + /* @var $record Record */ + switch ($record->type) { + case Message::TYPE_A: + case Message::TYPE_AAAA: + $binary = \inet_pton($record->data); + break; + case Message::TYPE_CNAME: + case Message::TYPE_NS: + case Message::TYPE_PTR: + $binary = $this->domainNameToBinary($record->data); + break; + case Message::TYPE_TXT: + case Message::TYPE_SPF: + $binary = $this->textsToBinary($record->data); + break; + case Message::TYPE_MX: + $binary = \pack('n', $record->data['priority']); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SRV: + $binary = \pack('n*', $record->data['priority'], $record->data['weight'], $record->data['port']); + $binary .= $this->domainNameToBinary($record->data['target']); + break; + case Message::TYPE_SOA: + $binary = $this->domainNameToBinary($record->data['mname']); + $binary .= $this->domainNameToBinary($record->data['rname']); + $binary .= \pack('N*', $record->data['serial'], $record->data['refresh'], $record->data['retry'], $record->data['expire'], $record->data['minimum']); + break; + case Message::TYPE_CAA: + $binary = \pack('C*', $record->data['flag'], \strlen($record->data['tag'])); + $binary .= $record->data['tag']; + $binary .= $record->data['value']; + break; + case Message::TYPE_SSHFP: + $binary = \pack('CCH*', $record->data['algorithm'], $record->data['type'], $record->data['fingerprint']); + break; + case Message::TYPE_OPT: + $binary = ''; + foreach ($record->data as $opt => $value) { + if ($opt === Message::OPT_TCP_KEEPALIVE && $value !== null) { + $value = \pack('n', \round($value * 10)); + } + $binary .= \pack('n*', $opt, \strlen((string) $value)) . $value; + } + break; + default: + // RDATA is already stored as binary value for unknown record types + $binary = $record->data; + } + $data .= $this->domainNameToBinary($record->name); + $data .= \pack('nnNn', $record->type, $record->class, $record->ttl, \strlen($binary)); + $data .= $binary; + } + return $data; + } + /** + * @param string[] $texts + * @return string + */ + private function textsToBinary(array $texts) + { + $data = ''; + foreach ($texts as $text) { + $data .= \chr(\strlen($text)) . $text; + } + return $data; + } + /** + * @param string $host + * @return string + */ + private function domainNameToBinary($host) + { + if ($host === '') { + return "\x00"; + } + // break up domain name at each dot that is not preceeded by a backslash (escaped notation) + return $this->textsToBinary(\array_map('stripcslashes', \preg_split('/(?parse($data, 0); + if ($message === null) { + throw new InvalidArgumentException('Unable to parse binary message'); + } + return $message; + } + /** + * @param string $data + * @param int $consumed + * @return ?Message + */ + private function parse($data, $consumed) + { + if (!isset($data[12 - 1])) { + return null; + } + list($id, $fields, $qdCount, $anCount, $nsCount, $arCount) = \array_values(\unpack('n*', \substr($data, 0, 12))); + $message = new Message(); + $message->id = $id; + $message->rcode = $fields & 0xf; + $message->ra = ($fields >> 7 & 1) === 1; + $message->rd = ($fields >> 8 & 1) === 1; + $message->tc = ($fields >> 9 & 1) === 1; + $message->aa = ($fields >> 10 & 1) === 1; + $message->opcode = $fields >> 11 & 0xf; + $message->qr = ($fields >> 15 & 1) === 1; + $consumed += 12; + // parse all questions + for ($i = $qdCount; $i > 0; --$i) { + list($question, $consumed) = $this->parseQuestion($data, $consumed); + if ($question === null) { + return null; + } else { + $message->questions[] = $question; + } + } + // parse all answer records + for ($i = $anCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->answers[] = $record; + } + } + // parse all authority records + for ($i = $nsCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->authority[] = $record; + } + } + // parse all additional records + for ($i = $arCount; $i > 0; --$i) { + list($record, $consumed) = $this->parseRecord($data, $consumed); + if ($record === null) { + return null; + } else { + $message->additional[] = $record; + } + } + return $message; + } + /** + * @param string $data + * @param int $consumed + * @return array + */ + private function parseQuestion($data, $consumed) + { + list($labels, $consumed) = $this->readLabels($data, $consumed); + if ($labels === null || !isset($data[$consumed + 4 - 1])) { + return array(null, null); + } + list($type, $class) = \array_values(\unpack('n*', \substr($data, $consumed, 4))); + $consumed += 4; + return array(new Query(\implode('.', $labels), $type, $class), $consumed); + } + /** + * @param string $data + * @param int $consumed + * @return array An array with a parsed Record on success or array with null if data is invalid/incomplete + */ + private function parseRecord($data, $consumed) + { + list($name, $consumed) = $this->readDomain($data, $consumed); + if ($name === null || !isset($data[$consumed + 10 - 1])) { + return array(null, null); + } + list($type, $class) = \array_values(\unpack('n*', \substr($data, $consumed, 4))); + $consumed += 4; + list($ttl) = \array_values(\unpack('N', \substr($data, $consumed, 4))); + $consumed += 4; + // TTL is a UINT32 that must not have most significant bit set for BC reasons + if ($ttl < 0 || $ttl >= 1 << 31) { + $ttl = 0; + } + list($rdLength) = \array_values(\unpack('n', \substr($data, $consumed, 2))); + $consumed += 2; + if (!isset($data[$consumed + $rdLength - 1])) { + return array(null, null); + } + $rdata = null; + $expected = $consumed + $rdLength; + if (Message::TYPE_A === $type) { + if ($rdLength === 4) { + $rdata = \inet_ntop(\substr($data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_AAAA === $type) { + if ($rdLength === 16) { + $rdata = \inet_ntop(\substr($data, $consumed, $rdLength)); + $consumed += $rdLength; + } + } elseif (Message::TYPE_CNAME === $type || Message::TYPE_PTR === $type || Message::TYPE_NS === $type) { + list($rdata, $consumed) = $this->readDomain($data, $consumed); + } elseif (Message::TYPE_TXT === $type || Message::TYPE_SPF === $type) { + $rdata = array(); + while ($consumed < $expected) { + $len = \ord($data[$consumed]); + $rdata[] = (string) \substr($data, $consumed + 1, $len); + $consumed += $len + 1; + } + } elseif (Message::TYPE_MX === $type) { + if ($rdLength > 2) { + list($priority) = \array_values(\unpack('n', \substr($data, $consumed, 2))); + list($target, $consumed) = $this->readDomain($data, $consumed + 2); + $rdata = array('priority' => $priority, 'target' => $target); + } + } elseif (Message::TYPE_SRV === $type) { + if ($rdLength > 6) { + list($priority, $weight, $port) = \array_values(\unpack('n*', \substr($data, $consumed, 6))); + list($target, $consumed) = $this->readDomain($data, $consumed + 6); + $rdata = array('priority' => $priority, 'weight' => $weight, 'port' => $port, 'target' => $target); + } + } elseif (Message::TYPE_SSHFP === $type) { + if ($rdLength > 2) { + list($algorithm, $hash) = \array_values(\unpack('C*', \substr($data, $consumed, 2))); + $fingerprint = \bin2hex(\substr($data, $consumed + 2, $rdLength - 2)); + $consumed += $rdLength; + $rdata = array('algorithm' => $algorithm, 'type' => $hash, 'fingerprint' => $fingerprint); + } + } elseif (Message::TYPE_SOA === $type) { + list($mname, $consumed) = $this->readDomain($data, $consumed); + list($rname, $consumed) = $this->readDomain($data, $consumed); + if ($mname !== null && $rname !== null && isset($data[$consumed + 20 - 1])) { + list($serial, $refresh, $retry, $expire, $minimum) = \array_values(\unpack('N*', \substr($data, $consumed, 20))); + $consumed += 20; + $rdata = array('mname' => $mname, 'rname' => $rname, 'serial' => $serial, 'refresh' => $refresh, 'retry' => $retry, 'expire' => $expire, 'minimum' => $minimum); + } + } elseif (Message::TYPE_OPT === $type) { + $rdata = array(); + while (isset($data[$consumed + 4 - 1])) { + list($code, $length) = \array_values(\unpack('n*', \substr($data, $consumed, 4))); + $value = (string) \substr($data, $consumed + 4, $length); + if ($code === Message::OPT_TCP_KEEPALIVE && $value === '') { + $value = null; + } elseif ($code === Message::OPT_TCP_KEEPALIVE && $length === 2) { + list($value) = \array_values(\unpack('n', $value)); + $value = \round($value * 0.1, 1); + } elseif ($code === Message::OPT_TCP_KEEPALIVE) { + break; + } + $rdata[$code] = $value; + $consumed += 4 + $length; + } + } elseif (Message::TYPE_CAA === $type) { + if ($rdLength > 3) { + list($flag, $tagLength) = \array_values(\unpack('C*', \substr($data, $consumed, 2))); + if ($tagLength > 0 && $rdLength - 2 - $tagLength > 0) { + $tag = \substr($data, $consumed + 2, $tagLength); + $value = \substr($data, $consumed + 2 + $tagLength, $rdLength - 2 - $tagLength); + $consumed += $rdLength; + $rdata = array('flag' => $flag, 'tag' => $tag, 'value' => $value); + } + } + } else { + // unknown types simply parse rdata as an opaque binary string + $rdata = \substr($data, $consumed, $rdLength); + $consumed += $rdLength; + } + // ensure parsing record data consumes expact number of bytes indicated in record length + if ($consumed !== $expected || $rdata === null) { + return array(null, null); + } + return array(new Record($name, $type, $class, $ttl, $rdata), $consumed); + } + private function readDomain($data, $consumed) + { + list($labels, $consumed) = $this->readLabels($data, $consumed); + if ($labels === null) { + return array(null, null); + } + // use escaped notation for each label part, then join using dots + return array(\implode('.', \array_map(function ($label) { + return \addcslashes($label, "\x00.. ."); + }, $labels)), $consumed); + } + /** + * @param string $data + * @param int $consumed + * @param int $compressionDepth maximum depth for compressed labels to avoid unreasonable recursion + * @return array + */ + private function readLabels($data, $consumed, $compressionDepth = 127) + { + $labels = array(); + while (\true) { + if (!isset($data[$consumed])) { + return array(null, null); + } + $length = \ord($data[$consumed]); + // end of labels reached + if ($length === 0) { + $consumed += 1; + break; + } + // first two bits set? this is a compressed label (14 bit pointer offset) + if (($length & 0xc0) === 0xc0 && isset($data[$consumed + 1]) && $compressionDepth) { + $offset = ($length & ~0xc0) << 8 | \ord($data[$consumed + 1]); + if ($offset >= $consumed) { + return array(null, null); + } + $consumed += 2; + list($newLabels) = $this->readLabels($data, $offset, $compressionDepth - 1); + if ($newLabels === null) { + return array(null, null); + } + $labels = \array_merge($labels, $newLabels); + break; + } + // length MUST be 0-63 (6 bits only) and data has to be large enough + if ($length & 0xc0 || !isset($data[$consumed + $length - 1])) { + return array(null, null); + } + $labels[] = \substr($data, $consumed + 1, $length); + $consumed += $length + 1; + } + return array($labels, $consumed); + } +} diff --git a/vendor/react/dns/src/Query/CachingExecutor.php b/vendor/react/dns/src/Query/CachingExecutor.php new file mode 100644 index 00000000000..3d513121fa2 --- /dev/null +++ b/vendor/react/dns/src/Query/CachingExecutor.php @@ -0,0 +1,74 @@ +executor = $executor; + $this->cache = $cache; + } + public function query(Query $query) + { + $id = $query->name . ':' . $query->type . ':' . $query->class; + $cache = $this->cache; + $that = $this; + $executor = $this->executor; + $pending = $cache->get($id); + return new Promise(function ($resolve, $reject) use($query, $id, $cache, $executor, &$pending, $that) { + $pending->then(function ($message) use($query, $id, $cache, $executor, &$pending, $that) { + // return cached response message on cache hit + if ($message !== null) { + return $message; + } + // perform DNS lookup if not already cached + return $pending = $executor->query($query)->then(function (Message $message) use($cache, $id, $that) { + // DNS response message received => store in cache when not truncated and return + if (!$message->tc) { + $cache->set($id, $message, $that->ttl($message)); + } + return $message; + }); + })->then($resolve, function ($e) use($reject, &$pending) { + $reject($e); + $pending = null; + }); + }, function ($_, $reject) use(&$pending, $query) { + $reject(new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled')); + $pending->cancel(); + $pending = null; + }); + } + /** + * @param Message $message + * @return int + * @internal + */ + public function ttl(Message $message) + { + // select TTL from answers (should all be the same), use smallest value if available + // @link https://tools.ietf.org/html/rfc2181#section-5.2 + $ttl = null; + foreach ($message->answers as $answer) { + if ($ttl === null || $answer->ttl < $ttl) { + $ttl = $answer->ttl; + } + } + if ($ttl === null) { + $ttl = self::TTL; + } + return $ttl; + } +} diff --git a/vendor/react/dns/src/Query/CancellationException.php b/vendor/react/dns/src/Query/CancellationException.php new file mode 100644 index 00000000000..8c76e2e6177 --- /dev/null +++ b/vendor/react/dns/src/Query/CancellationException.php @@ -0,0 +1,7 @@ +executor = $base; + } + public function query(Query $query) + { + $key = $this->serializeQueryToIdentity($query); + if (isset($this->pending[$key])) { + // same query is already pending, so use shared reference to pending query + $promise = $this->pending[$key]; + ++$this->counts[$key]; + } else { + // no such query pending, so start new query and keep reference until it's fulfilled or rejected + $promise = $this->executor->query($query); + $this->pending[$key] = $promise; + $this->counts[$key] = 1; + $pending =& $this->pending; + $counts =& $this->counts; + $promise->then(function () use($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }, function () use($key, &$pending, &$counts) { + unset($pending[$key], $counts[$key]); + }); + } + // Return a child promise awaiting the pending query. + // Cancelling this child promise should only cancel the pending query + // when no other child promise is awaiting the same query. + $pending =& $this->pending; + $counts =& $this->counts; + return new Promise(function ($resolve, $reject) use($promise) { + $promise->then($resolve, $reject); + }, function () use(&$promise, $key, $query, &$pending, &$counts) { + if (--$counts[$key] < 1) { + unset($pending[$key], $counts[$key]); + $promise->cancel(); + $promise = null; + } + throw new \RuntimeException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + } + private function serializeQueryToIdentity(Query $query) + { + return \sprintf('%s:%s:%s', $query->name, $query->type, $query->class); + } +} diff --git a/vendor/react/dns/src/Query/ExecutorInterface.php b/vendor/react/dns/src/Query/ExecutorInterface.php new file mode 100644 index 00000000000..56d1ca09401 --- /dev/null +++ b/vendor/react/dns/src/Query/ExecutorInterface.php @@ -0,0 +1,43 @@ +query($query)->then( + * function (React\Dns\Model\Message $response) { + * // response message successfully received + * var_dump($response->rcode, $response->answers); + * }, + * function (Exception $error) { + * // failed to query due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $executor->query($query); + * + * $promise->cancel(); + * ``` + * + * @param Query $query + * @return \React\Promise\PromiseInterface<\React\Dns\Model\Message> + * resolves with response message on success or rejects with an Exception on error + */ + public function query(Query $query); +} diff --git a/vendor/react/dns/src/Query/FallbackExecutor.php b/vendor/react/dns/src/Query/FallbackExecutor.php new file mode 100644 index 00000000000..a0d42ba6d2c --- /dev/null +++ b/vendor/react/dns/src/Query/FallbackExecutor.php @@ -0,0 +1,43 @@ +executor = $executor; + $this->fallback = $fallback; + } + public function query(Query $query) + { + $cancelled = \false; + $fallback = $this->fallback; + $promise = $this->executor->query($query); + return new Promise(function ($resolve, $reject) use(&$promise, $fallback, $query, &$cancelled) { + $promise->then($resolve, function (\Exception $e1) use($fallback, $query, $resolve, $reject, &$cancelled, &$promise) { + // reject if primary resolution rejected due to cancellation + if ($cancelled) { + $reject($e1); + return; + } + // start fallback query if primary query rejected + $promise = $fallback->query($query)->then($resolve, function (\Exception $e2) use($e1, $reject) { + $append = $e2->getMessage(); + if (($pos = \strpos($append, ':')) !== \false) { + $append = \substr($append, $pos + 2); + } + // reject with combined error message if both queries fail + $reject(new \RuntimeException($e1->getMessage() . '. ' . $append)); + }); + }); + }, function () use(&$promise, &$cancelled) { + // cancel pending query (primary or fallback) + $cancelled = \true; + $promise->cancel(); + }); + } +} diff --git a/vendor/react/dns/src/Query/HostsFileExecutor.php b/vendor/react/dns/src/Query/HostsFileExecutor.php new file mode 100644 index 00000000000..c1633a43597 --- /dev/null +++ b/vendor/react/dns/src/Query/HostsFileExecutor.php @@ -0,0 +1,75 @@ +hosts = $hosts; + $this->fallback = $fallback; + } + public function query(Query $query) + { + if ($query->class === Message::CLASS_IN && ($query->type === Message::TYPE_A || $query->type === Message::TYPE_AAAA)) { + // forward lookup for type A or AAAA + $records = array(); + $expectsColon = $query->type === Message::TYPE_AAAA; + foreach ($this->hosts->getIpsForHost($query->name) as $ip) { + // ensure this is an IPv4/IPV6 address according to query type + if ((\strpos($ip, ':') !== \false) === $expectsColon) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $ip); + } + } + if ($records) { + return Promise\resolve(Message::createResponseWithAnswersForQuery($query, $records)); + } + } elseif ($query->class === Message::CLASS_IN && $query->type === Message::TYPE_PTR) { + // reverse lookup: extract IPv4 or IPv6 from special `.arpa` domain + $ip = $this->getIpFromHost($query->name); + if ($ip !== null) { + $records = array(); + foreach ($this->hosts->getHostsForIp($ip) as $host) { + $records[] = new Record($query->name, $query->type, $query->class, 0, $host); + } + if ($records) { + return Promise\resolve(Message::createResponseWithAnswersForQuery($query, $records)); + } + } + } + return $this->fallback->query($query); + } + private function getIpFromHost($host) + { + if (\substr($host, -13) === '.in-addr.arpa') { + // IPv4: read as IP and reverse bytes + $ip = @\inet_pton(\substr($host, 0, -13)); + if ($ip === \false || isset($ip[4])) { + return null; + } + return \inet_ntop(\strrev($ip)); + } elseif (\substr($host, -9) === '.ip6.arpa') { + // IPv6: replace dots, reverse nibbles and interpret as hexadecimal string + $ip = @\inet_ntop(\pack('H*', \strrev(\str_replace('.', '', \substr($host, 0, -9))))); + if ($ip === \false) { + return null; + } + return $ip; + } else { + return null; + } + } +} diff --git a/vendor/react/dns/src/Query/Query.php b/vendor/react/dns/src/Query/Query.php new file mode 100644 index 00000000000..83386f40511 --- /dev/null +++ b/vendor/react/dns/src/Query/Query.php @@ -0,0 +1,62 @@ +name = $name; + $this->type = $type; + $this->class = $class; + } + /** + * Describes the hostname and query type/class for this query + * + * The output format is supposed to be human readable and is subject to change. + * The format is inspired by RFC 3597 when handling unkown types/classes. + * + * @return string "example.com (A)" or "example.com (CLASS0 TYPE1234)" + * @link https://tools.ietf.org/html/rfc3597 + */ + public function describe() + { + $class = $this->class !== Message::CLASS_IN ? 'CLASS' . $this->class . ' ' : ''; + $type = 'TYPE' . $this->type; + $ref = new \ReflectionClass('ECSPrefix202307\\React\\Dns\\Model\\Message'); + foreach ($ref->getConstants() as $name => $value) { + if ($value === $this->type && \strpos($name, 'TYPE_') === 0) { + $type = \substr($name, 5); + break; + } + } + return $this->name . ' (' . $class . $type . ')'; + } +} diff --git a/vendor/react/dns/src/Query/RetryExecutor.php b/vendor/react/dns/src/Query/RetryExecutor.php new file mode 100644 index 00000000000..52a1852683f --- /dev/null +++ b/vendor/react/dns/src/Query/RetryExecutor.php @@ -0,0 +1,65 @@ +executor = $executor; + $this->retries = $retries; + } + public function query(Query $query) + { + return $this->tryQuery($query, $this->retries); + } + public function tryQuery(Query $query, $retries) + { + $deferred = new Deferred(function () use(&$promise) { + if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) { + $promise->cancel(); + } + }); + $success = function ($value) use($deferred, &$errorback) { + $errorback = null; + $deferred->resolve($value); + }; + $executor = $this->executor; + $errorback = function ($e) use($deferred, &$promise, $query, $success, &$errorback, &$retries, $executor) { + if (!$e instanceof TimeoutException) { + $errorback = null; + $deferred->reject($e); + } elseif ($retries <= 0) { + $errorback = null; + $deferred->reject($e = new \RuntimeException('DNS query for ' . $query->describe() . ' failed: too many retries', 0, $e)); + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + $r->setAccessible(\true); + $trace = $r->getValue($e); + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } else { + --$retries; + $promise = $executor->query($query)->then($success, $errorback); + } + }; + $promise = $this->executor->query($query)->then($success, $errorback); + return $deferred->promise(); + } +} diff --git a/vendor/react/dns/src/Query/SelectiveTransportExecutor.php b/vendor/react/dns/src/Query/SelectiveTransportExecutor.php new file mode 100644 index 00000000000..6f3f5730b6c --- /dev/null +++ b/vendor/react/dns/src/Query/SelectiveTransportExecutor.php @@ -0,0 +1,78 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * Note that this executor only implements the logic to select the correct + * transport for the given DNS query. Implementing the correct transport logic, + * implementing timeouts and any retry logic is left up to the given executors, + * see also [`UdpTransportExecutor`](#udptransportexecutor) and + * [`TcpTransportExecutor`](#tcptransportexecutor) for more details. + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new SelectiveTransportExecutor( + * $datagramExecutor, + * $streamExecutor + * ) + * ); + * ``` + */ +class SelectiveTransportExecutor implements ExecutorInterface +{ + private $datagramExecutor; + private $streamExecutor; + public function __construct(ExecutorInterface $datagramExecutor, ExecutorInterface $streamExecutor) + { + $this->datagramExecutor = $datagramExecutor; + $this->streamExecutor = $streamExecutor; + } + public function query(Query $query) + { + $stream = $this->streamExecutor; + $pending = $this->datagramExecutor->query($query); + return new Promise(function ($resolve, $reject) use(&$pending, $stream, $query) { + $pending->then($resolve, function ($e) use(&$pending, $stream, $query, $resolve, $reject) { + if ($e->getCode() === (\defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90)) { + $pending = $stream->query($query)->then($resolve, $reject); + } else { + $reject($e); + } + }); + }, function () use(&$pending) { + $pending->cancel(); + $pending = null; + }); + } +} diff --git a/vendor/react/dns/src/Query/TcpTransportExecutor.php b/vendor/react/dns/src/Query/TcpTransportExecutor.php new file mode 100644 index 00000000000..79a829b2651 --- /dev/null +++ b/vendor/react/dns/src/Query/TcpTransportExecutor.php @@ -0,0 +1,322 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also [example #92](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Unlike the `UdpTransportExecutor`, this class uses a reliable TCP/IP + * transport, so you do not necessarily have to implement any retry logic. + * + * Note that this executor is entirely async and as such allows you to execute + * queries concurrently. The first query will establish a TCP/IP socket + * connection to the DNS server which will be kept open for a short period. + * Additional queries will automatically reuse this existing socket connection + * to the DNS server, will pipeline multiple requests over this single + * connection and will keep an idle connection open for a short period. The + * initial TCP/IP connection overhead may incur a slight delay if you only send + * occasional queries – when sending a larger number of concurrent queries over + * an existing connection, it becomes increasingly more efficient and avoids + * creating many concurrent sockets like the UDP-based executor. You may still + * want to limit the number of (concurrent) queries in your application or you + * may be facing rate limitations and bans on the resolver end. For many common + * applications, you may want to avoid sending the same query multiple times + * when the first one is still pending, so you will likely want to use this in + * combination with a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new TimeoutExecutor( + * new TcpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's TCP/IP sockets and does not take advantage + * of [react/socket](https://github.com/reactphp/socket) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Socket + * component instead of reimplementing this socket logic from scratch. + */ +class TcpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + /** + * @var ?resource + */ + private $socket; + /** + * @var Deferred[] + */ + private $pending = array(); + /** + * @var string[] + */ + private $names = array(); + /** + * Maximum idle time when socket is current unused (i.e. no pending queries outstanding) + * + * If a new query is to be sent during the idle period, we can reuse the + * existing socket without having to wait for a new socket connection. + * This uses a rather small, hard-coded value to not keep any unneeded + * sockets open and to not keep the loop busy longer than needed. + * + * A future implementation may take advantage of `edns-tcp-keepalive` to keep + * the socket open for longer periods. This will likely require explicit + * configuration because this may consume additional resources and also keep + * the loop busy for longer than expected in some applications. + * + * @var float + * @link https://tools.ietf.org/html/rfc7766#section-6.2.1 + * @link https://tools.ietf.org/html/rfc7828 + */ + private $idlePeriod = 0.001; + /** + * @var ?\React\EventLoop\TimerInterface + */ + private $idleTimer; + private $writeBuffer = ''; + private $writePending = \false; + private $readBuffer = ''; + private $readPending = \false; + /** @var string */ + private $readChunk = 0xffff; + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, LoopInterface $loop = null) + { + if (\strpos($nameserver, '[') === \false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === \false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + $parts = \parse_url((\strpos($nameserver, '://') === \false ? 'tcp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'tcp' || @\inet_pton(\trim($parts['host'], '[]')) === \false) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + $this->nameserver = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + // keep shuffing message ID to avoid using the same message ID for two pending queries at the same time + while (isset($this->pending[$request->id])) { + $request->id = \mt_rand(0, 0xffff); + // @codeCoverageIgnore + } + $queryData = $this->dumper->toBinary($request); + $length = \strlen($queryData); + if ($length > 0xffff) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: Query too large for TCP transport')); + } + $queryData = \pack('n', $length) . $queryData; + if ($this->socket === null) { + // create async TCP/IP connection (may take a while) + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT); + if ($socket === \false) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno)); + } + // set socket to non-blocking and wait for it to become writable (connection success/rejected) + \stream_set_blocking($socket, \false); + if (\function_exists('stream_set_chunk_size')) { + \stream_set_chunk_size($socket, $this->readChunk); + // @codeCoverageIgnore + } + $this->socket = $socket; + } + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + // wait for socket to become writable to actually write out data + $this->writeBuffer .= $queryData; + if (!$this->writePending) { + $this->writePending = \true; + $this->loop->addWriteStream($this->socket, array($this, 'handleWritable')); + } + $names =& $this->names; + $that = $this; + $deferred = new Deferred(function () use($that, &$names, $request) { + // remove from list of pending names, but remember pending query + $name = $names[$request->id]; + unset($names[$request->id]); + $that->checkIdle(); + throw new CancellationException('DNS query for ' . $name . ' has been cancelled'); + }); + $this->pending[$request->id] = $deferred; + $this->names[$request->id] = $query->describe(); + return $deferred->promise(); + } + /** + * @internal + */ + public function handleWritable() + { + if ($this->readPending === \false) { + $name = @\stream_socket_get_name($this->socket, \true); + if ($name === \false) { + // Connection failed? Check socket error if available for underlying errno/errstr. + // @codeCoverageIgnoreStart + if (\function_exists('socket_import_stream')) { + $socket = \socket_import_stream($this->socket); + $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR); + $errstr = \socket_strerror($errno); + } else { + $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111; + $errstr = 'Connection refused'; + } + // @codeCoverageIgnoreEnd + $this->closeError('Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno); + return; + } + $this->readPending = \true; + $this->loop->addReadStream($this->socket, array($this, 'handleRead')); + } + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fwrite(): Send of 327712 bytes failed with errno=32 Broken pipe + \preg_match('/errno=(\\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + $written = \fwrite($this->socket, $this->writeBuffer); + \restore_error_handler(); + if ($written === \false || $written === 0) { + $this->closeError('Unable to send query to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno); + return; + } + if (isset($this->writeBuffer[$written])) { + $this->writeBuffer = \substr($this->writeBuffer, $written); + } else { + $this->loop->removeWriteStream($this->socket); + $this->writePending = \false; + $this->writeBuffer = ''; + } + } + /** + * @internal + */ + public function handleRead() + { + // read one chunk of data from the DNS server + // any error is fatal, this is a stream of TCP/IP data + $chunk = @\fread($this->socket, $this->readChunk); + if ($chunk === \false || $chunk === '') { + $this->closeError('Connection to DNS server ' . $this->nameserver . ' lost'); + return; + } + // reassemble complete message by concatenating all chunks. + $this->readBuffer .= $chunk; + // response message header contains at least 12 bytes + while (isset($this->readBuffer[11])) { + // read response message length from first 2 bytes and ensure we have length + data in buffer + list(, $length) = \unpack('n', $this->readBuffer); + if (!isset($this->readBuffer[$length + 1])) { + return; + } + $data = \substr($this->readBuffer, 2, $length); + $this->readBuffer = (string) \substr($this->readBuffer, $length + 2); + try { + $response = $this->parser->parseMessage($data); + } catch (\Exception $e) { + // reject all pending queries if we received an invalid message from remote server + $this->closeError('Invalid message received from DNS server ' . $this->nameserver); + return; + } + // reject all pending queries if we received an unexpected response ID or truncated response + if (!isset($this->pending[$response->id]) || $response->tc) { + $this->closeError('Invalid response message received from DNS server ' . $this->nameserver); + return; + } + $deferred = $this->pending[$response->id]; + unset($this->pending[$response->id], $this->names[$response->id]); + $deferred->resolve($response); + $this->checkIdle(); + } + } + /** + * @internal + * @param string $reason + * @param int $code + */ + public function closeError($reason, $code = 0) + { + $this->readBuffer = ''; + if ($this->readPending) { + $this->loop->removeReadStream($this->socket); + $this->readPending = \false; + } + $this->writeBuffer = ''; + if ($this->writePending) { + $this->loop->removeWriteStream($this->socket); + $this->writePending = \false; + } + if ($this->idleTimer !== null) { + $this->loop->cancelTimer($this->idleTimer); + $this->idleTimer = null; + } + @\fclose($this->socket); + $this->socket = null; + foreach ($this->names as $id => $name) { + $this->pending[$id]->reject(new \RuntimeException('DNS query for ' . $name . ' failed: ' . $reason, $code)); + } + $this->pending = $this->names = array(); + } + /** + * @internal + */ + public function checkIdle() + { + if ($this->idleTimer === null && !$this->names) { + $that = $this; + $this->idleTimer = $this->loop->addTimer($this->idlePeriod, function () use($that) { + $that->closeError('Idle timeout'); + }); + } + } +} diff --git a/vendor/react/dns/src/Query/TimeoutException.php b/vendor/react/dns/src/Query/TimeoutException.php new file mode 100644 index 00000000000..4ca338b105c --- /dev/null +++ b/vendor/react/dns/src/Query/TimeoutException.php @@ -0,0 +1,7 @@ +executor = $executor; + $this->loop = $loop ?: Loop::get(); + $this->timeout = $timeout; + } + public function query(Query $query) + { + $promise = $this->executor->query($query); + $loop = $this->loop; + $time = $this->timeout; + return new Promise(function ($resolve, $reject) use($loop, $time, $promise, $query) { + $timer = null; + $promise = $promise->then(function ($v) use(&$timer, $loop, $resolve) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = \false; + $resolve($v); + }, function ($v) use(&$timer, $loop, $reject) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = \false; + $reject($v); + }); + // promise already resolved => no need to start timer + if ($timer === \false) { + return; + } + // start timeout timer which will cancel the pending promise + $timer = $loop->addTimer($time, function () use($time, &$promise, $reject, $query) { + $reject(new TimeoutException('DNS query for ' . $query->describe() . ' timed out')); + // Cancel pending query to clean up any underlying resources and references. + // Avoid garbage references in call stack by passing pending promise by reference. + \assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + }, function () use(&$promise) { + // Cancelling this promise will cancel the pending query, thus triggering the rejection logic above. + // Avoid garbage references in call stack by passing pending promise by reference. + \assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + } +} diff --git a/vendor/react/dns/src/Query/UdpTransportExecutor.php b/vendor/react/dns/src/Query/UdpTransportExecutor.php new file mode 100644 index 00000000000..32ba6161b1c --- /dev/null +++ b/vendor/react/dns/src/Query/UdpTransportExecutor.php @@ -0,0 +1,183 @@ +query( + * new Query($name, Message::TYPE_AAAA, Message::CLASS_IN) + * )->then(function (Message $message) { + * foreach ($message->answers as $answer) { + * echo 'IPv6: ' . $answer->data . PHP_EOL; + * } + * }, 'printf'); + * ``` + * + * See also the [fourth example](examples). + * + * Note that this executor does not implement a timeout, so you will very likely + * want to use this in combination with a `TimeoutExecutor` like this: + * + * ```php + * $executor = new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ); + * ``` + * + * Also note that this executor uses an unreliable UDP transport and that it + * does not implement any retry logic, so you will likely want to use this in + * combination with a `RetryExecutor` like this: + * + * ```php + * $executor = new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ); + * ``` + * + * Note that this executor is entirely async and as such allows you to execute + * any number of queries concurrently. You should probably limit the number of + * concurrent queries in your application or you're very likely going to face + * rate limitations and bans on the resolver end. For many common applications, + * you may want to avoid sending the same query multiple times when the first + * one is still pending, so you will likely want to use this in combination with + * a `CoopExecutor` like this: + * + * ```php + * $executor = new CoopExecutor( + * new RetryExecutor( + * new TimeoutExecutor( + * new UdpTransportExecutor($nameserver), + * 3.0 + * ) + * ) + * ); + * ``` + * + * > Internally, this class uses PHP's UDP sockets and does not take advantage + * of [react/datagram](https://github.com/reactphp/datagram) purely for + * organizational reasons to avoid a cyclic dependency between the two + * packages. Higher-level components should take advantage of the Datagram + * component instead of reimplementing this socket logic from scratch. + */ +final class UdpTransportExecutor implements ExecutorInterface +{ + private $nameserver; + private $loop; + private $parser; + private $dumper; + /** + * maximum UDP packet size to send and receive + * + * @var int + */ + private $maxPacketSize = 512; + /** + * @param string $nameserver + * @param ?LoopInterface $loop + */ + public function __construct($nameserver, LoopInterface $loop = null) + { + if (\strpos($nameserver, '[') === \false && \substr_count($nameserver, ':') >= 2 && \strpos($nameserver, '://') === \false) { + // several colons, but not enclosed in square brackets => enclose IPv6 address in square brackets + $nameserver = '[' . $nameserver . ']'; + } + $parts = \parse_url((\strpos($nameserver, '://') === \false ? 'udp://' : '') . $nameserver); + if (!isset($parts['scheme'], $parts['host']) || $parts['scheme'] !== 'udp' || @\inet_pton(\trim($parts['host'], '[]')) === \false) { + throw new \InvalidArgumentException('Invalid nameserver address given'); + } + $this->nameserver = 'udp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : 53); + $this->loop = $loop ?: Loop::get(); + $this->parser = new Parser(); + $this->dumper = new BinaryDumper(); + } + public function query(Query $query) + { + $request = Message::createRequestForQuery($query); + $queryData = $this->dumper->toBinary($request); + if (isset($queryData[$this->maxPacketSize])) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: Query too large for UDP transport', \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90)); + } + // UDP connections are instant, so try connection without a loop or timeout + $errno = 0; + $errstr = ''; + $socket = @\stream_socket_client($this->nameserver, $errno, $errstr, 0); + if ($socket === \false) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: Unable to connect to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno)); + } + // set socket to non-blocking and immediately try to send (fill write buffer) + \stream_set_blocking($socket, \false); + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // Write may potentially fail, but most common errors are already caught by connection check above. + // Among others, macOS is known to report here when trying to send to broadcast address. + // This can also be reproduced by writing data exceeding `stream_set_chunk_size()` to a server refusing UDP data. + // fwrite(): send of 8192 bytes failed with errno=111 Connection refused + \preg_match('/errno=(\\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + $written = \fwrite($socket, $queryData); + \restore_error_handler(); + if ($written !== \strlen($queryData)) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: Unable to send query to DNS server ' . $this->nameserver . ' (' . $errstr . ')', $errno)); + } + $loop = $this->loop; + $deferred = new Deferred(function () use($loop, $socket, $query) { + // cancellation should remove socket from loop and close socket + $loop->removeReadStream($socket); + \fclose($socket); + throw new CancellationException('DNS query for ' . $query->describe() . ' has been cancelled'); + }); + $max = $this->maxPacketSize; + $parser = $this->parser; + $nameserver = $this->nameserver; + $loop->addReadStream($socket, function ($socket) use($loop, $deferred, $query, $parser, $request, $max, $nameserver) { + // try to read a single data packet from the DNS server + // ignoring any errors, this is uses UDP packets and not a stream of data + $data = @\fread($socket, $max); + if ($data === \false) { + return; + } + try { + $response = $parser->parseMessage($data); + } catch (\Exception $e) { + // ignore and await next if we received an invalid message from remote server + // this may as well be a fake response from an attacker (possible DOS) + return; + } + // ignore and await next if we received an unexpected response ID + // this may as well be a fake response from an attacker (possible cache poisoning) + if ($response->id !== $request->id) { + return; + } + // we only react to the first valid message, so remove socket from loop and close + $loop->removeReadStream($socket); + \fclose($socket); + if ($response->tc) { + $deferred->reject(new \RuntimeException('DNS query for ' . $query->describe() . ' failed: The DNS server ' . $nameserver . ' returned a truncated result for a UDP query', \defined('SOCKET_EMSGSIZE') ? \SOCKET_EMSGSIZE : 90)); + return; + } + $deferred->resolve($response); + }); + return $deferred->promise(); + } +} diff --git a/vendor/react/dns/src/RecordNotFoundException.php b/vendor/react/dns/src/RecordNotFoundException.php new file mode 100644 index 00000000000..f4f70007b65 --- /dev/null +++ b/vendor/react/dns/src/RecordNotFoundException.php @@ -0,0 +1,7 @@ +decorateHostsFileExecutor($this->createExecutor($config, $loop ?: Loop::get())); + return new Resolver($executor); + } + /** + * Creates a cached DNS resolver instance for the given DNS config and cache + * + * As of v1.7.0 it's recommended to pass a `Config` object instead of a + * single nameserver address. If the given config contains more than one DNS + * nameserver, all DNS nameservers will be used in order. The primary DNS + * server will always be used first before falling back to the secondary or + * tertiary DNS server. + * + * @param Config|string $config DNS Config object (recommended) or single nameserver address + * @param ?LoopInterface $loop + * @param ?CacheInterface $cache + * @return \React\Dns\Resolver\ResolverInterface + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + public function createCached($config, LoopInterface $loop = null, CacheInterface $cache = null) + { + // default to keeping maximum of 256 responses in cache unless explicitly given + if (!$cache instanceof CacheInterface) { + $cache = new ArrayCache(256); + } + $executor = $this->createExecutor($config, $loop ?: Loop::get()); + $executor = new CachingExecutor($executor, $cache); + $executor = $this->decorateHostsFileExecutor($executor); + return new Resolver($executor); + } + /** + * Tries to load the hosts file and decorates the given executor on success + * + * @param ExecutorInterface $executor + * @return ExecutorInterface + * @codeCoverageIgnore + */ + private function decorateHostsFileExecutor(ExecutorInterface $executor) + { + try { + $executor = new HostsFileExecutor(HostsFile::loadFromPathBlocking(), $executor); + } catch (\RuntimeException $e) { + // ignore this file if it can not be loaded + } + // Windows does not store localhost in hosts file by default but handles this internally + // To compensate for this, we explicitly use hard-coded defaults for localhost + if (\DIRECTORY_SEPARATOR === '\\') { + $executor = new HostsFileExecutor(new HostsFile("127.0.0.1 localhost\n::1 localhost"), $executor); + } + return $executor; + } + /** + * @param Config|string $nameserver + * @param LoopInterface $loop + * @return CoopExecutor + * @throws \InvalidArgumentException for invalid DNS server address + * @throws \UnderflowException when given DNS Config object has an empty list of nameservers + */ + private function createExecutor($nameserver, LoopInterface $loop) + { + if ($nameserver instanceof Config) { + if (!$nameserver->nameservers) { + throw new \UnderflowException('Empty config with no DNS servers'); + } + // Hard-coded to check up to 3 DNS servers to match default limits in place in most systems (see MAXNS config). + // Note to future self: Recursion isn't too hard, but how deep do we really want to go? + $primary = \reset($nameserver->nameservers); + $secondary = \next($nameserver->nameservers); + $tertiary = \next($nameserver->nameservers); + if ($tertiary !== \false) { + // 3 DNS servers given => nest first with fallback for second and third + return new CoopExecutor(new RetryExecutor(new FallbackExecutor($this->createSingleExecutor($primary, $loop), new FallbackExecutor($this->createSingleExecutor($secondary, $loop), $this->createSingleExecutor($tertiary, $loop))))); + } elseif ($secondary !== \false) { + // 2 DNS servers given => fallback from first to second + return new CoopExecutor(new RetryExecutor(new FallbackExecutor($this->createSingleExecutor($primary, $loop), $this->createSingleExecutor($secondary, $loop)))); + } else { + // 1 DNS server given => use single executor + $nameserver = $primary; + } + } + return new CoopExecutor(new RetryExecutor($this->createSingleExecutor($nameserver, $loop))); + } + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return ExecutorInterface + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createSingleExecutor($nameserver, LoopInterface $loop) + { + $parts = \parse_url($nameserver); + if (isset($parts['scheme']) && $parts['scheme'] === 'tcp') { + $executor = $this->createTcpExecutor($nameserver, $loop); + } elseif (isset($parts['scheme']) && $parts['scheme'] === 'udp') { + $executor = $this->createUdpExecutor($nameserver, $loop); + } else { + $executor = new SelectiveTransportExecutor($this->createUdpExecutor($nameserver, $loop), $this->createTcpExecutor($nameserver, $loop)); + } + return $executor; + } + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createTcpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor(new TcpTransportExecutor($nameserver, $loop), 5.0, $loop); + } + /** + * @param string $nameserver + * @param LoopInterface $loop + * @return TimeoutExecutor + * @throws \InvalidArgumentException for invalid DNS server address + */ + private function createUdpExecutor($nameserver, LoopInterface $loop) + { + return new TimeoutExecutor(new UdpTransportExecutor($nameserver, $loop), 5.0, $loop); + } +} diff --git a/vendor/react/dns/src/Resolver/Resolver.php b/vendor/react/dns/src/Resolver/Resolver.php new file mode 100644 index 00000000000..0511280efa3 --- /dev/null +++ b/vendor/react/dns/src/Resolver/Resolver.php @@ -0,0 +1,121 @@ +executor = $executor; + } + public function resolve($domain) + { + return $this->resolveAll($domain, Message::TYPE_A)->then(function (array $ips) { + return $ips[\array_rand($ips)]; + }); + } + public function resolveAll($domain, $type) + { + $query = new Query($domain, $type, Message::CLASS_IN); + $that = $this; + return $this->executor->query($query)->then(function (Message $response) use($query, $that) { + return $that->extractValues($query, $response); + }); + } + /** + * [Internal] extract all resource record values from response for this query + * + * @param Query $query + * @param Message $response + * @return array + * @throws RecordNotFoundException when response indicates an error or contains no data + * @internal + */ + public function extractValues(Query $query, Message $response) + { + // reject if response code indicates this is an error response message + $code = $response->rcode; + if ($code !== Message::RCODE_OK) { + switch ($code) { + case Message::RCODE_FORMAT_ERROR: + $message = 'Format Error'; + break; + case Message::RCODE_SERVER_FAILURE: + $message = 'Server Failure'; + break; + case Message::RCODE_NAME_ERROR: + $message = 'Non-Existent Domain / NXDOMAIN'; + break; + case Message::RCODE_NOT_IMPLEMENTED: + $message = 'Not Implemented'; + break; + case Message::RCODE_REFUSED: + $message = 'Refused'; + break; + default: + $message = 'Unknown error response code ' . $code; + } + throw new RecordNotFoundException('DNS query for ' . $query->describe() . ' returned an error response (' . $message . ')', $code); + } + $answers = $response->answers; + $addresses = $this->valuesByNameAndType($answers, $query->name, $query->type); + // reject if we did not receive a valid answer (domain is valid, but no record for this type could be found) + if (0 === \count($addresses)) { + throw new RecordNotFoundException('DNS query for ' . $query->describe() . ' did not return a valid answer (NOERROR / NODATA)'); + } + return \array_values($addresses); + } + /** + * @param \React\Dns\Model\Record[] $answers + * @param string $name + * @param int $type + * @return array + */ + private function valuesByNameAndType(array $answers, $name, $type) + { + // return all record values for this name and type (if any) + $named = $this->filterByName($answers, $name); + $records = $this->filterByType($named, $type); + if ($records) { + return $this->mapRecordData($records); + } + // no matching records found? check if there are any matching CNAMEs instead + $cnameRecords = $this->filterByType($named, Message::TYPE_CNAME); + if ($cnameRecords) { + $cnames = $this->mapRecordData($cnameRecords); + foreach ($cnames as $cname) { + $records = \array_merge($records, $this->valuesByNameAndType($answers, $cname, $type)); + } + } + return $records; + } + private function filterByName(array $answers, $name) + { + return $this->filterByField($answers, 'name', $name); + } + private function filterByType(array $answers, $type) + { + return $this->filterByField($answers, 'type', $type); + } + private function filterByField(array $answers, $field, $value) + { + $value = \strtolower($value); + return \array_filter($answers, function ($answer) use($field, $value) { + return $value === \strtolower($answer->{$field}); + }); + } + private function mapRecordData(array $records) + { + return \array_map(function ($record) { + return $record->data; + }, $records); + } +} diff --git a/vendor/react/dns/src/Resolver/ResolverInterface.php b/vendor/react/dns/src/Resolver/ResolverInterface.php new file mode 100644 index 00000000000..b3a95ad8cfa --- /dev/null +++ b/vendor/react/dns/src/Resolver/ResolverInterface.php @@ -0,0 +1,93 @@ +resolve('reactphp.org')->then(function ($ip) { + * echo 'IP for reactphp.org is ' . $ip . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a single IP + * address on success. + * + * If the DNS server sends a DNS response message that contains more than + * one IP address for this query, it will randomly pick one of the IP + * addresses from the response. If you want the full list of IP addresses + * or want to send a different type of query, you should use the + * [`resolveAll()`](#resolveall) method instead. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolve('reactphp.org'); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * resolves with a single IP address on success or rejects with an Exception on error. + */ + public function resolve($domain); + /** + * Resolves all record values for the given $domain name and query $type. + * + * ```php + * $resolver->resolveAll('reactphp.org', Message::TYPE_A)->then(function ($ips) { + * echo 'IPv4 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * + * $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA)->then(function ($ips) { + * echo 'IPv6 addresses for reactphp.org ' . implode(', ', $ips) . PHP_EOL; + * }); + * ``` + * + * This is one of the main methods in this package. It sends a DNS query + * for the given $domain name to your DNS server and returns a list with all + * record values on success. + * + * If the DNS server sends a DNS response message that contains one or more + * records for this query, it will return a list with all record values + * from the response. You can use the `Message::TYPE_*` constants to control + * which type of query will be sent. Note that this method always returns a + * list of record values, but each record value type depends on the query + * type. For example, it returns the IPv4 addresses for type `A` queries, + * the IPv6 addresses for type `AAAA` queries, the hostname for type `NS`, + * `CNAME` and `PTR` queries and structured data for other queries. See also + * the `Record` documentation for more details. + * + * If the DNS server sends a DNS response message that indicates an error + * code, this method will reject with a `RecordNotFoundException`. Its + * message and code can be used to check for the response code. + * + * If the DNS communication fails and the server does not respond with a + * valid response message, this message will reject with an `Exception`. + * + * Pending DNS queries can be cancelled by cancelling its pending promise like so: + * + * ```php + * $promise = $resolver->resolveAll('reactphp.org', Message::TYPE_AAAA); + * + * $promise->cancel(); + * ``` + * + * @param string $domain + * @return \React\Promise\PromiseInterface + * Resolves with all record values on success or rejects with an Exception on error. + */ + public function resolveAll($domain, $type); +} diff --git a/vendor/react/event-loop/CHANGELOG.md b/vendor/react/event-loop/CHANGELOG.md new file mode 100644 index 00000000000..1647dbe3500 --- /dev/null +++ b/vendor/react/event-loop/CHANGELOG.md @@ -0,0 +1,457 @@ +# Changelog + +## 1.4.0 (2023-05-05) + +* Feature: Improve performance of `Loop` by avoiding unneeded method calls. + (#266 by @clue) + +* Feature: Support checking `EINTR` constant from `ext-pcntl` without `ext-sockets`. + (#265 by @clue) + +* Minor documentation improvements. + (#254 by @nhedger) + +* Improve test suite, run tests on PHP 8.2 and report failed assertions. + (#258 by @WyriHaximus, #264 by @clue and #251, #261 and #262 by @SimonFrings) + +## 1.3.0 (2022-03-17) + +* Feature: Improve default `StreamSelectLoop` to report any warnings for invalid streams. + (#245 by @clue) + +* Feature: Improve performance of `StreamSelectLoop` when no timers are scheduled. + (#246 by @clue) + +* Fix: Fix periodic timer with zero interval for `ExtEvLoop` and legacy `ExtLibevLoop`. + (#243 by @lucasnetau) + +* Minor documentation improvements, update PHP version references. + (#240, #248 and #250 by @SimonFrings, #241 by @dbu and #249 by @clue) + +* Improve test suite and test against PHP 8.1. + (#238 by @WyriHaximus and #242 by @clue) + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Introduce new concept of default loop with the new `Loop` class. + (#226 by @WyriHaximus, #229, #231 and #232 by @clue) + + The `Loop` class exists as a convenient global accessor for the event loop. + It provides all methods that exist on the `LoopInterface` as static methods and + will automatically execute the loop at the end of the program: + + ```php + $timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; + }); + + Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; + }); + ``` + + The explicit loop instructions are still valid and may still be useful in some applications, + especially for a transition period towards the more concise style. + The `Loop::get()` method can be used to get the currently active event loop instance. + + ```php + // deprecated + $loop = React\EventLoop\Factory::create(); + + // new + $loop = React\EventLoop\Loop::get(); + ``` + +* Minor documentation improvements and mark legacy extensions as deprecated. + (#234 by @SimonFrings, #214 by @WyriHaximus and #233 and #235 by @nhedger) + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config and run tests on PHP 8. + (#212 and #215 by @SimonFrings and #230 by @clue) + +## 1.1.1 (2020-01-01) + +* Fix: Fix reporting connection refused errors with `ExtUvLoop` on Linux and `StreamSelectLoop` on Windows. + (#207 and #208 by @clue) + +* Fix: Fix unsupported EventConfig and `SEGFAULT` on shutdown with `ExtEventLoop` on Windows. + (#205 by @clue) + +* Fix: Prevent interval overflow for timers very far in the future with `ExtUvLoop`. + (#196 by @PabloKowalczyk) + +* Fix: Check PCNTL functions for signal support instead of PCNTL extension with `StreamSelectLoop`. + (#195 by @clue) + +* Add `.gitattributes` to exclude dev files from exports. + (#201 by @reedy) + +* Improve test suite to fix testing `ExtUvLoop` on Travis, + fix Travis CI builds, do not install `libuv` on legacy PHP setups, + fix failing test cases due to inaccurate timers, + run tests on Windows via Travis CI and + run tests on PHP 7.4 and simplify test matrix and test setup. + (#197 by @WyriHaximus and #202, #203, #204 and #209 by @clue) + +## 1.1.0 (2019-02-07) + +* New UV based event loop (ext-uv). + (#112 by @WyriHaximus) + +* Use high resolution timer on PHP 7.3+. + (#182 by @clue) + +* Improve PCNTL signals by using async signal dispatching if available. + (#179 by @CharlotteDunois) + +* Improve test suite and test suite set up. + (#174 by @WyriHaximus, #181 by @clue) + +* Fix PCNTL signals edge case. + (#183 by @clue) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.5.3 release. + +## 0.5.3 (2018-07-09) + +* Improve performance by importing global functions. + (#167 by @Ocramius) + +* Improve test suite by simplifying test bootstrap by using dev autoloader. + (#169 by @lcobucci) + +* Minor internal changes to improved backward compatibility with PHP 5.3. + (#166 by @Donatello-za) + +## 0.5.2 (2018-04-24) + +* Feature: Improve memory consumption and runtime performance for `StreamSelectLoop` timers. + (#164 by @clue) + +* Improve test suite by removing I/O dependency at `StreamSelectLoopTest` to fix Mac OS X tests. + (#161 by @nawarian) + +## 0.5.1 (2018-04-09) + +* Feature: New `ExtEvLoop` (PECL ext-ev) (#148 by @kaduev13) + +## 0.5.0 (2018-04-05) + +A major feature release with a significant documentation overhaul and long overdue API cleanup! + +This update involves a number of BC breaks due to dropped support for deprecated +functionality. We've tried hard to avoid BC breaks where possible and minimize +impact otherwise. We expect that most consumers of this package will actually +not be affected by any BC breaks, see below for more details. + +We realize that the changes listed below may seem overwhelming, but we've tried +to be very clear about any possible BC breaks. Don't worry: In fact, all ReactPHP +components are already compatible and support both this new release as well as +providing backwards compatibility with the last release. + +* Feature / BC break: Add support for signal handling via new + `LoopInterface::addSignal()` and `LoopInterface::removeSignal()` methods. + (#104 by @WyriHaximus and #111 and #150 by @clue) + + ```php + $loop->addSignal(SIGINT, function () { + echo 'CTRL-C'; + }); + ``` + +* Feature: Significant documentation updates for `LoopInterface` and `Factory`. + (#100, #119, #126, #127, #159 and #160 by @clue, #113 by @WyriHaximus and #81 and #91 by @jsor) + +* Feature: Add examples to ease getting started + (#99, #100 and #125 by @clue, #59 by @WyriHaximus and #143 by @jsor) + +* Feature: Documentation for advanced timer concepts, such as monotonic time source vs wall-clock time + and high precision timers with millisecond accuracy or below. + (#130 and #157 by @clue) + +* Feature: Documentation for advanced stream concepts, such as edge-triggered event listeners + and stream buffers and allow throwing Exception if stream resource is not supported. + (#129 and #158 by @clue) + +* Feature: Throw `BadMethodCallException` on manual loop creation when required extension isn't installed. + (#153 by @WyriHaximus) + +* Feature / BC break: First class support for legacy PHP 5.3 through PHP 7.2 and HHVM + and remove all `callable` type hints for consistency reasons. + (#141 and #151 by @clue) + +* BC break: Documentation for timer API and clean up unneeded timer API. + (#102 by @clue) + + Remove `TimerInterface::cancel()`, use `LoopInterface::cancelTimer()` instead: + + ```php + // old (method invoked on timer instance) + $timer->cancel(); + + // already supported before: invoke method on loop instance + $loop->cancelTimer($timer); + ``` + + Remove unneeded `TimerInterface::setData()` and `TimerInterface::getData()`, + use closure binding to add arbitrary data to timer instead: + + ```php + // old (limited setData() and getData() only allows single variable) + $name = 'Tester'; + $timer = $loop->addTimer(1.0, function ($timer) { + echo 'Hello ' . $timer->getData() . PHP_EOL; + }); + $timer->setData($name); + + // already supported before: closure binding allows any number of variables + $name = 'Tester'; + $loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . PHP_EOL; + }); + ``` + + Remove unneeded `TimerInterface::getLoop()`, use closure binding instead: + + ```php + // old (getLoop() called on timer instance) + $loop->addTimer(0.1, function ($timer) { + $timer->getLoop()->stop(); + }); + + // already supported before: use closure binding as usual + $loop->addTimer(0.1, function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::isTimerActive()` and + `TimerInterface::isActive()` to reduce API surface. + (#133 by @clue) + + ```php + // old (method on timer instance or on loop instance) + $timer->isActive(); + $loop->isTimerActive($timer); + ``` + +* BC break: Move `TimerInterface` one level up to `React\EventLoop\TimerInterface`. + (#138 by @WyriHaximus) + + ```php + // old (notice obsolete "Timer" namespace) + assert($timer instanceof React\EventLoop\Timer\TimerInterface); + + // new + assert($timer instanceof React\EventLoop\TimerInterface); + ``` + +* BC break: Remove unneeded `LoopInterface::nextTick()` (and internal `NextTickQueue`), + use `LoopInterface::futureTick()` instead. + (#30 by @clue) + + ```php + // old (removed) + $loop->nextTick(function () { + echo 'tick'; + }); + + // already supported before + $loop->futureTick(function () { + echo 'tick'; + }); + ``` + +* BC break: Remove unneeded `$loop` argument for `LoopInterface::futureTick()` + (and fix internal cyclic dependency). + (#103 by @clue) + + ```php + // old ($loop gets passed by default) + $loop->futureTick(function ($loop) { + $loop->stop(); + }); + + // already supported before: use closure binding as usual + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::tick()`. + (#72 by @jsor) + + ```php + // old (removed) + $loop->tick(); + + // suggested work around for testing purposes only + $loop->futureTick(function () use ($loop) { + $loop->stop(); + }); + ``` + +* BC break: Documentation for advanced stream API and clean up unneeded stream API. + (#110 by @clue) + + Remove unneeded `$loop` argument for `LoopInterface::addReadStream()` + and `LoopInterface::addWriteStream()`, use closure binding instead: + + ```php + // old ($loop gets passed by default) + $loop->addReadStream($stream, function ($stream, $loop) { + $loop->removeReadStream($stream); + }); + + // already supported before: use closure binding as usual + $loop->addReadStream($stream, function ($stream) use ($loop) { + $loop->removeReadStream($stream); + }); + ``` + +* BC break: Remove unneeded `LoopInterface::removeStream()` method, + use `LoopInterface::removeReadStream()` and `LoopInterface::removeWriteStream()` instead. + (#118 by @clue) + + ```php + // old + $loop->removeStream($stream); + + // already supported before + $loop->removeReadStream($stream); + $loop->removeWriteStream($stream); + ``` + +* BC break: Rename `LibEventLoop` to `ExtLibeventLoop` and `LibEvLoop` to `ExtLibevLoop` + for consistent naming for event loop implementations. + (#128 by @clue) + +* BC break: Remove optional `EventBaseConfig` argument from `ExtEventLoop` + and make its `FEATURE_FDS` enabled by default. + (#156 by @WyriHaximus) + +* BC break: Mark all classes as final to discourage inheritance. + (#131 by @clue) + +* Fix: Fix `ExtEventLoop` to keep track of stream resources (refcount) + (#123 by @clue) + +* Fix: Ensure large timer interval does not overflow on 32bit systems + (#132 by @clue) + +* Fix: Fix separately removing readable and writable side of stream when closing + (#139 by @clue) + +* Fix: Properly clean up event watchers for `ext-event` and `ext-libev` + (#149 by @clue) + +* Fix: Minor code cleanup and remove unneeded references + (#145 by @seregazhuk) + +* Fix: Discourage outdated `ext-libevent` on PHP 7 + (#62 by @cboden) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and PHPUnit 5, + lock Travis distro so new defaults will not break the build, + improve test suite to be less fragile and increase test timeouts, + test against PHP 7.2 and reduce fwrite() call length to one chunk. + (#106 and #144 by @clue, #120 and #124 by @carusogabriel, #147 by nawarian and #92 by @kelunik) + +* A number of changes were originally planned for this release but have been backported + to the last `v0.4.3` already: #74, #76, #79, #81 (refs #65, #66, #67), #88 and #93 + +## 0.4.3 (2017-04-27) + +* Bug fix: Bugfix in the usage sample code #57 (@dandelionred) +* Improvement: Remove branch-alias definition #53 (@WyriHaximus) +* Improvement: StreamSelectLoop: Use fresh time so Timers added during stream events are accurate #51 (@andrewminerd) +* Improvement: Avoid deprecation warnings in test suite due to deprecation of getMock() in PHPUnit #68 (@martinschroeder) +* Improvement: Add PHPUnit 4.8 to require-dev #69 (@shaunbramley) +* Improvement: Increase test timeouts for HHVM and unify timeout handling #70 (@clue) +* Improvement: Travis improvements (backported from #74) #75 (@clue) +* Improvement: Test suite now uses socket pairs instead of memory streams #66 (@martinschroeder) +* Improvement: StreamSelectLoop: Test suite uses signal constant names in data provider #67 (@martinschroeder) +* Improvement: ExtEventLoop: No longer suppress all errors #65 (@mamciek) +* Improvement: Readme cleanup #89 (@jsor) +* Improvement: Restructure and improve README #90 (@jsor) +* Bug fix: StreamSelectLoop: Fix erroneous zero-time sleep (backport to 0.4) #94 (@jsor) + +## 0.4.2 (2016-03-07) + +* Bug fix: No longer error when signals sent to StreamSelectLoop +* Support HHVM and PHP7 (@ondrejmirtes, @cebe) +* Feature: Added support for EventConfig for ExtEventLoop (@steverhoades) +* Bug fix: Fixed an issue loading loop extension libs via autoloader (@czarpino) + +## 0.4.1 (2014-04-13) + +* Bug fix: null timeout in StreamSelectLoop causing 100% CPU usage (@clue) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.4.0 (2014-02-02) + +* Feature: Added `EventLoopInterface::nextTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `EventLoopInterface::futureTick()`, implemented in all event loops (@jmalloc) +* Feature: Added `ExtEventLoop` implementation using pecl/event (@jmalloc) +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: New method: `EventLoopInterface::nextTick()` +* BC break: New method: `EventLoopInterface::futureTick()` +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.5 (2016-12-28) + +This is a compatibility release that eases upgrading to the v0.4 release branch. +You should consider upgrading to the v0.4 release branch. + +* Feature: Cap min timer interval at 1µs, thus improving compatibility with v0.4 + (#47 by @clue) + +## 0.3.4 (2014-03-30) + +* Bug fix: Changed StreamSelectLoop to use non-blocking behavior on tick() (@astephens25) + +## 0.3.3 (2013-07-08) + +* Bug fix: No error on removing non-existent streams (@clue) +* Bug fix: Do not silently remove feof listeners in `LibEvLoop` + +## 0.3.0 (2013-04-14) + +* BC break: New timers API (@nrk) +* BC break: Remove check on return value from stream callbacks (@nrk) + +## 0.2.7 (2013-01-05) + +* Bug fix: Fix libevent timers with PHP 5.3 +* Bug fix: Fix libevent timer cancellation (@nrk) + +## 0.2.6 (2012-12-26) + +* Bug fix: Plug memory issue in libevent timers (@cameronjacobson) +* Bug fix: Correctly pause LibEvLoop on stop() + +## 0.2.3 (2012-11-14) + +* Feature: LibEvLoop, integration of `php-libev` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/vendor/react/event-loop/LICENSE b/vendor/react/event-loop/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/event-loop/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/event-loop/README.md b/vendor/react/event-loop/README.md new file mode 100644 index 00000000000..8ec9621af2b --- /dev/null +++ b/vendor/react/event-loop/README.md @@ -0,0 +1,930 @@ +# EventLoop + +[![CI status](https://github.com/reactphp/event-loop/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/event-loop/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/event-loop?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/event-loop) + +[ReactPHP](https://reactphp.org/)'s core reactor event loop that libraries can use for evented I/O. + +In order for async based libraries to be interoperable, they need to use the +same event loop. This component provides a common `LoopInterface` that any +library can target. This allows them to be used in the same loop, with one +single [`run()`](#run) call that is controlled by the user. + +**Table of contents** + +* [Quickstart example](#quickstart-example) +* [Usage](#usage) + * [Loop](#loop) + * [Loop methods](#loop-methods) + * [Loop autorun](#loop-autorun) + * [get()](#get) + * [~~Factory~~](#factory) + * [~~create()~~](#create) + * [Loop implementations](#loop-implementations) + * [StreamSelectLoop](#streamselectloop) + * [ExtEventLoop](#exteventloop) + * [ExtEvLoop](#extevloop) + * [ExtUvLoop](#extuvloop) + * [~~ExtLibeventLoop~~](#extlibeventloop) + * [~~ExtLibevLoop~~](#extlibevloop) + * [LoopInterface](#loopinterface) + * [run()](#run) + * [stop()](#stop) + * [addTimer()](#addtimer) + * [addPeriodicTimer()](#addperiodictimer) + * [cancelTimer()](#canceltimer) + * [futureTick()](#futuretick) + * [addSignal()](#addsignal) + * [removeSignal()](#removesignal) + * [addReadStream()](#addreadstream) + * [addWriteStream()](#addwritestream) + * [removeReadStream()](#removereadstream) + * [removeWriteStream()](#removewritestream) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Quickstart example + +Here is an async HTTP server built with just the event loop. + +```php +addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); + +$loop->run(); +``` + +While the former is more concise, the latter is more explicit. +In both cases, the program would perform the exact same steps. + +1. The event loop instance is created at the beginning of the program. This is + implicitly done the first time you call the [`Loop` class](#loop) or + explicitly when using the deprecated [`Factory::create()` method](#create) + (or manually instantiating any of the [loop implementations](#loop-implementations)). +2. The event loop is used directly or passed as an instance to library and + application code. In this example, a periodic timer is registered with the + event loop which simply outputs `Tick` every fraction of a second until another + timer stops the periodic timer after a second. +3. The event loop is run at the end of the program. This is automatically done + when using the [`Loop` class](#loop) or explicitly with a single [`run()`](#run) + call at the end of the program. + +As of `v1.2.0`, we highly recommend using the [`Loop` class](#loop). +The explicit loop instructions are still valid and may still be useful in some +applications, especially for a transition period towards the more concise style. + +### Loop + +The `Loop` class exists as a convenient global accessor for the event loop. + +#### Loop methods + +The `Loop` class provides all methods that exist on the [`LoopInterface`](#loopinterface) +as static methods: + +* [run()](#run) +* [stop()](#stop) +* [addTimer()](#addtimer) +* [addPeriodicTimer()](#addperiodictimer) +* [cancelTimer()](#canceltimer) +* [futureTick()](#futuretick) +* [addSignal()](#addsignal) +* [removeSignal()](#removesignal) +* [addReadStream()](#addreadstream) +* [addWriteStream()](#addwritestream) +* [removeReadStream()](#removereadstream) +* [removeWriteStream()](#removewritestream) + +If you're working with the event loop in your application code, it's often +easiest to directly interface with the static methods defined on the `Loop` class +like this: + +```php +use React\EventLoop\Loop; + +$timer = Loop::addPeriodicTimer(0.1, function () { + echo 'Tick' . PHP_EOL; +}); + +Loop::addTimer(1.0, function () use ($timer) { + Loop::cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +On the other hand, if you're familiar with object-oriented programming (OOP) and +dependency injection (DI), you may want to inject an event loop instance and +invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +Each static method call will be forwarded as-is to the underlying event loop +instance by using the [`Loop::get()`](#get) call internally. +See [`LoopInterface`](#loopinterface) for more details about available methods. + +#### Loop autorun + +When using the `Loop` class, it will automatically execute the loop at the end of +the program. This means the following example will schedule a timer and will +automatically execute the program until the timer event fires: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(1.0, function () { + echo 'Hello' . PHP_EOL; +}); +``` + +As of `v1.2.0`, we highly recommend using the `Loop` class this way and omitting any +explicit [`run()`](#run) calls. For BC reasons, the explicit [`run()`](#run) +method is still valid and may still be useful in some applications, especially +for a transition period towards the more concise style. + +If you don't want the `Loop` to run automatically, you can either explicitly +[`run()`](#run) or [`stop()`](#stop) it. This can be useful if you're using +a global exception handler like this: + +```php +use React\EventLoop\Loop; + +Loop::addTimer(10.0, function () { + echo 'Never happens'; +}); + +set_exception_handler(function (Throwable $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; + Loop::stop(); +}); + +throw new RuntimeException('Demo'); +``` + +#### get() + +The `get(): LoopInterface` method can be used to +get the currently active event loop instance. + +This method will always return the same event loop instance throughout the +lifetime of your application. + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +$loop = Loop::get(); + +assert($loop instanceof LoopInterface); +assert($loop === Loop::get()); +``` + +This is particularly useful if you're using object-oriented programming (OOP) +and dependency injection (DI). In this case, you may want to inject an event +loop instance and invoke instance methods on the `LoopInterface` like this: + +```php +use React\EventLoop\Loop; +use React\EventLoop\LoopInterface; + +class Greeter +{ + private $loop; + + public function __construct(LoopInterface $loop) + { + $this->loop = $loop; + } + + public function greet(string $name) + { + $this->loop->addTimer(1.0, function () use ($name) { + echo 'Hello ' . $name . '!' . PHP_EOL; + }); + } +} + +$greeter = new Greeter(Loop::get()); +$greeter->greet('Alice'); +$greeter->greet('Bob'); +``` + +See [`LoopInterface`](#loopinterface) for more details about available methods. + +### ~~Factory~~ + +> Deprecated since v1.2.0, see [`Loop` class](#loop) instead. + +The deprecated `Factory` class exists as a convenient way to pick the best available +[event loop implementation](#loop-implementations). + +#### ~~create()~~ + +> Deprecated since v1.2.0, see [`Loop::get()`](#get) instead. + +The deprecated `create(): LoopInterface` method can be used to +create a new event loop instance: + +```php +// deprecated +$loop = React\EventLoop\Factory::create(); + +// new +$loop = React\EventLoop\Loop::get(); +``` + +This method always returns an instance implementing [`LoopInterface`](#loopinterface), +the actual [event loop implementation](#loop-implementations) is an implementation detail. + +This method should usually only be called once at the beginning of the program. + +### Loop implementations + +In addition to the [`LoopInterface`](#loopinterface), there are a number of +event loop implementations provided. + +All of the event loops support these features: + +* File descriptor polling +* One-off timers +* Periodic timers +* Deferred execution on future loop tick + +For most consumers of this package, the underlying event loop implementation is +an implementation detail. +You should use the [`Loop` class](#loop) to automatically create a new instance. + +Advanced! If you explicitly need a certain event loop implementation, you can +manually instantiate one of the following classes. +Note that you may have to install the required PHP extensions for the respective +event loop implementation first or they will throw a `BadMethodCallException` on creation. + +#### StreamSelectLoop + +A `stream_select()` based event loop. + +This uses the [`stream_select()`](https://www.php.net/manual/en/function.stream-select.php) +function and is the only implementation that works out of the box with PHP. + +This event loop works out of the box on PHP 5.3 through PHP 8+ and HHVM. +This means that no installation is required and this library works on all +platforms and supported PHP versions. +Accordingly, the [`Loop` class](#loop) and the deprecated [`Factory`](#factory) +will use this event loop by default if you do not install any of the event loop +extensions listed below. + +Under the hood, it does a simple `select` system call. +This system call is limited to the maximum file descriptor number of +`FD_SETSIZE` (platform dependent, commonly 1024) and scales with `O(m)` +(`m` being the maximum file descriptor number passed). +This means that you may run into issues when handling thousands of streams +concurrently and you may want to look into using one of the alternative +event loop implementations listed below in this case. +If your use case is among the many common use cases that involve handling only +dozens or a few hundred streams at once, then this event loop implementation +performs really well. + +If you want to use signal handling (see also [`addSignal()`](#addsignal) below), +this event loop implementation requires `ext-pcntl`. +This extension is only available for Unix-like platforms and does not support +Windows. +It is commonly installed as part of many PHP distributions. +If this extension is missing (or you're running on Windows), signal handling is +not supported and throws a `BadMethodCallException` instead. + +This event loop is known to rely on wall-clock time to schedule future timers +when using any version before PHP 7.3, because a monotonic time source is +only available as of PHP 7.3 (`hrtime()`). +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s on PHP < 7.3 and +then adjust your system time forward by 20s, the timer may trigger in 10s. +See also [`addTimer()`](#addtimer) for more details. + +#### ExtEventLoop + +An `ext-event` based event loop. + +This uses the [`event` PECL extension](https://pecl.php.net/package/event), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 5.4 through PHP 8+. + +#### ExtEvLoop + +An `ext-ev` based event loop. + +This loop uses the [`ev` PECL extension](https://pecl.php.net/package/ev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + + +This loop is known to work with PHP 5.4 through PHP 8+. + +#### ExtUvLoop + +An `ext-uv` based event loop. + +This loop uses the [`uv` PECL extension](https://pecl.php.net/package/uv), +that provides an interface to `libuv` library. +`libuv` itself supports a number of system-specific backends (epoll, kqueue). + +This loop is known to work with PHP 7.x. + +#### ~~ExtLibeventLoop~~ + +> Deprecated since v1.2.0, use [`ExtEventLoop`](#exteventloop) instead. + +An `ext-libevent` based event loop. + +This uses the [`libevent` PECL extension](https://pecl.php.net/package/libevent), +that provides an interface to `libevent` library. +`libevent` itself supports a number of system-specific backends (epoll, kqueue). + +This event loop does only work with PHP 5. +An [unofficial update](https://github.com/php/pecl-event-libevent/pull/2) for +PHP 7 does exist, but it is known to cause regular crashes due to `SEGFAULT`s. +To reiterate: Using this event loop on PHP 7 is not recommended. +Accordingly, neither the [`Loop` class](#loop) nor the deprecated +[`Factory` class](#factory) will try to use this event loop on PHP 7. + +This event loop is known to trigger a readable listener only if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. +See also [`addReadStream()`](#addreadstream) for more details. + +#### ~~ExtLibevLoop~~ + +> Deprecated since v1.2.0, use [`ExtEvLoop`](#extevloop) instead. + +An `ext-libev` based event loop. + +This uses an [unofficial `libev` extension](https://github.com/m4rw3r/php-libev), +that provides an interface to `libev` library. +`libev` itself supports a number of system-specific backends (epoll, kqueue). + +This loop does only work with PHP 5. +An update for PHP 7 is [unlikely](https://github.com/m4rw3r/php-libev/issues/8) +to happen any time soon. + +### LoopInterface + +#### run() + +The `run(): void` method can be used to +run the event loop until there are no more tasks to perform. + +For many applications, this method is the only directly visible +invocation on the event loop. +As a rule of thumb, it is usually recommended to attach everything to the +same loop instance and then run the loop once at the bottom end of the +application. + +```php +$loop->run(); +``` + +This method will keep the loop running until there are no more tasks +to perform. In other words: This method will block until the last +timer, stream and/or signal has been removed. + +Likewise, it is imperative to ensure the application actually invokes +this method once. Adding listeners to the loop and missing to actually +run it will result in the application exiting without actually waiting +for any of the attached listeners. + +This method MUST NOT be called while the loop is already running. +This method MAY be called more than once after it has explicitly been +[`stop()`ped](#stop) or after it automatically stopped because it +previously did no longer have anything to do. + +#### stop() + +The `stop(): void` method can be used to +instruct a running event loop to stop. + +This method is considered advanced usage and should be used with care. +As a rule of thumb, it is usually recommended to let the loop stop +only automatically when it no longer has anything to do. + +This method can be used to explicitly instruct the event loop to stop: + +```php +$loop->addTimer(3.0, function () use ($loop) { + $loop->stop(); +}); +``` + +Calling this method on a loop instance that is not currently running or +on a loop instance that has already been stopped has no effect. + +#### addTimer() + +The `addTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked once after the given interval. + +The second parameter MUST be a timer callback function that accepts +the timer instance as its only parameter. +If you don't use the timer instance inside your timer callback function +you MAY use a function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +This method returns a timer instance. The same timer instance will also be +passed into the timer callback function as described above. +You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. +Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure +the callback will be invoked only once after the given interval. + +```php +$loop->addTimer(0.8, function () { + echo 'world!' . PHP_EOL; +}); + +$loop->addTimer(0.3, function () { + echo 'hello '; +}); +``` + +See also [example #1](examples). + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->addTimer(1.0, function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +#### addPeriodicTimer() + +The `addPeriodicTimer(float $interval, callable $callback): TimerInterface` method can be used to +enqueue a callback to be invoked repeatedly after the given interval. + +The second parameter MUST be a timer callback function that accepts +the timer instance as its only parameter. +If you don't use the timer instance inside your timer callback function +you MAY use a function which has no parameters at all. + +The timer callback function MUST NOT throw an `Exception`. +The return value of the timer callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +This method returns a timer instance. The same timer instance will also be +passed into the timer callback function as described above. +Unlike [`addTimer()`](#addtimer), this method will ensure the callback +will be invoked infinitely after the given interval or until you invoke +[`cancelTimer`](#canceltimer). + +```php +$timer = $loop->addPeriodicTimer(0.1, function () { + echo 'tick!' . PHP_EOL; +}); + +$loop->addTimer(1.0, function () use ($loop, $timer) { + $loop->cancelTimer($timer); + echo 'Done' . PHP_EOL; +}); +``` + +See also [example #2](examples). + +If you want to limit the number of executions, you can bind +arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $n = 3; + $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + if ($n > 0) { + --$n; + echo "hello $name\n"; + } else { + $loop->cancelTimer($timer); + } + }); +} + +hello('Tester', $loop); +``` + +This interface does not enforce any particular timer resolution, so +special care may have to be taken if you rely on very high precision with +millisecond accuracy or below. Event loop implementations SHOULD work on +a best effort basis and SHOULD provide at least millisecond accuracy +unless otherwise noted. Many existing event loop implementations are +known to provide microsecond accuracy, but it's generally not recommended +to rely on this high precision. + +Similarly, the execution order of timers scheduled to execute at the +same time (within its possible accuracy) is not guaranteed. + +This interface suggests that event loop implementations SHOULD use a +monotonic time source if available. Given that a monotonic time source is +only available as of PHP 7.3 by default, event loop implementations MAY +fall back to using wall-clock time. +While this does not affect many common use cases, this is an important +distinction for programs that rely on a high time precision or on systems +that are subject to discontinuous time adjustments (time jumps). +This means that if you schedule a timer to trigger in 30s and then adjust +your system time forward by 20s, the timer SHOULD still trigger in 30s. +See also [event loop implementations](#loop-implementations) for more details. + +Additionally, periodic timers may be subject to timer drift due to +re-scheduling after each invocation. As such, it's generally not +recommended to rely on this for high precision intervals with millisecond +accuracy or below. + +#### cancelTimer() + +The `cancelTimer(TimerInterface $timer): void` method can be used to +cancel a pending timer. + +See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + +Calling this method on a timer instance that has not been added to this +loop instance or on a timer that has already been cancelled has no effect. + +#### futureTick() + +The `futureTick(callable $listener): void` method can be used to +schedule a callback to be invoked on a future tick of the event loop. + +This works very much similar to timers with an interval of zero seconds, +but does not require the overhead of scheduling a timer queue. + +The tick callback function MUST be able to accept zero parameters. + +The tick callback function MUST NOT throw an `Exception`. +The return value of the tick callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +function hello($name, LoopInterface $loop) +{ + $loop->futureTick(function () use ($name) { + echo "hello $name\n"; + }); +} + +hello('Tester', $loop); +``` + +Unlike timers, tick callbacks are guaranteed to be executed in the order +they are enqueued. +Also, once a callback is enqueued, there's no way to cancel this operation. + +This is often used to break down bigger tasks into smaller steps (a form +of cooperative multitasking). + +```php +$loop->futureTick(function () { + echo 'b'; +}); +$loop->futureTick(function () { + echo 'c'; +}); +echo 'a'; +``` + +See also [example #3](examples). + +#### addSignal() + +The `addSignal(int $signal, callable $listener): void` method can be used to +register a listener to be notified when a signal has been caught by this process. + +This is useful to catch user interrupt signals or shutdown signals from +tools like `supervisor` or `systemd`. + +The second parameter MUST be a listener callback function that accepts +the signal as its only parameter. +If you don't use the signal inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +```php +$loop->addSignal(SIGINT, function (int $signal) { + echo 'Caught user interrupt signal' . PHP_EOL; +}); +``` + +See also [example #4](examples). + +Signaling is only available on Unix-like platforms, Windows isn't +supported due to operating system limitations. +This method may throw a `BadMethodCallException` if signals aren't +supported on this platform, for example when required extensions are +missing. + +**Note: A listener can only be added once to the same signal, any +attempts to add it more than once will be ignored.** + +#### removeSignal() + +The `removeSignal(int $signal, callable $listener): void` method can be used to +remove a previously added signal listener. + +```php +$loop->removeSignal(SIGINT, $listener); +``` + +Any attempts to remove listeners that aren't registered will be ignored. + +#### addReadStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [readable Stream API](https://github.com/reactphp/stream#readablestreaminterface) + instead. + +The `addReadStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to read. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to read by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeReadStream()`](#removereadstream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The second parameter MUST be a listener callback function that accepts +the stream resource as its only parameter. +If you don't use the stream resource inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addReadStream($stream, function ($stream) use ($name) { + echo $name . ' said: ' . fread($stream); +}); +``` + +See also [example #11](examples). + +You can invoke [`removeReadStream()`](#removereadstream) to remove the +read event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +Some event loop implementations are known to only trigger the listener if +the stream *becomes* readable (edge-triggered) and may not trigger if the +stream has already been readable from the beginning. +This also implies that a stream may not be recognized as readable when data +is still left in PHP's internal stream buffers. +As such, it's recommended to use `stream_set_read_buffer($stream, 0);` +to disable PHP's internal read buffer in this case. + +#### addWriteStream() + +> Advanced! Note that this low-level API is considered advanced usage. + Most use cases should probably use the higher-level + [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + instead. + +The `addWriteStream(resource $stream, callable $callback): void` method can be used to +register a listener to be notified when a stream is ready to write. + +The first parameter MUST be a valid stream resource that supports +checking whether it is ready to write by this loop implementation. +A single stream resource MUST NOT be added more than once. +Instead, either call [`removeWriteStream()`](#removewritestream) first or +react to this event with a single listener and then dispatch from this +listener. This method MAY throw an `Exception` if the given resource type +is not supported by this loop implementation. + +The second parameter MUST be a listener callback function that accepts +the stream resource as its only parameter. +If you don't use the stream resource inside your listener callback function +you MAY use a function which has no parameters at all. + +The listener callback function MUST NOT throw an `Exception`. +The return value of the listener callback function will be ignored and has +no effect, so for performance reasons you're recommended to not return +any excessive data structures. + +If you want to access any variables within your callback function, you +can bind arbitrary data to a callback closure like this: + +```php +$loop->addWriteStream($stream, function ($stream) use ($name) { + fwrite($stream, 'Hello ' . $name); +}); +``` + +See also [example #12](examples). + +You can invoke [`removeWriteStream()`](#removewritestream) to remove the +write event listener for this stream. + +The execution order of listeners when multiple streams become ready at +the same time is not guaranteed. + +#### removeReadStream() + +The `removeReadStream(resource $stream): void` method can be used to +remove the read event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +#### removeWriteStream() + +The `removeWriteStream(resource $stream): void` method can be used to +remove the write event listener for the given stream. + +Removing a stream from the loop that has already been removed or trying +to remove a stream that was never added or is invalid has no effect. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/event-loop:^1.4 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and +HHVM. +It's *highly recommended to use the latest supported PHP version* for this project. + +Installing any of the event loop extensions is suggested, but entirely optional. +See also [event loop implementations](#loop-implementations) for more details. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See our [Stream component](https://github.com/reactphp/stream) for more + information on how streams are used in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/event-loop/dependents) + for a list of packages that use the EventLoop in real-world applications. diff --git a/vendor/react/event-loop/composer.json b/vendor/react/event-loop/composer.json new file mode 100644 index 00000000000..3712d9d2612 --- /dev/null +++ b/vendor/react/event-loop/composer.json @@ -0,0 +1,50 @@ +{ + "name": "react\/event-loop", + "description": "ReactPHP's core reactor event loop that libraries can use for evented I\/O.", + "keywords": [ + "event-loop", + "asynchronous" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit\/phpunit": "^9.6 || ^5.7 || ^4.8.36" + }, + "suggest": { + "ext-pcntl": "For signal handling support when using the StreamSelectLoop" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\EventLoop\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\EventLoop\\": "tests\/" + } + } +} \ No newline at end of file diff --git a/vendor/react/event-loop/src/ExtEvLoop.php b/vendor/react/event-loop/src/ExtEvLoop.php new file mode 100644 index 00000000000..f415ac2492b --- /dev/null +++ b/vendor/react/event-loop/src/ExtEvLoop.php @@ -0,0 +1,203 @@ +loop = new EvLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readStreams[$key])) { + return; + } + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::READ, $callback); + $this->readStreams[$key] = $event; + } + /** + * @param resource $stream + * @param callable $listener + * + * @return \Closure + */ + private function getStreamListenerClosure($stream, $listener) + { + return function () use($stream, $listener) { + \call_user_func($listener, $stream); + }; + } + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeStreams[$key])) { + return; + } + $callback = $this->getStreamListenerClosure($stream, $listener); + $event = $this->loop->io($stream, Ev::WRITE, $callback); + $this->writeStreams[$key] = $event; + } + public function removeReadStream($stream) + { + $key = (int) $stream; + if (!isset($this->readStreams[$key])) { + return; + } + $this->readStreams[$key]->stop(); + unset($this->readStreams[$key]); + } + public function removeWriteStream($stream) + { + $key = (int) $stream; + if (!isset($this->writeStreams[$key])) { + return; + } + $this->writeStreams[$key]->stop(); + unset($this->writeStreams[$key]); + } + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $that = $this; + $timers = $this->timers; + $callback = function () use($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + $event = $this->loop->timer($timer->getInterval(), 0.0, $callback); + $this->timers->attach($timer, $event); + return $timer; + } + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $callback = function () use($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + $event = $this->loop->timer($timer->getInterval(), $timer->getInterval(), $callback); + $this->timers->attach($timer, $event); + return $timer; + } + public function cancelTimer(TimerInterface $timer) + { + if (!isset($this->timers[$timer])) { + return; + } + $event = $this->timers[$timer]; + $event->stop(); + $this->timers->detach($timer); + } + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams && !$this->writeStreams && !$this->timers->count() && $this->signals->isEmpty(); + $flags = Ev::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags |= Ev::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + $this->loop->run($flags); + } + } + public function stop() + { + $this->running = \false; + } + public function __destruct() + { + /** @var TimerInterface $timer */ + foreach ($this->timers as $timer) { + $this->cancelTimer($timer); + } + foreach ($this->readStreams as $key => $stream) { + $this->removeReadStream($key); + } + foreach ($this->writeStreams as $key => $stream) { + $this->removeWriteStream($key); + } + } + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = $this->loop->signal($signal, function () use($signal) { + $this->signals->call($signal); + }); + } + } + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + if (isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal]->stop(); + unset($this->signalEvents[$signal]); + } + } +} diff --git a/vendor/react/event-loop/src/ExtEventLoop.php b/vendor/react/event-loop/src/ExtEventLoop.php new file mode 100644 index 00000000000..6d08b40a7a4 --- /dev/null +++ b/vendor/react/event-loop/src/ExtEventLoop.php @@ -0,0 +1,224 @@ +requireFeatures(\EventConfig::FEATURE_FDS); + } + $this->eventBase = new EventBase($config); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + $this->createTimerCallback(); + $this->createStreamCallback(); + } + public function __destruct() + { + // explicitly clear all references to Event objects to prevent SEGFAULTs on Windows + foreach ($this->timerEvents as $timer) { + $this->timerEvents->detach($timer); + } + $this->readEvents = array(); + $this->writeEvents = array(); + } + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::READ, $this->streamCallback); + $event->add(); + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->readRefs[$key] = $stream; + } + } + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + $event = new Event($this->eventBase, $stream, Event::PERSIST | Event::WRITE, $this->streamCallback); + $event->add(); + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + // ext-event does not increase refcount on stream resources for PHP 7+ + // manually keep track of stream resource to prevent premature garbage collection + if (\PHP_VERSION_ID >= 70000) { + $this->writeRefs[$key] = $stream; + } + } + public function removeReadStream($stream) + { + $key = (int) $stream; + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->free(); + unset($this->readEvents[$key], $this->readListeners[$key], $this->readRefs[$key]); + } + } + public function removeWriteStream($stream) + { + $key = (int) $stream; + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->free(); + unset($this->writeEvents[$key], $this->writeListeners[$key], $this->writeRefs[$key]); + } + } + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $this->scheduleTimer($timer); + return $timer; + } + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $this->scheduleTimer($timer); + return $timer; + } + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->contains($timer)) { + $this->timerEvents[$timer]->free(); + $this->timerEvents->detach($timer); + } + } + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = Event::signal($this->eventBase, $signal, array($this->signals, 'call')); + $this->signalEvents[$signal]->add(); + } + } + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->free(); + unset($this->signalEvents[$signal]); + } + } + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $flags = EventBase::LOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventBase::LOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + $this->eventBase->loop($flags); + } + } + public function stop() + { + $this->running = \false; + } + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $flags = Event::TIMEOUT; + if ($timer->isPeriodic()) { + $flags |= Event::PERSIST; + } + $event = new Event($this->eventBase, -1, $flags, $this->timerCallback, $timer); + $this->timerEvents[$timer] = $event; + $event->add($timer->getInterval()); + } + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use($timers) { + \call_user_func($timer->getCallback(), $timer); + if (!$timer->isPeriodic() && $timers->contains($timer)) { + $this->cancelTimer($timer); + } + }; + } + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use(&$read, &$write) { + $key = (int) $stream; + if (Event::READ === (Event::READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + if (Event::WRITE === (Event::WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/vendor/react/event-loop/src/ExtLibevLoop.php b/vendor/react/event-loop/src/ExtLibevLoop.php new file mode 100644 index 00000000000..c2dfcf3cfe7 --- /dev/null +++ b/vendor/react/event-loop/src/ExtLibevLoop.php @@ -0,0 +1,166 @@ +loop = new EventLoop(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + } + public function addReadStream($stream, $listener) + { + if (isset($this->readEvents[(int) $stream])) { + return; + } + $callback = function () use($stream, $listener) { + \call_user_func($listener, $stream); + }; + $event = new IOEvent($callback, $stream, IOEvent::READ); + $this->loop->add($event); + $this->readEvents[(int) $stream] = $event; + } + public function addWriteStream($stream, $listener) + { + if (isset($this->writeEvents[(int) $stream])) { + return; + } + $callback = function () use($stream, $listener) { + \call_user_func($listener, $stream); + }; + $event = new IOEvent($callback, $stream, IOEvent::WRITE); + $this->loop->add($event); + $this->writeEvents[(int) $stream] = $event; + } + public function removeReadStream($stream) + { + $key = (int) $stream; + if (isset($this->readEvents[$key])) { + $this->readEvents[$key]->stop(); + $this->loop->remove($this->readEvents[$key]); + unset($this->readEvents[$key]); + } + } + public function removeWriteStream($stream) + { + $key = (int) $stream; + if (isset($this->writeEvents[$key])) { + $this->writeEvents[$key]->stop(); + $this->loop->remove($this->writeEvents[$key]); + unset($this->writeEvents[$key]); + } + } + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $that = $this; + $timers = $this->timerEvents; + $callback = function () use($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + $event = new TimerEvent($callback, $timer->getInterval()); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + return $timer; + } + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $callback = function () use($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + $event = new TimerEvent($callback, $timer->getInterval(), $timer->getInterval()); + $this->timerEvents->attach($timer, $event); + $this->loop->add($event); + return $timer; + } + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timerEvents[$timer])) { + $this->loop->remove($this->timerEvents[$timer]); + $this->timerEvents->detach($timer); + } + } + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = new SignalEvent(function () use($signals, $signal) { + $signals->call($signal); + }, $signal); + $this->loop->add($this->signalEvents[$signal]); + } + } + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + $this->signalEvents[$signal]->stop(); + $this->loop->remove($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $flags = EventLoop::RUN_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= EventLoop::RUN_NOWAIT; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + $this->loop->run($flags); + } + } + public function stop() + { + $this->running = \false; + } +} diff --git a/vendor/react/event-loop/src/ExtLibeventLoop.php b/vendor/react/event-loop/src/ExtLibeventLoop.php new file mode 100644 index 00000000000..06be8887769 --- /dev/null +++ b/vendor/react/event-loop/src/ExtLibeventLoop.php @@ -0,0 +1,232 @@ +eventBase = \event_base_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timerEvents = new SplObjectStorage(); + $this->signals = new SignalsHandler(); + $this->createTimerCallback(); + $this->createStreamCallback(); + } + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + return; + } + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_READ, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + $this->readEvents[$key] = $event; + $this->readListeners[$key] = $listener; + } + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + return; + } + $event = \event_new(); + \event_set($event, $stream, \EV_PERSIST | \EV_WRITE, $this->streamCallback); + \event_base_set($event, $this->eventBase); + \event_add($event); + $this->writeEvents[$key] = $event; + $this->writeListeners[$key] = $listener; + } + public function removeReadStream($stream) + { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + $event = $this->readEvents[$key]; + \event_del($event); + \event_free($event); + unset($this->readEvents[$key], $this->readListeners[$key]); + } + } + public function removeWriteStream($stream) + { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + $event = $this->writeEvents[$key]; + \event_del($event); + \event_free($event); + unset($this->writeEvents[$key], $this->writeListeners[$key]); + } + } + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $this->scheduleTimer($timer); + return $timer; + } + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $this->scheduleTimer($timer); + return $timer; + } + public function cancelTimer(TimerInterface $timer) + { + if ($this->timerEvents->contains($timer)) { + $event = $this->timerEvents[$timer]; + \event_del($event); + \event_free($event); + $this->timerEvents->detach($timer); + } + } + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + if (!isset($this->signalEvents[$signal])) { + $this->signalEvents[$signal] = \event_new(); + \event_set($this->signalEvents[$signal], $signal, \EV_PERSIST | \EV_SIGNAL, array($this->signals, 'call')); + \event_base_set($this->signalEvents[$signal], $this->eventBase); + \event_add($this->signalEvents[$signal]); + } + } + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \event_del($this->signalEvents[$signal]); + \event_free($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $flags = \EVLOOP_ONCE; + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $flags |= \EVLOOP_NONBLOCK; + } elseif (!$this->readEvents && !$this->writeEvents && !$this->timerEvents->count() && $this->signals->isEmpty()) { + break; + } + \event_base_loop($this->eventBase, $flags); + } + } + public function stop() + { + $this->running = \false; + } + /** + * Schedule a timer for execution. + * + * @param TimerInterface $timer + */ + private function scheduleTimer(TimerInterface $timer) + { + $this->timerEvents[$timer] = $event = \event_timer_new(); + \event_timer_set($event, $this->timerCallback, $timer); + \event_base_set($event, $this->eventBase); + \event_add($event, $timer->getInterval() * self::MICROSECONDS_PER_SECOND); + } + /** + * Create a callback used as the target of timer events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createTimerCallback() + { + $that = $this; + $timers = $this->timerEvents; + $this->timerCallback = function ($_, $__, $timer) use($timers, $that) { + \call_user_func($timer->getCallback(), $timer); + // Timer already cancelled ... + if (!$timers->contains($timer)) { + return; + } + // Reschedule periodic timers ... + if ($timer->isPeriodic()) { + \event_add($timers[$timer], $timer->getInterval() * ExtLibeventLoop::MICROSECONDS_PER_SECOND); + // Clean-up one shot timers ... + } else { + $that->cancelTimer($timer); + } + }; + } + /** + * Create a callback used as the target of stream events. + * + * A reference is kept to the callback for the lifetime of the loop + * to prevent "Cannot destroy active lambda function" fatal error from + * the event extension. + */ + private function createStreamCallback() + { + $read =& $this->readListeners; + $write =& $this->writeListeners; + $this->streamCallback = function ($stream, $flags) use(&$read, &$write) { + $key = (int) $stream; + if (\EV_READ === (\EV_READ & $flags) && isset($read[$key])) { + \call_user_func($read[$key], $stream); + } + if (\EV_WRITE === (\EV_WRITE & $flags) && isset($write[$key])) { + \call_user_func($write[$key], $stream); + } + }; + } +} diff --git a/vendor/react/event-loop/src/ExtUvLoop.php b/vendor/react/event-loop/src/ExtUvLoop.php new file mode 100644 index 00000000000..4f1a8a8406d --- /dev/null +++ b/vendor/react/event-loop/src/ExtUvLoop.php @@ -0,0 +1,275 @@ +uv = \uv_loop_new(); + $this->futureTickQueue = new FutureTickQueue(); + $this->timers = new SplObjectStorage(); + $this->streamListener = $this->createStreamListener(); + $this->signals = new SignalsHandler(); + } + /** + * Returns the underlying ext-uv event loop. (Internal ReactPHP use only.) + * + * @internal + * + * @return resource + */ + public function getUvLoop() + { + return $this->uv; + } + /** + * {@inheritdoc} + */ + public function addReadStream($stream, $listener) + { + if (isset($this->readStreams[(int) $stream])) { + return; + } + $this->readStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + /** + * {@inheritdoc} + */ + public function addWriteStream($stream, $listener) + { + if (isset($this->writeStreams[(int) $stream])) { + return; + } + $this->writeStreams[(int) $stream] = $listener; + $this->addStream($stream); + } + /** + * {@inheritdoc} + */ + public function removeReadStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + unset($this->readStreams[(int) $stream]); + $this->removeStream($stream); + } + /** + * {@inheritdoc} + */ + public function removeWriteStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + unset($this->writeStreams[(int) $stream]); + $this->removeStream($stream); + } + /** + * {@inheritdoc} + */ + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $that = $this; + $timers = $this->timers; + $callback = function () use($timer, $timers, $that) { + \call_user_func($timer->getCallback(), $timer); + if ($timers->contains($timer)) { + $that->cancelTimer($timer); + } + }; + $event = \uv_timer_init($this->uv); + $this->timers->attach($timer, $event); + \uv_timer_start($event, $this->convertFloatSecondsToMilliseconds($interval), 0, $callback); + return $timer; + } + /** + * {@inheritdoc} + */ + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $callback = function () use($timer) { + \call_user_func($timer->getCallback(), $timer); + }; + $interval = $this->convertFloatSecondsToMilliseconds($interval); + $event = \uv_timer_init($this->uv); + $this->timers->attach($timer, $event); + \uv_timer_start($event, $interval, (int) $interval === 0 ? 1 : $interval, $callback); + return $timer; + } + /** + * {@inheritdoc} + */ + public function cancelTimer(TimerInterface $timer) + { + if (isset($this->timers[$timer])) { + @\uv_timer_stop($this->timers[$timer]); + $this->timers->detach($timer); + } + } + /** + * {@inheritdoc} + */ + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function addSignal($signal, $listener) + { + $this->signals->add($signal, $listener); + if (!isset($this->signalEvents[$signal])) { + $signals = $this->signals; + $this->signalEvents[$signal] = \ECSPrefix202307\uv_signal_init($this->uv); + \ECSPrefix202307\uv_signal_start($this->signalEvents[$signal], function () use($signals, $signal) { + $signals->call($signal); + }, $signal); + } + } + public function removeSignal($signal, $listener) + { + $this->signals->remove($signal, $listener); + if (isset($this->signalEvents[$signal]) && $this->signals->count($signal) === 0) { + \uv_signal_stop($this->signalEvents[$signal]); + unset($this->signalEvents[$signal]); + } + } + /** + * {@inheritdoc} + */ + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $hasPendingCallbacks = !$this->futureTickQueue->isEmpty(); + $wasJustStopped = !$this->running; + $nothingLeftToDo = !$this->readStreams && !$this->writeStreams && !$this->timers->count() && $this->signals->isEmpty(); + // Use UV::RUN_ONCE when there are only I/O events active in the loop and block until one of those triggers, + // otherwise use UV::RUN_NOWAIT. + // @link http://docs.libuv.org/en/v1.x/loop.html#c.uv_run + $flags = \UV::RUN_ONCE; + if ($wasJustStopped || $hasPendingCallbacks) { + $flags = \UV::RUN_NOWAIT; + } elseif ($nothingLeftToDo) { + break; + } + \uv_run($this->uv, $flags); + } + } + /** + * {@inheritdoc} + */ + public function stop() + { + $this->running = \false; + } + private function addStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + $this->streamEvents[(int) $stream] = \ECSPrefix202307\uv_poll_init_socket($this->uv, $stream); + } + if ($this->streamEvents[(int) $stream] !== \false) { + $this->pollStream($stream); + } + } + private function removeStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + if (!isset($this->readStreams[(int) $stream]) && !isset($this->writeStreams[(int) $stream])) { + \uv_poll_stop($this->streamEvents[(int) $stream]); + \uv_close($this->streamEvents[(int) $stream]); + unset($this->streamEvents[(int) $stream]); + return; + } + $this->pollStream($stream); + } + private function pollStream($stream) + { + if (!isset($this->streamEvents[(int) $stream])) { + return; + } + $flags = 0; + if (isset($this->readStreams[(int) $stream])) { + $flags |= \UV::READABLE; + } + if (isset($this->writeStreams[(int) $stream])) { + $flags |= \UV::WRITABLE; + } + \uv_poll_start($this->streamEvents[(int) $stream], $flags, $this->streamListener); + } + /** + * Create a stream listener + * + * @return callable Returns a callback + */ + private function createStreamListener() + { + $callback = function ($event, $status, $events, $stream) { + // libuv automatically stops polling on error, re-enable polling to match other loop implementations + if ($status !== 0) { + $this->pollStream($stream); + // libuv may report no events on error, but this should still invoke stream listeners to report closed connections + // re-enable both readable and writable, correct listeners will be checked below anyway + if ($events === 0) { + $events = \UV::READABLE | \UV::WRITABLE; + } + } + if (isset($this->readStreams[(int) $stream]) && $events & \UV::READABLE) { + \call_user_func($this->readStreams[(int) $stream], $stream); + } + if (isset($this->writeStreams[(int) $stream]) && $events & \UV::WRITABLE) { + \call_user_func($this->writeStreams[(int) $stream], $stream); + } + }; + return $callback; + } + /** + * @param float $interval + * @return int + */ + private function convertFloatSecondsToMilliseconds($interval) + { + if ($interval < 0) { + return 0; + } + $maxValue = (int) (\PHP_INT_MAX / 1000); + $intInterval = (int) $interval; + if ($intInterval <= 0 && $interval > 1 || $intInterval >= $maxValue) { + throw new \InvalidArgumentException("Interval overflow, value must be lower than '{$maxValue}', but '{$interval}' passed."); + } + return (int) \floor($interval * 1000); + } +} diff --git a/vendor/react/event-loop/src/Factory.php b/vendor/react/event-loop/src/Factory.php new file mode 100644 index 00000000000..8e1d21aaf0d --- /dev/null +++ b/vendor/react/event-loop/src/Factory.php @@ -0,0 +1,67 @@ +futureTick(function () use(&$hasRun) { + $hasRun = \true; + }); + $stopped =& self::$stopped; + \register_shutdown_function(function () use($loop, &$hasRun, &$stopped) { + // Don't run if we're coming from a fatal error (uncaught exception). + $error = \error_get_last(); + if ((isset($error['type']) ? $error['type'] : 0) & (\E_ERROR | \E_CORE_ERROR | \E_COMPILE_ERROR | \E_USER_ERROR | \E_RECOVERABLE_ERROR)) { + return; + } + if (!$hasRun && !$stopped) { + $loop->run(); + } + }); + // @codeCoverageIgnoreEnd + return self::$instance; + } + /** + * Internal undocumented method, behavior might change or throw in the + * future. Use with caution and at your own risk. + * + * @internal + * @return void + */ + public static function set(LoopInterface $loop) + { + self::$instance = $loop; + } + /** + * [Advanced] Register a listener to be notified when a stream is ready to read. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addReadStream() + */ + public static function addReadStream($stream, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->addReadStream($stream, $listener); + } + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * @param resource $stream + * @param callable $listener + * @return void + * @throws \Exception + * @see LoopInterface::addWriteStream() + */ + public static function addWriteStream($stream, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->addWriteStream($stream, $listener); + } + /** + * Remove the read event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeReadStream() + */ + public static function removeReadStream($stream) + { + if (self::$instance !== null) { + self::$instance->removeReadStream($stream); + } + } + /** + * Remove the write event listener for the given stream. + * + * @param resource $stream + * @return void + * @see LoopInterface::removeWriteStream() + */ + public static function removeWriteStream($stream) + { + if (self::$instance !== null) { + self::$instance->removeWriteStream($stream); + } + } + /** + * Enqueue a callback to be invoked once after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addTimer() + */ + public static function addTimer($interval, $callback) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + return self::$instance->addTimer($interval, $callback); + } + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * @param float $interval + * @param callable $callback + * @return TimerInterface + * @see LoopInterface::addPeriodicTimer() + */ + public static function addPeriodicTimer($interval, $callback) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + return self::$instance->addPeriodicTimer($interval, $callback); + } + /** + * Cancel a pending timer. + * + * @param TimerInterface $timer + * @return void + * @see LoopInterface::cancelTimer() + */ + public static function cancelTimer(TimerInterface $timer) + { + if (self::$instance !== null) { + self::$instance->cancelTimer($timer); + } + } + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * @param callable $listener + * @return void + * @see LoopInterface::futureTick() + */ + public static function futureTick($listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->futureTick($listener); + } + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::addSignal() + */ + public static function addSignal($signal, $listener) + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->addSignal($signal, $listener); + } + /** + * Removes a previously added signal listener. + * + * @param int $signal + * @param callable $listener + * @return void + * @see LoopInterface::removeSignal() + */ + public static function removeSignal($signal, $listener) + { + if (self::$instance !== null) { + self::$instance->removeSignal($signal, $listener); + } + } + /** + * Run the event loop until there are no more tasks to perform. + * + * @return void + * @see LoopInterface::run() + */ + public static function run() + { + // create loop instance on demand (legacy PHP < 7 doesn't like ternaries in method calls) + if (self::$instance === null) { + self::get(); + } + self::$instance->run(); + } + /** + * Instruct a running event loop to stop. + * + * @return void + * @see LoopInterface::stop() + */ + public static function stop() + { + self::$stopped = \true; + if (self::$instance !== null) { + self::$instance->stop(); + } + } +} diff --git a/vendor/react/event-loop/src/LoopInterface.php b/vendor/react/event-loop/src/LoopInterface.php new file mode 100644 index 00000000000..3e2be6d8881 --- /dev/null +++ b/vendor/react/event-loop/src/LoopInterface.php @@ -0,0 +1,461 @@ +addReadStream($stream, function ($stream) use ($name) { + * echo $name . ' said: ' . fread($stream); + * }); + * ``` + * + * See also [example #11](examples). + * + * You can invoke [`removeReadStream()`](#removereadstream) to remove the + * read event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeReadStream() + */ + public function addReadStream($stream, $listener); + /** + * [Advanced] Register a listener to be notified when a stream is ready to write. + * + * Note that this low-level API is considered advanced usage. + * Most use cases should probably use the higher-level + * [writable Stream API](https://github.com/reactphp/stream#writablestreaminterface) + * instead. + * + * The first parameter MUST be a valid stream resource that supports + * checking whether it is ready to write by this loop implementation. + * A single stream resource MUST NOT be added more than once. + * Instead, either call [`removeWriteStream()`](#removewritestream) first or + * react to this event with a single listener and then dispatch from this + * listener. This method MAY throw an `Exception` if the given resource type + * is not supported by this loop implementation. + * + * The second parameter MUST be a listener callback function that accepts + * the stream resource as its only parameter. + * If you don't use the stream resource inside your listener callback function + * you MAY use a function which has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * $loop->addWriteStream($stream, function ($stream) use ($name) { + * fwrite($stream, 'Hello ' . $name); + * }); + * ``` + * + * See also [example #12](examples). + * + * You can invoke [`removeWriteStream()`](#removewritestream) to remove the + * write event listener for this stream. + * + * The execution order of listeners when multiple streams become ready at + * the same time is not guaranteed. + * + * Some event loop implementations are known to only trigger the listener if + * the stream *becomes* readable (edge-triggered) and may not trigger if the + * stream has already been readable from the beginning. + * This also implies that a stream may not be recognized as readable when data + * is still left in PHP's internal stream buffers. + * As such, it's recommended to use `stream_set_read_buffer($stream, 0);` + * to disable PHP's internal read buffer in this case. + * + * @param resource $stream The PHP stream resource to check. + * @param callable $listener Invoked when the stream is ready. + * @throws \Exception if the given resource type is not supported by this loop implementation + * @see self::removeWriteStream() + */ + public function addWriteStream($stream, $listener); + /** + * Remove the read event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeReadStream($stream); + /** + * Remove the write event listener for the given stream. + * + * Removing a stream from the loop that has already been removed or trying + * to remove a stream that was never added or is invalid has no effect. + * + * @param resource $stream The PHP stream resource. + */ + public function removeWriteStream($stream); + /** + * Enqueue a callback to be invoked once after the given interval. + * + * The second parameter MUST be a timer callback function that accepts + * the timer instance as its only parameter. + * If you don't use the timer instance inside your timer callback function + * you MAY use a function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * This method returns a timer instance. The same timer instance will also be + * passed into the timer callback function as described above. + * You can invoke [`cancelTimer`](#canceltimer) to cancel a pending timer. + * Unlike [`addPeriodicTimer()`](#addperiodictimer), this method will ensure + * the callback will be invoked only once after the given interval. + * + * ```php + * $loop->addTimer(0.8, function () { + * echo 'world!' . PHP_EOL; + * }); + * + * $loop->addTimer(0.3, function () { + * echo 'hello '; + * }); + * ``` + * + * See also [example #1](examples). + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->addTimer(1.0, function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addTimer($interval, $callback); + /** + * Enqueue a callback to be invoked repeatedly after the given interval. + * + * The second parameter MUST be a timer callback function that accepts + * the timer instance as its only parameter. + * If you don't use the timer instance inside your timer callback function + * you MAY use a function which has no parameters at all. + * + * The timer callback function MUST NOT throw an `Exception`. + * The return value of the timer callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * This method returns a timer instance. The same timer instance will also be + * passed into the timer callback function as described above. + * Unlike [`addTimer()`](#addtimer), this method will ensure the callback + * will be invoked infinitely after the given interval or until you invoke + * [`cancelTimer`](#canceltimer). + * + * ```php + * $timer = $loop->addPeriodicTimer(0.1, function () { + * echo 'tick!' . PHP_EOL; + * }); + * + * $loop->addTimer(1.0, function () use ($loop, $timer) { + * $loop->cancelTimer($timer); + * echo 'Done' . PHP_EOL; + * }); + * ``` + * + * See also [example #2](examples). + * + * If you want to limit the number of executions, you can bind + * arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $n = 3; + * $loop->addPeriodicTimer(1.0, function ($timer) use ($name, $loop, &$n) { + * if ($n > 0) { + * --$n; + * echo "hello $name\n"; + * } else { + * $loop->cancelTimer($timer); + * } + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * This interface does not enforce any particular timer resolution, so + * special care may have to be taken if you rely on very high precision with + * millisecond accuracy or below. Event loop implementations SHOULD work on + * a best effort basis and SHOULD provide at least millisecond accuracy + * unless otherwise noted. Many existing event loop implementations are + * known to provide microsecond accuracy, but it's generally not recommended + * to rely on this high precision. + * + * Similarly, the execution order of timers scheduled to execute at the + * same time (within its possible accuracy) is not guaranteed. + * + * This interface suggests that event loop implementations SHOULD use a + * monotonic time source if available. Given that a monotonic time source is + * only available as of PHP 7.3 by default, event loop implementations MAY + * fall back to using wall-clock time. + * While this does not affect many common use cases, this is an important + * distinction for programs that rely on a high time precision or on systems + * that are subject to discontinuous time adjustments (time jumps). + * This means that if you schedule a timer to trigger in 30s and then adjust + * your system time forward by 20s, the timer SHOULD still trigger in 30s. + * See also [event loop implementations](#loop-implementations) for more details. + * + * Additionally, periodic timers may be subject to timer drift due to + * re-scheduling after each invocation. As such, it's generally not + * recommended to rely on this for high precision intervals with millisecond + * accuracy or below. + * + * @param int|float $interval The number of seconds to wait before execution. + * @param callable $callback The callback to invoke. + * + * @return TimerInterface + */ + public function addPeriodicTimer($interval, $callback); + /** + * Cancel a pending timer. + * + * See also [`addPeriodicTimer()`](#addperiodictimer) and [example #2](examples). + * + * Calling this method on a timer instance that has not been added to this + * loop instance or on a timer that has already been cancelled has no effect. + * + * @param TimerInterface $timer The timer to cancel. + * + * @return void + */ + public function cancelTimer(TimerInterface $timer); + /** + * Schedule a callback to be invoked on a future tick of the event loop. + * + * This works very much similar to timers with an interval of zero seconds, + * but does not require the overhead of scheduling a timer queue. + * + * The tick callback function MUST be able to accept zero parameters. + * + * The tick callback function MUST NOT throw an `Exception`. + * The return value of the tick callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * If you want to access any variables within your callback function, you + * can bind arbitrary data to a callback closure like this: + * + * ```php + * function hello($name, LoopInterface $loop) + * { + * $loop->futureTick(function () use ($name) { + * echo "hello $name\n"; + * }); + * } + * + * hello('Tester', $loop); + * ``` + * + * Unlike timers, tick callbacks are guaranteed to be executed in the order + * they are enqueued. + * Also, once a callback is enqueued, there's no way to cancel this operation. + * + * This is often used to break down bigger tasks into smaller steps (a form + * of cooperative multitasking). + * + * ```php + * $loop->futureTick(function () { + * echo 'b'; + * }); + * $loop->futureTick(function () { + * echo 'c'; + * }); + * echo 'a'; + * ``` + * + * See also [example #3](examples). + * + * @param callable $listener The callback to invoke. + * + * @return void + */ + public function futureTick($listener); + /** + * Register a listener to be notified when a signal has been caught by this process. + * + * This is useful to catch user interrupt signals or shutdown signals from + * tools like `supervisor` or `systemd`. + * + * The second parameter MUST be a listener callback function that accepts + * the signal as its only parameter. + * If you don't use the signal inside your listener callback function + * you MAY use a function which has no parameters at all. + * + * The listener callback function MUST NOT throw an `Exception`. + * The return value of the listener callback function will be ignored and has + * no effect, so for performance reasons you're recommended to not return + * any excessive data structures. + * + * ```php + * $loop->addSignal(SIGINT, function (int $signal) { + * echo 'Caught user interrupt signal' . PHP_EOL; + * }); + * ``` + * + * See also [example #4](examples). + * + * Signaling is only available on Unix-like platforms, Windows isn't + * supported due to operating system limitations. + * This method may throw a `BadMethodCallException` if signals aren't + * supported on this platform, for example when required extensions are + * missing. + * + * **Note: A listener can only be added once to the same signal, any + * attempts to add it more than once will be ignored.** + * + * @param int $signal + * @param callable $listener + * + * @throws \BadMethodCallException when signals aren't supported on this + * platform, for example when required extensions are missing. + * + * @return void + */ + public function addSignal($signal, $listener); + /** + * Removes a previously added signal listener. + * + * ```php + * $loop->removeSignal(SIGINT, $listener); + * ``` + * + * Any attempts to remove listeners that aren't registered will be ignored. + * + * @param int $signal + * @param callable $listener + * + * @return void + */ + public function removeSignal($signal, $listener); + /** + * Run the event loop until there are no more tasks to perform. + * + * For many applications, this method is the only directly visible + * invocation on the event loop. + * As a rule of thumb, it is usually recommended to attach everything to the + * same loop instance and then run the loop once at the bottom end of the + * application. + * + * ```php + * $loop->run(); + * ``` + * + * This method will keep the loop running until there are no more tasks + * to perform. In other words: This method will block until the last + * timer, stream and/or signal has been removed. + * + * Likewise, it is imperative to ensure the application actually invokes + * this method once. Adding listeners to the loop and missing to actually + * run it will result in the application exiting without actually waiting + * for any of the attached listeners. + * + * This method MUST NOT be called while the loop is already running. + * This method MAY be called more than once after it has explicitly been + * [`stop()`ped](#stop) or after it automatically stopped because it + * previously did no longer have anything to do. + * + * @return void + */ + public function run(); + /** + * Instruct a running event loop to stop. + * + * This method is considered advanced usage and should be used with care. + * As a rule of thumb, it is usually recommended to let the loop stop + * only automatically when it no longer has anything to do. + * + * This method can be used to explicitly instruct the event loop to stop: + * + * ```php + * $loop->addTimer(3.0, function () use ($loop) { + * $loop->stop(); + * }); + * ``` + * + * Calling this method on a loop instance that is not currently running or + * on a loop instance that has already been stopped has no effect. + * + * @return void + */ + public function stop(); +} diff --git a/vendor/react/event-loop/src/SignalsHandler.php b/vendor/react/event-loop/src/SignalsHandler.php new file mode 100644 index 00000000000..e3f396e6149 --- /dev/null +++ b/vendor/react/event-loop/src/SignalsHandler.php @@ -0,0 +1,52 @@ +signals[$signal])) { + $this->signals[$signal] = array(); + } + if (\in_array($listener, $this->signals[$signal])) { + return; + } + $this->signals[$signal][] = $listener; + } + public function remove($signal, $listener) + { + if (!isset($this->signals[$signal])) { + return; + } + $index = \array_search($listener, $this->signals[$signal], \true); + unset($this->signals[$signal][$index]); + if (isset($this->signals[$signal]) && \count($this->signals[$signal]) === 0) { + unset($this->signals[$signal]); + } + } + public function call($signal) + { + if (!isset($this->signals[$signal])) { + return; + } + foreach ($this->signals[$signal] as $listener) { + \call_user_func($listener, $signal); + } + } + public function count($signal) + { + if (!isset($this->signals[$signal])) { + return 0; + } + return \count($this->signals[$signal]); + } + public function isEmpty() + { + return !$this->signals; + } +} diff --git a/vendor/react/event-loop/src/StreamSelectLoop.php b/vendor/react/event-loop/src/StreamSelectLoop.php new file mode 100644 index 00000000000..4bb17eb93f9 --- /dev/null +++ b/vendor/react/event-loop/src/StreamSelectLoop.php @@ -0,0 +1,278 @@ +futureTickQueue = new FutureTickQueue(); + $this->timers = new Timers(); + $this->pcntl = \function_exists('pcntl_signal') && \function_exists('pcntl_signal_dispatch'); + $this->pcntlPoll = $this->pcntl && !\function_exists('pcntl_async_signals'); + $this->signals = new SignalsHandler(); + // prefer async signals if available (PHP 7.1+) or fall back to dispatching on each tick + if ($this->pcntl && !$this->pcntlPoll) { + \pcntl_async_signals(\true); + } + } + public function addReadStream($stream, $listener) + { + $key = (int) $stream; + if (!isset($this->readStreams[$key])) { + $this->readStreams[$key] = $stream; + $this->readListeners[$key] = $listener; + } + } + public function addWriteStream($stream, $listener) + { + $key = (int) $stream; + if (!isset($this->writeStreams[$key])) { + $this->writeStreams[$key] = $stream; + $this->writeListeners[$key] = $listener; + } + } + public function removeReadStream($stream) + { + $key = (int) $stream; + unset($this->readStreams[$key], $this->readListeners[$key]); + } + public function removeWriteStream($stream) + { + $key = (int) $stream; + unset($this->writeStreams[$key], $this->writeListeners[$key]); + } + public function addTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \false); + $this->timers->add($timer); + return $timer; + } + public function addPeriodicTimer($interval, $callback) + { + $timer = new Timer($interval, $callback, \true); + $this->timers->add($timer); + return $timer; + } + public function cancelTimer(TimerInterface $timer) + { + $this->timers->cancel($timer); + } + public function futureTick($listener) + { + $this->futureTickQueue->add($listener); + } + public function addSignal($signal, $listener) + { + if ($this->pcntl === \false) { + throw new \BadMethodCallException('Event loop feature "signals" isn\'t supported by the "StreamSelectLoop"'); + } + $first = $this->signals->count($signal) === 0; + $this->signals->add($signal, $listener); + if ($first) { + \pcntl_signal($signal, array($this->signals, 'call')); + } + } + public function removeSignal($signal, $listener) + { + if (!$this->signals->count($signal)) { + return; + } + $this->signals->remove($signal, $listener); + if ($this->signals->count($signal) === 0) { + \pcntl_signal($signal, \SIG_DFL); + } + } + public function run() + { + $this->running = \true; + while ($this->running) { + $this->futureTickQueue->tick(); + $this->timers->tick(); + // Future-tick queue has pending callbacks ... + if (!$this->running || !$this->futureTickQueue->isEmpty()) { + $timeout = 0; + // There is a pending timer, only block until it is due ... + } elseif ($scheduledAt = $this->timers->getFirst()) { + $timeout = $scheduledAt - $this->timers->getTime(); + if ($timeout < 0) { + $timeout = 0; + } else { + // Convert float seconds to int microseconds. + // Ensure we do not exceed maximum integer size, which may + // cause the loop to tick once every ~35min on 32bit systems. + $timeout *= self::MICROSECONDS_PER_SECOND; + $timeout = $timeout > \PHP_INT_MAX ? \PHP_INT_MAX : (int) $timeout; + } + // The only possible event is stream or signal activity, so wait forever ... + } elseif ($this->readStreams || $this->writeStreams || !$this->signals->isEmpty()) { + $timeout = null; + // There's nothing left to do ... + } else { + break; + } + $this->waitForStreamActivity($timeout); + } + } + public function stop() + { + $this->running = \false; + } + /** + * Wait/check for stream activity, or until the next timer is due. + * + * @param integer|null $timeout Activity timeout in microseconds, or null to wait forever. + */ + private function waitForStreamActivity($timeout) + { + $read = $this->readStreams; + $write = $this->writeStreams; + $available = $this->streamSelect($read, $write, $timeout); + if ($this->pcntlPoll) { + \pcntl_signal_dispatch(); + } + if (\false === $available) { + // if a system call has been interrupted, + // we cannot rely on it's outcome + return; + } + foreach ($read as $stream) { + $key = (int) $stream; + if (isset($this->readListeners[$key])) { + \call_user_func($this->readListeners[$key], $stream); + } + } + foreach ($write as $stream) { + $key = (int) $stream; + if (isset($this->writeListeners[$key])) { + \call_user_func($this->writeListeners[$key], $stream); + } + } + } + /** + * Emulate a stream_select() implementation that does not break when passed + * empty stream arrays. + * + * @param array $read An array of read streams to select upon. + * @param array $write An array of write streams to select upon. + * @param int|null $timeout Activity timeout in microseconds, or null to wait forever. + * + * @return int|false The total number of streams that are ready for read/write. + * Can return false if stream_select() is interrupted by a signal. + */ + private function streamSelect(array &$read, array &$write, $timeout) + { + if ($read || $write) { + // We do not usually use or expose the `exceptfds` parameter passed to the underlying `select`. + // However, Windows does not report failed connection attempts in `writefds` passed to `select` like most other platforms. + // Instead, it uses `writefds` only for successful connection attempts and `exceptfds` for failed connection attempts. + // We work around this by adding all sockets that look like a pending connection attempt to `exceptfds` automatically on Windows and merge it back later. + // This ensures the public API matches other loop implementations across all platforms (see also test suite or rather test matrix). + // Lacking better APIs, every write-only socket that has not yet read any data is assumed to be in a pending connection attempt state. + // @link https://docs.microsoft.com/de-de/windows/win32/api/winsock2/nf-winsock2-select + $except = null; + if (\DIRECTORY_SEPARATOR === '\\') { + $except = array(); + foreach ($write as $key => $socket) { + if (!isset($read[$key]) && @\ftell($socket) === 0) { + $except[$key] = $socket; + } + } + } + /** @var ?callable $previous */ + $previous = \set_error_handler(function ($errno, $errstr) use(&$previous) { + // suppress warnings that occur when `stream_select()` is interrupted by a signal + // PHP defines `EINTR` through `ext-sockets` or `ext-pcntl`, otherwise use common default (Linux & Mac) + $eintr = \defined('SOCKET_EINTR') ? \SOCKET_EINTR : (\defined('PCNTL_EINTR') ? \PCNTL_EINTR : 4); + if ($errno === \E_WARNING && \strpos($errstr, '[' . $eintr . ']: ') !== \false) { + return; + } + // forward any other error to registered error handler or print warning + return $previous !== null ? \call_user_func_array($previous, \func_get_args()) : \false; + }); + try { + $ret = \stream_select($read, $write, $except, $timeout === null ? null : 0, $timeout); + \restore_error_handler(); + } catch (\Throwable $e) { + // @codeCoverageIgnoreStart + \restore_error_handler(); + throw $e; + } catch (\Exception $e) { + \restore_error_handler(); + throw $e; + } + // @codeCoverageIgnoreEnd + if ($except) { + $write = \array_merge($write, $except); + } + return $ret; + } + if ($timeout > 0) { + \usleep($timeout); + } elseif ($timeout === null) { + // wait forever (we only reach this if we're only awaiting signals) + // this may be interrupted and return earlier when a signal is received + \sleep(\PHP_INT_MAX); + } + return 0; + } +} diff --git a/vendor/react/event-loop/src/Tick/FutureTickQueue.php b/vendor/react/event-loop/src/Tick/FutureTickQueue.php new file mode 100644 index 00000000000..9f4bc3143c9 --- /dev/null +++ b/vendor/react/event-loop/src/Tick/FutureTickQueue.php @@ -0,0 +1,52 @@ +queue = new SplQueue(); + } + /** + * Add a callback to be invoked on a future tick of the event loop. + * + * Callbacks are guaranteed to be executed in the order they are enqueued. + * + * @param callable $listener The callback to invoke. + */ + public function add($listener) + { + $this->queue->enqueue($listener); + } + /** + * Flush the callback queue. + */ + public function tick() + { + // Only invoke as many callbacks as were on the queue when tick() was called. + $count = $this->queue->count(); + while ($count--) { + \call_user_func($this->queue->dequeue()); + } + } + /** + * Check if the next tick queue is empty. + * + * @return boolean + */ + public function isEmpty() + { + return $this->queue->isEmpty(); + } +} diff --git a/vendor/react/event-loop/src/Timer/Timer.php b/vendor/react/event-loop/src/Timer/Timer.php new file mode 100644 index 00000000000..358a3b31535 --- /dev/null +++ b/vendor/react/event-loop/src/Timer/Timer.php @@ -0,0 +1,48 @@ +interval = (float) $interval; + $this->callback = $callback; + $this->periodic = (bool) $periodic; + } + public function getInterval() + { + return $this->interval; + } + public function getCallback() + { + return $this->callback; + } + public function isPeriodic() + { + return $this->periodic; + } +} diff --git a/vendor/react/event-loop/src/Timer/Timers.php b/vendor/react/event-loop/src/Timer/Timers.php new file mode 100644 index 00000000000..61626cac3bc --- /dev/null +++ b/vendor/react/event-loop/src/Timer/Timers.php @@ -0,0 +1,95 @@ +useHighResolution = \function_exists('hrtime'); + } + public function updateTime() + { + return $this->time = $this->useHighResolution ? \hrtime(\true) * 1.0E-9 : \microtime(\true); + } + public function getTime() + { + return $this->time ?: $this->updateTime(); + } + public function add(TimerInterface $timer) + { + $id = \spl_object_hash($timer); + $this->timers[$id] = $timer; + $this->schedule[$id] = $timer->getInterval() + $this->updateTime(); + $this->sorted = \false; + } + public function contains(TimerInterface $timer) + { + return isset($this->timers[\spl_object_hash($timer)]); + } + public function cancel(TimerInterface $timer) + { + $id = \spl_object_hash($timer); + unset($this->timers[$id], $this->schedule[$id]); + } + public function getFirst() + { + // ensure timers are sorted to simply accessing next (first) one + if (!$this->sorted) { + $this->sorted = \true; + \asort($this->schedule); + } + return \reset($this->schedule); + } + public function isEmpty() + { + return \count($this->timers) === 0; + } + public function tick() + { + // hot path: skip timers if nothing is scheduled + if (!$this->schedule) { + return; + } + // ensure timers are sorted so we can execute in order + if (!$this->sorted) { + $this->sorted = \true; + \asort($this->schedule); + } + $time = $this->updateTime(); + foreach ($this->schedule as $id => $scheduled) { + // schedule is ordered, so loop until first timer that is not scheduled for execution now + if ($scheduled >= $time) { + break; + } + // skip any timers that are removed while we process the current schedule + if (!isset($this->schedule[$id]) || $this->schedule[$id] !== $scheduled) { + continue; + } + $timer = $this->timers[$id]; + \call_user_func($timer->getCallback(), $timer); + // re-schedule if this is a periodic timer and it has not been cancelled explicitly already + if ($timer->isPeriodic() && isset($this->timers[$id])) { + $this->schedule[$id] = $timer->getInterval() + $time; + $this->sorted = \false; + } else { + unset($this->timers[$id], $this->schedule[$id]); + } + } + } +} diff --git a/vendor/react/event-loop/src/TimerInterface.php b/vendor/react/event-loop/src/TimerInterface.php new file mode 100644 index 00000000000..c9747318cf6 --- /dev/null +++ b/vendor/react/event-loop/src/TimerInterface.php @@ -0,0 +1,25 @@ +` and `reject(Throwable $reason): PromiseInterface`. + It is no longer possible to resolve a promise without a value (use `null` instead) or reject a promise without a reason (use `Throwable` instead). + (#93, #141 and #142 by @jsor, #138, #149 and #247 by @WyriHaximus and #213 and #246 by @clue) + + ```php + // old (arguments used to be optional) + $promise = resolve(); + $promise = reject(); + + // new (already supported before) + $promise = resolve(null); + $promise = reject(new RuntimeException()); + ``` + +* Feature / BC break: Report all unhandled rejections by default and remove ~~`done()`~~ method. + Add new `set_rejection_handler()` function to set the global rejection handler for unhandled promise rejections. + (#248, #249 and #224 by @clue) + + ```php + // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 + reject(new RuntimeException('Unhandled')); + ``` + +* BC break: Remove all deprecated APIs and reduce API surface. + Remove ~~`some()`~~, ~~`map()`~~, ~~`reduce()`~~ functions, use `any()` and `all()` functions instead. + Remove internal ~~`FulfilledPromise`~~ and ~~`RejectedPromise`~~ classes, use `resolve()` and `reject()` functions instead. + Remove legacy promise progress API (deprecated third argument to `then()` method) and deprecated ~~`LazyPromise`~~ class. + (#32 and #98 by @jsor and #164, #219 and #220 by @clue) + +* BC break: Make all classes final to encourage composition over inheritance. + (#80 by @jsor) + +* Feature / BC break: Require `array` (or `iterable`) type for `all()` + `race()` + `any()` functions and bring in line with ES6 specification. + These functions now require a single argument with a variable number of promises or values as input. + (#225 by @clue and #35 by @jsor) + +* Fix / BC break: Fix `race()` to return a forever pending promise when called with an empty `array` (or `iterable`) and bring in line with ES6 specification. + (#83 by @jsor and #225 by @clue) + +* Minor performance improvements by initializing `Deferred` in the constructor and avoiding `call_user_func()` calls. + (#151 by @WyriHaximus and #171 by @Kubo2) + +* Minor documentation improvements. + (#110 by @seregazhuk, #132 by @CharlotteDunois, #145 by @danielecr, #178 by @WyriHaximus, #189 by @srdante, #212 by @clue, #214, #239 and #243 by @SimonFrings and #231 by @nhedger) + +The following changes had to be ported to this release due to our branching +strategy, but also appeared in the [`2.x` branch](https://github.com/reactphp/promise/tree/2.x): + +* Feature: Support union types and address deprecation of `ReflectionType::getClass()` (PHP 8+). + (#197 by @cdosoftei and @SimonFrings) + +* Feature: Support intersection types (PHP 8.1+). + (#209 by @bzikarsky) + +* Feature: Support DNS types (PHP 8.2+). + (#236 by @nhedger) + +* Feature: Port all memory improvements from `2.x` to `3.x`. + (#150 by @clue and @WyriHaximus) + +* Fix: Fix checking whether cancellable promise is an object and avoid possible warning. + (#161 by @smscr) + +* Improve performance by prefixing all global functions calls with \ to skip the look up and resolve process and go straight to the global function. + (#134 by @WyriHaximus) + +* Improve test suite, update PHPUnit and PHP versions and add `.gitattributes` to exclude dev files from exports. + (#107 by @carusogabriel, #148 and #234 by @WyriHaximus, #153 by @reedy, #162, #230 and #240 by @clue, #173, #177, #185 and #199 by @SimonFrings, #193 by @woodongwong and #210 by @bzikarsky) + +The following changes were originally planned for this release but later reverted +and are not part of the final release: + +* Add iterative callback queue handler to avoid recursion (later removed to improve Fiber support). + (#28, #82 and #86 by @jsor, #158 by @WyriHaximus and #229 and #238 by @clue) + +* Trigger an `E_USER_ERROR` instead of throwing an exception from `done()` (later removed entire `done()` method to globally report unhandled rejections). + (#97 by @jsor and #224 and #248 by @clue) + +* Add type declarations for `some()` (later removed entire `some()` function). + (#172 by @WyriHaximus and #219 by @clue) + +## 2.0.0 (2013-12-10) + +See [`2.x` CHANGELOG](https://github.com/reactphp/promise/blob/2.x/CHANGELOG.md) for more details. + +## 1.0.0 (2012-11-07) + +See [`1.x` CHANGELOG](https://github.com/reactphp/promise/blob/1.x/CHANGELOG.md) for more details. diff --git a/vendor/react/promise/LICENSE b/vendor/react/promise/LICENSE new file mode 100644 index 00000000000..21c1357b7a1 --- /dev/null +++ b/vendor/react/promise/LICENSE @@ -0,0 +1,24 @@ +The MIT License (MIT) + +Copyright (c) 2012 Jan Sorgalla, Christian Lück, Cees-Jan Kiewiet, Chris Boden + +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. diff --git a/vendor/react/promise/README.md b/vendor/react/promise/README.md new file mode 100644 index 00000000000..6b8f9722009 --- /dev/null +++ b/vendor/react/promise/README.md @@ -0,0 +1,722 @@ +Promise +======= + +A lightweight implementation of +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +[![CI status](https://github.com/reactphp/promise/workflows/CI/badge.svg)](https://github.com/reactphp/promise/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/promise?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/promise) + +Table of Contents +----------------- + +1. [Introduction](#introduction) +2. [Concepts](#concepts) + * [Deferred](#deferred) + * [Promise](#promise-1) +3. [API](#api) + * [Deferred](#deferred-1) + * [Deferred::promise()](#deferredpromise) + * [Deferred::resolve()](#deferredresolve) + * [Deferred::reject()](#deferredreject) + * [PromiseInterface](#promiseinterface) + * [PromiseInterface::then()](#promiseinterfacethen) + * [PromiseInterface::catch()](#promiseinterfacecatch) + * [PromiseInterface::finally()](#promiseinterfacefinally) + * [PromiseInterface::cancel()](#promiseinterfacecancel) + * [~~PromiseInterface::otherwise()~~](#promiseinterfaceotherwise) + * [~~PromiseInterface::always()~~](#promiseinterfacealways) + * [Promise](#promise-2) + * [Functions](#functions) + * [resolve()](#resolve) + * [reject()](#reject) + * [all()](#all) + * [race()](#race) + * [any()](#any) + * [set_rejection_handler()](#set_rejection_handler) +4. [Examples](#examples) + * [How to use Deferred](#how-to-use-deferred) + * [How promise forwarding works](#how-promise-forwarding-works) + * [Resolution forwarding](#resolution-forwarding) + * [Rejection forwarding](#rejection-forwarding) + * [Mixed resolution and rejection forwarding](#mixed-resolution-and-rejection-forwarding) +5. [Install](#install) +6. [Tests](#tests) +7. [Credits](#credits) +8. [License](#license) + +Introduction +------------ + +Promise is a library implementing +[CommonJS Promises/A](http://wiki.commonjs.org/wiki/Promises/A) for PHP. + +It also provides several other useful promise-related concepts, such as joining +multiple promises and mapping and reducing collections of promises. + +If you've never heard about promises before, +[read this first](https://gist.github.com/3889970). + +Concepts +-------- + +### Deferred + +A **Deferred** represents a computation or unit of work that may not have +completed yet. Typically (but not always), that computation will be something +that executes asynchronously and completes at some point in the future. + +### Promise + +While a deferred represents the computation itself, a **Promise** represents +the result of that computation. Thus, each deferred has a promise that acts as +a placeholder for its actual result. + +API +--- + +### Deferred + +A deferred represents an operation whose resolution is pending. It has separate +promise and resolver parts. + +```php +$deferred = new React\Promise\Deferred(); + +$promise = $deferred->promise(); + +$deferred->resolve(mixed $value); +$deferred->reject(\Throwable $reason); +``` + +The `promise` method returns the promise of the deferred. + +The `resolve` and `reject` methods control the state of the deferred. + +The constructor of the `Deferred` accepts an optional `$canceller` argument. +See [Promise](#promise-2) for more information. + +#### Deferred::promise() + +```php +$promise = $deferred->promise(); +``` + +Returns the promise of the deferred, which you can hand out to others while +keeping the authority to modify its state to yourself. + +#### Deferred::resolve() + +```php +$deferred->resolve(mixed $value); +``` + +Resolves the promise returned by `promise()`. All consumers are notified by +having `$onFulfilled` (which they registered via `$promise->then()`) called with +`$value`. + +If `$value` itself is a promise, the promise will transition to the state of +this promise once it is resolved. + +See also the [`resolve()` function](#resolve). + +#### Deferred::reject() + +```php +$deferred->reject(\Throwable $reason); +``` + +Rejects the promise returned by `promise()`, signalling that the deferred's +computation failed. +All consumers are notified by having `$onRejected` (which they registered via +`$promise->then()`) called with `$reason`. + +See also the [`reject()` function](#reject). + +### PromiseInterface + +The promise interface provides the common interface for all promise +implementations. +See [Promise](#promise-2) for the only public implementation exposed by this +package. + +A promise represents an eventual outcome, which is either fulfillment (success) +and an associated value, or rejection (failure) and an associated reason. + +Once in the fulfilled or rejected state, a promise becomes immutable. +Neither its state nor its result (or error) can be modified. + +#### PromiseInterface::then() + +```php +$transformedPromise = $promise->then(callable $onFulfilled = null, callable $onRejected = null); +``` + +Transforms a promise's value by applying a function to the promise's fulfillment +or rejection value. Returns a new promise for the transformed result. + +The `then()` method registers new fulfilled and rejection handlers with a promise +(all parameters are optional): + + * `$onFulfilled` will be invoked once the promise is fulfilled and passed + the result as the first argument. + * `$onRejected` will be invoked once the promise is rejected and passed the + reason as the first argument. + +It returns a new promise that will fulfill with the return value of either +`$onFulfilled` or `$onRejected`, whichever is called, or will reject with +the thrown exception if either throws. + +A promise makes the following guarantees about handlers registered in +the same call to `then()`: + + 1. Only one of `$onFulfilled` or `$onRejected` will be called, + never both. + 2. `$onFulfilled` and `$onRejected` will never be called more + than once. + +#### See also + +* [resolve()](#resolve) - Creating a resolved promise +* [reject()](#reject) - Creating a rejected promise + +#### PromiseInterface::catch() + +```php +$promise->catch(callable $onRejected); +``` + +Registers a rejection handler for promise. It is a shortcut for: + +```php +$promise->then(null, $onRejected); +``` + +Additionally, you can type hint the `$reason` argument of `$onRejected` to catch +only specific errors. + +```php +$promise + ->catch(function (\RuntimeException $reason) { + // Only catch \RuntimeException instances + // All other types of errors will propagate automatically + }) + ->catch(function (\Throwable $reason) { + // Catch other errors + }); +``` + +#### PromiseInterface::finally() + +```php +$newPromise = $promise->finally(callable $onFulfilledOrRejected); +``` + +Allows you to execute "cleanup" type tasks in a promise chain. + +It arranges for `$onFulfilledOrRejected` to be called, with no arguments, +when the promise is either fulfilled or rejected. + +* If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will fulfill with the same value as `$promise`. +* If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. +* If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + `$newPromise` will reject with the same reason as `$promise`. +* If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + rejected promise, `$newPromise` will reject with the thrown exception or + rejected promise's reason. + +`finally()` behaves similarly to the synchronous finally statement. When combined +with `catch()`, `finally()` allows you to write code that is similar to the familiar +synchronous catch/finally pair. + +Consider the following synchronous code: + +```php +try { + return doSomething(); +} catch (\Throwable $e) { + return handleError($e); +} finally { + cleanup(); +} +``` + +Similar asynchronous code (with `doSomething()` that returns a promise) can be +written: + +```php +return doSomething() + ->catch('handleError') + ->finally('cleanup'); +``` + +#### PromiseInterface::cancel() + +``` php +$promise->cancel(); +``` + +The `cancel()` method notifies the creator of the promise that there is no +further interest in the results of the operation. + +Once a promise is settled (either fulfilled or rejected), calling `cancel()` on +a promise has no effect. + +#### ~~PromiseInterface::otherwise()~~ + +> Deprecated since v3.0.0, see [`catch()`](#promiseinterfacecatch) instead. + +The `otherwise()` method registers a rejection handler for a promise. + +This method continues to exist only for BC reasons and to ease upgrading +between versions. It is an alias for: + +```php +$promise->catch($onRejected); +``` + +#### ~~PromiseInterface::always()~~ + +> Deprecated since v3.0.0, see [`finally()`](#promiseinterfacefinally) instead. + +The `always()` method allows you to execute "cleanup" type tasks in a promise chain. + +This method continues to exist only for BC reasons and to ease upgrading +between versions. It is an alias for: + +```php +$promise->finally($onFulfilledOrRejected); +``` + +### Promise + +Creates a promise whose state is controlled by the functions passed to +`$resolver`. + +```php +$resolver = function (callable $resolve, callable $reject) { + // Do some work, possibly asynchronously, and then + // resolve or reject. + + $resolve($awesomeResult); + // or throw new Exception('Promise rejected'); + // or $resolve($anotherPromise); + // or $reject($nastyError); +}; + +$canceller = function () { + // Cancel/abort any running operations like network connections, streams etc. + + // Reject promise by throwing an exception + throw new Exception('Promise cancelled'); +}; + +$promise = new React\Promise\Promise($resolver, $canceller); +``` + +The promise constructor receives a resolver function and an optional canceller +function which both will be called with 3 arguments: + + * `$resolve($value)` - Primary function that seals the fate of the + returned promise. Accepts either a non-promise value, or another promise. + When called with a non-promise value, fulfills promise with that value. + When called with another promise, e.g. `$resolve($otherPromise)`, promise's + fate will be equivalent to that of `$otherPromise`. + * `$reject($reason)` - Function that rejects the promise. It is recommended to + just throw an exception instead of using `$reject()`. + +If the resolver or canceller throw an exception, the promise will be rejected +with that thrown exception as the rejection reason. + +The resolver function will be called immediately, the canceller function only +once all consumers called the `cancel()` method of the promise. + +### Functions + +Useful functions for creating and joining collections of promises. + +All functions working on promise collections (like `all()`, `race()`, +etc.) support cancellation. This means, if you call `cancel()` on the returned +promise, all promises in the collection are cancelled. + +#### resolve() + +```php +$promise = React\Promise\resolve(mixed $promiseOrValue); +``` + +Creates a promise for the supplied `$promiseOrValue`. + +If `$promiseOrValue` is a value, it will be the resolution value of the +returned promise. + +If `$promiseOrValue` is a thenable (any object that provides a `then()` method), +a trusted promise that follows the state of the thenable is returned. + +If `$promiseOrValue` is a promise, it will be returned as is. + +The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) +and can be consumed like any other promise: + +```php +$promise = React\Promise\resolve(42); + +$promise->then(function (int $result): void { + var_dump($result); +}, function (\Throwable $e): void { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +#### reject() + +```php +$promise = React\Promise\reject(\Throwable $reason); +``` + +Creates a rejected promise for the supplied `$reason`. + +Note that the [`\Throwable`](https://www.php.net/manual/en/class.throwable.php) interface introduced in PHP 7 covers +both user land [`\Exception`](https://www.php.net/manual/en/class.exception.php)'s and +[`\Error`](https://www.php.net/manual/en/class.error.php) internal PHP errors. By enforcing `\Throwable` as reason to +reject a promise, any language error or user land exception can be used to reject a promise. + +The resulting `$promise` implements the [`PromiseInterface`](#promiseinterface) +and can be consumed like any other promise: + +```php +$promise = React\Promise\reject(new RuntimeException('Request failed')); + +$promise->then(function (int $result): void { + var_dump($result); +}, function (\Throwable $e): void { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that rejected promises should always be handled similar to how any +exceptions should always be caught in a `try` + `catch` block. If you remove the +last reference to a rejected promise that has not been handled, it will +report an unhandled promise rejection: + +```php +function incorrect(): int +{ + $promise = React\Promise\reject(new RuntimeException('Request failed')); + + // Commented out: No rejection handler registered here. + // $promise->then(null, function (\Throwable $e): void { /* ignore */ }); + + // Returning from a function will remove all local variable references, hence why + // this will report an unhandled promise rejection here. + return 42; +} + +// Calling this function will log an error message plus its stack trace: +// Unhandled promise rejection with RuntimeException: Request failed in example.php:10 +incorrect(); +``` + +A rejected promise will be considered "handled" if you catch the rejection +reason with either the [`then()` method](#promiseinterfacethen), the +[`catch()` method](#promiseinterfacecatch), or the +[`finally()` method](#promiseinterfacefinally). Note that each of these methods +return a new promise that may again be rejected if you re-throw an exception. + +A rejected promise will also be considered "handled" if you abort the operation +with the [`cancel()` method](#promiseinterfacecancel) (which in turn would +usually reject the promise if it is still pending). + +See also the [`set_rejection_handler()` function](#set_rejection_handler). + +#### all() + +```php +$promise = React\Promise\all(iterable $promisesOrValues); +``` + +Returns a promise that will resolve only once all the items in +`$promisesOrValues` have resolved. The resolution value of the returned promise +will be an array containing the resolution values of each of the items in +`$promisesOrValues`. + +#### race() + +```php +$promise = React\Promise\race(iterable $promisesOrValues); +``` + +Initiates a competitive race that allows one winner. Returns a promise which is +resolved in the same way the first settled promise resolves. + +The returned promise will become **infinitely pending** if `$promisesOrValues` +contains 0 items. + +#### any() + +```php +$promise = React\Promise\any(iterable $promisesOrValues); +``` + +Returns a promise that will resolve when any one of the items in +`$promisesOrValues` resolves. The resolution value of the returned promise +will be the resolution value of the triggering item. + +The returned promise will only reject if *all* items in `$promisesOrValues` are +rejected. The rejection value will be a `React\Promise\Exception\CompositeException` +which holds all rejection reasons. The rejection reasons can be obtained with +`CompositeException::getThrowables()`. + +The returned promise will also reject with a `React\Promise\Exception\LengthException` +if `$promisesOrValues` contains 0 items. + +#### set_rejection_handler() + +```php +React\Promise\set_rejection_handler(?callable $callback): ?callable; +``` + +Sets the global rejection handler for unhandled promise rejections. + +Note that rejected promises should always be handled similar to how any +exceptions should always be caught in a `try` + `catch` block. If you remove +the last reference to a rejected promise that has not been handled, it will +report an unhandled promise rejection. See also the [`reject()` function](#reject) +for more details. + +The `?callable $callback` argument MUST be a valid callback function that +accepts a single `Throwable` argument or a `null` value to restore the +default promise rejection handler. The return value of the callback function +will be ignored and has no effect, so you SHOULD return a `void` value. The +callback function MUST NOT throw or the program will be terminated with a +fatal error. + +The function returns the previous rejection handler or `null` if using the +default promise rejection handler. + +The default promise rejection handler will log an error message plus its stack +trace: + +```php +// Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 +React\Promise\reject(new RuntimeException('Unhandled')); +``` + +The promise rejection handler may be used to use customize the log message or +write to custom log targets. As a rule of thumb, this function should only be +used as a last resort and promise rejections are best handled with either the +[`then()` method](#promiseinterfacethen), the +[`catch()` method](#promiseinterfacecatch), or the +[`finally()` method](#promiseinterfacefinally). +See also the [`reject()` function](#reject) for more details. + +Examples +-------- + +### How to use Deferred + +```php +function getAwesomeResultPromise() +{ + $deferred = new React\Promise\Deferred(); + + // Execute a Node.js-style function using the callback pattern + computeAwesomeResultAsynchronously(function (\Throwable $error, $result) use ($deferred) { + if ($error) { + $deferred->reject($error); + } else { + $deferred->resolve($result); + } + }); + + // Return the promise + return $deferred->promise(); +} + +getAwesomeResultPromise() + ->then( + function ($value) { + // Deferred resolved, do something with $value + }, + function (\Throwable $reason) { + // Deferred rejected, do something with $reason + } + ); +``` + +### How promise forwarding works + +A few simple examples to show how the mechanics of Promises/A forwarding works. +These examples are contrived, of course, and in real usage, promise chains will +typically be spread across several function calls, or even several levels of +your application architecture. + +#### Resolution forwarding + +Resolved promises forward resolution values to the next promise. +The first promise, `$deferred->promise()`, will resolve with the value passed +to `$deferred->resolve()` below. + +Each call to `then()` returns a new promise that will resolve with the return +value of the previous handler. This creates a promise "pipeline". + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + // $x will be the value passed to $deferred->resolve() below + // and returns a *new promise* for $x + 1 + return $x + 1; + }) + ->then(function ($x) { + // $x === 2 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 3 + // This handler receives the return value of the + // previous handler. + return $x + 1; + }) + ->then(function ($x) { + // $x === 4 + // This handler receives the return value of the + // previous handler. + echo 'Resolve ' . $x; + }); + +$deferred->resolve(1); // Prints "Resolve 4" +``` + +#### Rejection forwarding + +Rejected promises behave similarly, and also work similarly to try/catch: +When you catch an exception, you must rethrow for it to propagate. + +Similarly, when you handle a rejected promise, to propagate the rejection, +"rethrow" it by either returning a rejected promise, or actually throwing +(since promise translates thrown exceptions into rejections) + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->catch(function (\Exception $x) { + // Propagate the rejection + throw $x; + }) + ->catch(function (\Exception $x) { + // Can also propagate by returning another rejection + return React\Promise\reject( + new \Exception($x->getMessage() + 1) + ); + }) + ->catch(function ($x) { + echo 'Reject ' . $x->getMessage(); // 3 + }); + +$deferred->resolve(1); // Prints "Reject 3" +``` + +#### Mixed resolution and rejection forwarding + +Just like try/catch, you can choose to propagate or not. Mixing resolutions and +rejections will still forward handler results in a predictable way. + +```php +$deferred = new React\Promise\Deferred(); + +$deferred->promise() + ->then(function ($x) { + return $x + 1; + }) + ->then(function ($x) { + throw new \Exception($x + 1); + }) + ->catch(function (\Exception $x) { + // Handle the rejection, and don't propagate. + // This is like catch without a rethrow + return $x->getMessage() + 1; + }) + ->then(function ($x) { + echo 'Mixed ' . $x; // 4 + }); + +$deferred->resolve(1); // Prints "Mixed 4" +``` + +Install +------- + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version from this branch: + +```bash +composer require react/promise:^3 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on PHP 7.1 through current PHP 8+. +It's *highly recommended to use the latest supported PHP version* for this project. + +We're committed to providing long-term support (LTS) options and to provide a +smooth upgrade path. If you're using an older PHP version, you may use the +[`2.x` branch](https://github.com/reactphp/promise/tree/2.x) (PHP 5.4+) or +[`1.x` branch](https://github.com/reactphp/promise/tree/1.x) (PHP 5.3+) which both +provide a compatible API but do not take advantage of newer language features. +You may target multiple versions at the same time to support a wider range of +PHP versions like this: + +```bash +composer require "react/promise:^3 || ^2 || ^1" +``` + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +On top of this, we use PHPStan on max level to ensure type safety across the project: + +```bash +vendor/bin/phpstan +``` + +Credits +------- + +Promise is a port of [when.js](https://github.com/cujojs/when) +by [Brian Cavalier](https://github.com/briancavalier). + +Also, large parts of the documentation have been ported from the when.js +[Wiki](https://github.com/cujojs/when/wiki) and the +[API docs](https://github.com/cujojs/when/blob/master/docs/api.md). + +License +------- + +Released under the [MIT](LICENSE) license. diff --git a/vendor/react/promise/composer.json b/vendor/react/promise/composer.json new file mode 100644 index 00000000000..73556fbc02a --- /dev/null +++ b/vendor/react/promise/composer.json @@ -0,0 +1,57 @@ +{ + "name": "react\/promise", + "description": "A lightweight implementation of CommonJS Promises\/A for PHP", + "license": "MIT", + "authors": [ + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=7.1.0" + }, + "require-dev": { + "phpstan\/phpstan": "1.10.20 || 1.4.10", + "phpunit\/phpunit": "^9.5 || ^7.5" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Promise\\": "src\/" + }, + "files": [ + "src\/functions_include.php" + ] + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Promise\\": [ + "tests\/fixtures\/", + "tests\/" + ] + }, + "files": [ + "tests\/Fiber.php" + ] + }, + "keywords": [ + "promise", + "promises" + ] +} \ No newline at end of file diff --git a/vendor/react/promise/src/Deferred.php b/vendor/react/promise/src/Deferred.php new file mode 100644 index 00000000000..49f1587a9a0 --- /dev/null +++ b/vendor/react/promise/src/Deferred.php @@ -0,0 +1,43 @@ + + */ + private $promise; + /** @var callable */ + private $resolveCallback; + /** @var callable */ + private $rejectCallback; + public function __construct(callable $canceller = null) + { + $this->promise = new Promise(function ($resolve, $reject) : void { + $this->resolveCallback = $resolve; + $this->rejectCallback = $reject; + }, $canceller); + } + /** + * @return PromiseInterface + */ + public function promise() : PromiseInterface + { + return $this->promise; + } + /** + * @param T $value + */ + public function resolve($value) : void + { + ($this->resolveCallback)($value); + } + public function reject(\Throwable $reason) : void + { + ($this->rejectCallback)($reason); + } +} diff --git a/vendor/react/promise/src/Exception/CompositeException.php b/vendor/react/promise/src/Exception/CompositeException.php new file mode 100644 index 00000000000..8db490b6ecc --- /dev/null +++ b/vendor/react/promise/src/Exception/CompositeException.php @@ -0,0 +1,29 @@ +throwables = $throwables; + } + /** + * @return \Throwable[] + */ + public function getThrowables() : array + { + return $this->throwables; + } +} diff --git a/vendor/react/promise/src/Exception/LengthException.php b/vendor/react/promise/src/Exception/LengthException.php new file mode 100644 index 00000000000..bd8cb2317de --- /dev/null +++ b/vendor/react/promise/src/Exception/LengthException.php @@ -0,0 +1,7 @@ +started) { + return; + } + $this->started = \true; + $this->drain(); + } + /** + * @param mixed $cancellable + */ + public function enqueue($cancellable) : void + { + if (!\is_object($cancellable) || !\method_exists($cancellable, 'then') || !\method_exists($cancellable, 'cancel')) { + return; + } + $length = \array_push($this->queue, $cancellable); + if ($this->started && 1 === $length) { + $this->drain(); + } + } + private function drain() : void + { + for ($i = \key($this->queue); isset($this->queue[$i]); $i++) { + $cancellable = $this->queue[$i]; + \assert(\method_exists($cancellable, 'cancel')); + $exception = null; + try { + $cancellable->cancel(); + } catch (\Throwable $exception) { + } + unset($this->queue[$i]); + if ($exception) { + throw $exception; + } + } + $this->queue = []; + } +} diff --git a/vendor/react/promise/src/Internal/FulfilledPromise.php b/vendor/react/promise/src/Internal/FulfilledPromise.php new file mode 100644 index 00000000000..0186a6bdd6a --- /dev/null +++ b/vendor/react/promise/src/Internal/FulfilledPromise.php @@ -0,0 +1,79 @@ + + */ +final class FulfilledPromise implements PromiseInterface +{ + /** @var T */ + private $value; + /** + * @param T $value + * @throws \InvalidArgumentException + */ + public function __construct($value = null) + { + if ($value instanceof PromiseInterface) { + throw new \InvalidArgumentException('You cannot create React\\Promise\\FulfilledPromise with a promise. Use React\\Promise\\resolve($promiseOrValue) instead.'); + } + $this->value = $value; + } + /** + * @template TFulfilled + * @param ?(callable((T is void ? null : T)): (PromiseInterface|TFulfilled)) $onFulfilled + * @return PromiseInterface<($onFulfilled is null ? T : TFulfilled)> + */ + public function then(callable $onFulfilled = null, callable $onRejected = null) : PromiseInterface + { + if (null === $onFulfilled) { + return $this; + } + try { + /** + * @var PromiseInterface|T $result + */ + $result = $onFulfilled($this->value); + return resolve($result); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } + } + public function catch(callable $onRejected) : PromiseInterface + { + return $this; + } + public function finally(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->then(function ($value) use($onFulfilledOrRejected) : PromiseInterface { + return resolve($onFulfilledOrRejected())->then(function () use($value) { + return $value; + }); + }); + } + public function cancel() : void + { + } + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected) : PromiseInterface + { + return $this->catch($onRejected); + } + /** + * @deprecated 3.0.0 Use `finally()` instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } +} diff --git a/vendor/react/promise/src/Internal/RejectedPromise.php b/vendor/react/promise/src/Internal/RejectedPromise.php new file mode 100644 index 00000000000..793ef01eff5 --- /dev/null +++ b/vendor/react/promise/src/Internal/RejectedPromise.php @@ -0,0 +1,111 @@ + + */ +final class RejectedPromise implements PromiseInterface +{ + /** @var \Throwable */ + private $reason; + /** @var bool */ + private $handled = \false; + /** + * @param \Throwable $reason + */ + public function __construct(\Throwable $reason) + { + $this->reason = $reason; + } + /** @throws void */ + public function __destruct() + { + if ($this->handled) { + return; + } + $handler = set_rejection_handler(null); + if ($handler === null) { + $message = 'Unhandled promise rejection with ' . \get_class($this->reason) . ': ' . $this->reason->getMessage() . ' in ' . $this->reason->getFile() . ':' . $this->reason->getLine() . \PHP_EOL; + $message .= 'Stack trace:' . \PHP_EOL . $this->reason->getTraceAsString(); + \error_log($message); + return; + } + try { + $handler($this->reason); + } catch (\Throwable $e) { + $message = 'Fatal error: Uncaught ' . \get_class($e) . ' from unhandled promise rejection handler: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine() . \PHP_EOL; + $message .= 'Stack trace:' . \PHP_EOL . $e->getTraceAsString(); + \error_log($message); + exit(255); + } + } + /** + * @template TRejected + * @param ?callable $onFulfilled + * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected + * @return PromiseInterface<($onRejected is null ? never : TRejected)> + */ + public function then(callable $onFulfilled = null, callable $onRejected = null) : PromiseInterface + { + if (null === $onRejected) { + return $this; + } + $this->handled = \true; + try { + return resolve($onRejected($this->reason)); + } catch (\Throwable $exception) { + return new RejectedPromise($exception); + } + } + /** + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected) : PromiseInterface + { + if (!_checkTypehint($onRejected, $this->reason)) { + return $this; + } + /** + * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected + */ + return $this->then(null, $onRejected); + } + public function finally(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->then(null, function (\Throwable $reason) use($onFulfilledOrRejected) : PromiseInterface { + return resolve($onFulfilledOrRejected())->then(function () use($reason) : PromiseInterface { + return new RejectedPromise($reason); + }); + }); + } + public function cancel() : void + { + $this->handled = \true; + } + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected) : PromiseInterface + { + return $this->catch($onRejected); + } + /** + * @deprecated 3.0.0 Use `always()` instead + * @see self::always() + */ + public function always(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } +} diff --git a/vendor/react/promise/src/Promise.php b/vendor/react/promise/src/Promise.php new file mode 100644 index 00000000000..2ca0fbdbec7 --- /dev/null +++ b/vendor/react/promise/src/Promise.php @@ -0,0 +1,244 @@ + + */ +final class Promise implements PromiseInterface +{ + /** @var ?callable */ + private $canceller; + /** @var ?PromiseInterface */ + private $result; + /** @var callable[] */ + private $handlers = []; + /** @var int */ + private $requiredCancelRequests = 0; + /** @var bool */ + private $cancelled = \false; + public function __construct(callable $resolver, callable $canceller = null) + { + $this->canceller = $canceller; + // Explicitly overwrite arguments with null values before invoking + // resolver function. This ensure that these arguments do not show up + // in the stack trace in PHP 7+ only. + $cb = $resolver; + $resolver = $canceller = null; + $this->call($cb); + } + public function then(callable $onFulfilled = null, callable $onRejected = null) : PromiseInterface + { + if (null !== $this->result) { + return $this->result->then($onFulfilled, $onRejected); + } + if (null === $this->canceller) { + return new static($this->resolver($onFulfilled, $onRejected)); + } + // This promise has a canceller, so we create a new child promise which + // has a canceller that invokes the parent canceller if all other + // followers are also cancelled. We keep a reference to this promise + // instance for the static canceller function and clear this to avoid + // keeping a cyclic reference between parent and follower. + $parent = $this; + ++$parent->requiredCancelRequests; + return new static($this->resolver($onFulfilled, $onRejected), static function () use(&$parent) { + \assert($parent instanceof self); + --$parent->requiredCancelRequests; + if ($parent->requiredCancelRequests <= 0) { + $parent->cancel(); + } + $parent = null; + }); + } + /** + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected) : PromiseInterface + { + return $this->then(null, static function ($reason) use($onRejected) { + if (!_checkTypehint($onRejected, $reason)) { + return new RejectedPromise($reason); + } + /** + * @var callable(\Throwable):(PromiseInterface|TRejected) $onRejected + */ + return $onRejected($reason); + }); + } + public function finally(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->then(static function ($value) use($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use($value) { + return $value; + }); + }, static function ($reason) use($onFulfilledOrRejected) { + return resolve($onFulfilledOrRejected())->then(function () use($reason) { + return new RejectedPromise($reason); + }); + }); + } + public function cancel() : void + { + $this->cancelled = \true; + $canceller = $this->canceller; + $this->canceller = null; + $parentCanceller = null; + if (null !== $this->result) { + // Forward cancellation to rejected promise to avoid reporting unhandled rejection + if ($this->result instanceof RejectedPromise) { + $this->result->cancel(); + } + // Go up the promise chain and reach the top most promise which is + // itself not following another promise + $root = $this->unwrap($this->result); + // Return if the root promise is already resolved or a + // FulfilledPromise or RejectedPromise + if (!$root instanceof self || null !== $root->result) { + return; + } + $root->requiredCancelRequests--; + if ($root->requiredCancelRequests <= 0) { + $parentCanceller = [$root, 'cancel']; + } + } + if (null !== $canceller) { + $this->call($canceller); + } + // For BC, we call the parent canceller after our own canceller + if ($parentCanceller) { + $parentCanceller(); + } + } + /** + * @deprecated 3.0.0 Use `catch()` instead + * @see self::catch() + */ + public function otherwise(callable $onRejected) : PromiseInterface + { + return $this->catch($onRejected); + } + /** + * @deprecated 3.0.0 Use `finally()` instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected) : PromiseInterface + { + return $this->finally($onFulfilledOrRejected); + } + private function resolver(callable $onFulfilled = null, callable $onRejected = null) : callable + { + return function ($resolve, $reject) use($onFulfilled, $onRejected) { + $this->handlers[] = static function (PromiseInterface $promise) use($onFulfilled, $onRejected, $resolve, $reject) { + $promise = $promise->then($onFulfilled, $onRejected); + if ($promise instanceof self && $promise->result === null) { + $promise->handlers[] = static function (PromiseInterface $promise) use($resolve, $reject) { + $promise->then($resolve, $reject); + }; + } else { + $promise->then($resolve, $reject); + } + }; + }; + } + private function reject(\Throwable $reason) : void + { + if (null !== $this->result) { + return; + } + $this->settle(reject($reason)); + } + /** + * @param PromiseInterface $result + */ + private function settle(PromiseInterface $result) : void + { + $result = $this->unwrap($result); + if ($result === $this) { + $result = new RejectedPromise(new \LogicException('Cannot resolve a promise with itself.')); + } + if ($result instanceof self) { + $result->requiredCancelRequests++; + } else { + // Unset canceller only when not following a pending promise + $this->canceller = null; + } + $handlers = $this->handlers; + $this->handlers = []; + $this->result = $result; + foreach ($handlers as $handler) { + $handler($result); + } + // Forward cancellation to rejected promise to avoid reporting unhandled rejection + if ($this->cancelled && $result instanceof RejectedPromise) { + $result->cancel(); + } + } + /** + * @param PromiseInterface $promise + * @return PromiseInterface + */ + private function unwrap(PromiseInterface $promise) : PromiseInterface + { + while ($promise instanceof self && null !== $promise->result) { + /** @var PromiseInterface $promise */ + $promise = $promise->result; + } + return $promise; + } + private function call(callable $cb) : void + { + // Explicitly overwrite argument with null value. This ensure that this + // argument does not show up in the stack trace in PHP 7+ only. + $callback = $cb; + $cb = null; + // Use reflection to inspect number of arguments expected by this callback. + // We did some careful benchmarking here: Using reflection to avoid unneeded + // function arguments is actually faster than blindly passing them. + // Also, this helps avoiding unnecessary function arguments in the call stack + // if the callback creates an Exception (creating garbage cycles). + if (\is_array($callback)) { + $ref = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $ref = new \ReflectionMethod($callback, '__invoke'); + } else { + \assert($callback instanceof \Closure || \is_string($callback)); + $ref = new \ReflectionFunction($callback); + } + $args = $ref->getNumberOfParameters(); + try { + if ($args === 0) { + $callback(); + } else { + // Keep references to this promise instance for the static resolve/reject functions. + // By using static callbacks that are not bound to this instance + // and passing the target promise instance by reference, we can + // still execute its resolving logic and still clear this + // reference when settling the promise. This helps avoiding + // garbage cycles if any callback creates an Exception. + // These assumptions are covered by the test suite, so if you ever feel like + // refactoring this, go ahead, any alternative suggestions are welcome! + $target =& $this; + $callback(static function ($value) use(&$target) { + if ($target !== null) { + $target->settle(resolve($value)); + $target = null; + } + }, static function (\Throwable $reason) use(&$target) { + if ($target !== null) { + $target->reject($reason); + $target = null; + } + }); + } + } catch (\Throwable $e) { + $target = null; + $this->reject($e); + } + } +} diff --git a/vendor/react/promise/src/PromiseInterface.php b/vendor/react/promise/src/PromiseInterface.php new file mode 100644 index 00000000000..d27cb0268f9 --- /dev/null +++ b/vendor/react/promise/src/PromiseInterface.php @@ -0,0 +1,147 @@ +|TFulfilled)) $onFulfilled + * @param ?(callable(\Throwable): (PromiseInterface|TRejected)) $onRejected + * @return PromiseInterface<($onRejected is null ? ($onFulfilled is null ? T : TFulfilled) : ($onFulfilled is null ? T|TRejected : TFulfilled|TRejected))> + */ + public function then(?callable $onFulfilled = null, ?callable $onRejected = null) : PromiseInterface; + /** + * Registers a rejection handler for promise. It is a shortcut for: + * + * ```php + * $promise->then(null, $onRejected); + * ``` + * + * Additionally, you can type hint the `$reason` argument of `$onRejected` to catch + * only specific errors. + * + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + */ + public function catch(callable $onRejected) : PromiseInterface; + /** + * Allows you to execute "cleanup" type tasks in a promise chain. + * + * It arranges for `$onFulfilledOrRejected` to be called, with no arguments, + * when the promise is either fulfilled or rejected. + * + * * If `$promise` fulfills, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will fulfill with the same value as `$promise`. + * * If `$promise` fulfills, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * * If `$promise` rejects, and `$onFulfilledOrRejected` returns successfully, + * `$newPromise` will reject with the same reason as `$promise`. + * * If `$promise` rejects, and `$onFulfilledOrRejected` throws or returns a + * rejected promise, `$newPromise` will reject with the thrown exception or + * rejected promise's reason. + * + * `finally()` behaves similarly to the synchronous finally statement. When combined + * with `catch()`, `finally()` allows you to write code that is similar to the familiar + * synchronous catch/finally pair. + * + * Consider the following synchronous code: + * + * ```php + * try { + * return doSomething(); + * } catch(\Exception $e) { + * return handleError($e); + * } finally { + * cleanup(); + * } + * ``` + * + * Similar asynchronous code (with `doSomething()` that returns a promise) can be + * written: + * + * ```php + * return doSomething() + * ->catch('handleError') + * ->finally('cleanup'); + * ``` + * + * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected + * @return PromiseInterface + */ + public function finally(callable $onFulfilledOrRejected) : PromiseInterface; + /** + * The `cancel()` method notifies the creator of the promise that there is no + * further interest in the results of the operation. + * + * Once a promise is settled (either fulfilled or rejected), calling `cancel()` on + * a promise has no effect. + * + * @return void + */ + public function cancel() : void; + /** + * [Deprecated] Registers a rejection handler for a promise. + * + * This method continues to exist only for BC reasons and to ease upgrading + * between versions. It is an alias for: + * + * ```php + * $promise->catch($onRejected); + * ``` + * + * @template TThrowable of \Throwable + * @template TRejected + * @param callable(TThrowable): (PromiseInterface|TRejected) $onRejected + * @return PromiseInterface + * @deprecated 3.0.0 Use catch() instead + * @see self::catch() + */ + public function otherwise(callable $onRejected) : PromiseInterface; + /** + * [Deprecated] Allows you to execute "cleanup" type tasks in a promise chain. + * + * This method continues to exist only for BC reasons and to ease upgrading + * between versions. It is an alias for: + * + * ```php + * $promise->finally($onFulfilledOrRejected); + * ``` + * + * @param callable(): (void|PromiseInterface) $onFulfilledOrRejected + * @return PromiseInterface + * @deprecated 3.0.0 Use finally() instead + * @see self::finally() + */ + public function always(callable $onFulfilledOrRejected) : PromiseInterface; +} diff --git a/vendor/react/promise/src/functions.php b/vendor/react/promise/src/functions.php new file mode 100644 index 00000000000..f4f35c6e24e --- /dev/null +++ b/vendor/react/promise/src/functions.php @@ -0,0 +1,288 @@ +|T $promiseOrValue + * @return PromiseInterface + */ +function resolve($promiseOrValue) : PromiseInterface +{ + if ($promiseOrValue instanceof PromiseInterface) { + return $promiseOrValue; + } + if (\is_object($promiseOrValue) && \method_exists($promiseOrValue, 'then')) { + $canceller = null; + if (\method_exists($promiseOrValue, 'cancel')) { + $canceller = [$promiseOrValue, 'cancel']; + \assert(\is_callable($canceller)); + } + return new Promise(function ($resolve, $reject) use($promiseOrValue) : void { + $promiseOrValue->then($resolve, $reject); + }, $canceller); + } + return new FulfilledPromise($promiseOrValue); +} +/** + * Creates a rejected promise for the supplied `$reason`. + * + * If `$reason` is a value, it will be the rejection value of the + * returned promise. + * + * If `$reason` is a promise, its completion value will be the rejected + * value of the returned promise. + * + * This can be useful in situations where you need to reject a promise without + * throwing an exception. For example, it allows you to propagate a rejection with + * the value of another promise. + * + * @return PromiseInterface + */ +function reject(\Throwable $reason) : PromiseInterface +{ + return new RejectedPromise($reason); +} +/** + * Returns a promise that will resolve only once all the items in + * `$promisesOrValues` have resolved. The resolution value of the returned promise + * will be an array containing the resolution values of each of the items in + * `$promisesOrValues`. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface> + */ +function all(iterable $promisesOrValues) : PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + return new Promise(function ($resolve, $reject) use($promisesOrValues, $cancellationQueue) : void { + $toResolve = 0; + /** @var bool */ + $continue = \true; + $values = []; + foreach ($promisesOrValues as $i => $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + $values[$i] = null; + ++$toResolve; + resolve($promiseOrValue)->then(function ($value) use($i, &$values, &$toResolve, &$continue, $resolve) : void { + $values[$i] = $value; + if (0 === --$toResolve && !$continue) { + $resolve($values); + } + }, function (\Throwable $reason) use(&$continue, $reject) : void { + $continue = \false; + $reject($reason); + }); + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + $continue = \false; + if ($toResolve === 0) { + $resolve($values); + } + }, $cancellationQueue); +} +/** + * Initiates a competitive race that allows one winner. Returns a promise which is + * resolved in the same way the first settled promise resolves. + * + * The returned promise will become **infinitely pending** if `$promisesOrValues` + * contains 0 items. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface + */ +function race(iterable $promisesOrValues) : PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + return new Promise(function (callable $resolve, callable $reject) use($promisesOrValues, $cancellationQueue) : void { + $continue = \true; + foreach ($promisesOrValues as $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + resolve($promiseOrValue)->then($resolve, $reject)->finally(function () use(&$continue) : void { + $continue = \false; + }); + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + }, $cancellationQueue); +} +/** + * Returns a promise that will resolve when any one of the items in + * `$promisesOrValues` resolves. The resolution value of the returned promise + * will be the resolution value of the triggering item. + * + * The returned promise will only reject if *all* items in `$promisesOrValues` are + * rejected. The rejection value will be an array of all rejection reasons. + * + * The returned promise will also reject with a `React\Promise\Exception\LengthException` + * if `$promisesOrValues` contains 0 items. + * + * @template T + * @param iterable|T> $promisesOrValues + * @return PromiseInterface + */ +function any(iterable $promisesOrValues) : PromiseInterface +{ + $cancellationQueue = new Internal\CancellationQueue(); + return new Promise(function ($resolve, $reject) use($promisesOrValues, $cancellationQueue) : void { + $toReject = 0; + $continue = \true; + $reasons = []; + foreach ($promisesOrValues as $i => $promiseOrValue) { + $cancellationQueue->enqueue($promiseOrValue); + ++$toReject; + resolve($promiseOrValue)->then(function ($value) use($resolve, &$continue) : void { + $continue = \false; + $resolve($value); + }, function (\Throwable $reason) use($i, &$reasons, &$toReject, $reject, &$continue) : void { + $reasons[$i] = $reason; + if (0 === --$toReject && !$continue) { + $reject(new CompositeException($reasons, 'All promises rejected.')); + } + }); + if (!$continue && !\is_array($promisesOrValues)) { + break; + } + } + $continue = \false; + if ($toReject === 0 && !$reasons) { + $reject(new Exception\LengthException('Must contain at least 1 item but contains only 0 items.')); + } elseif ($toReject === 0) { + $reject(new CompositeException($reasons, 'All promises rejected.')); + } + }, $cancellationQueue); +} +/** + * Sets the global rejection handler for unhandled promise rejections. + * + * Note that rejected promises should always be handled similar to how any + * exceptions should always be caught in a `try` + `catch` block. If you remove + * the last reference to a rejected promise that has not been handled, it will + * report an unhandled promise rejection. See also the [`reject()` function](#reject) + * for more details. + * + * The `?callable $callback` argument MUST be a valid callback function that + * accepts a single `Throwable` argument or a `null` value to restore the + * default promise rejection handler. The return value of the callback function + * will be ignored and has no effect, so you SHOULD return a `void` value. The + * callback function MUST NOT throw or the program will be terminated with a + * fatal error. + * + * The function returns the previous rejection handler or `null` if using the + * default promise rejection handler. + * + * The default promise rejection handler will log an error message plus its + * stack trace: + * + * ```php + * // Unhandled promise rejection with RuntimeException: Unhandled in example.php:2 + * React\Promise\reject(new RuntimeException('Unhandled')); + * ``` + * + * The promise rejection handler may be used to use customize the log message or + * write to custom log targets. As a rule of thumb, this function should only be + * used as a last resort and promise rejections are best handled with either the + * [`then()` method](#promiseinterfacethen), the + * [`catch()` method](#promiseinterfacecatch), or the + * [`finally()` method](#promiseinterfacefinally). + * See also the [`reject()` function](#reject) for more details. + * + * @param callable(\Throwable):void|null $callback + * @return callable(\Throwable):void|null + */ +function set_rejection_handler(?callable $callback) : ?callable +{ + static $current = null; + $previous = $current; + $current = $callback; + return $previous; +} +/** + * @internal + */ +function _checkTypehint(callable $callback, \Throwable $reason) : bool +{ + if (\is_array($callback)) { + $callbackReflection = new \ReflectionMethod($callback[0], $callback[1]); + } elseif (\is_object($callback) && !$callback instanceof \Closure) { + $callbackReflection = new \ReflectionMethod($callback, '__invoke'); + } else { + \assert($callback instanceof \Closure || \is_string($callback)); + $callbackReflection = new \ReflectionFunction($callback); + } + $parameters = $callbackReflection->getParameters(); + if (!isset($parameters[0])) { + return \true; + } + $expectedException = $parameters[0]; + // Extract the type of the argument and handle different possibilities + $type = $expectedException->getType(); + $isTypeUnion = \true; + $types = []; + switch (\true) { + case $type === null: + break; + case $type instanceof \ReflectionNamedType: + $types = [$type]; + break; + case $type instanceof \ReflectionIntersectionType: + $isTypeUnion = \false; + case $type instanceof \ReflectionUnionType: + $types = $type->getTypes(); + break; + default: + throw new \LogicException('Unexpected return value of ReflectionParameter::getType'); + } + // If there is no type restriction, it matches + if (empty($types)) { + return \true; + } + foreach ($types as $type) { + if ($type instanceof \ReflectionIntersectionType) { + foreach ($type->getTypes() as $typeToMatch) { + \assert($typeToMatch instanceof \ReflectionNamedType); + $name = $typeToMatch->getName(); + if (!($matches = !$typeToMatch->isBuiltin() && $reason instanceof $name)) { + break; + } + } + \assert(isset($matches)); + } else { + \assert($type instanceof \ReflectionNamedType); + $name = $type->getName(); + $matches = !$type->isBuiltin() && $reason instanceof $name; + } + // If we look for a single match (union), we can return early on match + // If we look for a full match (intersection), we can return early on mismatch + if ($matches) { + if ($isTypeUnion) { + return \true; + } + } else { + if (!$isTypeUnion) { + return \false; + } + } + } + // If we look for a single match (union) and did not return early, we matched no type and are false + // If we look for a full match (intersection) and did not return early, we matched all types and are true + return $isTypeUnion ? \false : \true; +} diff --git a/vendor/react/promise/src/functions_include.php b/vendor/react/promise/src/functions_include.php new file mode 100644 index 00000000000..7ff95fc68d1 --- /dev/null +++ b/vendor/react/promise/src/functions_include.php @@ -0,0 +1,7 @@ +connect($uri)->then(function (React\Socket\ConnectionInterface $conn) { + // … + }, function (Exception $e) { + echo 'Error:' . $e->getMessage() . PHP_EOL; + }); + ``` + +* Improve test suite, test against PHP 8.1 release. + (#274 by @SimonFrings) + +## 1.9.0 (2021-08-03) + +* Feature: Add new `SocketServer` and deprecate `Server` to avoid class name collisions. + (#263 by @clue) + + The new `SocketServer` class has been added with an improved constructor signature + as a replacement for the previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + In its most basic form, the deprecated `Server` can now be considered an alias for new `SocketServer`. + + ```php + // deprecated + $socket = new React\Socket\Server(0); + $socket = new React\Socket\Server('127.0.0.1:8000'); + $socket = new React\Socket\Server('127.0.0.1:8000', null, $context); + $socket = new React\Socket\Server('127.0.0.1:8000', $loop, $context); + + // new + $socket = new React\Socket\SocketServer('127.0.0.1:0'); + $socket = new React\Socket\SocketServer('127.0.0.1:8000'); + $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context); + $socket = new React\Socket\SocketServer('127.0.0.1:8000', $context, $loop); + ``` + +* Feature: Update `Connector` signature to take optional `$context` as first argument. + (#264 by @clue) + + The new signature has been added to match the new `SocketServer` and + consistently move the now commonly unneeded loop argument to the last argument. + The previous signature has been deprecated and should not be used anymore. + In its most basic form, both signatures are compatible. + + ```php + // deprecated + $connector = new React\Socket\Connector(null, $context); + $connector = new React\Socket\Connector($loop, $context); + + // new + $connector = new React\Socket\Connector($context); + $connector = new React\Socket\Connector($context, $loop); + ``` + +## 1.8.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#260 by @clue) + + ```php + // old (still supported) + $socket = new React\Socket\Server('127.0.0.1:8080', $loop); + $connector = new React\Socket\Connector($loop); + + // new (using default loop) + $socket = new React\Socket\Server('127.0.0.1:8080'); + $connector = new React\Socket\Connector(); + ``` + +## 1.7.0 (2021-06-25) + +* Feature: Support falling back to multiple DNS servers from DNS config. + (#257 by @clue) + + If you're using the default `Connector`, it will now use all DNS servers + configured on your system. If you have multiple DNS servers configured and + connectivity to the primary DNS server is broken, it will now fall back to + your other DNS servers, thus providing improved connectivity and redundancy + for broken DNS configurations. + +* Feature: Use round robin for happy eyeballs DNS responses (load balancing). + (#247 by @clue) + + If you're using the default `Connector`, it will now randomize the order of + the IP addresses resolved via DNS when connecting. This allows the load to + be distributed more evenly across all returned IP addresses. This can be + used as a very basic DNS load balancing mechanism. + +* Internal improvement to avoid unhandled rejection for future Promise API. + (#258 by @clue) + +* Improve test suite, use GitHub actions for continuous integration (CI). + (#254 by @SimonFrings) + +## 1.6.0 (2020-08-28) + +* Feature: Support upcoming PHP 8 release. + (#246 by @clue) + +* Feature: Change default socket backlog size to 511. + (#242 by @clue) + +* Fix: Fix closing connection when cancelling during TLS handshake. + (#241 by @clue) + +* Fix: Fix blocking during possible `accept()` race condition + when multiple socket servers listen on same socket address. + (#244 by @clue) + +* Improve test suite, update PHPUnit config and add full core team to the license. + (#243 by @SimonFrings and #245 by @WyriHaximus) + +## 1.5.0 (2020-07-01) + +* Feature / Fix: Improve error handling and reporting for happy eyeballs and + immediately try next connection when one connection attempt fails. + (#230, #231, #232 and #233 by @clue) + + Error messages for failed connection attempts now include more details to + ease debugging. Additionally, the happy eyeballs algorithm has been improved + to avoid having to wait for some timers to expire which significantly + improves connection setup times (in particular when IPv6 isn't available). + +* Improve test suite, minor code cleanup and improve code coverage to 100%. + Update to PHPUnit 9 and skip legacy TLS 1.0 / TLS 1.1 tests if disabled by + system. Run tests on Windows and simplify Travis CI test matrix for Mac OS X + setup and skip all TLS tests on legacy HHVM. + (#229, #235, #236 and #238 by @clue and #239 by @SimonFrings) + +## 1.4.0 (2020-03-12) + +A major new feature release, see [**release announcement**](https://clue.engineering/2020/introducing-ipv6-for-reactphp). + +* Feature: Add IPv6 support to `Connector` (implement "Happy Eyeballs" algorithm to support IPv6 probing). + IPv6 support is turned on by default, use new `happy_eyeballs` option in `Connector` to toggle behavior. + (#196, #224 and #225 by @WyriHaximus and @clue) + +* Feature: Default to using DNS cache (with max 256 entries) for `Connector`. + (#226 by @clue) + +* Add `.gitattributes` to exclude dev files from exports and some minor code style fixes. + (#219 by @reedy and #218 by @mmoreram) + +* Improve test suite to fix failing test cases when using new DNS component, + significantly improve test performance by awaiting events instead of sleeping, + exclude TLS 1.3 test on PHP 7.3, run tests on PHP 7.4 and simplify test matrix. + (#208, #209, #210, #217 and #223 by @clue) + +## 1.3.0 (2019-07-10) + +* Feature: Forward compatibility with upcoming stable DNS component. + (#206 by @clue) + +## 1.2.1 (2019-06-03) + +* Avoid uneeded fragmented TLS work around for PHP 7.3.3+ and + work around failing test case detecting EOF on TLS 1.3 socket streams. + (#201 and #202 by @clue) + +* Improve TLS certificate/passphrase example. + (#190 by @jsor) + +## 1.2.0 (2019-01-07) + +* Feature / Fix: Improve TLS 1.3 support. + (#186 by @clue) + + TLS 1.3 is now an official standard as of August 2018! :tada: + The protocol has major improvements in the areas of security, performance, and privacy. + TLS 1.3 is supported by default as of [OpenSSL 1.1.1](https://www.openssl.org/blog/blog/2018/09/11/release111/). + For example, this version ships with Ubuntu 18.10 (and newer) by default, meaning that recent installations support TLS 1.3 out of the box :shipit: + +* Fix: Avoid possibility of missing remote address when TLS handshake fails. + (#188 by @clue) + +* Improve performance by prefixing all global functions calls with `\` to skip the look up and resolve process and go straight to the global function. + (#183 by @WyriHaximus) + +* Update documentation to use full class names with namespaces. + (#187 by @clue) + +* Improve test suite to avoid some possible race conditions, + test against PHP 7.3 on Travis and + use dedicated `assertInstanceOf()` assertions. + (#185 by @clue, #178 by @WyriHaximus and #181 by @carusogabriel) + +## 1.1.0 (2018-10-01) + +* Feature: Improve error reporting for failed connection attempts and improve + cancellation forwarding during DNS lookup, TCP/IP connection or TLS handshake. + (#168, #169, #170, #171, #176 and #177 by @clue) + + All error messages now always contain a reference to the remote URI to give + more details which connection actually failed and the reason for this error. + Accordingly, failures during DNS lookup will now mention both the remote URI + as well as the DNS error reason. TCP/IP connection issues and errors during + a secure TLS handshake will both mention the remote URI as well as the + underlying socket error. Similarly, lost/dropped connections during a TLS + handshake will now report a lost connection instead of an empty error reason. + + For most common use cases this means that simply reporting the `Exception` + message should give the most relevant details for any connection issues: + + ```php + $promise = $connector->connect('tls://example.com:443'); + $promise->then(function (ConnectionInterface $conn) use ($loop) { + // … + }, function (Exception $e) { + echo $e->getMessage(); + }); + ``` + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.8.12 release. + +## 0.8.12 (2018-06-11) + +* Feature: Improve memory consumption for failed and cancelled connection attempts. + (#161 by @clue) + +* Improve test suite to fix Travis config to test against legacy PHP 5.3 again. + (#162 by @clue) + +## 0.8.11 (2018-04-24) + +* Feature: Improve memory consumption for cancelled connection attempts and + simplify skipping DNS lookup when connecting to IP addresses. + (#159 and #160 by @clue) + +## 0.8.10 (2018-02-28) + +* Feature: Update DNS dependency to support loading system default DNS + nameserver config on all supported platforms + (`/etc/resolv.conf` on Unix/Linux/Mac/Docker/WSL and WMIC on Windows) + (#152 by @clue) + + This means that connecting to hosts that are managed by a local DNS server, + such as a corporate DNS server or when using Docker containers, will now + work as expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('intranet.example:80')->then(function ($connection) { + // … + }); + ``` + +## 0.8.9 (2018-01-18) + +* Feature: Support explicitly choosing TLS version to negotiate with remote side + by respecting `crypto_method` context parameter for all classes. + (#149 by @clue) + + By default, all connector and server classes support TLSv1.0+ and exclude + support for legacy SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly + choose the TLS version you want to negotiate with the remote side: + + ```php + // new: now supports 'crypto_method` context parameter for all classes + $connector = new Connector($loop, array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) + )); + ``` + +* Minor internal clean up to unify class imports + (#148 by @clue) + +## 0.8.8 (2018-01-06) + +* Improve test suite by adding test group to skip integration tests relying on + internet connection and fix minor documentation typo. + (#146 by @clue and #145 by @cn007b) + +## 0.8.7 (2017-12-24) + +* Fix: Fix closing socket resource before removing from loop + (#141 by @clue) + + This fixes the root cause of an uncaught `Exception` that only manifested + itself after the recent Stream v0.7.4 component update and only if you're + using `ext-event` (`ExtEventLoop`). + +* Improve test suite by testing against PHP 7.2 + (#140 by @carusogabriel) + +## 0.8.6 (2017-11-18) + +* Feature: Add Unix domain socket (UDS) support to `Server` with `unix://` URI scheme + and add advanced `UnixServer` class. + (#120 by @andig) + + ```php + // new: Server now supports "unix://" scheme + $server = new Server('unix:///tmp/server.sock', $loop); + + // new: advanced usage + $server = new UnixServer('/tmp/server.sock', $loop); + ``` + +* Restructure examples to ease getting started + (#136 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#133 by @gabriel-caruso and #134 by @clue) + +## 0.8.5 (2017-10-23) + +* Fix: Work around PHP bug with Unix domain socket (UDS) paths for Mac OS X + (#123 by @andig) + +* Fix: Fix `SecureServer` to return `null` URI if server socket is already closed + (#129 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit v5 and + forward compatibility with upcoming EventLoop releases in tests and + test Mac OS X on Travis + (#122 by @andig and #125, #127 and #130 by @clue) + +* Readme improvements + (#118 by @jsor) + +## 0.8.4 (2017-09-16) + +* Feature: Add `FixedUriConnector` decorator to use fixed, preconfigured URI instead + (#117 by @clue) + + This can be useful for consumers that do not support certain URIs, such as + when you want to explicitly connect to a Unix domain socket (UDS) path + instead of connecting to a default address assumed by an higher-level API: + + ```php + $connector = new FixedUriConnector( + 'unix:///var/run/docker.sock', + new UnixConnector($loop) + ); + + // destination will be ignored, actually connects to Unix domain socket + $promise = $connector->connect('localhost:80'); + ``` + +## 0.8.3 (2017-09-08) + +* Feature: Reduce memory consumption for failed connections + (#113 by @valga) + +* Fix: Work around write chunk size for TLS streams for PHP < 7.1.14 + (#114 by @clue) + +## 0.8.2 (2017-08-25) + +* Feature: Update DNS dependency to support hosts file on all platforms + (#112 by @clue) + + This means that connecting to hosts such as `localhost` will now work as + expected across all platforms with no changes required: + + ```php + $connector = new Connector($loop); + $connector->connect('localhost:8080')->then(function ($connection) { + // … + }); + ``` + +## 0.8.1 (2017-08-15) + +* Feature: Forward compatibility with upcoming EventLoop v1.0 and v0.5 and + target evenement 3.0 a long side 2.0 and 1.0 + (#104 by @clue and #111 by @WyriHaximus) + +* Improve test suite by locking Travis distro so new defaults will not break the build and + fix HHVM build for now again and ignore future HHVM build errors + (#109 and #110 by @clue) + +* Minor documentation fixes + (#103 by @christiaan and #108 by @hansott) + +## 0.8.0 (2017-05-09) + +* Feature: New `Server` class now acts as a facade for existing server classes + and renamed old `Server` to `TcpServer` for advanced usage. + (#96 and #97 by @clue) + + The `Server` class is now the main class in this package that implements the + `ServerInterface` and allows you to accept incoming streaming connections, + such as plaintext TCP/IP or secure TLS connection streams. + + > This is not a BC break and consumer code does not have to be updated. + +* Feature / BC break: All addresses are now URIs that include the URI scheme + (#98 by @clue) + + ```diff + - $parts = parse_url('tcp://' . $conn->getRemoteAddress()); + + $parts = parse_url($conn->getRemoteAddress()); + ``` + +* Fix: Fix `unix://` addresses for Unix domain socket (UDS) paths + (#100 by @clue) + +* Feature: Forward compatibility with Stream v1.0 and v0.7 + (#99 by @clue) + +## 0.7.2 (2017-04-24) + +* Fix: Work around latest PHP 7.0.18 and 7.1.4 no longer accepting full URIs + (#94 by @clue) + +## 0.7.1 (2017-04-10) + +* Fix: Ignore HHVM errors when closing connection that is already closing + (#91 by @clue) + +## 0.7.0 (2017-04-10) + +* Feature: Merge SocketClient component into this component + (#87 by @clue) + + This means that this package now provides async, streaming plaintext TCP/IP + and secure TLS socket server and client connections for ReactPHP. + + ``` + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + + Accordingly, the `ConnectionInterface` is now used to represent both incoming + server side connections as well as outgoing client side connections. + + If you've previously used the SocketClient component to establish outgoing + client connections, upgrading should take no longer than a few minutes. + All classes have been merged as-is from the latest `v0.7.0` release with no + other changes, so you can simply update your code to use the updated namespace + like this: + + ```php + // old from SocketClient component and namespace + $connector = new React\SocketClient\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + + // new + $connector = new React\Socket\Connector($loop); + $connector->connect('google.com:80')->then(function (ConnectionInterface $conn) { + $connection->write('…'); + }); + ``` + +## 0.6.0 (2017-04-04) + +* Feature: Add `LimitingServer` to limit and keep track of open connections + (#86 by @clue) + + ```php + $server = new Server(0, $loop); + $server = new LimitingServer($server, 100); + + $server->on('connection', function (ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … + }); + ``` + +* Feature / BC break: Add `pause()` and `resume()` methods to limit active + connections + (#84 by @clue) + + ```php + $server = new Server(0, $loop); + $server->pause(); + + $loop->addTimer(1.0, function() use ($server) { + $server->resume(); + }); + ``` + +## 0.5.1 (2017-03-09) + +* Feature: Forward compatibility with Stream v0.5 and upcoming v0.6 + (#79 by @clue) + +## 0.5.0 (2017-02-14) + +* Feature / BC break: Replace `listen()` call with URIs passed to constructor + and reject listening on hostnames with `InvalidArgumentException` + and replace `ConnectionException` with `RuntimeException` for consistency + (#61, #66 and #72 by @clue) + + ```php + // old + $server = new Server($loop); + $server->listen(8080); + + // new + $server = new Server(8080, $loop); + ``` + + Similarly, you can now pass a full listening URI to the constructor to change + the listening host: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, '127.0.0.1'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + Trying to start listening on (DNS) host names will now throw an + `InvalidArgumentException`, use IP addresses instead: + + ```php + // old + $server = new Server($loop); + $server->listen(8080, 'localhost'); + + // new + $server = new Server('127.0.0.1:8080', $loop); + ``` + + If trying to listen fails (such as if port is already in use or port below + 1024 may require root access etc.), it will now throw a `RuntimeException`, + the `ConnectionException` class has been removed: + + ```php + // old: throws React\Socket\ConnectionException + $server = new Server($loop); + $server->listen(80); + + // new: throws RuntimeException + $server = new Server(80, $loop); + ``` + +* Feature / BC break: Rename `shutdown()` to `close()` for consistency throughout React + (#62 by @clue) + + ```php + // old + $server->shutdown(); + + // new + $server->close(); + ``` + +* Feature / BC break: Replace `getPort()` with `getAddress()` + (#67 by @clue) + + ```php + // old + echo $server->getPort(); // 8080 + + // new + echo $server->getAddress(); // 127.0.0.1:8080 + ``` + +* Feature / BC break: `getRemoteAddress()` returns full address instead of only IP + (#65 by @clue) + + ```php + // old + echo $connection->getRemoteAddress(); // 192.168.0.1 + + // new + echo $connection->getRemoteAddress(); // 192.168.0.1:51743 + ``` + +* Feature / BC break: Add `getLocalAddress()` method + (#68 by @clue) + + ```php + echo $connection->getLocalAddress(); // 127.0.0.1:8080 + ``` + +* BC break: The `Server` and `SecureServer` class are now marked `final` + and you can no longer `extend` them + (which was never documented or recommended anyway). + Public properties and event handlers are now internal only. + Please use composition instead of extension. + (#71, #70 and #69 by @clue) + +## 0.4.6 (2017-01-26) + +* Feature: Support socket context options passed to `Server` + (#64 by @clue) + +* Fix: Properly return `null` for unknown addresses + (#63 by @clue) + +* Improve documentation for `ServerInterface` and lock test suite requirements + (#60 by @clue, #57 by @shaunbramley) + +## 0.4.5 (2017-01-08) + +* Feature: Add `SecureServer` for secure TLS connections + (#55 by @clue) + +* Add functional integration tests + (#54 by @clue) + +## 0.4.4 (2016-12-19) + +* Feature / Fix: `ConnectionInterface` should extend `DuplexStreamInterface` + documentation + (#50 by @clue) + +* Feature / Fix: Improve test suite and switch to normal stream handler + (#51 by @clue) + +* Feature: Add examples + (#49 by @clue) + +## 0.4.3 (2016-03-01) + +* Bug fix: Suppress errors on stream_socket_accept to prevent PHP from crashing +* Support for PHP7 and HHVM +* Support PHP 5.3 again + +## 0.4.2 (2014-05-25) + +* Verify stream is a valid resource in Connection + +## 0.4.1 (2014-04-13) + +* Bug fix: Check read buffer for data before shutdown signal and end emit (@ArtyDev) +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: Reset socket to non-blocking after shutting down (PHP bug) + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to React/Promise 2.0 +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 +* Bump React dependencies to v0.4 + +## 0.3.3 (2013-07-08) + +* Version bump + +## 0.3.2 (2013-05-10) + +* Version bump + +## 0.3.1 (2013-04-21) + +* Feature: Support binding to IPv6 addresses (@clue) + +## 0.3.0 (2013-04-14) + +* Bump React dependencies to v0.3 + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.0 (2012-09-10) + +* Bump React dependencies to v0.2 + +## 0.1.1 (2012-07-12) + +* Version bump + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/vendor/react/socket/LICENSE b/vendor/react/socket/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/socket/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/socket/README.md b/vendor/react/socket/README.md new file mode 100644 index 00000000000..6aa9c59cdfa --- /dev/null +++ b/vendor/react/socket/README.md @@ -0,0 +1,1564 @@ +# Socket + +[![CI status](https://github.com/reactphp/socket/workflows/CI/badge.svg)](https://github.com/reactphp/socket/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/socket?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/socket) + +Async, streaming plaintext TCP/IP and secure TLS socket server and client +connections for [ReactPHP](https://reactphp.org/). + +The socket library provides re-usable interfaces for a socket-layer +server and client based on the [`EventLoop`](https://github.com/reactphp/event-loop) +and [`Stream`](https://github.com/reactphp/stream) components. +Its server component allows you to build networking servers that accept incoming +connections from networking clients (such as an HTTP server). +Its client component allows you to build networking clients that establish +outgoing connections to networking servers (such as an HTTP or database client). +This library provides async, streaming means for all of this, so you can +handle multiple concurrent connections without blocking. + +**Table of Contents** + +* [Quickstart example](#quickstart-example) +* [Connection usage](#connection-usage) + * [ConnectionInterface](#connectioninterface) + * [getRemoteAddress()](#getremoteaddress) + * [getLocalAddress()](#getlocaladdress) +* [Server usage](#server-usage) + * [ServerInterface](#serverinterface) + * [connection event](#connection-event) + * [error event](#error-event) + * [getAddress()](#getaddress) + * [pause()](#pause) + * [resume()](#resume) + * [close()](#close) + * [SocketServer](#socketserver) + * [Advanced server usage](#advanced-server-usage) + * [TcpServer](#tcpserver) + * [SecureServer](#secureserver) + * [UnixServer](#unixserver) + * [LimitingServer](#limitingserver) + * [getConnections()](#getconnections) +* [Client usage](#client-usage) + * [ConnectorInterface](#connectorinterface) + * [connect()](#connect) + * [Connector](#connector) + * [Advanced client usage](#advanced-client-usage) + * [TcpConnector](#tcpconnector) + * [HappyEyeBallsConnector](#happyeyeballsconnector) + * [DnsConnector](#dnsconnector) + * [SecureConnector](#secureconnector) + * [TimeoutConnector](#timeoutconnector) + * [UnixConnector](#unixconnector) + * [FixUriConnector](#fixeduriconnector) +* [Install](#install) +* [Tests](#tests) +* [License](#license) + +## Quickstart example + +Here is a server that closes the connection if you send it anything: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); + +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write("Hello " . $connection->getRemoteAddress() . "!\n"); + $connection->write("Welcome to this amazing server!\n"); + $connection->write("Here's a tip: don't say anything.\n"); + + $connection->on('data', function ($data) use ($connection) { + $connection->close(); + }); +}); +``` + +See also the [examples](examples). + +Here's a client that outputs the output of said server and then attempts to +send it a string: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect('127.0.0.1:8080')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->pipe(new React\Stream\WritableResourceStream(STDOUT)); + $connection->write("Hello World!\n"); +}, function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +## Connection usage + +### ConnectionInterface + +The `ConnectionInterface` is used to represent any incoming and outgoing +connection, such as a normal TCP/IP connection. + +An incoming or outgoing connection is a duplex stream (both readable and +writable) that implements React's +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). +It contains additional properties for the local and remote address (client IP) +where this connection has been established to/from. + +Most commonly, instances implementing this `ConnectionInterface` are emitted +by all classes implementing the [`ServerInterface`](#serverinterface) and +used by all classes implementing the [`ConnectorInterface`](#connectorinterface). + +Because the `ConnectionInterface` implements the underlying +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface) +you can use any of its events and methods as usual: + +```php +$connection->on('data', function ($chunk) { + echo $chunk; +}); + +$connection->on('end', function () { + echo 'ended'; +}); + +$connection->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage(); +}); + +$connection->on('close', function () { + echo 'closed'; +}); + +$connection->write($data); +$connection->end($data = null); +$connection->close(); +// … +``` + +For more details, see the +[`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + +#### getRemoteAddress() + +The `getRemoteAddress(): ?string` method returns the full remote address +(URI) where this connection has been established with. + +```php +$address = $connection->getRemoteAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the remote address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based connection and you only want the remote IP, you may +use something like this: + +```php +$address = $connection->getRemoteAddress(); +$ip = trim(parse_url($address, PHP_URL_HOST), '[]'); +echo 'Connection with ' . $ip . PHP_EOL; +``` + +#### getLocalAddress() + +The `getLocalAddress(): ?string` method returns the full local address +(URI) where this connection has been established with. + +```php +$address = $connection->getLocalAddress(); +echo 'Connection with ' . $address . PHP_EOL; +``` + +If the local address can not be determined or is unknown at this time (such as +after the connection has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +This method complements the [`getRemoteAddress()`](#getremoteaddress) method, +so they should not be confused. + +If your `TcpServer` instance is listening on multiple interfaces (e.g. using +the address `0.0.0.0`), you can use this method to find out which interface +actually accepted this connection (such as a public or local interface). + +If your system has multiple interfaces (e.g. a WAN and a LAN interface), +you can use this method to find out which interface was actually +used for this connection. + +## Server usage + +### ServerInterface + +The `ServerInterface` is responsible for providing an interface for accepting +incoming streaming connections, such as a normal TCP/IP connection. + +Most higher-level components (such as a HTTP server) accept an instance +implementing this interface to accept incoming streaming connections. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. +This means that you SHOULD typehint against this interface instead of a concrete +implementation of this interface. + +Besides defining a few methods, this interface also implements the +[`EventEmitterInterface`](https://github.com/igorw/evenement) +which allows you to react to certain events. + +#### connection event + +The `connection` event will be emitted whenever a new connection has been +established, i.e. a new client connects to this server socket: + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'new connection' . PHP_EOL; +}); +``` + +See also the [`ConnectionInterface`](#connectioninterface) for more details +about handling the incoming connection. + +#### error event + +The `error` event will be emitted whenever there's an error accepting a new +connection from a client. + +```php +$socket->on('error', function (Exception $e) { + echo 'error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +Note that this is not a fatal error event, i.e. the server keeps listening for +new connections even after this event. + +#### getAddress() + +The `getAddress(): ?string` method can be used to +return the full address (URI) this server is currently listening on. + +```php +$address = $socket->getAddress(); +echo 'Server listening on ' . $address . PHP_EOL; +``` + +If the address can not be determined or is unknown at this time (such as +after the socket has been closed), it MAY return a `NULL` value instead. + +Otherwise, it will return the full address (URI) as a string value, such +as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443` +`unix://example.sock` or `unix:///path/to/example.sock`. +Note that individual URI components are application specific and depend +on the underlying transport protocol. + +If this is a TCP/IP based server and you only want the local port, you may +use something like this: + +```php +$address = $socket->getAddress(); +$port = parse_url($address, PHP_URL_PORT); +echo 'Server listening on port ' . $port . PHP_EOL; +``` + +#### pause() + +The `pause(): void` method can be used to +pause accepting new incoming connections. + +Removes the socket resource from the EventLoop and thus stop accepting +new connections. Note that the listening socket stays active and is not +closed. + +This means that new incoming connections will stay pending in the +operating system backlog until its configurable backlog is filled. +Once the backlog is filled, the operating system may reject further +incoming connections until the backlog is drained again by resuming +to accept new connections. + +Once the server is paused, no futher `connection` events SHOULD +be emitted. + +```php +$socket->pause(); + +$socket->on('connection', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +server MAY continue emitting `connection` events. + +Unless otherwise noted, a successfully opened server SHOULD NOT start +in paused state. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### resume() + +The `resume(): void` method can be used to +resume accepting new incoming connections. + +Re-attach the socket resource to the EventLoop after a previous `pause()`. + +```php +$socket->pause(); + +Loop::addTimer(1.0, function () use ($socket) { + $socket->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. +Similarly, calling this after `close()` is a NO-OP. + +#### close() + +The `close(): void` method can be used to +shut down this listening socket. + +This will stop listening for new incoming connections on this socket. + +```php +echo 'Shutting down server socket' . PHP_EOL; +$socket->close(); +``` + +Calling this method more than once on the same instance is a NO-OP. + +### SocketServer + + + +The `SocketServer` class is the main class in this package that implements the +[`ServerInterface`](#serverinterface) and allows you to accept incoming +streaming connections, such as plaintext TCP/IP or secure TLS connection streams. + +In order to accept plaintext TCP/IP connections, you can simply pass a host +and port combination like this: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +Listening on the localhost address `127.0.0.1` means it will not be reachable from +outside of this system. +In order to change the host the socket is listening on, you can provide an IP +address of an interface or use the special `0.0.0.0` address to listen on all +interfaces: + +```php +$socket = new React\Socket\SocketServer('0.0.0.0:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080'); +``` + +In order to use a random port assignment, you can use the port `0`: + +```php +$socket = new React\Socket\SocketServer('127.0.0.1:0'); +$address = $socket->getAddress(); +``` + +To listen on a Unix domain socket (UDS) path, you MUST prefix the URI with the +`unix://` scheme: + +```php +$socket = new React\Socket\SocketServer('unix:///tmp/server.sock'); +``` + +In order to listen on an existing file descriptor (FD) number, you MUST prefix +the URI with `php://fd/` like this: + +```php +$socket = new React\Socket\SocketServer('php://fd/3'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$socket = new React\Socket\SocketServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\SocketServer('127.0.0.1:8080'); + +// throws RuntimeException because port is already in use +$second = new React\Socket\SocketServer('127.0.0.1:8080'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + See the exception message and code for more details about the actual error + condition. + +Optionally, you can specify [TCP socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$socket = new React\Socket\SocketServer('[::1]:8080', array( + 'tcp' => array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true + ) +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + Passing unknown context options has no effect. + The `backlog` context option defaults to `511` unless given explicitly. + +You can start a secure TLS (formerly known as SSL) server by simply prepending +the `tls://` URI scheme. +Internally, it will wait for plaintext TCP/IP connections and then performs a +TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8080', array( + 'tls' => array( + 'local_cert' => 'server.pem' + ) +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an + incoming connection initializes its TLS context. + This implies that any invalid certificate file paths or contents will only cause + an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' + ) +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$socket = new React\Socket\SocketServer('tls://127.0.0.1:8000', array( + 'tls' => array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER + ) +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), + their defaults and effects of changing these may vary depending on your system + and/or PHP version. + The outer context array allows you to also use `tcp` (and possibly more) + context options at the same time. + Passing unknown context options has no effect. + If you do not use the `tls://` scheme, then passing `tls` context options + has no effect. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$socket->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Note that the `SocketServer` class is a concrete implementation for TCP/IP sockets. + If you want to typehint in your higher-level protocol implementation, you SHOULD + use the generic [`ServerInterface`](#serverinterface) instead. + +> Changelog v1.9.0: This class has been added with an improved constructor signature + as a replacement for the previous `Server` class in order to avoid any ambiguities. + The previous name has been deprecated and should not be used anymore. + +### Advanced server usage + +#### TcpServer + +The `TcpServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting plaintext TCP/IP connections. + +```php +$server = new React\Socket\TcpServer(8080); +``` + +As above, the `$uri` parameter can consist of only a port, in which case the +server will default to listening on the localhost address `127.0.0.1`, +which means it will not be reachable from outside of this system. + +In order to use a random port assignment, you can use the port `0`: + +```php +$server = new React\Socket\TcpServer(0); +$address = $server->getAddress(); +``` + +In order to change the host the socket is listening on, you can provide an IP +address through the first parameter provided to the constructor, optionally +preceded by the `tcp://` scheme: + +```php +$server = new React\Socket\TcpServer('192.168.0.1:8080'); +``` + +If you want to listen on an IPv6 address, you MUST enclose the host in square +brackets: + +```php +$server = new React\Socket\TcpServer('[::1]:8080'); +``` + +If the given URI is invalid, does not contain a port, any other scheme or if it +contains a hostname, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException due to missing port +$server = new React\Socket\TcpServer('127.0.0.1'); +``` + +If the given URI appears to be valid, but listening on it fails (such as if port +is already in use or port below 1024 may require root access etc.), it will +throw a `RuntimeException`: + +```php +$first = new React\Socket\TcpServer(8080); + +// throws RuntimeException because port is already in use +$second = new React\Socket\TcpServer(8080); +``` + +> Note that these error conditions may vary depending on your system and/or +configuration. +See the exception message and code for more details about the actual error +condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) +for the underlying stream socket resource like this: + +```php +$server = new React\Socket\TcpServer('[::1]:8080', null, array( + 'backlog' => 200, + 'so_reuseport' => true, + 'ipv6_v6only' => true +)); +``` + +> Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. +The `backlog` context option defaults to `511` unless given explicitly. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### SecureServer + +The `SecureServer` class implements the [`ServerInterface`](#serverinterface) +and is responsible for providing a secure TLS (formerly known as SSL) server. + +It does so by wrapping a [`TcpServer`](#tcpserver) instance which waits for plaintext +TCP/IP connections and then performs a TLS handshake for each connection. +It thus requires valid [TLS context options](https://www.php.net/manual/en/context.ssl.php), +which in its most basic form may look something like this if you're using a +PEM encoded certificate file: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem' +)); +``` + +> Note that the certificate file will not be loaded on instantiation but when an +incoming connection initializes its TLS context. +This implies that any invalid certificate file paths or contents will only cause +an `error` event at a later time. + +If your private key is encrypted with a passphrase, you have to specify it +like this: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'passphrase' => 'secret' +)); +``` + +By default, this server supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$server = new React\Socket\TcpServer(8000); +$server = new React\Socket\SecureServer($server, null, array( + 'local_cert' => 'server.pem', + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_SERVER +)); +``` + +> Note that available [TLS context options](https://www.php.net/manual/en/context.ssl.php), +their defaults and effects of changing these may vary depending on your system +and/or PHP version. +Passing unknown context options has no effect. + +Whenever a client completes the TLS handshake, it will emit a `connection` event +with a connection instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +Whenever a client fails to perform a successful TLS handshake, it will emit an +`error` event and then close the underlying TCP/IP connection: + +```php +$server->on('error', function (Exception $e) { + echo 'Error' . $e->getMessage() . PHP_EOL; +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +Note that the `SecureServer` class is a concrete implementation for TLS sockets. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ServerInterface`](#serverinterface) instead. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Despite allowing any `ServerInterface` as first parameter, +you SHOULD pass a `TcpServer` instance as first parameter, unless you +know what you're doing. +Internally, the `SecureServer` has to set the required TLS context options on +the underlying stream resources. +These resources are not exposed through any of the interfaces defined in this +package, but only through the internal `Connection` class. +The `TcpServer` class is guaranteed to emit connections that implement +the `ConnectionInterface` and uses the internal `Connection` class in order to +expose these underlying resources. +If you use a custom `ServerInterface` and its `connection` event does not +meet this requirement, the `SecureServer` will emit an `error` event and +then close the underlying connection. + +#### UnixServer + +The `UnixServer` class implements the [`ServerInterface`](#serverinterface) and +is responsible for accepting connections on Unix domain sockets (UDS). + +```php +$server = new React\Socket\UnixServer('/tmp/server.sock'); +``` + +As above, the `$uri` parameter can consist of only a socket path or socket path +prefixed by the `unix://` scheme. + +If the given URI appears to be valid, but listening on it fails (such as if the +socket is already in use or the file not accessible etc.), it will throw a +`RuntimeException`: + +```php +$first = new React\Socket\UnixServer('/tmp/same.sock'); + +// throws RuntimeException because socket is already in use +$second = new React\Socket\UnixServer('/tmp/same.sock'); +``` + +> Note that these error conditions may vary depending on your system and/or + configuration. + In particular, Zend PHP does only report "Unknown error" when the UDS path + already exists and can not be bound. You may want to check `is_file()` on the + given UDS path to report a more user-friendly error message in this case. + See the exception message and code for more details about the actual error + condition. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Whenever a client connects, it will emit a `connection` event with a connection +instance implementing [`ConnectionInterface`](#connectioninterface): + +```php +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + echo 'New connection' . PHP_EOL; + + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [`ServerInterface`](#serverinterface) for more details. + +#### LimitingServer + +The `LimitingServer` decorator wraps a given `ServerInterface` and is responsible +for limiting and keeping track of open connections to this server instance. + +Whenever the underlying server emits a `connection` event, it will check its +limits and then either + - keep track of this connection by adding it to the list of + open connections and then forward the `connection` event + - or reject (close) the connection when its limits are exceeded and will + forward an `error` event instead. + +Whenever a connection closes, it will remove this connection from the list of +open connections. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +See also the [second example](examples) for more details. + +You have to pass a maximum number of open connections to ensure +the server will automatically reject (close) connections once this limit +is exceeded. In this case, it will emit an `error` event to inform about +this and no `connection` event will be emitted. + +```php +$server = new React\Socket\LimitingServer($server, 100); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +You MAY pass a `null` limit in order to put no limit on the number of +open connections and keep accepting new connection until you run out of +operating system resources (such as open file handles). This may be +useful if you do not want to take care of applying a limit but still want +to use the `getConnections()` method. + +You can optionally configure the server to pause accepting new +connections once the connection limit is reached. In this case, it will +pause the underlying server and no longer process any new connections at +all, thus also no longer closing any excessive connections. +The underlying operating system is responsible for keeping a backlog of +pending connections until its limit is reached, at which point it will +start rejecting further connections. +Once the server is below the connection limit, it will continue consuming +connections from the backlog and will process any outstanding data on +each connection. +This mode may be useful for some protocols that are designed to wait for +a response message (such as HTTP), but may be less useful for other +protocols that demand immediate responses (such as a "welcome" message in +an interactive chat). + +```php +$server = new React\Socket\LimitingServer($server, 100, true); +$server->on('connection', function (React\Socket\ConnectionInterface $connection) { + $connection->write('hello there!' . PHP_EOL); + … +}); +``` + +##### getConnections() + +The `getConnections(): ConnectionInterface[]` method can be used to +return an array with all currently active connections. + +```php +foreach ($server->getConnection() as $connection) { + $connection->write('Hi!'); +} +``` + +## Client usage + +### ConnectorInterface + +The `ConnectorInterface` is responsible for providing an interface for +establishing streaming connections, such as a normal TCP/IP connection. + +This is the main interface defined in this package and it is used throughout +React's vast ecosystem. + +Most higher-level components (such as HTTP, database or other networking +service clients) accept an instance implementing this interface to create their +TCP/IP connection to the underlying networking service. +This is usually done via dependency injection, so it's fairly simple to actually +swap this implementation against any other implementation of this interface. + +The interface only offers a single method: + +#### connect() + +The `connect(string $uri): PromiseInterface` method +can be used to create a streaming connection to the given remote address. + +It returns a [Promise](https://github.com/reactphp/promise) which either +fulfills with a stream implementing [`ConnectionInterface`](#connectioninterface) +on success or rejects with an `Exception` if the connection is not successful: + +```php +$connector->connect('google.com:443')->then( + function (React\Socket\ConnectionInterface $connection) { + // connection successfully established + }, + function (Exception $error) { + // failed to connect due to $error + } +); +``` + +See also [`ConnectionInterface`](#connectioninterface) for more details. + +The returned Promise MUST be implemented in such a way that it can be +cancelled when it is still pending. Cancelling a pending promise MUST +reject its value with an `Exception`. It SHOULD clean up any underlying +resources and references as applicable: + +```php +$promise = $connector->connect($uri); + +$promise->cancel(); +``` + +### Connector + +The `Connector` class is the main class in this package that implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create streaming connections. + +You can use this connector to create any kind of streaming connections, such +as plaintext TCP/IP, secure TLS or local Unix connection streams. + +It binds to the main event loop and can be used like this: + +```php +$connector = new React\Socket\Connector(); + +$connector->connect($uri)->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}, function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +In order to create a plaintext TCP/IP connection, you can simply pass a host +and port combination like this: + +```php +$connector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> If you do no specify a URI scheme in the destination URI, it will assume + `tcp://` as a default and establish a plaintext TCP/IP connection. + Note that TCP/IP connections require a host and port part in the destination + URI like above, all other URI components are optional. + +In order to create a secure TLS connection, you can use the `tls://` URI scheme +like this: + +```php +$connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +In order to create a local Unix domain socket connection, you can use the +`unix://` URI scheme like this: + +```php +$connector->connect('unix:///tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, including + the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +Under the hood, the `Connector` is implemented as a *higher-level facade* +for the lower-level connectors implemented in this package. This means it +also shares all of their features and implementation details. +If you want to typehint in your higher-level protocol implementation, you SHOULD +use the generic [`ConnectorInterface`](#connectorinterface) instead. + +As of `v1.4.0`, the `Connector` class defaults to using the +[happy eyeballs algorithm](https://en.wikipedia.org/wiki/Happy_Eyeballs) to +automatically connect over IPv4 or IPv6 when a hostname is given. +This automatically attempts to connect using both IPv4 and IPv6 at the same time +(preferring IPv6), thus avoiding the usual problems faced by users with imperfect +IPv6 connections or setups. +If you want to revert to the old behavior of only doing an IPv4 lookup and +only attempt a single IPv4 connection, you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'happy_eyeballs' => false +)); +``` + +Similarly, you can also affect the default DNS behavior as follows. +The `Connector` class will try to detect your system DNS settings (and uses +Google's public DNS server `8.8.8.8` as a fallback if unable to determine your +system settings) to resolve all public hostnames into underlying IP addresses by +default. +If you explicitly want to use a custom DNS server (such as a local DNS relay or +a company wide DNS server), you can set up the `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => '127.0.1.1' +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +If you do not want to use a DNS resolver at all and want to connect to IP +addresses only, you can also set up your `Connector` like this: + +```php +$connector = new React\Socket\Connector(array( + 'dns' => false +)); + +$connector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +Advanced: If you need a custom DNS `React\Dns\Resolver\ResolverInterface` instance, you +can also set up your `Connector` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); + +$connector = new React\Socket\Connector(array( + 'dns' => $resolver +)); + +$connector->connect('localhost:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, the `tcp://` and `tls://` URI schemes will use timeout value that +respects your `default_socket_timeout` ini setting (which defaults to 60s). +If you want a custom timeout value, you can simply pass this like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => 10.0 +)); +``` + +Similarly, if you do not want to apply a timeout at all and let the operating +system handle this, you can pass a boolean flag like this: + +```php +$connector = new React\Socket\Connector(array( + 'timeout' => false +)); +``` + +By default, the `Connector` supports the `tcp://`, `tls://` and `unix://` +URI schemes. If you want to explicitly prohibit any of these, you can simply +pass boolean flags like this: + +```php +// only allow secure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => false, + 'tls' => true, + 'unix' => false, +)); + +$connector->connect('tls://google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +The `tcp://` and `tls://` also accept additional context options passed to +the underlying connectors. +If you want to explicitly pass additional context options, you can simply +pass arrays of context options like this: + +```php +// allow insecure TLS connections +$connector = new React\Socket\Connector(array( + 'tcp' => array( + 'bindto' => '192.168.0.1:0' + ), + 'tls' => array( + 'verify_peer' => false, + 'verify_peer_name' => false + ), +)); + +$connector->connect('tls://localhost:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$connector = new React\Socket\Connector(array( + 'tls' => array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT + ) +)); +``` + +> For more details about context options, please refer to the PHP documentation + about [socket context options](https://www.php.net/manual/en/context.socket.php) + and [SSL context options](https://www.php.net/manual/en/context.ssl.php). + +Advanced: By default, the `Connector` supports the `tcp://`, `tls://` and +`unix://` URI schemes. +For this, it sets up the required connector classes automatically. +If you want to explicitly pass custom connectors for any of these, you can simply +pass an instance implementing the `ConnectorInterface` like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$resolver = $dnsResolverFactory->createCached('127.0.1.1'); +$tcp = new React\Socket\HappyEyeBallsConnector(null, new React\Socket\TcpConnector(), $resolver); + +$tls = new React\Socket\SecureConnector($tcp); + +$unix = new React\Socket\UnixConnector(); + +$connector = new React\Socket\Connector(array( + 'tcp' => $tcp, + 'tls' => $tls, + 'unix' => $unix, + + 'dns' => false, + 'timeout' => false, +)); + +$connector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +> Internally, the `tcp://` connector will always be wrapped by the DNS resolver, + unless you disable DNS like in the above example. In this case, the `tcp://` + connector receives the actual hostname instead of only the resolved IP address + and is thus responsible for performing the lookup. + Internally, the automatically created `tls://` connector will always wrap the + underlying `tcp://` connector for establishing the underlying plaintext + TCP/IP connection before enabling secure TLS mode. If you want to use a custom + underlying `tcp://` connector for secure TLS connections only, you may + explicitly pass a `tls://` connector like above instead. + Internally, the `tcp://` and `tls://` connectors will always be wrapped by + `TimeoutConnector`, unless you disable timeouts like in the above example. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Changelog v1.9.0: The constructur signature has been updated to take the +> optional `$context` as the first parameter and the optional `$loop` as a second +> argument. The previous signature has been deprecated and should not be used anymore. +> +> ```php +> // constructor signature as of v1.9.0 +> $connector = new React\Socket\Connector(array $context = [], ?LoopInterface $loop = null); +> +> // legacy constructor signature before v1.9.0 +> $connector = new React\Socket\Connector(?LoopInterface $loop = null, array $context = []); +> ``` + +### Advanced client usage + +#### TcpConnector + +The `TcpConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any IP-port-combination: + +```php +$tcpConnector = new React\Socket\TcpConnector(); + +$tcpConnector->connect('127.0.0.1:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $tcpConnector->connect('127.0.0.1:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will close the underlying socket +resource, thus cancelling the pending TCP/IP connection, and reject the +resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[socket context options](https://www.php.net/manual/en/context.socket.php) +to the constructor like this: + +```php +$tcpConnector = new React\Socket\TcpConnector(null, array( + 'bindto' => '192.168.0.1:0' +)); +``` + +Note that this class only allows you to connect to IP-port-combinations. +If the given URI is invalid, does not contain a valid IP address and port +or contains any other scheme, it will reject with an +`InvalidArgumentException`: + +If the given URI appears to be valid, but connecting to it fails (such as if +the remote host rejects the connection etc.), it will reject with a +`RuntimeException`. + +If you want to connect to hostname-port-combinations, see also the following chapter. + +> Advanced usage: Internally, the `TcpConnector` allocates an empty *context* +resource for each stream resource. +If the destination URI contains a `hostname` query parameter, its value will +be used to set up the TLS peer name. +This is used by the `SecureConnector` and `DnsConnector` to verify the peer +name and can also be used if you want a custom TLS peer name. + +#### HappyEyeBallsConnector + +The `HappyEyeBallsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. Internally it implements the +happy eyeballs algorithm from [`RFC6555`](https://tools.ietf.org/html/rfc6555) and +[`RFC8305`](https://tools.ietf.org/html/rfc8305) to support IPv6 and IPv4 hostnames. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\HappyEyeBallsConnector(null, $tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookups +and/or the underlying TCP/IP connection(s) and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +> Advanced usage: Internally, the `HappyEyeBallsConnector` relies on a `Resolver` to +look up the IP addresses for the given hostname. +It will then replace the hostname in the destination URI with this IP's and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The Happy Eye Balls algorithm describes looking the IPv6 and IPv4 address for +the given hostname so this connector sends out two DNS lookups for the A and +AAAA records. It then uses all IP addresses (both v6 and v4) and tries to +connect to all of them with a 50ms interval in between. Alterating between IPv6 +and IPv4 addresses. When a connection is established all the other DNS lookups +and connection attempts are cancelled. + +#### DnsConnector + +The `DnsConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create plaintext +TCP/IP connections to any hostname-port-combination. + +It does so by decorating a given `TcpConnector` instance so that it first +looks up the given domain name via DNS (if applicable) and then establishes the +underlying TCP/IP connection to the resolved target IP address. + +Make sure to set up your DNS resolver and underlying TCP connector like this: + +```php +$dnsResolverFactory = new React\Dns\Resolver\Factory(); +$dns = $dnsResolverFactory->createCached('8.8.8.8'); + +$dnsConnector = new React\Socket\DnsConnector($tcpConnector, $dns); + +$dnsConnector->connect('www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write('...'); + $connection->end(); +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $dnsConnector->connect('www.google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying DNS lookup +and/or the underlying TCP/IP connection and reject the resulting promise. + +> Advanced usage: Internally, the `DnsConnector` relies on a `React\Dns\Resolver\ResolverInterface` +to look up the IP address for the given hostname. +It will then replace the hostname in the destination URI with this IP and +append a `hostname` query parameter and pass this updated URI to the underlying +connector. +The underlying connector is thus responsible for creating a connection to the +target IP address, while this query parameter can be used to check the original +hostname and is used by the `TcpConnector` to set up the TLS peer name. +If a `hostname` is given explicitly, this query parameter will not be modified, +which can be useful if you want a custom TLS peer name. + +#### SecureConnector + +The `SecureConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to create secure +TLS (formerly known as SSL) connections to any hostname-port-combination. + +It does so by decorating a given `DnsConnector` instance so that it first +creates a plaintext TCP/IP connection and then enables TLS encryption on this +stream. + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector); + +$secureConnector->connect('www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n"); + ... +}); +``` + +See also the [examples](examples). + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $secureConnector->connect('www.google.com:443'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying TCP/IP +connection and/or the SSL/TLS negotiation and reject the resulting promise. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +You can optionally pass additional +[SSL context options](https://www.php.net/manual/en/context.ssl.php) +to the constructor like this: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'verify_peer' => false, + 'verify_peer_name' => false +)); +``` + +By default, this connector supports TLSv1.0+ and excludes support for legacy +SSLv2/SSLv3. As of PHP 5.6+ you can also explicitly choose the TLS version you +want to negotiate with the remote side: + +```php +$secureConnector = new React\Socket\SecureConnector($dnsConnector, null, array( + 'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT +)); +``` + +> Advanced usage: Internally, the `SecureConnector` relies on setting up the +required *context options* on the underlying stream resource. +It should therefor be used with a `TcpConnector` somewhere in the connector +stack so that it can allocate an empty *context* resource for each stream +resource and verify the peer name. +Failing to do so may result in a TLS peer name mismatch error or some hard to +trace race conditions, because all stream resources will use a single, shared +*default context* resource otherwise. + +#### TimeoutConnector + +The `TimeoutConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to add timeout +handling to any existing connector instance. + +It does so by decorating any given [`ConnectorInterface`](#connectorinterface) +instance and starting a timer that will automatically reject and abort any +underlying connection attempt if it takes too long. + +```php +$timeoutConnector = new React\Socket\TimeoutConnector($connector, 3.0); + +$timeoutConnector->connect('google.com:80')->then(function (React\Socket\ConnectionInterface $connection) { + // connection succeeded within 3.0 seconds +}); +``` + +See also any of the [examples](examples). + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +Pending connection attempts can be cancelled by cancelling its pending promise like so: + +```php +$promise = $timeoutConnector->connect('google.com:80'); + +$promise->cancel(); +``` + +Calling `cancel()` on a pending promise will cancel the underlying connection +attempt, abort the timer and reject the resulting promise. + +#### UnixConnector + +The `UnixConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and allows you to connect to +Unix domain socket (UDS) paths like this: + +```php +$connector = new React\Socket\UnixConnector(); + +$connector->connect('/tmp/demo.sock')->then(function (React\Socket\ConnectionInterface $connection) { + $connection->write("HELLO\n"); +}); +``` + +Connecting to Unix domain sockets is an atomic operation, i.e. its promise will +settle (either resolve or reject) immediately. +As such, calling `cancel()` on the resulting promise has no effect. + +> The [`getRemoteAddress()`](#getremoteaddress) method will return the target + Unix domain socket (UDS) path as given to the `connect()` method, prepended + with the `unix://` scheme, for example `unix:///tmp/demo.sock`. + The [`getLocalAddress()`](#getlocaladdress) method will most likely return a + `null` value as this value is not applicable to UDS connections here. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +#### FixedUriConnector + +The `FixedUriConnector` class implements the +[`ConnectorInterface`](#connectorinterface) and decorates an existing Connector +to always use a fixed, preconfigured URI. + +This can be useful for consumers that do not support certain URIs, such as +when you want to explicitly connect to a Unix domain socket (UDS) path +instead of connecting to a default address assumed by an higher-level API: + +```php +$connector = new React\Socket\FixedUriConnector( + 'unix:///var/run/docker.sock', + new React\Socket\UnixConnector() +); + +// destination will be ignored, actually connects to Unix domain socket +$promise = $connector->connect('localhost:80'); +``` + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org/). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/socket:^1.13 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use the latest supported PHP version* for this project, +partly due to its vast performance improvements and partly because legacy PHP +versions require several workarounds as described below. + +Secure TLS connections received some major upgrades starting with PHP 5.6, with +the defaults now being more secure, while older versions required explicit +context options. +This library does not take responsibility over these context options, so it's +up to consumers of this library to take care of setting appropriate context +options as described above. + +PHP < 7.3.3 (and PHP < 7.2.15) suffers from a bug where feof() might +block with 100% CPU usage on fragmented TLS records. +We try to work around this by always consuming the complete receive +buffer at once to avoid stale data in TLS buffers. This is known to +work around high CPU usage for well-behaving peers, but this may +cause very large data chunks for high throughput scenarios. The buggy +behavior can still be triggered due to network I/O buffers or +malicious peers on affected versions, upgrading is highly recommended. + +PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big +chunks of data over TLS streams at once. +We try to work around this by limiting the write chunk size to 8192 +bytes for older PHP versions only. +This is only a work-around and has a noticable performance penalty on +affected versions. + +This project also supports running on HHVM. +Note that really old HHVM < 3.8 does not support secure TLS connections, as it +lacks the required `stream_socket_enable_crypto()` function. +As such, trying to create a secure TLS connections on affected versions will +return a rejected promise instead. +This issue is also covered by our test suite, which will skip related tests +on affected versions. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org/): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). diff --git a/vendor/react/socket/composer.json b/vendor/react/socket/composer.json new file mode 100644 index 00000000000..3eab5a8388e --- /dev/null +++ b/vendor/react/socket/composer.json @@ -0,0 +1,58 @@ +{ + "name": "react\/socket", + "description": "Async, streaming plaintext TCP\/IP and secure TLS socket server and client connections for ReactPHP", + "keywords": [ + "async", + "socket", + "stream", + "connection", + "ReactPHP" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.0", + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0", + "react\/dns": "^1.11", + "react\/event-loop": "^1.2", + "react\/promise": "^3 || ^2.6 || ^1.2.1", + "react\/stream": "^1.2" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "react\/async": "^4 || ^3 || ^2", + "react\/promise-stream": "^1.4", + "react\/promise-timer": "^1.9" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Socket\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\Socket\\": "tests" + } + } +} \ No newline at end of file diff --git a/vendor/react/socket/src/Connection.php b/vendor/react/socket/src/Connection.php new file mode 100644 index 00000000000..3760dbe4e4a --- /dev/null +++ b/vendor/react/socket/src/Connection.php @@ -0,0 +1,151 @@ += 70300 && \PHP_VERSION_ID < 70303; + // PHP < 7.1.4 (and PHP < 7.0.18) suffers from a bug when writing big + // chunks of data over TLS streams at once. + // We try to work around this by limiting the write chunk size to 8192 + // bytes for older PHP versions only. + // This is only a work-around and has a noticable performance penalty on + // affected versions. Please update your PHP version. + // This applies to all streams because TLS may be enabled later on. + // See https://github.com/reactphp/socket/issues/105 + $limitWriteChunks = \PHP_VERSION_ID < 70018 || \PHP_VERSION_ID >= 70100 && \PHP_VERSION_ID < 70104; + $this->input = new DuplexResourceStream($resource, $loop, $clearCompleteBuffer ? -1 : null, new WritableResourceStream($resource, $loop, null, $limitWriteChunks ? 8192 : null)); + $this->stream = $resource; + Util::forwardEvents($this->input, $this, array('data', 'end', 'error', 'close', 'pipe', 'drain')); + $this->input->on('close', array($this, 'close')); + } + public function isReadable() + { + return $this->input->isReadable(); + } + public function isWritable() + { + return $this->input->isWritable(); + } + public function pause() + { + $this->input->pause(); + } + public function resume() + { + $this->input->resume(); + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return $this->input->pipe($dest, $options); + } + public function write($data) + { + return $this->input->write($data); + } + public function end($data = null) + { + $this->input->end($data); + } + public function close() + { + $this->input->close(); + $this->handleClose(); + $this->removeAllListeners(); + } + public function handleClose() + { + if (!\is_resource($this->stream)) { + return; + } + // Try to cleanly shut down socket and ignore any errors in case other + // side already closed. Underlying Stream implementation will take care + // of closing stream resource, so we otherwise keep this open here. + @\stream_socket_shutdown($this->stream, \STREAM_SHUT_RDWR); + } + public function getRemoteAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + return $this->parseAddress(\stream_socket_get_name($this->stream, \true)); + } + public function getLocalAddress() + { + if (!\is_resource($this->stream)) { + return null; + } + return $this->parseAddress(\stream_socket_get_name($this->stream, \false)); + } + private function parseAddress($address) + { + if ($address === \false) { + return null; + } + if ($this->unix) { + // remove trailing colon from address for HHVM < 3.19: https://3v4l.org/5C1lo + // note that technically ":" is a valid address, so keep this in place otherwise + if (\substr($address, -1) === ':' && \defined('ECSPrefix202307\\HHVM_VERSION_ID') && \ECSPrefix202307\HHVM_VERSION_ID < 31900) { + $address = (string) \substr($address, 0, -1); + // @codeCoverageIgnore + } + // work around unknown addresses should return null value: https://3v4l.org/5C1lo and https://bugs.php.net/bug.php?id=74556 + // PHP uses "\0" string and HHVM uses empty string (colon removed above) + if ($address === '' || $address[0] === "\x00") { + return null; + // @codeCoverageIgnore + } + return 'unix://' . $address; + } + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== \false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); + // @codeCoverageIgnore + } + return ($this->encryptionEnabled ? 'tls' : 'tcp') . '://' . $address; + } +} diff --git a/vendor/react/socket/src/ConnectionInterface.php b/vendor/react/socket/src/ConnectionInterface.php new file mode 100644 index 00000000000..89d58623b23 --- /dev/null +++ b/vendor/react/socket/src/ConnectionInterface.php @@ -0,0 +1,117 @@ +on('data', function ($chunk) { + * echo $chunk; + * }); + * + * $connection->on('end', function () { + * echo 'ended'; + * }); + * + * $connection->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage(); + * }); + * + * $connection->on('close', function () { + * echo 'closed'; + * }); + * + * $connection->write($data); + * $connection->end($data = null); + * $connection->close(); + * // … + * ``` + * + * For more details, see the + * [`DuplexStreamInterface`](https://github.com/reactphp/stream#duplexstreaminterface). + * + * @see DuplexStreamInterface + * @see ServerInterface + * @see ConnectorInterface + */ +interface ConnectionInterface extends DuplexStreamInterface +{ + /** + * Returns the full remote address (URI) where this connection has been established with + * + * ```php + * $address = $connection->getRemoteAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the remote address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based connection and you only want the remote IP, you may + * use something like this: + * + * ```php + * $address = $connection->getRemoteAddress(); + * $ip = trim(parse_url($address, PHP_URL_HOST), '[]'); + * echo 'Connection with ' . $ip . PHP_EOL; + * ``` + * + * @return ?string remote address (URI) or null if unknown + */ + public function getRemoteAddress(); + /** + * Returns the full local address (full URI with scheme, IP and port) where this connection has been established with + * + * ```php + * $address = $connection->getLocalAddress(); + * echo 'Connection with ' . $address . PHP_EOL; + * ``` + * + * If the local address can not be determined or is unknown at this time (such as + * after the connection has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80`, `tls://127.0.0.1:443`, + * `unix://example.sock` or `unix:///path/to/example.sock`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * This method complements the [`getRemoteAddress()`](#getremoteaddress) method, + * so they should not be confused. + * + * If your `TcpServer` instance is listening on multiple interfaces (e.g. using + * the address `0.0.0.0`), you can use this method to find out which interface + * actually accepted this connection (such as a public or local interface). + * + * If your system has multiple interfaces (e.g. a WAN and a LAN interface), + * you can use this method to find out which interface was actually + * used for this connection. + * + * @return ?string local address (URI) or null if unknown + * @see self::getRemoteAddress() + */ + public function getLocalAddress(); +} diff --git a/vendor/react/socket/src/Connector.php b/vendor/react/socket/src/Connector.php new file mode 100644 index 00000000000..ec0da85a93d --- /dev/null +++ b/vendor/react/socket/src/Connector.php @@ -0,0 +1,179 @@ + \true, 'tls' => \true, 'unix' => \true, 'dns' => \true, 'timeout' => \true, 'happy_eyeballs' => \true); + if ($context['timeout'] === \true) { + $context['timeout'] = (float) \ini_get("default_socket_timeout"); + } + if ($context['tcp'] instanceof ConnectorInterface) { + $tcp = $context['tcp']; + } else { + $tcp = new TcpConnector($loop, \is_array($context['tcp']) ? $context['tcp'] : array()); + } + if ($context['dns'] !== \false) { + if ($context['dns'] instanceof ResolverInterface) { + $resolver = $context['dns']; + } else { + if ($context['dns'] !== \true) { + $config = $context['dns']; + } else { + // try to load nameservers from system config or default to Google's public DNS + $config = DnsConfig::loadSystemConfigBlocking(); + if (!$config->nameservers) { + $config->nameservers[] = '8.8.8.8'; + // @codeCoverageIgnore + } + } + $factory = new DnsFactory(); + $resolver = $factory->createCached($config, $loop); + } + if ($context['happy_eyeballs'] === \true) { + $tcp = new HappyEyeBallsConnector($loop, $tcp, $resolver); + } else { + $tcp = new DnsConnector($tcp, $resolver); + } + } + if ($context['tcp'] !== \false) { + $context['tcp'] = $tcp; + if ($context['timeout'] !== \false) { + $context['tcp'] = new TimeoutConnector($context['tcp'], $context['timeout'], $loop); + } + $this->connectors['tcp'] = $context['tcp']; + } + if ($context['tls'] !== \false) { + if (!$context['tls'] instanceof ConnectorInterface) { + $context['tls'] = new SecureConnector($tcp, $loop, \is_array($context['tls']) ? $context['tls'] : array()); + } + if ($context['timeout'] !== \false) { + $context['tls'] = new TimeoutConnector($context['tls'], $context['timeout'], $loop); + } + $this->connectors['tls'] = $context['tls']; + } + if ($context['unix'] !== \false) { + if (!$context['unix'] instanceof ConnectorInterface) { + $context['unix'] = new UnixConnector($loop); + } + $this->connectors['unix'] = $context['unix']; + } + } + public function connect($uri) + { + $scheme = 'tcp'; + if (\strpos($uri, '://') !== \false) { + $scheme = (string) \substr($uri, 0, \strpos($uri, '://')); + } + if (!isset($this->connectors[$scheme])) { + return \ECSPrefix202307\React\Promise\reject(new \RuntimeException('No connector available for URI scheme "' . $scheme . '" (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + return $this->connectors[$scheme]->connect($uri); + } + /** + * [internal] Builds on URI from the given URI parts and ip address with original hostname as query + * + * @param array $parts + * @param string $host + * @param string $ip + * @return string + * @internal + */ + public static function uri(array $parts, $host, $ip) + { + $uri = ''; + // prepend original scheme if known + if (isset($parts['scheme'])) { + $uri .= $parts['scheme'] . '://'; + } + if (\strpos($ip, ':') !== \false) { + // enclose IPv6 addresses in square brackets before appending port + $uri .= '[' . $ip . ']'; + } else { + $uri .= $ip; + } + // append original port if known + if (isset($parts['port'])) { + $uri .= ':' . $parts['port']; + } + // append orignal path if known + if (isset($parts['path'])) { + $uri .= $parts['path']; + } + // append original query if known + if (isset($parts['query'])) { + $uri .= '?' . $parts['query']; + } + // append original hostname as query if resolved via DNS and if + // destination URI does not contain "hostname" query param already + $args = array(); + \parse_str(isset($parts['query']) ? $parts['query'] : '', $args); + if ($host !== $ip && !isset($args['hostname'])) { + $uri .= (isset($parts['query']) ? '&' : '?') . 'hostname=' . \rawurlencode($host); + } + // append original fragment if known + if (isset($parts['fragment'])) { + $uri .= '#' . $parts['fragment']; + } + return $uri; + } +} diff --git a/vendor/react/socket/src/ConnectorInterface.php b/vendor/react/socket/src/ConnectorInterface.php new file mode 100644 index 00000000000..ac2efd010a7 --- /dev/null +++ b/vendor/react/socket/src/ConnectorInterface.php @@ -0,0 +1,58 @@ +connect('google.com:443')->then( + * function (React\Socket\ConnectionInterface $connection) { + * // connection successfully established + * }, + * function (Exception $error) { + * // failed to connect due to $error + * } + * ); + * ``` + * + * The returned Promise MUST be implemented in such a way that it can be + * cancelled when it is still pending. Cancelling a pending promise MUST + * reject its value with an Exception. It SHOULD clean up any underlying + * resources and references as applicable. + * + * ```php + * $promise = $connector->connect($uri); + * + * $promise->cancel(); + * ``` + * + * @param string $uri + * @return \React\Promise\PromiseInterface resolves with a stream implementing ConnectionInterface on success or rejects with an Exception on error + * @see ConnectionInterface + */ + public function connect($uri); +} diff --git a/vendor/react/socket/src/DnsConnector.php b/vendor/react/socket/src/DnsConnector.php new file mode 100644 index 00000000000..61907102a8a --- /dev/null +++ b/vendor/react/socket/src/DnsConnector.php @@ -0,0 +1,88 @@ +connector = $connector; + $this->resolver = $resolver; + } + public function connect($uri) + { + $original = $uri; + if (\strpos($uri, '://') === \false) { + $uri = 'tcp://' . $uri; + $parts = \parse_url($uri); + if (isset($parts['scheme'])) { + unset($parts['scheme']); + } + } else { + $parts = \parse_url($uri); + } + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + $host = \trim($parts['host'], '[]'); + $connector = $this->connector; + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (@\inet_pton($host) !== \false) { + return $connector->connect($original); + } + $promise = $this->resolver->resolve($host); + $resolved = null; + return new Promise\Promise(function ($resolve, $reject) use(&$promise, &$resolved, $uri, $connector, $host, $parts) { + // resolve/reject with result of DNS lookup + $promise->then(function ($ip) use(&$promise, &$resolved, $uri, $connector, $host, $parts) { + $resolved = $ip; + return $promise = $connector->connect(Connector::uri($parts, $host, $ip))->then(null, function (\Exception $e) use($uri) { + if ($e instanceof \RuntimeException) { + $message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage()); + $e = new \RuntimeException('Connection to ' . $uri . ' failed: ' . $message, $e->getCode(), $e); + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + $r->setAccessible(\true); + $trace = $r->getValue($e); + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } + throw $e; + }); + }, function ($e) use($uri, $reject) { + $reject(new \RuntimeException('Connection to ' . $uri . ' failed during DNS lookup: ' . $e->getMessage(), 0, $e)); + })->then($resolve, $reject); + }, function ($_, $reject) use(&$promise, &$resolved, $uri) { + // cancellation should reject connection attempt + // reject DNS resolution with custom reason, otherwise rely on connection cancellation below + if ($resolved === null) { + $reject(new \RuntimeException('Connection to ' . $uri . ' cancelled during DNS lookup (ECONNABORTED)', \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103)); + } + // (try to) cancel pending DNS lookup / connection attempt + if ($promise instanceof PromiseInterface && \method_exists($promise, 'cancel')) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $_ = $reject = null; + $promise->cancel(); + $promise = null; + } + }); + } +} diff --git a/vendor/react/socket/src/FdServer.php b/vendor/react/socket/src/FdServer.php new file mode 100644 index 00000000000..0f9b01e0c1e --- /dev/null +++ b/vendor/react/socket/src/FdServer.php @@ -0,0 +1,178 @@ +on('connection', function (ConnectionInterface $connection) { + * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + * @internal + */ +final class FdServer extends EventEmitter implements ServerInterface +{ + private $master; + private $loop; + private $unix = \false; + private $listening = \false; + /** + * Creates a socket server and starts listening on the given file descriptor + * + * This starts accepting new incoming connections on the given file descriptor. + * See also the `connection event` documented in the `ServerInterface` + * for more details. + * + * ```php + * $socket = new React\Socket\FdServer(3); + * ``` + * + * If the given FD is invalid or out of range, it will throw an `InvalidArgumentException`: + * + * ```php + * // throws InvalidArgumentException + * $socket = new React\Socket\FdServer(-1); + * ``` + * + * If the given FD appears to be valid, but listening on it fails (such as + * if the FD does not exist or does not refer to a socket server), it will + * throw a `RuntimeException`: + * + * ```php + * // throws RuntimeException because FD does not reference a socket server + * $socket = new React\Socket\FdServer(0, $loop); + * ``` + * + * Note that these error conditions may vary depending on your system and/or + * configuration. + * See the exception message and code for more details about the actual error + * condition. + * + * @param int|string $fd FD number such as `3` or as URL in the form of `php://fd/3` + * @param ?LoopInterface $loop + * @throws \InvalidArgumentException if the listening address is invalid + * @throws \RuntimeException if listening on this address fails (already in use etc.) + */ + public function __construct($fd, LoopInterface $loop = null) + { + if (\preg_match('#^php://fd/(\\d+)$#', $fd, $m)) { + $fd = (int) $m[1]; + } + if (!\is_int($fd) || $fd < 0 || $fd >= \PHP_INT_MAX) { + throw new \InvalidArgumentException('Invalid FD number given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)); + } + $this->loop = $loop ?: Loop::get(); + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fopen(php://fd/3): Failed to open stream: Error duping file descriptor 3; possibly it doesn't exist: [9]: Bad file descriptor + \preg_match('/\\[(\\d+)\\]: (.*)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + $this->master = \fopen('php://fd/' . $fd, 'r+'); + \restore_error_handler(); + if (\false === $this->master) { + throw new \RuntimeException('Failed to listen on FD ' . $fd . ': ' . $errstr . SocketServer::errconst($errno), $errno); + } + $meta = \stream_get_meta_data($this->master); + if (!isset($meta['stream_type']) || $meta['stream_type'] !== 'tcp_socket') { + \fclose($this->master); + $errno = \defined('SOCKET_ENOTSOCK') ? \SOCKET_ENOTSOCK : 88; + $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Not a socket'; + throw new \RuntimeException('Failed to listen on FD ' . $fd . ': ' . $errstr . ' (ENOTSOCK)', $errno); + } + // Socket should not have a peer address if this is a listening socket. + // Looks like this work-around is the closest we can get because PHP doesn't expose SO_ACCEPTCONN even with ext-sockets. + if (\stream_socket_get_name($this->master, \true) !== \false) { + \fclose($this->master); + $errno = \defined('SOCKET_EISCONN') ? \SOCKET_EISCONN : 106; + $errstr = \function_exists('socket_strerror') ? \socket_strerror($errno) : 'Socket is connected'; + throw new \RuntimeException('Failed to listen on FD ' . $fd . ': ' . $errstr . ' (EISCONN)', $errno); + } + // Assume this is a Unix domain socket (UDS) when its listening address doesn't parse as a valid URL with a port. + // Looks like this work-around is the closest we can get because PHP doesn't expose SO_DOMAIN even with ext-sockets. + $this->unix = \parse_url($this->getAddress(), \PHP_URL_PORT) === \false; + \stream_set_blocking($this->master, \false); + $this->resume(); + } + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + $address = \stream_socket_get_name($this->master, \false); + if ($this->unix === \true) { + return 'unix://' . $address; + } + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== \false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); + // @codeCoverageIgnore + } + return 'tcp://' . $address; + } + public function pause() + { + if (!$this->listening) { + return; + } + $this->loop->removeReadStream($this->master); + $this->listening = \false; + } + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = \true; + } + public function close() + { + if (!\is_resource($this->master)) { + return; + } + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + /** @internal */ + public function handleConnection($socket) + { + $connection = new Connection($socket, $this->loop); + $connection->unix = $this->unix; + $this->emit('connection', array($connection)); + } +} diff --git a/vendor/react/socket/src/FixedUriConnector.php b/vendor/react/socket/src/FixedUriConnector.php new file mode 100644 index 00000000000..ba0a55602a5 --- /dev/null +++ b/vendor/react/socket/src/FixedUriConnector.php @@ -0,0 +1,39 @@ +connect('localhost:80'); + * ``` + */ +class FixedUriConnector implements ConnectorInterface +{ + private $uri; + private $connector; + /** + * @param string $uri + * @param ConnectorInterface $connector + */ + public function __construct($uri, ConnectorInterface $connector) + { + $this->uri = $uri; + $this->connector = $connector; + } + public function connect($_) + { + return $this->connector->connect($this->uri); + } +} diff --git a/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php b/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php new file mode 100644 index 00000000000..066c67b3e17 --- /dev/null +++ b/vendor/react/socket/src/HappyEyeBallsConnectionBuilder.php @@ -0,0 +1,275 @@ + \false, Message::TYPE_AAAA => \false); + public $resolverPromises = array(); + public $connectionPromises = array(); + public $connectQueue = array(); + public $nextAttemptTimer; + public $parts; + public $ipsCount = 0; + public $failureCount = 0; + public $resolve; + public $reject; + public $lastErrorFamily; + public $lastError6; + public $lastError4; + public function __construct(LoopInterface $loop, ConnectorInterface $connector, ResolverInterface $resolver, $uri, $host, $parts) + { + $this->loop = $loop; + $this->connector = $connector; + $this->resolver = $resolver; + $this->uri = $uri; + $this->host = $host; + $this->parts = $parts; + } + public function connect() + { + $timer = null; + $that = $this; + return new Promise\Promise(function ($resolve, $reject) use($that, &$timer) { + $lookupResolve = function ($type) use($that, $resolve, $reject) { + return function (array $ips) use($that, $type, $resolve, $reject) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = \true; + $that->mixIpsIntoConnectQueue($ips); + // start next connection attempt if not already awaiting next + if ($that->nextAttemptTimer === null && $that->connectQueue) { + $that->check($resolve, $reject); + } + }; + }; + $that->resolverPromises[Message::TYPE_AAAA] = $that->resolve(Message::TYPE_AAAA, $reject)->then($lookupResolve(Message::TYPE_AAAA)); + $that->resolverPromises[Message::TYPE_A] = $that->resolve(Message::TYPE_A, $reject)->then(function (array $ips) use($that, &$timer) { + // happy path: IPv6 has resolved already (or could not resolve), continue with IPv4 addresses + if ($that->resolved[Message::TYPE_AAAA] === \true || !$ips) { + return $ips; + } + // Otherwise delay processing IPv4 lookup until short timer passes or IPv6 resolves in the meantime + $deferred = new Promise\Deferred(); + $timer = $that->loop->addTimer($that::RESOLUTION_DELAY, function () use($deferred, $ips) { + $deferred->resolve($ips); + }); + $that->resolverPromises[Message::TYPE_AAAA]->then(function () use($that, $timer, $deferred, $ips) { + $that->loop->cancelTimer($timer); + $deferred->resolve($ips); + }); + return $deferred->promise(); + })->then($lookupResolve(Message::TYPE_A)); + }, function ($_, $reject) use($that, &$timer) { + $reject(new \RuntimeException('Connection to ' . $that->uri . ' cancelled' . (!$that->connectionPromises ? ' during DNS lookup' : '') . ' (ECONNABORTED)', \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103)); + $_ = $reject = null; + $that->cleanUp(); + if ($timer instanceof TimerInterface) { + $that->loop->cancelTimer($timer); + } + }); + } + /** + * @internal + * @param int $type DNS query type + * @param callable $reject + * @return \React\Promise\PromiseInterface Returns a promise that + * always resolves with a list of IP addresses on success or an empty + * list on error. + */ + public function resolve($type, $reject) + { + $that = $this; + return $that->resolver->resolveAll($that->host, $type)->then(null, function (\Exception $e) use($type, $reject, $that) { + unset($that->resolverPromises[$type]); + $that->resolved[$type] = \true; + if ($type === Message::TYPE_A) { + $that->lastError4 = $e->getMessage(); + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $e->getMessage(); + $that->lastErrorFamily = 6; + } + // cancel next attempt timer when there are no more IPs to connect to anymore + if ($that->nextAttemptTimer !== null && !$that->connectQueue) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + if ($that->hasBeenResolved() && $that->ipsCount === 0) { + $reject(new \RuntimeException($that->error(), 0, $e)); + } + // Exception already handled above, so don't throw an unhandled rejection here + return array(); + }); + } + /** + * @internal + */ + public function check($resolve, $reject) + { + $ip = \array_shift($this->connectQueue); + // start connection attempt and remember array position to later unset again + $this->connectionPromises[] = $this->attemptConnection($ip); + \end($this->connectionPromises); + $index = \key($this->connectionPromises); + $that = $this; + $that->connectionPromises[$index]->then(function ($connection) use($that, $index, $resolve) { + unset($that->connectionPromises[$index]); + $that->cleanUp(); + $resolve($connection); + }, function (\Exception $e) use($that, $index, $ip, $resolve, $reject) { + unset($that->connectionPromises[$index]); + $that->failureCount++; + $message = \preg_replace('/^(Connection to [^ ]+)[&?]hostname=[^ &]+/', '$1', $e->getMessage()); + if (\strpos($ip, ':') === \false) { + $that->lastError4 = $message; + $that->lastErrorFamily = 4; + } else { + $that->lastError6 = $message; + $that->lastErrorFamily = 6; + } + // start next connection attempt immediately on error + if ($that->connectQueue) { + if ($that->nextAttemptTimer !== null) { + $that->loop->cancelTimer($that->nextAttemptTimer); + $that->nextAttemptTimer = null; + } + $that->check($resolve, $reject); + } + if ($that->hasBeenResolved() === \false) { + return; + } + if ($that->ipsCount === $that->failureCount) { + $that->cleanUp(); + $reject(new \RuntimeException($that->error(), $e->getCode(), $e)); + } + }); + // Allow next connection attempt in 100ms: https://tools.ietf.org/html/rfc8305#section-5 + // Only start timer when more IPs are queued or when DNS query is still pending (might add more IPs) + if ($this->nextAttemptTimer === null && (\count($this->connectQueue) > 0 || $this->resolved[Message::TYPE_A] === \false || $this->resolved[Message::TYPE_AAAA] === \false)) { + $this->nextAttemptTimer = $this->loop->addTimer(self::CONNECTION_ATTEMPT_DELAY, function () use($that, $resolve, $reject) { + $that->nextAttemptTimer = null; + if ($that->connectQueue) { + $that->check($resolve, $reject); + } + }); + } + } + /** + * @internal + */ + public function attemptConnection($ip) + { + $uri = Connector::uri($this->parts, $this->host, $ip); + return $this->connector->connect($uri); + } + /** + * @internal + */ + public function cleanUp() + { + // clear list of outstanding IPs to avoid creating new connections + $this->connectQueue = array(); + foreach ($this->connectionPromises as $connectionPromise) { + if ($connectionPromise instanceof PromiseInterface && \method_exists($connectionPromise, 'cancel')) { + $connectionPromise->cancel(); + } + } + foreach ($this->resolverPromises as $resolverPromise) { + if ($resolverPromise instanceof PromiseInterface && \method_exists($resolverPromise, 'cancel')) { + $resolverPromise->cancel(); + } + } + if ($this->nextAttemptTimer instanceof TimerInterface) { + $this->loop->cancelTimer($this->nextAttemptTimer); + $this->nextAttemptTimer = null; + } + } + /** + * @internal + */ + public function hasBeenResolved() + { + foreach ($this->resolved as $typeHasBeenResolved) { + if ($typeHasBeenResolved === \false) { + return \false; + } + } + return \true; + } + /** + * Mixes an array of IP addresses into the connect queue in such a way they alternate when attempting to connect. + * The goal behind it is first attempt to connect to IPv6, then to IPv4, then to IPv6 again until one of those + * attempts succeeds. + * + * @link https://tools.ietf.org/html/rfc8305#section-4 + * + * @internal + */ + public function mixIpsIntoConnectQueue(array $ips) + { + \shuffle($ips); + $this->ipsCount += \count($ips); + $connectQueueStash = $this->connectQueue; + $this->connectQueue = array(); + while (\count($connectQueueStash) > 0 || \count($ips) > 0) { + if (\count($ips) > 0) { + $this->connectQueue[] = \array_shift($ips); + } + if (\count($connectQueueStash) > 0) { + $this->connectQueue[] = \array_shift($connectQueueStash); + } + } + } + /** + * @internal + * @return string + */ + public function error() + { + if ($this->lastError4 === $this->lastError6) { + $message = $this->lastError6; + } elseif ($this->lastErrorFamily === 6) { + $message = 'Last error for IPv6: ' . $this->lastError6 . '. Previous error for IPv4: ' . $this->lastError4; + } else { + $message = 'Last error for IPv4: ' . $this->lastError4 . '. Previous error for IPv6: ' . $this->lastError6; + } + if ($this->hasBeenResolved() && $this->ipsCount === 0) { + if ($this->lastError6 === $this->lastError4) { + $message = ' during DNS lookup: ' . $this->lastError6; + } else { + $message = ' during DNS lookup. ' . $message; + } + } else { + $message = ': ' . $message; + } + return 'Connection to ' . $this->uri . ' failed' . $message; + } +} diff --git a/vendor/react/socket/src/HappyEyeBallsConnector.php b/vendor/react/socket/src/HappyEyeBallsConnector.php new file mode 100644 index 00000000000..2b0a4b8db94 --- /dev/null +++ b/vendor/react/socket/src/HappyEyeBallsConnector.php @@ -0,0 +1,51 @@ +loop = $loop ?: Loop::get(); + $this->connector = $connector; + $this->resolver = $resolver; + } + public function connect($uri) + { + $original = $uri; + if (\strpos($uri, '://') === \false) { + $uri = 'tcp://' . $uri; + $parts = \parse_url($uri); + if (isset($parts['scheme'])) { + unset($parts['scheme']); + } + } else { + $parts = \parse_url($uri); + } + if (!$parts || !isset($parts['host'])) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $original . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + $host = \trim($parts['host'], '[]'); + // skip DNS lookup / URI manipulation if this URI already contains an IP + if (@\inet_pton($host) !== \false) { + return $this->connector->connect($original); + } + $builder = new HappyEyeBallsConnectionBuilder($this->loop, $this->connector, $this->resolver, $uri, $host, $parts); + return $builder->connect(); + } +} diff --git a/vendor/react/socket/src/LimitingServer.php b/vendor/react/socket/src/LimitingServer.php new file mode 100644 index 00000000000..54d8dc72c7b --- /dev/null +++ b/vendor/react/socket/src/LimitingServer.php @@ -0,0 +1,183 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +class LimitingServer extends EventEmitter implements ServerInterface +{ + private $connections = array(); + private $server; + private $limit; + private $pauseOnLimit = \false; + private $autoPaused = \false; + private $manuPaused = \false; + /** + * Instantiates a new LimitingServer. + * + * You have to pass a maximum number of open connections to ensure + * the server will automatically reject (close) connections once this limit + * is exceeded. In this case, it will emit an `error` event to inform about + * this and no `connection` event will be emitted. + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * You MAY pass a `null` limit in order to put no limit on the number of + * open connections and keep accepting new connection until you run out of + * operating system resources (such as open file handles). This may be + * useful if you do not want to take care of applying a limit but still want + * to use the `getConnections()` method. + * + * You can optionally configure the server to pause accepting new + * connections once the connection limit is reached. In this case, it will + * pause the underlying server and no longer process any new connections at + * all, thus also no longer closing any excessive connections. + * The underlying operating system is responsible for keeping a backlog of + * pending connections until its limit is reached, at which point it will + * start rejecting further connections. + * Once the server is below the connection limit, it will continue consuming + * connections from the backlog and will process any outstanding data on + * each connection. + * This mode may be useful for some protocols that are designed to wait for + * a response message (such as HTTP), but may be less useful for other + * protocols that demand immediate responses (such as a "welcome" message in + * an interactive chat). + * + * ```php + * $server = new React\Socket\LimitingServer($server, 100, true); + * $server->on('connection', function (React\Socket\ConnectionInterface $connection) { + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * @param ServerInterface $server + * @param int|null $connectionLimit + * @param bool $pauseOnLimit + */ + public function __construct(ServerInterface $server, $connectionLimit, $pauseOnLimit = \false) + { + $this->server = $server; + $this->limit = $connectionLimit; + if ($connectionLimit !== null) { + $this->pauseOnLimit = $pauseOnLimit; + } + $this->server->on('connection', array($this, 'handleConnection')); + $this->server->on('error', array($this, 'handleError')); + } + /** + * Returns an array with all currently active connections + * + * ```php + * foreach ($server->getConnection() as $connection) { + * $connection->write('Hi!'); + * } + * ``` + * + * @return ConnectionInterface[] + */ + public function getConnections() + { + return $this->connections; + } + public function getAddress() + { + return $this->server->getAddress(); + } + public function pause() + { + if (!$this->manuPaused) { + $this->manuPaused = \true; + if (!$this->autoPaused) { + $this->server->pause(); + } + } + } + public function resume() + { + if ($this->manuPaused) { + $this->manuPaused = \false; + if (!$this->autoPaused) { + $this->server->resume(); + } + } + } + public function close() + { + $this->server->close(); + } + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + // close connection if limit exceeded + if ($this->limit !== null && \count($this->connections) >= $this->limit) { + $this->handleError(new \OverflowException('Connection closed because server reached connection limit')); + $connection->close(); + return; + } + $this->connections[] = $connection; + $that = $this; + $connection->on('close', function () use($that, $connection) { + $that->handleDisconnection($connection); + }); + // pause accepting new connections if limit exceeded + if ($this->pauseOnLimit && !$this->autoPaused && \count($this->connections) >= $this->limit) { + $this->autoPaused = \true; + if (!$this->manuPaused) { + $this->server->pause(); + } + } + $this->emit('connection', array($connection)); + } + /** @internal */ + public function handleDisconnection(ConnectionInterface $connection) + { + unset($this->connections[\array_search($connection, $this->connections)]); + // continue accepting new connection if below limit + if ($this->autoPaused && \count($this->connections) < $this->limit) { + $this->autoPaused = \false; + if (!$this->manuPaused) { + $this->server->resume(); + } + } + } + /** @internal */ + public function handleError(\Exception $error) + { + $this->emit('error', array($error)); + } +} diff --git a/vendor/react/socket/src/SecureConnector.php b/vendor/react/socket/src/SecureConnector.php new file mode 100644 index 00000000000..f3e524c57ef --- /dev/null +++ b/vendor/react/socket/src/SecureConnector.php @@ -0,0 +1,91 @@ +connector = $connector; + $this->streamEncryption = new StreamEncryption($loop ?: Loop::get(), \false); + $this->context = $context; + } + public function connect($uri) + { + if (!\function_exists('stream_socket_enable_crypto')) { + return Promise\reject(new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)')); + // @codeCoverageIgnore + } + if (\strpos($uri, '://') === \false) { + $uri = 'tls://' . $uri; + } + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme']) || $parts['scheme'] !== 'tls') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + $context = $this->context; + $encryption = $this->streamEncryption; + $connected = \false; + /** @var \React\Promise\PromiseInterface $promise */ + $promise = $this->connector->connect(\str_replace('tls://', '', $uri))->then(function (ConnectionInterface $connection) use($context, $encryption, $uri, &$promise, &$connected) { + // (unencrypted) TCP/IP connection succeeded + $connected = \true; + if (!$connection instanceof Connection) { + $connection->close(); + throw new \UnexpectedValueException('Base connector does not use internal Connection class exposing stream resource'); + } + // set required SSL/TLS context options + foreach ($context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + // try to enable encryption + return $promise = $encryption->enable($connection)->then(null, function ($error) use($connection, $uri) { + // establishing encryption failed => close invalid connection and return error + $connection->close(); + throw new \RuntimeException('Connection to ' . $uri . ' failed during TLS handshake: ' . $error->getMessage(), $error->getCode()); + }); + }, function (\Exception $e) use($uri) { + if ($e instanceof \RuntimeException) { + $message = \preg_replace('/^Connection to [^ ]+/', '', $e->getMessage()); + $e = new \RuntimeException('Connection to ' . $uri . $message, $e->getCode(), $e); + // avoid garbage references by replacing all closures in call stack. + // what a lovely piece of code! + $r = new \ReflectionProperty('Exception', 'trace'); + $r->setAccessible(\true); + $trace = $r->getValue($e); + // Exception trace arguments are not available on some PHP 7.4 installs + // @codeCoverageIgnoreStart + foreach ($trace as $ti => $one) { + if (isset($one['args'])) { + foreach ($one['args'] as $ai => $arg) { + if ($arg instanceof \Closure) { + $trace[$ti]['args'][$ai] = 'Object(' . \get_class($arg) . ')'; + } + } + } + } + // @codeCoverageIgnoreEnd + $r->setValue($e, $trace); + } + throw $e; + }); + return new \ECSPrefix202307\React\Promise\Promise(function ($resolve, $reject) use($promise) { + $promise->then($resolve, $reject); + }, function ($_, $reject) use(&$promise, $uri, &$connected) { + if ($connected) { + $reject(new \RuntimeException('Connection to ' . $uri . ' cancelled during TLS handshake (ECONNABORTED)', \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103)); + } + $promise->cancel(); + $promise = null; + }); + } +} diff --git a/vendor/react/socket/src/SecureServer.php b/vendor/react/socket/src/SecureServer.php new file mode 100644 index 00000000000..9a146c13ec4 --- /dev/null +++ b/vendor/react/socket/src/SecureServer.php @@ -0,0 +1,184 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Secure connection from' . $connection->getRemoteAddress() . PHP_EOL; + * + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * Whenever a client fails to perform a successful TLS handshake, it will emit an + * `error` event and then close the underlying TCP/IP connection: + * + * ```php + * $server->on('error', function (Exception $e) { + * echo 'Error' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * Note that the `SecureServer` class is a concrete implementation for TLS sockets. + * If you want to typehint in your higher-level protocol implementation, you SHOULD + * use the generic `ServerInterface` instead. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class SecureServer extends EventEmitter implements ServerInterface +{ + private $tcp; + private $encryption; + private $context; + /** + * Creates a secure TLS server and starts waiting for incoming connections + * + * It does so by wrapping a `TcpServer` instance which waits for plaintext + * TCP/IP connections and then performs a TLS handshake for each connection. + * It thus requires valid [TLS context options], + * which in its most basic form may look something like this if you're using a + * PEM encoded certificate file: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem' + * )); + * ``` + * + * Note that the certificate file will not be loaded on instantiation but when an + * incoming connection initializes its TLS context. + * This implies that any invalid certificate file paths or contents will only cause + * an `error` event at a later time. + * + * If your private key is encrypted with a passphrase, you have to specify it + * like this: + * + * ```php + * $server = new React\Socket\TcpServer(8000); + * $server = new React\Socket\SecureServer($server, null, array( + * 'local_cert' => 'server.pem', + * 'passphrase' => 'secret' + * )); + * ``` + * + * Note that available [TLS context options], + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Advanced usage: Despite allowing any `ServerInterface` as first parameter, + * you SHOULD pass a `TcpServer` instance as first parameter, unless you + * know what you're doing. + * Internally, the `SecureServer` has to set the required TLS context options on + * the underlying stream resources. + * These resources are not exposed through any of the interfaces defined in this + * package, but only through the internal `Connection` class. + * The `TcpServer` class is guaranteed to emit connections that implement + * the `ConnectionInterface` and uses the internal `Connection` class in order to + * expose these underlying resources. + * If you use a custom `ServerInterface` and its `connection` event does not + * meet this requirement, the `SecureServer` will emit an `error` event and + * then close the underlying connection. + * + * @param ServerInterface|TcpServer $tcp + * @param ?LoopInterface $loop + * @param array $context + * @throws BadMethodCallException for legacy HHVM < 3.8 due to lack of support + * @see TcpServer + * @link https://www.php.net/manual/en/context.ssl.php for TLS context options + */ + public function __construct(ServerInterface $tcp, LoopInterface $loop = null, array $context = array()) + { + if (!\function_exists('stream_socket_enable_crypto')) { + throw new \BadMethodCallException('Encryption not supported on your platform (HHVM < 3.8?)'); + // @codeCoverageIgnore + } + // default to empty passphrase to suppress blocking passphrase prompt + $context += array('passphrase' => ''); + $this->tcp = $tcp; + $this->encryption = new StreamEncryption($loop ?: Loop::get()); + $this->context = $context; + $that = $this; + $this->tcp->on('connection', function ($connection) use($that) { + $that->handleConnection($connection); + }); + $this->tcp->on('error', function ($error) use($that) { + $that->emit('error', array($error)); + }); + } + public function getAddress() + { + $address = $this->tcp->getAddress(); + if ($address === null) { + return null; + } + return \str_replace('tcp://', 'tls://', $address); + } + public function pause() + { + $this->tcp->pause(); + } + public function resume() + { + $this->tcp->resume(); + } + public function close() + { + return $this->tcp->close(); + } + /** @internal */ + public function handleConnection(ConnectionInterface $connection) + { + if (!$connection instanceof Connection) { + $this->emit('error', array(new \UnexpectedValueException('Base server does not use internal Connection class exposing stream resource'))); + $connection->close(); + return; + } + foreach ($this->context as $name => $value) { + \stream_context_set_option($connection->stream, 'ssl', $name, $value); + } + // get remote address before starting TLS handshake in case connection closes during handshake + $remote = $connection->getRemoteAddress(); + $that = $this; + $this->encryption->enable($connection)->then(function ($conn) use($that) { + $that->emit('connection', array($conn)); + }, function ($error) use($that, $connection, $remote) { + $error = new \RuntimeException('Connection from ' . $remote . ' failed during TLS handshake: ' . $error->getMessage(), $error->getCode()); + $that->emit('error', array($error)); + $connection->close(); + }); + } +} diff --git a/vendor/react/socket/src/Server.php b/vendor/react/socket/src/Server.php new file mode 100644 index 00000000000..ba6dc62780e --- /dev/null +++ b/vendor/react/socket/src/Server.php @@ -0,0 +1,97 @@ + $context); + } + // apply default options if not explicitly given + $context += array('tcp' => array(), 'tls' => array(), 'unix' => array()); + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== \false) { + $scheme = \substr($uri, 0, $pos); + } + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } else { + $server = new TcpServer(\str_replace('tls://', '', $uri), $loop, $context['tcp']); + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + $this->server = $server; + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (Exception $error) use($that) { + $that->emit('error', array($error)); + }); + } + public function getAddress() + { + return $this->server->getAddress(); + } + public function pause() + { + $this->server->pause(); + } + public function resume() + { + $this->server->resume(); + } + public function close() + { + $this->server->close(); + } +} diff --git a/vendor/react/socket/src/ServerInterface.php b/vendor/react/socket/src/ServerInterface.php new file mode 100644 index 00000000000..800084144e5 --- /dev/null +++ b/vendor/react/socket/src/ServerInterface.php @@ -0,0 +1,147 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'new connection' . PHP_EOL; + * }); + * ``` + * + * See also the `ConnectionInterface` for more details about handling the + * incoming connection. + * + * error event: + * The `error` event will be emitted whenever there's an error accepting a new + * connection from a client. + * + * ```php + * $socket->on('error', function (Exception $e) { + * echo 'error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * Note that this is not a fatal error event, i.e. the server keeps listening for + * new connections even after this event. + * + * @see ConnectionInterface + */ +interface ServerInterface extends EventEmitterInterface +{ + /** + * Returns the full address (URI) this server is currently listening on + * + * ```php + * $address = $socket->getAddress(); + * echo 'Server listening on ' . $address . PHP_EOL; + * ``` + * + * If the address can not be determined or is unknown at this time (such as + * after the socket has been closed), it MAY return a `NULL` value instead. + * + * Otherwise, it will return the full address (URI) as a string value, such + * as `tcp://127.0.0.1:8080`, `tcp://[::1]:80` or `tls://127.0.0.1:443`. + * Note that individual URI components are application specific and depend + * on the underlying transport protocol. + * + * If this is a TCP/IP based server and you only want the local port, you may + * use something like this: + * + * ```php + * $address = $socket->getAddress(); + * $port = parse_url($address, PHP_URL_PORT); + * echo 'Server listening on port ' . $port . PHP_EOL; + * ``` + * + * @return ?string the full listening address (URI) or NULL if it is unknown (not applicable to this server socket or already closed) + */ + public function getAddress(); + /** + * Pauses accepting new incoming connections. + * + * Removes the socket resource from the EventLoop and thus stop accepting + * new connections. Note that the listening socket stays active and is not + * closed. + * + * This means that new incoming connections will stay pending in the + * operating system backlog until its configurable backlog is filled. + * Once the backlog is filled, the operating system may reject further + * incoming connections until the backlog is drained again by resuming + * to accept new connections. + * + * Once the server is paused, no futher `connection` events SHOULD + * be emitted. + * + * ```php + * $socket->pause(); + * + * $socket->on('connection', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * server MAY continue emitting `connection` events. + * + * Unless otherwise noted, a successfully opened server SHOULD NOT start + * in paused state. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::resume() + * @return void + */ + public function pause(); + /** + * Resumes accepting new incoming connections. + * + * Re-attach the socket resource to the EventLoop after a previous `pause()`. + * + * ```php + * $socket->pause(); + * + * Loop::addTimer(1.0, function () use ($socket) { + * $socket->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * Similarly, calling this after `close()` is a NO-OP. + * + * @see self::pause() + * @return void + */ + public function resume(); + /** + * Shuts down this listening socket + * + * This will stop listening for new incoming connections on this socket. + * + * Calling this method more than once on the same instance is a NO-OP. + * + * @return void + */ + public function close(); +} diff --git a/vendor/react/socket/src/SocketServer.php b/vendor/react/socket/src/SocketServer.php new file mode 100644 index 00000000000..e43682e571f --- /dev/null +++ b/vendor/react/socket/src/SocketServer.php @@ -0,0 +1,178 @@ + array(), 'tls' => array(), 'unix' => array()); + $scheme = 'tcp'; + $pos = \strpos($uri, '://'); + if ($pos !== \false) { + $scheme = \substr($uri, 0, $pos); + } + if ($scheme === 'unix') { + $server = new UnixServer($uri, $loop, $context['unix']); + } elseif ($scheme === 'php') { + $server = new FdServer($uri, $loop); + } else { + if (\preg_match('#^(?:\\w+://)?\\d+$#', $uri)) { + throw new \InvalidArgumentException('Invalid URI given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)); + } + $server = new TcpServer(\str_replace('tls://', '', $uri), $loop, $context['tcp']); + if ($scheme === 'tls') { + $server = new SecureServer($server, $loop, $context['tls']); + } + } + $this->server = $server; + $that = $this; + $server->on('connection', function (ConnectionInterface $conn) use($that) { + $that->emit('connection', array($conn)); + }); + $server->on('error', function (\Exception $error) use($that) { + $that->emit('error', array($error)); + }); + } + public function getAddress() + { + return $this->server->getAddress(); + } + public function pause() + { + $this->server->pause(); + } + public function resume() + { + $this->server->resume(); + } + public function close() + { + $this->server->close(); + } + /** + * [internal] Internal helper method to accept new connection from given server socket + * + * @param resource $socket server socket to accept connection from + * @return resource new client socket if any + * @throws \RuntimeException if accepting fails + * @internal + */ + public static function accept($socket) + { + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // stream_socket_accept(): accept failed: Connection timed out + $errstr = \preg_replace('#.*: #', '', $error); + $errno = SocketServer::errno($errstr); + }); + $newSocket = \stream_socket_accept($socket, 0); + \restore_error_handler(); + if (\false === $newSocket) { + throw new \RuntimeException('Unable to accept new connection: ' . $errstr . self::errconst($errno), $errno); + } + return $newSocket; + } + /** + * [Internal] Returns errno value for given errstr + * + * The errno and errstr values describes the type of error that has been + * encountered. This method tries to look up the given errstr and find a + * matching errno value which can be useful to provide more context to error + * messages. It goes through the list of known errno constants when either + * `ext-sockets`, `ext-posix` or `ext-pcntl` is available to find an errno + * matching the given errstr. + * + * @param string $errstr + * @return int errno value (e.g. value of `SOCKET_ECONNREFUSED`) or 0 if not found + * @internal + * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission + * @codeCoverageIgnore + */ + public static function errno($errstr) + { + // PHP defines the required `strerror()` function through either `ext-sockets`, `ext-posix` or `ext-pcntl` + $strerror = \function_exists('socket_strerror') ? 'socket_strerror' : (\function_exists('posix_strerror') ? 'posix_strerror' : (\function_exists('pcntl_strerror') ? 'pcntl_strerror' : null)); + if ($strerror !== null) { + \assert(\is_string($strerror) && \is_callable($strerror)); + // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED` + // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE` + // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errstr` + foreach (\get_defined_constants(\false) as $name => $value) { + if (\is_int($value) && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0) && $strerror($value) === $errstr) { + return $value; + } + } + // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available) + // go through list of all possible errno values from 1 to `MAX_ERRNO` and see if they match the given `$errstr` + for ($errno = 1, $max = \defined('ECSPrefix202307\\MAX_ERRNO') ? \ECSPrefix202307\MAX_ERRNO : 4095; $errno <= $max; ++$errno) { + if ($strerror($errno) === $errstr) { + return $errno; + } + } + } + // if we reach this, no matching errno value could be found (unlikely when either `ext-sockets`, `ext-posix` or `ext-pcntl` is available) + return 0; + } + /** + * [Internal] Returns errno constant name for given errno value + * + * The errno value describes the type of error that has been encountered. + * This method tries to look up the given errno value and find a matching + * errno constant name which can be useful to provide more context and more + * descriptive error messages. It goes through the list of known errno + * constants when either `ext-sockets` or `ext-pcntl` is available to find + * the matching errno constant name. + * + * Because this method is used to append more context to error messages, the + * constant name will be prefixed with a space and put between parenthesis + * when found. + * + * @param int $errno + * @return string e.g. ` (ECONNREFUSED)` or empty string if no matching const for the given errno could be found + * @internal + * @copyright Copyright (c) 2023 Christian Lück, taken from https://github.com/clue/errno with permission + * @codeCoverageIgnore + */ + public static function errconst($errno) + { + // PHP defines most useful errno constants like `ECONNREFUSED` through constants in `ext-sockets` like `SOCKET_ECONNREFUSED` + // PHP also defines a hand full of errno constants like `EMFILE` through constants in `ext-pcntl` like `PCNTL_EMFILE` + // go through list of all defined constants like `SOCKET_E*` and `PCNTL_E*` and see if they match the given `$errno` + foreach (\get_defined_constants(\false) as $name => $value) { + if ($value === $errno && (\strpos($name, 'SOCKET_E') === 0 || \strpos($name, 'PCNTL_E') === 0)) { + return ' (' . \substr($name, \strpos($name, '_') + 1) . ')'; + } + } + // if we reach this, no matching errno constant could be found (unlikely when `ext-sockets` is available) + return ''; + } +} diff --git a/vendor/react/socket/src/StreamEncryption.php b/vendor/react/socket/src/StreamEncryption.php new file mode 100644 index 00000000000..84b3d493f9c --- /dev/null +++ b/vendor/react/socket/src/StreamEncryption.php @@ -0,0 +1,116 @@ +loop = $loop; + $this->server = $server; + // support TLSv1.0+ by default and exclude legacy SSLv2/SSLv3. + // As of PHP 7.2+ the main crypto method constant includes all TLS versions. + // As of PHP 5.6+ the crypto method is a bitmask, so we explicitly include all TLS versions. + // For legacy PHP < 5.6 the crypto method is a single value only and this constant includes all TLS versions. + // @link https://3v4l.org/9PSST + if ($server) { + $this->method = \STREAM_CRYPTO_METHOD_TLS_SERVER; + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_1_SERVER | \STREAM_CRYPTO_METHOD_TLSv1_2_SERVER; + // @codeCoverageIgnore + } + } else { + $this->method = \STREAM_CRYPTO_METHOD_TLS_CLIENT; + if (\PHP_VERSION_ID < 70200 && \PHP_VERSION_ID >= 50600) { + $this->method |= \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT | \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT; + // @codeCoverageIgnore + } + } + } + public function enable(Connection $stream) + { + return $this->toggle($stream, \true); + } + public function toggle(Connection $stream, $toggle) + { + // pause actual stream instance to continue operation on raw stream socket + $stream->pause(); + // TODO: add write() event to make sure we're not sending any excessive data + // cancelling this leaves this stream in an inconsistent state… + $deferred = new Deferred(function () { + throw new \RuntimeException(); + }); + // get actual stream socket from stream instance + $socket = $stream->stream; + // get crypto method from context options or use global setting from constructor + $method = $this->method; + $context = \stream_context_get_options($socket); + if (isset($context['ssl']['crypto_method'])) { + $method = $context['ssl']['crypto_method']; + } + $that = $this; + $toggleCrypto = function () use($socket, $deferred, $toggle, $method, $that) { + $that->toggleCrypto($socket, $deferred, $toggle, $method); + }; + $this->loop->addReadStream($socket, $toggleCrypto); + if (!$this->server) { + $toggleCrypto(); + } + $loop = $this->loop; + return $deferred->promise()->then(function () use($stream, $socket, $loop, $toggle) { + $loop->removeReadStream($socket); + $stream->encryptionEnabled = $toggle; + $stream->resume(); + return $stream; + }, function ($error) use($stream, $socket, $loop) { + $loop->removeReadStream($socket); + $stream->resume(); + throw $error; + }); + } + public function toggleCrypto($socket, Deferred $deferred, $toggle, $method) + { + $error = null; + \set_error_handler(function ($_, $errstr) use(&$error) { + $error = \str_replace(array("\r", "\n"), ' ', $errstr); + // remove useless function name from error message + if (($pos = \strpos($error, "): ")) !== \false) { + $error = \substr($error, $pos + 3); + } + }); + $result = \stream_socket_enable_crypto($socket, $toggle, $method); + \restore_error_handler(); + if (\true === $result) { + $deferred->resolve(null); + } else { + if (\false === $result) { + // overwrite callback arguments for PHP7+ only, so they do not show + // up in the Exception trace and do not cause a possible cyclic reference. + $d = $deferred; + $deferred = null; + if (\feof($socket) || $error === null) { + // EOF or failed without error => connection closed during handshake + $d->reject(new \UnexpectedValueException('Connection lost during TLS handshake (ECONNRESET)', \defined('SOCKET_ECONNRESET') ? \SOCKET_ECONNRESET : 104)); + } else { + // handshake failed with error message + $d->reject(new \UnexpectedValueException($error)); + } + } else { + // need more data, will retry + } + } + } +} diff --git a/vendor/react/socket/src/TcpConnector.php b/vendor/react/socket/src/TcpConnector.php new file mode 100644 index 00000000000..b6cf07de881 --- /dev/null +++ b/vendor/react/socket/src/TcpConnector.php @@ -0,0 +1,116 @@ +loop = $loop ?: Loop::get(); + $this->context = $context; + } + public function connect($uri) + { + if (\strpos($uri, '://') === \false) { + $uri = 'tcp://' . $uri; + } + $parts = \parse_url($uri); + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + $ip = \trim($parts['host'], '[]'); + if (@\inet_pton($ip) === \false) { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + // use context given in constructor + $context = array('socket' => $this->context); + // parse arguments from query component of URI + $args = array(); + if (isset($parts['query'])) { + \parse_str($parts['query'], $args); + } + // If an original hostname has been given, use this for TLS setup. + // This can happen due to layers of nested connectors, such as a + // DnsConnector reporting its original hostname. + // These context options are here in case TLS is enabled later on this stream. + // If TLS is not enabled later, this doesn't hurt either. + if (isset($args['hostname'])) { + $context['ssl'] = array('SNI_enabled' => \true, 'peer_name' => $args['hostname']); + // Legacy PHP < 5.6 ignores peer_name and requires legacy context options instead. + // The SNI_server_name context option has to be set here during construction, + // as legacy PHP ignores any values set later. + // @codeCoverageIgnoreStart + if (\PHP_VERSION_ID < 50600) { + $context['ssl'] += array('SNI_server_name' => $args['hostname'], 'CN_match' => $args['hostname']); + } + // @codeCoverageIgnoreEnd + } + // latest versions of PHP no longer accept any other URI components and + // HHVM fails to parse URIs with a query but no path, so let's simplify our URI here + $remote = 'tcp://' . $parts['host'] . ':' . $parts['port']; + $stream = @\stream_socket_client($remote, $errno, $errstr, 0, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT, \stream_context_create($context)); + if (\false === $stream) { + return Promise\reject(new \RuntimeException('Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno), $errno)); + } + // wait for connection + $loop = $this->loop; + return new Promise\Promise(function ($resolve, $reject) use($loop, $stream, $uri) { + $loop->addWriteStream($stream, function ($stream) use($loop, $resolve, $reject, $uri) { + $loop->removeWriteStream($stream); + // The following hack looks like the only way to + // detect connection refused errors with PHP's stream sockets. + if (\false === \stream_socket_get_name($stream, \true)) { + // If we reach this point, we know the connection is dead, but we don't know the underlying error condition. + // @codeCoverageIgnoreStart + if (\function_exists('socket_import_stream')) { + // actual socket errno and errstr can be retrieved with ext-sockets on PHP 5.4+ + $socket = \socket_import_stream($stream); + $errno = \socket_get_option($socket, \SOL_SOCKET, \SO_ERROR); + $errstr = \socket_strerror($errno); + } elseif (\PHP_OS === 'Linux') { + // Linux reports socket errno and errstr again when trying to write to the dead socket. + // Suppress error reporting to get error message below and close dead socket before rejecting. + // This is only known to work on Linux, Mac and Windows are known to not support this. + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // Match errstr from PHP's warning message. + // fwrite(): send of 1 bytes failed with errno=111 Connection refused + \preg_match('/errno=(\\d+) (.+)/', $error, $m); + $errno = isset($m[1]) ? (int) $m[1] : 0; + $errstr = isset($m[2]) ? $m[2] : $error; + }); + \fwrite($stream, \PHP_EOL); + \restore_error_handler(); + } else { + // Not on Linux and ext-sockets not available? Too bad. + $errno = \defined('SOCKET_ECONNREFUSED') ? \SOCKET_ECONNREFUSED : 111; + $errstr = 'Connection refused?'; + } + // @codeCoverageIgnoreEnd + \fclose($stream); + $reject(new \RuntimeException('Connection to ' . $uri . ' failed: ' . $errstr . SocketServer::errconst($errno), $errno)); + } else { + $resolve(new Connection($stream, $loop)); + } + }); + }, function () use($loop, $stream, $uri) { + $loop->removeWriteStream($stream); + \fclose($stream); + // @codeCoverageIgnoreStart + // legacy PHP 5.3 sometimes requires a second close call (see tests) + if (\PHP_VERSION_ID < 50400 && \is_resource($stream)) { + \fclose($stream); + } + // @codeCoverageIgnoreEnd + throw new \RuntimeException('Connection to ' . $uri . ' cancelled during TCP/IP handshake (ECONNABORTED)', \defined('SOCKET_ECONNABORTED') ? \SOCKET_ECONNABORTED : 103); + }); + } +} diff --git a/vendor/react/socket/src/TcpServer.php b/vendor/react/socket/src/TcpServer.php new file mode 100644 index 00000000000..a6eb7f7333d --- /dev/null +++ b/vendor/react/socket/src/TcpServer.php @@ -0,0 +1,221 @@ +on('connection', function (React\Socket\ConnectionInterface $connection) { + * echo 'Plaintext connection from ' . $connection->getRemoteAddress() . PHP_EOL; + * $connection->write('hello there!' . PHP_EOL); + * … + * }); + * ``` + * + * See also the `ServerInterface` for more details. + * + * @see ServerInterface + * @see ConnectionInterface + */ +final class TcpServer extends EventEmitter implements ServerInterface +{ + private $master; + private $loop; + private $listening = \false; + /** + * Creates a plaintext TCP/IP socket server and starts listening on the given address + * + * This starts accepting new incoming connections on the given address. + * See also the `connection event` documented in the `ServerInterface` + * for more details. + * + * ```php + * $server = new React\Socket\TcpServer(8080); + * ``` + * + * As above, the `$uri` parameter can consist of only a port, in which case the + * server will default to listening on the localhost address `127.0.0.1`, + * which means it will not be reachable from outside of this system. + * + * In order to use a random port assignment, you can use the port `0`: + * + * ```php + * $server = new React\Socket\TcpServer(0); + * $address = $server->getAddress(); + * ``` + * + * In order to change the host the socket is listening on, you can provide an IP + * address through the first parameter provided to the constructor, optionally + * preceded by the `tcp://` scheme: + * + * ```php + * $server = new React\Socket\TcpServer('192.168.0.1:8080'); + * ``` + * + * If you want to listen on an IPv6 address, you MUST enclose the host in square + * brackets: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080'); + * ``` + * + * If the given URI is invalid, does not contain a port, any other scheme or if it + * contains a hostname, it will throw an `InvalidArgumentException`: + * + * ```php + * // throws InvalidArgumentException due to missing port + * $server = new React\Socket\TcpServer('127.0.0.1'); + * ``` + * + * If the given URI appears to be valid, but listening on it fails (such as if port + * is already in use or port below 1024 may require root access etc.), it will + * throw a `RuntimeException`: + * + * ```php + * $first = new React\Socket\TcpServer(8080); + * + * // throws RuntimeException because port is already in use + * $second = new React\Socket\TcpServer(8080); + * ``` + * + * Note that these error conditions may vary depending on your system and/or + * configuration. + * See the exception message and code for more details about the actual error + * condition. + * + * This class takes an optional `LoopInterface|null $loop` parameter that can be used to + * pass the event loop instance to use for this object. You can use a `null` value + * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). + * This value SHOULD NOT be given unless you're sure you want to explicitly use a + * given event loop instance. + * + * Optionally, you can specify [socket context options](https://www.php.net/manual/en/context.socket.php) + * for the underlying stream socket resource like this: + * + * ```php + * $server = new React\Socket\TcpServer('[::1]:8080', null, array( + * 'backlog' => 200, + * 'so_reuseport' => true, + * 'ipv6_v6only' => true + * )); + * ``` + * + * Note that available [socket context options](https://www.php.net/manual/en/context.socket.php), + * their defaults and effects of changing these may vary depending on your system + * and/or PHP version. + * Passing unknown context options has no effect. + * The `backlog` context option defaults to `511` unless given explicitly. + * + * @param string|int $uri + * @param ?LoopInterface $loop + * @param array $context + * @throws InvalidArgumentException if the listening address is invalid + * @throws RuntimeException if listening on this address fails (already in use etc.) + */ + public function __construct($uri, LoopInterface $loop = null, array $context = array()) + { + $this->loop = $loop ?: Loop::get(); + // a single port has been given => assume localhost + if ((string) (int) $uri === (string) $uri) { + $uri = '127.0.0.1:' . $uri; + } + // assume default scheme if none has been given + if (\strpos($uri, '://') === \false) { + $uri = 'tcp://' . $uri; + } + // parse_url() does not accept null ports (random port assignment) => manually remove + if (\substr($uri, -2) === ':0') { + $parts = \parse_url(\substr($uri, 0, -2)); + if ($parts) { + $parts['port'] = 0; + } + } else { + $parts = \parse_url($uri); + } + // ensure URI contains TCP scheme, host and port + if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || $parts['scheme'] !== 'tcp') { + throw new \InvalidArgumentException('Invalid URI "' . $uri . '" given (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)); + } + if (@\inet_pton(\trim($parts['host'], '[]')) === \false) { + throw new \InvalidArgumentException('Given URI "' . $uri . '" does not contain a valid host IP (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)); + } + $this->master = @\stream_socket_server($uri, $errno, $errstr, \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, \stream_context_create(array('socket' => $context + array('backlog' => 511)))); + if (\false === $this->master) { + if ($errno === 0) { + // PHP does not seem to report errno, so match errno from errstr + // @link https://3v4l.org/3qOBl + $errno = SocketServer::errno($errstr); + } + throw new \RuntimeException('Failed to listen on "' . $uri . '": ' . $errstr . SocketServer::errconst($errno), $errno); + } + \stream_set_blocking($this->master, \false); + $this->resume(); + } + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + $address = \stream_socket_get_name($this->master, \false); + // check if this is an IPv6 address which includes multiple colons but no square brackets + $pos = \strrpos($address, ':'); + if ($pos !== \false && \strpos($address, ':') < $pos && \substr($address, 0, 1) !== '[') { + $address = '[' . \substr($address, 0, $pos) . ']:' . \substr($address, $pos + 1); + // @codeCoverageIgnore + } + return 'tcp://' . $address; + } + public function pause() + { + if (!$this->listening) { + return; + } + $this->loop->removeReadStream($this->master); + $this->listening = \false; + } + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = \true; + } + public function close() + { + if (!\is_resource($this->master)) { + return; + } + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + /** @internal */ + public function handleConnection($socket) + { + $this->emit('connection', array(new Connection($socket, $this->loop))); + } +} diff --git a/vendor/react/socket/src/TimeoutConnector.php b/vendor/react/socket/src/TimeoutConnector.php new file mode 100644 index 00000000000..7e3cddb76e4 --- /dev/null +++ b/vendor/react/socket/src/TimeoutConnector.php @@ -0,0 +1,60 @@ +connector = $connector; + $this->timeout = $timeout; + $this->loop = $loop ?: Loop::get(); + } + public function connect($uri) + { + $promise = $this->connector->connect($uri); + $loop = $this->loop; + $time = $this->timeout; + return new Promise(function ($resolve, $reject) use($loop, $time, $promise, $uri) { + $timer = null; + $promise = $promise->then(function ($v) use(&$timer, $loop, $resolve) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = \false; + $resolve($v); + }, function ($v) use(&$timer, $loop, $reject) { + if ($timer) { + $loop->cancelTimer($timer); + } + $timer = \false; + $reject($v); + }); + // promise already resolved => no need to start timer + if ($timer === \false) { + return; + } + // start timeout timer which will cancel the pending promise + $timer = $loop->addTimer($time, function () use($time, &$promise, $reject, $uri) { + $reject(new \RuntimeException('Connection to ' . $uri . ' timed out after ' . $time . ' seconds (ETIMEDOUT)', \defined('SOCKET_ETIMEDOUT') ? \SOCKET_ETIMEDOUT : 110)); + // Cancel pending connection to clean up any underlying resources and references. + // Avoid garbage references in call stack by passing pending promise by reference. + \assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + }, function () use(&$promise) { + // Cancelling this promise will cancel the pending connection, thus triggering the rejection logic above. + // Avoid garbage references in call stack by passing pending promise by reference. + \assert(\method_exists($promise, 'cancel')); + $promise->cancel(); + $promise = null; + }); + } +} diff --git a/vendor/react/socket/src/UnixConnector.php b/vendor/react/socket/src/UnixConnector.php new file mode 100644 index 00000000000..d665fbb5dd6 --- /dev/null +++ b/vendor/react/socket/src/UnixConnector.php @@ -0,0 +1,38 @@ +loop = $loop ?: Loop::get(); + } + public function connect($path) + { + if (\strpos($path, '://') === \false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + return Promise\reject(new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22))); + } + $resource = @\stream_socket_client($path, $errno, $errstr, 1.0); + if (!$resource) { + return Promise\reject(new \RuntimeException('Unable to connect to unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno), $errno)); + } + $connection = new Connection($resource, $this->loop); + $connection->unix = \true; + return Promise\resolve($connection); + } +} diff --git a/vendor/react/socket/src/UnixServer.php b/vendor/react/socket/src/UnixServer.php new file mode 100644 index 00000000000..935f790dd4f --- /dev/null +++ b/vendor/react/socket/src/UnixServer.php @@ -0,0 +1,126 @@ +loop = $loop ?: Loop::get(); + if (\strpos($path, '://') === \false) { + $path = 'unix://' . $path; + } elseif (\substr($path, 0, 7) !== 'unix://') { + throw new \InvalidArgumentException('Given URI "' . $path . '" is invalid (EINVAL)', \defined('SOCKET_EINVAL') ? \SOCKET_EINVAL : (\defined('PCNTL_EINVAL') ? \PCNTL_EINVAL : 22)); + } + $errno = 0; + $errstr = ''; + \set_error_handler(function ($_, $error) use(&$errno, &$errstr) { + // PHP does not seem to report errno/errstr for Unix domain sockets (UDS) right now. + // This only applies to UDS server sockets, see also https://3v4l.org/NAhpr. + // Parse PHP warning message containing unknown error, HHVM reports proper info at least. + if (\preg_match('/\\(([^\\)]+)\\)|\\[(\\d+)\\]: (.*)/', $error, $match)) { + $errstr = isset($match[3]) ? $match['3'] : $match[1]; + $errno = isset($match[2]) ? (int) $match[2] : 0; + } + }); + $this->master = \stream_socket_server($path, $errno, $errstr, \STREAM_SERVER_BIND | \STREAM_SERVER_LISTEN, \stream_context_create(array('socket' => $context))); + \restore_error_handler(); + if (\false === $this->master) { + throw new \RuntimeException('Failed to listen on Unix domain socket "' . $path . '": ' . $errstr . SocketServer::errconst($errno), $errno); + } + \stream_set_blocking($this->master, 0); + $this->resume(); + } + public function getAddress() + { + if (!\is_resource($this->master)) { + return null; + } + return 'unix://' . \stream_socket_get_name($this->master, \false); + } + public function pause() + { + if (!$this->listening) { + return; + } + $this->loop->removeReadStream($this->master); + $this->listening = \false; + } + public function resume() + { + if ($this->listening || !\is_resource($this->master)) { + return; + } + $that = $this; + $this->loop->addReadStream($this->master, function ($master) use($that) { + try { + $newSocket = SocketServer::accept($master); + } catch (\RuntimeException $e) { + $that->emit('error', array($e)); + return; + } + $that->handleConnection($newSocket); + }); + $this->listening = \true; + } + public function close() + { + if (!\is_resource($this->master)) { + return; + } + $this->pause(); + \fclose($this->master); + $this->removeAllListeners(); + } + /** @internal */ + public function handleConnection($socket) + { + $connection = new Connection($socket, $this->loop); + $connection->unix = \true; + $this->emit('connection', array($connection)); + } +} diff --git a/vendor/react/stream/CHANGELOG.md b/vendor/react/stream/CHANGELOG.md new file mode 100644 index 00000000000..b4e230710ce --- /dev/null +++ b/vendor/react/stream/CHANGELOG.md @@ -0,0 +1,449 @@ +# Changelog + +## 1.3.0 (2023-06-16) + +* Feature: Full PHP 8.1 and PHP 8.2 compatibility. + (#160 by @SimonFrings, #165 by @clue and #169 by @WyriHaximus) + +* Feature: Avoid unneeded syscall when creating non-blocking `DuplexResourceStream`. + (#164 by @clue) + +* Minor documentation improvements. + (#161 by @mrsimonbennett, #162 by @SimonFrings and #166 by @nhedger) + +* Improve test suite and project setup and report failed assertions. + (#168 and #170 by @clue and #163 by @SimonFrings) + +## 1.2.0 (2021-07-11) + +A major new feature release, see [**release announcement**](https://clue.engineering/2021/announcing-reactphp-default-loop). + +* Feature: Simplify usage by supporting new [default loop](https://reactphp.org/event-loop/#loop). + (#159 by @clue) + + ```php + // old (still supported) + $stream = new ReadableResourceStream($resource, $loop); + $stream = new WritabeResourceStream($resource, $loop); + $stream = new DuplexResourceStream($resource, $loop); + + // new (using default loop) + $stream = new ReadableResourceStream($resource); + $stream = new WritabeResourceStream($resource); + $stream = new DuplexResourceStream($resource); + ``` + +* Improve test suite, use GitHub actions for continuous integration (CI), + update PHPUnit config, run tests on PHP 8 and add full core team to the license. + (#153, #156 and #157 by @SimonFrings and #154 by @WyriHaximus) + +## 1.1.1 (2020-05-04) + +* Fix: Fix faulty write buffer behavior when sending large data chunks over TLS (Mac OS X only). + (#150 by @clue) + +* Minor code style improvements to fix phpstan analysis warnings and + add `.gitattributes` to exclude dev files from exports. + (#140 by @flow-control and #144 by @reedy) + +* Improve test suite to run tests on PHP 7.4 and simplify test matrix. + (#147 by @clue) + +## 1.1.0 (2019-01-01) + +* Improvement: Increase performance by optimizing global function and constant look ups. + (#137 by @WyriHaximus) + +* Travis: Test against PHP 7.3. + (#138 by @WyriHaximus) + +* Fix: Ignore empty reads. + (#139 by @WyriHaximus) + +## 1.0.0 (2018-07-11) + +* First stable LTS release, now following [SemVer](https://semver.org/). + We'd like to emphasize that this component is production ready and battle-tested. + We plan to support all long-term support (LTS) releases for at least 24 months, + so you have a rock-solid foundation to build on top of. + +> Contains no other changes, so it's actually fully compatible with the v0.7.7 release. + +## 0.7.7 (2018-01-19) + +* Improve test suite by fixing forward compatibility with upcoming EventLoop + releases, avoid risky tests and add test group to skip integration tests + relying on internet connection and apply appropriate test timeouts. + (#128, #131 and #132 by @clue) + +## 0.7.6 (2017-12-21) + +* Fix: Work around reading from unbuffered pipe stream in legacy PHP < 5.4.28 and PHP < 5.5.12 + (#126 by @clue) + +* Improve test suite by simplifying test bootstrapping logic via Composer and + test against PHP 7.2 + (#127 by @clue and #124 by @carusogabriel) + +## 0.7.5 (2017-11-20) + +* Fix: Igore excessive `fopen()` mode flags for `WritableResourceStream` + (#119 by @clue) + +* Fix: Fix forward compatibility with upcoming EventLoop releases + (#121 by @clue) + +* Restructure examples to ease getting started + (#123 by @clue) + +* Improve test suite by adding forward compatibility with PHPUnit 6 and + ignore Mac OS X test failures for now until Travis tests work again + (#122 by @gabriel-caruso and #120 by @clue) + +## 0.7.4 (2017-10-11) + +* Fix: Remove event listeners from `CompositeStream` once closed and + remove undocumented left-over `close` event argument + (#116 by @clue) + +* Minor documentation improvements: Fix wrong class name in example, + fix typos in README and + fix forward compatibility with upcoming EventLoop releases in example + (#113 by @docteurklein and #114 and #115 by @clue) + +* Improve test suite by running against Mac OS X on Travis + (#112 by @clue) + +## 0.7.3 (2017-08-05) + +* Improvement: Support Événement 3.0 a long side 2.0 and 1.0 + (#108 by @WyriHaximus) + +* Readme: Corrected loop initialization in usage example + (#109 by @pulyavin) + +* Travis: Lock linux distribution preventing future builds from breaking + (#110 by @clue) + +## 0.7.2 (2017-06-15) + +* Bug fix: WritableResourceStream: Close the underlying stream when closing the stream. + (#107 by @WyriHaximus) + +## 0.7.1 (2017-05-20) + +* Feature: Add optional `$writeChunkSize` parameter to limit maximum number of + bytes to write at once. + (#105 by @clue) + + ```php + $stream = new WritableResourceStream(STDOUT, $loop, null, 8192); + ``` + +* Ignore HHVM test failures for now until Travis tests work again + (#106 by @clue) + +## 0.7.0 (2017-05-04) + +* Removed / BC break: Remove deprecated and unneeded functionality + (#45, #87, #90, #91 and #93 by @clue) + + * Remove deprecated `Stream` class, use `DuplexResourceStream` instead + (#87 by @clue) + + * Remove public `$buffer` property, use new constructor parameters instead + (#91 by @clue) + + * Remove public `$stream` property from all resource streams + (#90 by @clue) + + * Remove undocumented and now unused `ReadableStream` and `WritableStream` + (#93 by @clue) + + * Remove `BufferedSink` + (#45 by @clue) + +* Feature / BC break: Simplify `ThroughStream` by using data callback instead of + inheritance. It is now a direct implementation of `DuplexStreamInterface`. + (#88 and #89 by @clue) + + ```php + $through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; + }); + $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + + $through->write(array(2, true)); + ``` + +* Feature / BC break: The `CompositeStream` starts closed if either side is + already closed and forwards pause to pipe source on first write attempt. + (#96 and #103 by @clue) + + If either side of the composite stream closes, it will also close the other + side. We now also ensure that if either side is already closed during + instantiation, it will also close the other side. + +* BC break: Mark all classes as `final` and + mark internal API as `private` to discourage inheritance + (#95 and #99 by @clue) + +* Feature / BC break: Only emit `error` event for fatal errors + (#92 by @clue) + + > The `error` event was previously also allowed to be emitted for non-fatal + errors, but our implementations actually only ever emitted this as a fatal + error and then closed the stream. + +* Feature: Explicitly allow custom events and exclude any semantics + (#97 by @clue) + +* Strict definition for event callback functions + (#101 by @clue) + +* Support legacy PHP 5.3 through PHP 7.1 and HHVM and improve usage documentation + (#100 and #102 by @clue) + +* Actually require all dependencies so this is self-contained and improve + forward compatibility with EventLoop v1.0 and v0.5 + (#94 and #98 by @clue) + +## 0.6.0 (2017-03-26) + +* Feature / Fix / BC break: Add `DuplexResourceStream` and deprecate `Stream` + (#85 by @clue) + + ```php + // old (does still work for BC reasons) + $stream = new Stream($connection, $loop); + + // new + $stream = new DuplexResourceStream($connection, $loop); + ``` + + Note that the `DuplexResourceStream` now rejects read-only or write-only + streams, so this may affect BC. If you want a read-only or write-only + resource, use `ReadableResourceStream` or `WritableResourceStream` instead of + `DuplexResourceStream`. + + > BC note: This class was previously called `Stream`. The `Stream` class still + exists for BC reasons and will be removed in future versions of this package. + +* Feature / BC break: Add `WritableResourceStream` (previously called `Buffer`) + (#84 by @clue) + + ```php + // old + $stream = new Buffer(STDOUT, $loop); + + // new + $stream = new WritableResourceStream(STDOUT, $loop); + ``` + +* Feature: Add `ReadableResourceStream` + (#83 by @clue) + + ```php + $stream = new ReadableResourceStream(STDIN, $loop); + ``` + +* Fix / BC Break: Enforce using non-blocking I/O + (#46 by @clue) + + > BC note: This is known to affect process pipes on Windows which do not + support non-blocking I/O and could thus block the whole EventLoop previously. + +* Feature / Fix / BC break: Consistent semantics for + `DuplexStreamInterface::end()` to ensure it SHOULD also end readable side + (#86 by @clue) + +* Fix: Do not use unbuffered reads on pipe streams for legacy PHP < 5.4 + (#80 by @clue) + +## 0.5.0 (2017-03-08) + +* Feature / BC break: Consistent `end` event semantics (EOF) + (#70 by @clue) + + The `end` event will now only be emitted for a *successful* end, not if the + stream closes due to an unrecoverable `error` event or if you call `close()` + explicitly. + If you want to detect when the stream closes (terminates), use the `close` + event instead. + +* BC break: Remove custom (undocumented) `full-drain` event from `Buffer` + (#63 and #68 by @clue) + + > The `full-drain` event was undocumented and mostly used internally. + Relying on this event has attracted some low-quality code in the past, so + we've removed this from the public API in order to work out a better + solution instead. + If you want to detect when the buffer finishes flushing data to the stream, + you may want to look into its `end()` method or the `close` event instead. + +* Feature / BC break: Consistent event semantics and documentation, + explicitly state *when* events will be emitted and *which* arguments they + receive. + (#73 and #69 by @clue) + + The documentation now explicitly defines each event and its arguments. + Custom events and event arguments are still supported. + Most notably, all defined events only receive inherently required event + arguments and no longer transmit the instance they are emitted on for + consistency and performance reasons. + + ```php + // old (inconsistent and not supported by all implementations) + $stream->on('data', function ($data, $stream) { + // process $data + }); + + // new (consistent throughout the whole ecosystem) + $stream->on('data', function ($data) use ($stream) { + // process $data + }); + ``` + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature / BC break: Consistent method semantics and documentation + (#72 by @clue) + + > This mostly adds documentation (and thus some stricter, consistent + definitions) for the existing behavior, it does NOT define any major + changes otherwise. + Most existing code should be compatible with these changes, unless + it relied on some undocumented/unintended semantics. + +* Feature: Consistent `pipe()` semantics for closed and closing streams + (#71 from @clue) + + The source stream will now always be paused via `pause()` when the + destination stream closes. Also, properly stop piping if the source + stream closes and remove all event forwarding. + +* Improve test suite by adding PHPUnit to `require-dev` and improving coverage. + (#74 and #75 by @clue, #66 by @nawarian) + +## 0.4.6 (2017-01-25) + +* Feature: The `Buffer` can now be injected into the `Stream` (or be used standalone) + (#62 by @clue) + +* Fix: Forward `close` event only once for `CompositeStream` and `ThroughStream` + (#60 by @clue) + +* Fix: Consistent `close` event behavior for `Buffer` + (#61 by @clue) + +## 0.4.5 (2016-11-13) + +* Feature: Support setting read buffer size to `null` (infinite) + (#42 by @clue) + +* Fix: Do not emit `full-drain` event if `Buffer` is closed during `drain` event + (#55 by @clue) + +* Vastly improved performance by factor of 10x to 20x. + Raise default buffer sizes to 64 KiB and simplify and improve error handling + and unneeded function calls. + (#53, #55, #56 by @clue) + +## 0.4.4 (2016-08-22) + +* Bug fix: Emit `error` event and close `Stream` when accessing the underlying + stream resource fails with a permanent error. + (#52 and #40 by @clue, #25 by @lysenkobv) + +* Bug fix: Do not emit empty `data` event if nothing has been read (stream reached EOF) + (#39 by @clue) + +* Bug fix: Ignore empty writes to `Buffer` + (#51 by @clue) + +* Add benchmarking script to measure throughput in CI + (#41 by @clue) + +## 0.4.3 (2015-10-07) + +* Bug fix: Read buffer to 0 fixes error with libevent and large quantity of I/O (@mbonneau) +* Bug fix: No double-write during drain call (@arnaud-lb) +* Bug fix: Support HHVM (@clue) +* Adjust compatibility to 5.3 (@clue) + +## 0.4.2 (2014-09-09) + +* Added DuplexStreamInterface +* Stream sets stream resources to non-blocking +* Fixed potential race condition in pipe + +## 0.4.1 (2014-04-13) + +* Bug fix: v0.3.4 changes merged for v0.4.1 + +## 0.3.4 (2014-03-30) + +* Bug fix: [Stream] Fixed 100% CPU spike from non-empty write buffer on closed stream + +## 0.4.0 (2014-02-02) + +* BC break: Bump minimum PHP version to PHP 5.4, remove 5.3 specific hacks +* BC break: Update to Evenement 2.0 +* Dependency: Autoloading and filesystem structure now PSR-4 instead of PSR-0 + +## 0.3.3 (2013-07-08) + +* Bug fix: [Stream] Correctly detect closed connections + +## 0.3.2 (2013-05-10) + +* Bug fix: [Stream] Make sure CompositeStream is closed properly + +## 0.3.1 (2013-04-21) + +* Bug fix: [Stream] Allow any `ReadableStreamInterface` on `BufferedSink::createPromise()` + +## 0.3.0 (2013-04-14) + +* Feature: [Stream] Factory method for BufferedSink + +## 0.2.6 (2012-12-26) + +* Version bump + +## 0.2.5 (2012-11-26) + +* Feature: Make BufferedSink trigger progress events on the promise (@jsor) + +## 0.2.4 (2012-11-18) + +* Feature: Added ThroughStream, CompositeStream, ReadableStream and WritableStream +* Feature: Added BufferedSink + +## 0.2.3 (2012-11-14) + +* Version bump + +## 0.2.2 (2012-10-28) + +* Version bump + +## 0.2.1 (2012-10-14) + +* Bug fix: Check for EOF in `Buffer::write()` + +## 0.2.0 (2012-09-10) + +* Version bump + +## 0.1.1 (2012-07-12) + +* Bug fix: Testing and functional against PHP >= 5.3.3 and <= 5.3.8 + +## 0.1.0 (2012-07-11) + +* First tagged release diff --git a/vendor/react/stream/LICENSE b/vendor/react/stream/LICENSE new file mode 100644 index 00000000000..d6f8901f9ad --- /dev/null +++ b/vendor/react/stream/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 Christian Lück, Cees-Jan Kiewiet, Jan Sorgalla, Chris Boden, Igor Wiedler + +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. diff --git a/vendor/react/stream/README.md b/vendor/react/stream/README.md new file mode 100644 index 00000000000..2bfcbbe8c28 --- /dev/null +++ b/vendor/react/stream/README.md @@ -0,0 +1,1249 @@ +# Stream + +[![CI status](https://github.com/reactphp/stream/actions/workflows/ci.yml/badge.svg)](https://github.com/reactphp/stream/actions) +[![installs on Packagist](https://img.shields.io/packagist/dt/react/stream?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/react/stream) + +Event-driven readable and writable streams for non-blocking I/O in [ReactPHP](https://reactphp.org/). + +In order to make the [EventLoop](https://github.com/reactphp/event-loop) +easier to use, this component introduces the powerful concept of "streams". +Streams allow you to efficiently process huge amounts of data (such as a multi +Gigabyte file download) in small chunks without having to store everything in +memory at once. +They are very similar to the streams found in PHP itself, +but have an interface more suited for async, non-blocking I/O. + +**Table of contents** + +* [Stream usage](#stream-usage) + * [ReadableStreamInterface](#readablestreaminterface) + * [data event](#data-event) + * [end event](#end-event) + * [error event](#error-event) + * [close event](#close-event) + * [isReadable()](#isreadable) + * [pause()](#pause) + * [resume()](#resume) + * [pipe()](#pipe) + * [close()](#close) + * [WritableStreamInterface](#writablestreaminterface) + * [drain event](#drain-event) + * [pipe event](#pipe-event) + * [error event](#error-event-1) + * [close event](#close-event-1) + * [isWritable()](#iswritable) + * [write()](#write) + * [end()](#end) + * [close()](#close-1) + * [DuplexStreamInterface](#duplexstreaminterface) +* [Creating streams](#creating-streams) + * [ReadableResourceStream](#readableresourcestream) + * [WritableResourceStream](#writableresourcestream) + * [DuplexResourceStream](#duplexresourcestream) + * [ThroughStream](#throughstream) + * [CompositeStream](#compositestream) +* [Usage](#usage) +* [Install](#install) +* [Tests](#tests) +* [License](#license) +* [More](#more) + +## Stream usage + +ReactPHP uses the concept of "streams" throughout its ecosystem to provide a +consistent higher-level abstraction for processing streams of arbitrary data +contents and size. +While a stream itself is a quite low-level concept, it can be used as a powerful +abstraction to build higher-level components and protocols on top. + +If you're new to this concept, it helps to think of them as a water pipe: +You can consume water from a source or you can produce water and forward (pipe) +it to any destination (sink). + +Similarly, streams can either be + +* readable (such as `STDIN` terminal input) or +* writable (such as `STDOUT` terminal output) or +* duplex (both readable *and* writable, such as a TCP/IP connection) + +Accordingly, this package defines the following three interfaces + +* [`ReadableStreamInterface`](#readablestreaminterface) +* [`WritableStreamInterface`](#writablestreaminterface) +* [`DuplexStreamInterface`](#duplexstreaminterface) + +### ReadableStreamInterface + +The `ReadableStreamInterface` is responsible for providing an interface for +read-only streams and the readable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### data event + +The `data` event will be emitted whenever some data was read/received +from this source stream. +The event receives a single mixed argument for incoming data. + +```php +$stream->on('data', function ($data) { + echo $data; +}); +``` + +This event MAY be emitted any number of times, which may be zero times if +this stream does not send any data at all. +It SHOULD not be emitted after an `end` or `close` event. + +The given `$data` argument may be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit the raw (binary) payload data that is received over the wire as +chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end event + +The `end` event will be emitted once the source stream has successfully +reached the end of the stream (EOF). + +```php +$stream->on('end', function () { + echo 'END'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +a successful end was detected. +It SHOULD NOT be emitted after a previous `end` or `close` event. +It MUST NOT be emitted if the stream closes due to a non-successful +end, such as after a previous `error` event. + +After the stream is ended, it MUST switch to non-readable mode, +see also `isReadable()`. + +This event will only be emitted if the *end* was reached successfully, +not if the stream was interrupted by an unrecoverable error or explicitly +closed. Not all streams know this concept of a "successful end". +Many use-cases involve detecting when the stream closes (terminates) +instead, in this case you should use the `close` event. +After the stream emits an `end` event, it SHOULD usually be followed by a +`close` event. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will emit this event if either the remote side closes the connection or +a file handle was successfully read until reaching its end (EOF). + +Note that this event should not be confused with the `end()` method. +This event defines a successful end *reading* from a source stream, while +the `end()` method defines *writing* a successful end to a destination +stream. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to read from this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$server->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error or after an unexpected `data` or premature +`end` event. +It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-readable mode, see +also `close()` and `isReadable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and do not make assumption about data +boundaries (such as unexpected `data` or premature `end` events). +In other words, many lower-level protocols (such as TCP/IP) may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-readable mode, +see also `isReadable()`. + +Unlike the `end` event, this event SHOULD be emitted whenever the stream +closes, irrespective of whether this happens implicitly due to an +unrecoverable error or explicitly when either side closes the stream. +If you only want to detect a *successful* end, you should use the `end` +event instead. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after reading a *successful* `end` +event or after a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this event should not be confused with the `end` event. + +#### isReadable() + +The `isReadable(): bool` method can be used to +check whether this stream is in a readable state (not closed already). + +This method can be used to check if the stream still accepts incoming +data events or if it is ended or closed already. +Once the stream is non-readable, no further `data` or `end` events SHOULD +be emitted. + +```php +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +A successfully opened stream always MUST start in readable mode. + +Once the stream ends or closes, it MUST switch to non-readable mode. +This can happen any time, explicitly through `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-readable mode, it MUST NOT transition +back to readable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements an `isWritable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### pause() + +The `pause(): void` method can be used to +pause reading incoming data events. + +Removes the data source file descriptor from the event loop. This +allows you to throttle incoming data. + +Unless otherwise noted, a successfully opened stream SHOULD NOT start +in paused state. + +Once the stream is paused, no futher `data` or `end` events SHOULD +be emitted. + +```php +$stream->pause(); + +$stream->on('data', assertShouldNeverCalled()); +$stream->on('end', assertShouldNeverCalled()); +``` + +This method is advisory-only, though generally not recommended, the +stream MAY continue emitting `data` events. + +You can continue processing events by calling `resume()` again. + +Note that both methods can be called any number of times, in particular +calling `pause()` more than once SHOULD NOT have any effect. + +See also `resume()`. + +#### resume() + +The `resume(): void` method can be used to +resume reading incoming data events. + +Re-attach the data source after a previous `pause()`. + +```php +$stream->pause(); + +Loop::addTimer(1.0, function () use ($stream) { + $stream->resume(); +}); +``` + +Note that both methods can be called any number of times, in particular +calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + +See also `pause()`. + +#### pipe() + +The `pipe(WritableStreamInterface $dest, array $options = [])` method can be used to +pipe all the data from this readable source into the given writable destination. + +Automatically sends all incoming data to the destination. +Automatically throttles the source based on what the destination can handle. + +```php +$source->pipe($dest); +``` + +Similarly, you can also pipe an instance implementing `DuplexStreamInterface` +into itself in order to write back all the data that is received. +This may be a useful feature for a TCP/IP echo service: + +```php +$connection->pipe($connection); +``` + +This method returns the destination stream as-is, which can be used to +set up chains of piped streams: + +```php +$source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); +``` + +By default, this will call `end()` on the destination stream once the +source stream emits an `end` event. This can be disabled like this: + +```php +$source->pipe($dest, array('end' => false)); +``` + +Note that this only applies to the `end` event. +If an `error` or explicit `close` event happens on the source stream, +you'll have to manually close the destination stream: + +```php +$source->pipe($dest); +$source->on('close', function () use ($dest) { + $dest->end('BYE!'); +}); +``` + +If the source stream is not readable (closed state), then this is a NO-OP. + +```php +$source->close(); +$source->pipe($dest); // NO-OP +``` + +If the destinantion stream is not writable (closed state), then this will simply +throttle (pause) the source stream: + +```php +$dest->close(); +$source->pipe($dest); // calls $source->pause() +``` + +Similarly, if the destination stream is closed while the pipe is still +active, it will also throttle (pause) the source stream: + +```php +$source->pipe($dest); +$dest->close(); // calls $source->pause() +``` + +Once the pipe is set up successfully, the destination stream MUST emit +a `pipe` event with this source stream an event argument. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to (forcefully) close the stream. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-readable +mode, see also `isReadable()`. +This means that no further `data` or `end` events SHOULD be emitted. + +```php +$stream->close(); +assert($stream->isReadable() === false); + +$stream->on('data', assertNeverCalled()); +$stream->on('end', assertNeverCalled()); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the writable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isWritable()`. +Note that this method should not be confused with the `end()` method. + +### WritableStreamInterface + +The `WritableStreamInterface` is responsible for providing an interface for +write-only streams and the writable side of duplex streams. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to certain events. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +#### drain event + +The `drain` event will be emitted whenever the write buffer became full +previously and is now ready to accept more data. + +```php +$stream->on('drain', function () use ($stream) { + echo 'Stream is now ready to accept more data'; +}); +``` + +This event SHOULD be emitted once every time the buffer became full +previously and is now ready to accept more data. +In other words, this event MAY be emitted any number of times, which may +be zero times if the buffer never became full in the first place. +This event SHOULD NOT be emitted if the buffer has not become full +previously. + +This event is mostly used internally, see also `write()` for more details. + +#### pipe event + +The `pipe` event will be emitted whenever a readable stream is `pipe()`d +into this stream. +The event receives a single `ReadableStreamInterface` argument for the +source stream. + +```php +$stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + echo 'Now receiving piped data'; + + // explicitly close target if source emits an error + $source->on('error', function () use ($stream) { + $stream->close(); + }); +}); + +$source->pipe($stream); +``` + +This event MUST be emitted once for each readable stream that is +successfully piped into this destination stream. +In other words, this event MAY be emitted any number of times, which may +be zero times if no stream is ever piped into this stream. +This event MUST NOT be emitted if either the source is not readable +(closed already) or this destination is not writable (closed already). + +This event is mostly used internally, see also `pipe()` for more details. + +#### error event + +The `error` event will be emitted once a fatal error occurs, usually while +trying to write to this stream. +The event receives a single `Exception` argument for the error instance. + +```php +$stream->on('error', function (Exception $e) { + echo 'Error: ' . $e->getMessage() . PHP_EOL; +}); +``` + +This event SHOULD be emitted once the stream detects a fatal error, such +as a fatal transmission error. +It SHOULD NOT be emitted after a previous `error` or `close` event. +It MUST NOT be emitted if this is not a fatal error condition, such as +a temporary network issue that did not cause any data to be lost. + +After the stream errors, it MUST close the stream and SHOULD thus be +followed by a `close` event and then switch to non-writable mode, see +also `close()` and `isWritable()`. + +Many common streams (such as a TCP/IP connection or a file-based stream) +only deal with data transmission and may choose +to only emit this for a fatal transmission error once and will then +close (terminate) the stream in response. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `error` event. +In other words, an error may occur while either reading or writing the +stream which should result in the same error processing. + +#### close event + +The `close` event will be emitted once the stream closes (terminates). + +```php +$stream->on('close', function () { + echo 'CLOSED'; +}); +``` + +This event SHOULD be emitted once or never at all, depending on whether +the stream ever terminates. +It SHOULD NOT be emitted after a previous `close` event. + +After the stream is closed, it MUST switch to non-writable mode, +see also `isWritable()`. + +This event SHOULD be emitted whenever the stream closes, irrespective of +whether this happens implicitly due to an unrecoverable error or +explicitly when either side closes the stream. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will likely choose to emit this event after flushing the buffer from +the `end()` method, after receiving a *successful* `end` event or after +a fatal transmission `error` event. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close` event. +In other words, after receiving this event, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. +Note that this event should not be confused with the `end` event. + +#### isWritable() + +The `isWritable(): bool` method can be used to +check whether this stream is in a writable state (not closed already). + +This method can be used to check if the stream still accepts writing +any data or if it is ended or closed already. +Writing any data to a non-writable stream is a NO-OP: + +```php +assert($stream->isWritable() === false); + +$stream->write('end'); // NO-OP +$stream->end('end'); // NO-OP +``` + +A successfully opened stream always MUST start in writable mode. + +Once the stream ends or closes, it MUST switch to non-writable mode. +This can happen any time, explicitly through `end()` or `close()` or +implicitly due to a remote close or an unrecoverable transmission error. +Once a stream has switched to non-writable mode, it MUST NOT transition +back to writable mode. + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements an `isReadable()` +method. Unless this is a half-open duplex stream, they SHOULD usually +have the same return value. + +#### write() + +The `write(mixed $data): bool` method can be used to +write some data into the stream. + +A successful write MUST be confirmed with a boolean `true`, which means +that either the data was written (flushed) immediately or is buffered and +scheduled for a future write. Note that this interface gives you no +control over explicitly flushing the buffered data, as finding the +appropriate time for this is beyond the scope of this interface and left +up to the implementation of this interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +If a stream cannot handle writing (or flushing) the data, it SHOULD emit +an `error` event and MAY `close()` the stream if it can not recover from +this error. + +If the internal buffer is full after adding `$data`, then `write()` +SHOULD return `false`, indicating that the caller should stop sending +data until the buffer drains. +The stream SHOULD send a `drain` event once the buffer is ready to accept +more data. + +Similarly, if the stream is not writable (already in a closed state) +it MUST NOT process the given `$data` and SHOULD return `false`, +indicating that the caller should stop sending data. + +The given `$data` argument MAY be of mixed type, but it's usually +recommended it SHOULD be a `string` value or MAY use a type that allows +representation as a `string` for maximum compatibility. + +Many common streams (such as a TCP/IP connection or a file-based stream) +will only accept the raw (binary) payload data that is transferred over +the wire as chunks of `string` values. + +Due to the stream-based nature of this, the sender may send any number +of chunks with varying sizes. There are no guarantees that these chunks +will be received with the exact same framing the sender intended to send. +In other words, many lower-level protocols (such as TCP/IP) transfer the +data in chunks that may be anywhere between single-byte values to several +dozens of kilobytes. You may want to apply a higher-level protocol to +these low-level data chunks in order to achieve proper message framing. + +#### end() + +The `end(mixed $data = null): void` method can be used to +successfully end the stream (after optionally sending some final data). + +This method can be used to successfully end the stream, i.e. close +the stream after sending out all data that is currently buffered. + +```php +$stream->write('hello'); +$stream->write('world'); +$stream->end(); +``` + +If there's no data currently buffered and nothing to be flushed, then +this method MAY `close()` the stream immediately. + +If there's still data in the buffer that needs to be flushed first, then +this method SHOULD try to write out this data and only then `close()` +the stream. +Once the stream is closed, it SHOULD emit a `close` event. + +Note that this interface gives you no control over explicitly flushing +the buffered data, as finding the appropriate time for this is beyond the +scope of this interface and left up to the implementation of this +interface. + +Many common streams (such as a TCP/IP connection or file-based stream) +may choose to buffer all given data and schedule a future flush by using +an underlying EventLoop to check when the resource is actually writable. + +You can optionally pass some final data that is written to the stream +before ending the stream. If a non-`null` value is given as `$data`, then +this method will behave just like calling `write($data)` before ending +with no data. + +```php +// shorter version +$stream->end('bye'); + +// same as longer version +$stream->write('bye'); +$stream->end(); +``` + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->end(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +If this stream is a `DuplexStreamInterface`, calling this method SHOULD +also end its readable side, unless the stream supports half-open mode. +In other words, after calling this method, these streams SHOULD switch +into non-writable AND non-readable mode, see also `isReadable()`. +This implies that in this case, the stream SHOULD NOT emit any `data` +or `end` events anymore. +Streams MAY choose to use the `pause()` method logic for this, but +special care may have to be taken to ensure a following call to the +`resume()` method SHOULD NOT continue emitting readable events. + +Note that this method should not be confused with the `close()` method. + +#### close() + +The `close(): void` method can be used to +close the stream (forcefully). + +This method can be used to forcefully close the stream, i.e. close +the stream without waiting for any buffered data to be flushed. +If there's still data in the buffer, this data SHOULD be discarded. + +```php +$stream->close(); +``` + +Once the stream is closed, it SHOULD emit a `close` event. +Note that this event SHOULD NOT be emitted more than once, in particular +if this method is called multiple times. + +After calling this method, the stream MUST switch into a non-writable +mode, see also `isWritable()`. +This means that no further writes are possible, so any additional +`write()` or `end()` calls have no effect. + +```php +$stream->close(); +assert($stream->isWritable() === false); + +$stream->write('nope'); // NO-OP +$stream->end(); // NO-OP +``` + +Note that this method should not be confused with the `end()` method. +Unlike the `end()` method, this method does not take care of any existing +buffers and simply discards any buffer contents. +Likewise, this method may also be called after calling `end()` on a +stream in order to stop waiting for the stream to flush its final data. + +```php +$stream->end(); +Loop::addTimer(1.0, function () use ($stream) { + $stream->close(); +}); +``` + +If this stream is a `DuplexStreamInterface`, you should also notice +how the readable side of the stream also implements a `close()` method. +In other words, after calling this method, the stream MUST switch into +non-writable AND non-readable mode, see also `isReadable()`. + +### DuplexStreamInterface + +The `DuplexStreamInterface` is responsible for providing an interface for +duplex streams (both readable and writable). + +It builds on top of the existing interfaces for readable and writable streams +and follows the exact same method and event semantics. +If you're new to this concept, you should look into the +`ReadableStreamInterface` and `WritableStreamInterface` first. + +Besides defining a few methods, this interface also implements the +`EventEmitterInterface` which allows you to react to the same events defined +on the `ReadbleStreamInterface` and `WritableStreamInterface`. + +The event callback functions MUST be a valid `callable` that obeys strict +parameter definitions and MUST accept event parameters exactly as documented. +The event callback functions MUST NOT throw an `Exception`. +The return value of the event callback functions will be ignored and has no +effect, so for performance reasons you're recommended to not return any +excessive data structures. + +Every implementation of this interface MUST follow these event semantics in +order to be considered a well-behaving stream. + +> Note that higher-level implementations of this interface may choose to + define additional events with dedicated semantics not defined as part of + this low-level stream specification. Conformance with these event semantics + is out of scope for this interface, so you may also have to refer to the + documentation of such a higher-level implementation. + +See also [`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) for more details. + +## Creating streams + +ReactPHP uses the concept of "streams" throughout its ecosystem, so that +many higher-level consumers of this package only deal with +[stream usage](#stream-usage). +This implies that stream instances are most often created within some +higher-level components and many consumers never actually have to deal with +creating a stream instance. + +* Use [react/socket](https://github.com/reactphp/socket) + if you want to accept incoming or establish outgoing plaintext TCP/IP or + secure TLS socket connection streams. +* Use [react/http](https://github.com/reactphp/http) + if you want to receive an incoming HTTP request body streams. +* Use [react/child-process](https://github.com/reactphp/child-process) + if you want to communicate with child processes via process pipes such as + STDIN, STDOUT, STDERR etc. +* Use experimental [react/filesystem](https://github.com/reactphp/filesystem) + if you want to read from / write to the filesystem. +* See also the last chapter for [more real-world applications](#more). + +However, if you are writing a lower-level component or want to create a stream +instance from a stream resource, then the following chapter is for you. + +> Note that the following examples use `fopen()` and `stream_socket_client()` + for illustration purposes only. + These functions SHOULD NOT be used in a truly async program because each call + may take several seconds to complete and would block the EventLoop otherwise. + Additionally, the `fopen()` call will return a file handle on some platforms + which may or may not be supported by all EventLoop implementations. + As an alternative, you may want to use higher-level libraries listed above. + +### ReadableResourceStream + +The `ReadableResourceStream` is a concrete implementation of the +[`ReadableStreamInterface`](#readablestreaminterface) for PHP's stream resources. + +This can be used to represent a read-only resource like a file stream opened in +readable mode or a stream such as `STDIN`: + +```php +$stream = new ReadableResourceStream(STDIN); +$stream->on('data', function ($chunk) { + echo $chunk; +}); +$stream->on('end', function () { + echo 'END'; +}); +``` + +See also [`ReadableStreamInterface`](#readablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened in reading mode (e.g. `fopen()` mode `r`). +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new ReadableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDIN etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new ReadableResourceStream(STDIN); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$stream = new ReadableResourceStream(STDIN, null, 8192); +``` + +> PHP bug warning: If the PHP process has explicitly been started without a + `STDIN` stream, then trying to read from `STDIN` may return data from + another stream resource. This does not happen if you start this with an empty + stream like `php test.php < /dev/null` instead of `php test.php <&-`. + See [#81](https://github.com/reactphp/stream/issues/81) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### WritableResourceStream + +The `WritableResourceStream` is a concrete implementation of the +[`WritableStreamInterface`](#writablestreaminterface) for PHP's stream resources. + +This can be used to represent a write-only resource like a file stream opened in +writable mode or a stream such as `STDOUT` or `STDERR`: + +```php +$stream = new WritableResourceStream(STDOUT); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`WritableStreamInterface`](#writablestreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new WritableResourceStream(false); +``` + +See also the [`DuplexResourceStream`](#readableresourcestream) for read-and-write +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new WritableResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $writeBufferSoftLimit` parameter that controls +this maximum buffer size in bytes. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +```php +$stream = new WritableResourceStream(STDOUT, null, 8192); +``` + +This class takes an optional `int|null $writeChunkSize` parameter that controls +this maximum buffer size in bytes to write at once to the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be written +at once to the underlying stream resource. Note that the actual number +of bytes written may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "write everything available" to the +underlying stream resource. + +```php +$stream = new WritableResourceStream(STDOUT, null, null, 8192); +``` + +See also [`write()`](#write) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### DuplexResourceStream + +The `DuplexResourceStream` is a concrete implementation of the +[`DuplexStreamInterface`](#duplexstreaminterface) for PHP's stream resources. + +This can be used to represent a read-and-write resource like a file stream opened +in read and write mode mode or a stream such as a TCP/IP connection: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn); +$stream->write('hello!'); +$stream->end(); +``` + +See also [`DuplexStreamInterface`](#duplexstreaminterface) for more details. + +The first parameter given to the constructor MUST be a valid stream resource +that is opened for reading *and* writing. +Otherwise, it will throw an `InvalidArgumentException`: + +```php +// throws InvalidArgumentException +$stream = new DuplexResourceStream(false); +``` + +See also the [`ReadableResourceStream`](#readableresourcestream) for read-only +and the [`WritableResourceStream`](#writableresourcestream) for write-only +stream resources otherwise. + +Internally, this class tries to enable non-blocking mode on the stream resource +which may not be supported for all stream resources. +Most notably, this is not supported by pipes on Windows (STDOUT, STDERR etc.). +If this fails, it will throw a `RuntimeException`: + +```php +// throws RuntimeException on Windows +$stream = new DuplexResourceStream(STDOUT); +``` + +Once the constructor is called with a valid stream resource, this class will +take care of the underlying stream resource. +You SHOULD only use its public API and SHOULD NOT interfere with the underlying +stream resource manually. + +This class takes an optional `LoopInterface|null $loop` parameter that can be used to +pass the event loop instance to use for this object. You can use a `null` value +here in order to use the [default loop](https://github.com/reactphp/event-loop#loop). +This value SHOULD NOT be given unless you're sure you want to explicitly use a +given event loop instance. + +This class takes an optional `int|null $readChunkSize` parameter that controls +the maximum buffer size in bytes to read at once from the stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. +This can be a positive number which means that up to X bytes will be read +at once from the underlying stream resource. Note that the actual number +of bytes read may be lower if the stream resource has less than X bytes +currently available. +This can be `-1` which means "read everything available" from the +underlying stream resource. +This should read until the stream resource is not readable anymore +(i.e. underlying buffer drained), note that this does not neccessarily +mean it reached EOF. + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$stream = new DuplexResourceStream($conn, null, 8192); +``` + +Any `write()` calls to this class will not be performed instantly, but will +be performed asynchronously, once the EventLoop reports the stream resource is +ready to accept data. +For this, it uses an in-memory buffer string to collect all outstanding writes. +This buffer has a soft-limit applied which defines how much data it is willing +to accept before the caller SHOULD stop sending further data. + +This class takes another optional `WritableStreamInterface|null $buffer` parameter +that controls this write behavior of this stream. +You can use a `null` value here in order to apply its default value. +This value SHOULD NOT be changed unless you know what you're doing. + +If you want to change the write buffer soft limit, you can pass an instance of +[`WritableResourceStream`](#writableresourcestream) like this: + +```php +$conn = stream_socket_client('tcp://google.com:80'); +$buffer = new WritableResourceStream($conn, null, 8192); +$stream = new DuplexResourceStream($conn, null, null, $buffer); +``` + +See also [`WritableResourceStream`](#writableresourcestream) for more details. + +> Changelog: As of v1.2.0 the `$loop` parameter can be omitted (or skipped with a + `null` value) to use the [default loop](https://github.com/reactphp/event-loop#loop). + +### ThroughStream + +The `ThroughStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and will simply pass any data +you write to it through to its readable end. + +```php +$through = new ThroughStream(); +$through->on('data', $this->expectCallableOnceWith('hello')); + +$through->write('hello'); +``` + +Similarly, the [`end()` method](#end) will end the stream and emit an +[`end` event](#end-event) and then [`close()`](#close-1) the stream. +The [`close()` method](#close-1) will close the stream and emit a +[`close` event](#close-event). +Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + +```php +$through = new ThroughStream(); +$source->pipe($through)->pipe($dest); +``` + +Optionally, its constructor accepts any callable function which will then be +used to *filter* any data written to it. This function receives a single data +argument as passed to the writable side and must return the data as it will be +passed to its readable end: + +```php +$through = new ThroughStream('strtoupper'); +$source->pipe($through)->pipe($dest); +``` + +Note that this class makes no assumptions about any data types. This can be +used to convert data, for example for transforming any structured data into +a newline-delimited JSON (NDJSON) stream like this: + +```php +$through = new ThroughStream(function ($data) { + return json_encode($data) . PHP_EOL; +}); +$through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + +$through->write(array(2, true)); +``` + +The callback function is allowed to throw an `Exception`. In this case, +the stream will emit an `error` event and then [`close()`](#close-1) the stream. + +```php +$through = new ThroughStream(function ($data) { + if (!is_string($data)) { + throw new \UnexpectedValueException('Only strings allowed'); + } + return $data; +}); +$through->on('error', $this->expectCallableOnce())); +$through->on('close', $this->expectCallableOnce())); +$through->on('data', $this->expectCallableNever())); + +$through->write(2); +``` + +### CompositeStream + +The `CompositeStream` implements the +[`DuplexStreamInterface`](#duplexstreaminterface) and can be used to create a +single duplex stream from two individual streams implementing +[`ReadableStreamInterface`](#readablestreaminterface) and +[`WritableStreamInterface`](#writablestreaminterface) respectively. + +This is useful for some APIs which may require a single +[`DuplexStreamInterface`](#duplexstreaminterface) or simply because it's often +more convenient to work with a single stream instance like this: + +```php +$stdin = new ReadableResourceStream(STDIN); +$stdout = new WritableResourceStream(STDOUT); + +$stdio = new CompositeStream($stdin, $stdout); + +$stdio->on('data', function ($chunk) use ($stdio) { + $stdio->write('You said: ' . $chunk); +}); +``` + +This is a well-behaving stream which forwards all stream events from the +underlying streams and forwards all streams calls to the underlying streams. + +If you `write()` to the duplex stream, it will simply `write()` to the +writable side and return its status. + +If you `end()` the duplex stream, it will `end()` the writable side and will +`pause()` the readable side. + +If you `close()` the duplex stream, both input streams will be closed. +If either of the two input streams emits a `close` event, the duplex stream +will also close. +If either of the two input streams is already closed while constructing the +duplex stream, it will `close()` the other side and return a closed stream. + +## Usage + +The following example can be used to pipe the contents of a source file into +a destination file without having to ever read the whole file into memory: + +```php +$source = new React\Stream\ReadableResourceStream(fopen('source.txt', 'r')); +$dest = new React\Stream\WritableResourceStream(fopen('destination.txt', 'w')); + +$source->pipe($dest); +``` + +> Note that this example uses `fopen()` for illustration purposes only. + This should not be used in a truly async program because the filesystem is + inherently blocking and each call could potentially take several seconds. + See also [creating streams](#creating-streams) for more sophisticated + examples. + +## Install + +The recommended way to install this library is [through Composer](https://getcomposer.org). +[New to Composer?](https://getcomposer.org/doc/00-intro.md) + +This project follows [SemVer](https://semver.org/). +This will install the latest supported version: + +```bash +composer require react/stream:^1.3 +``` + +See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades. + +This project aims to run on any platform and thus does not require any PHP +extensions and supports running on legacy PHP 5.3 through current PHP 8+ and HHVM. +It's *highly recommended to use PHP 7+* for this project due to its vast +performance improvements. + +## Tests + +To run the test suite, you first need to clone this repo and then install all +dependencies [through Composer](https://getcomposer.org): + +```bash +composer install +``` + +To run the test suite, go to the project root and run: + +```bash +vendor/bin/phpunit +``` + +The test suite also contains a number of functional integration tests that rely +on a stable internet connection. +If you do not want to run these, they can simply be skipped like this: + +```bash +vendor/bin/phpunit --exclude-group internet +``` + +## License + +MIT, see [LICENSE file](LICENSE). + +## More + +* See [creating streams](#creating-streams) for more information on how streams + are created in real-world applications. +* See our [users wiki](https://github.com/reactphp/react/wiki/Users) and the + [dependents on Packagist](https://packagist.org/packages/react/stream/dependents) + for a list of packages that use streams in real-world applications. diff --git a/vendor/react/stream/composer.json b/vendor/react/stream/composer.json new file mode 100644 index 00000000000..ee785309e1a --- /dev/null +++ b/vendor/react/stream/composer.json @@ -0,0 +1,56 @@ +{ + "name": "react\/stream", + "description": "Event-driven readable and writable streams for non-blocking I\/O in ReactPHP", + "keywords": [ + "event-driven", + "readable", + "writable", + "stream", + "non-blocking", + "io", + "pipe", + "ReactPHP" + ], + "license": "MIT", + "authors": [ + { + "name": "Christian L\u00fcck", + "homepage": "https:\/\/clue.engineering\/", + "email": "christian@clue.engineering" + }, + { + "name": "Cees-Jan Kiewiet", + "homepage": "https:\/\/wyrihaximus.net\/", + "email": "reactphp@ceesjankiewiet.nl" + }, + { + "name": "Jan Sorgalla", + "homepage": "https:\/\/sorgalla.com\/", + "email": "jsorgalla@gmail.com" + }, + { + "name": "Chris Boden", + "homepage": "https:\/\/cboden.dev\/", + "email": "cboden@gmail.com" + } + ], + "require": { + "php": ">=5.3.8", + "react\/event-loop": "^1.2", + "evenement\/evenement": "^3.0 || ^2.0 || ^1.0" + }, + "require-dev": { + "phpunit\/phpunit": "^9.5 || ^5.7 || ^4.8.35", + "clue\/stream-filter": "~1.2" + }, + "autoload": { + "psr-4": { + "ECSPrefix202307\\React\\Stream\\": "src\/" + } + }, + "autoload-dev": { + "psr-4": { + "ECSPrefix202307\\React\\Tests\\Stream\\": "tests\/" + } + } +} \ No newline at end of file diff --git a/vendor/react/stream/src/CompositeStream.php b/vendor/react/stream/src/CompositeStream.php new file mode 100644 index 00000000000..06481a853a5 --- /dev/null +++ b/vendor/react/stream/src/CompositeStream.php @@ -0,0 +1,67 @@ +readable = $readable; + $this->writable = $writable; + if (!$readable->isReadable() || !$writable->isWritable()) { + $this->close(); + return; + } + Util::forwardEvents($this->readable, $this, array('data', 'end', 'error')); + Util::forwardEvents($this->writable, $this, array('drain', 'error', 'pipe')); + $this->readable->on('close', array($this, 'close')); + $this->writable->on('close', array($this, 'close')); + } + public function isReadable() + { + return $this->readable->isReadable(); + } + public function pause() + { + $this->readable->pause(); + } + public function resume() + { + if (!$this->writable->isWritable()) { + return; + } + $this->readable->resume(); + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + public function isWritable() + { + return $this->writable->isWritable(); + } + public function write($data) + { + return $this->writable->write($data); + } + public function end($data = null) + { + $this->readable->pause(); + $this->writable->end($data); + } + public function close() + { + if ($this->closed) { + return; + } + $this->closed = \true; + $this->readable->close(); + $this->writable->close(); + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/vendor/react/stream/src/DuplexResourceStream.php b/vendor/react/stream/src/DuplexResourceStream.php new file mode 100644 index 00000000000..cc3a7b9b4ac --- /dev/null +++ b/vendor/react/stream/src/DuplexResourceStream.php @@ -0,0 +1,183 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + if ($buffer === null) { + $buffer = new WritableResourceStream($stream, $loop); + } + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = $readChunkSize === null ? 65536 : (int) $readChunkSize; + $this->buffer = $buffer; + $that = $this; + $this->buffer->on('error', function ($error) use($that) { + $that->emit('error', array($error)); + }); + $this->buffer->on('close', array($this, 'close')); + $this->buffer->on('drain', function () use($that) { + $that->emit('drain'); + }); + $this->resume(); + } + public function isReadable() + { + return $this->readable; + } + public function isWritable() + { + return $this->writable; + } + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = \false; + } + } + public function resume() + { + if (!$this->listening && $this->readable) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = \true; + } + } + public function write($data) + { + if (!$this->writable) { + return \false; + } + return $this->buffer->write($data); + } + public function close() + { + if (!$this->writable && !$this->closing) { + return; + } + $this->closing = \false; + $this->readable = \false; + $this->writable = \false; + $this->emit('close'); + $this->pause(); + $this->buffer->close(); + $this->removeAllListeners(); + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + public function end($data = null) + { + if (!$this->writable) { + return; + } + $this->closing = \true; + $this->readable = \false; + $this->writable = \false; + $this->pause(); + $this->buffer->end($data); + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + /** @internal */ + public function handleData($stream) + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use(&$error) { + $error = new \ErrorException($errstr, 0, $errno, $errfile, $errline); + }); + $data = \stream_get_contents($stream, $this->bufferSize); + \restore_error_handler(); + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || \PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512) { + $meta = \stream_get_meta_data($resource); + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return \true; + } + } + return \false; + } +} diff --git a/vendor/react/stream/src/DuplexStreamInterface.php b/vendor/react/stream/src/DuplexStreamInterface.php new file mode 100644 index 00000000000..8c2d567673e --- /dev/null +++ b/vendor/react/stream/src/DuplexStreamInterface.php @@ -0,0 +1,39 @@ + Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see ReadableStreamInterface + * @see WritableStreamInterface + */ +interface DuplexStreamInterface extends ReadableStreamInterface, WritableStreamInterface +{ +} diff --git a/vendor/react/stream/src/ReadableResourceStream.php b/vendor/react/stream/src/ReadableResourceStream.php new file mode 100644 index 00000000000..15ecd6d9633 --- /dev/null +++ b/vendor/react/stream/src/ReadableResourceStream.php @@ -0,0 +1,148 @@ +isLegacyPipe($stream)) { + \stream_set_read_buffer($stream, 0); + } + $this->stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->bufferSize = $readChunkSize === null ? 65536 : (int) $readChunkSize; + $this->resume(); + } + public function isReadable() + { + return !$this->closed; + } + public function pause() + { + if ($this->listening) { + $this->loop->removeReadStream($this->stream); + $this->listening = \false; + } + } + public function resume() + { + if (!$this->listening && !$this->closed) { + $this->loop->addReadStream($this->stream, array($this, 'handleData')); + $this->listening = \true; + } + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + public function close() + { + if ($this->closed) { + return; + } + $this->closed = \true; + $this->emit('close'); + $this->pause(); + $this->removeAllListeners(); + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + /** @internal */ + public function handleData() + { + $error = null; + \set_error_handler(function ($errno, $errstr, $errfile, $errline) use(&$error) { + $error = new \ErrorException($errstr, 0, $errno, $errfile, $errline); + }); + $data = \stream_get_contents($this->stream, $this->bufferSize); + \restore_error_handler(); + if ($error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to read from stream: ' . $error->getMessage(), 0, $error))); + $this->close(); + return; + } + if ($data !== '') { + $this->emit('data', array($data)); + } elseif (\feof($this->stream)) { + // no data read => we reached the end and close the stream + $this->emit('end'); + $this->close(); + } + } + /** + * Returns whether this is a pipe resource in a legacy environment + * + * This works around a legacy PHP bug (#61019) that was fixed in PHP 5.4.28+ + * and PHP 5.5.12+ and newer. + * + * @param resource $resource + * @return bool + * @link https://github.com/reactphp/child-process/issues/40 + * + * @codeCoverageIgnore + */ + private function isLegacyPipe($resource) + { + if (\PHP_VERSION_ID < 50428 || \PHP_VERSION_ID >= 50500 && \PHP_VERSION_ID < 50512) { + $meta = \stream_get_meta_data($resource); + if (isset($meta['stream_type']) && $meta['stream_type'] === 'STDIO') { + return \true; + } + } + return \false; + } +} diff --git a/vendor/react/stream/src/ReadableStreamInterface.php b/vendor/react/stream/src/ReadableStreamInterface.php new file mode 100644 index 00000000000..73799894087 --- /dev/null +++ b/vendor/react/stream/src/ReadableStreamInterface.php @@ -0,0 +1,357 @@ +on('data', function ($data) { + * echo $data; + * }); + * ``` + * + * This event MAY be emitted any number of times, which may be zero times if + * this stream does not send any data at all. + * It SHOULD not be emitted after an `end` or `close` event. + * + * The given `$data` argument may be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit the raw (binary) payload data that is received over the wire as + * chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * end event: + * The `end` event will be emitted once the source stream has successfully + * reached the end of the stream (EOF). + * + * ```php + * $stream->on('end', function () { + * echo 'END'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * a successful end was detected. + * It SHOULD NOT be emitted after a previous `end` or `close` event. + * It MUST NOT be emitted if the stream closes due to a non-successful + * end, such as after a previous `error` event. + * + * After the stream is ended, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * This event will only be emitted if the *end* was reached successfully, + * not if the stream was interrupted by an unrecoverable error or explicitly + * closed. Not all streams know this concept of a "successful end". + * Many use-cases involve detecting when the stream closes (terminates) + * instead, in this case you should use the `close` event. + * After the stream emits an `end` event, it SHOULD usually be followed by a + * `close` event. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will emit this event if either the remote side closes the connection or + * a file handle was successfully read until reaching its end (EOF). + * + * Note that this event should not be confused with the `end()` method. + * This event defines a successful end *reading* from a source stream, while + * the `end()` method defines *writing* a successful end to a destination + * stream. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to read from this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error or after an unexpected `data` or premature + * `end` event. + * It SHOULD NOT be emitted after a previous `error`, `end` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-readable mode, see + * also `close()` and `isReadable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and do not make assumption about data + * boundaries (such as unexpected `data` or premature `end` events). + * In other words, many lower-level protocols (such as TCP/IP) may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-readable mode, + * see also `isReadable()`. + * + * Unlike the `end` event, this event SHOULD be emitted whenever the stream + * closes, irrespective of whether this happens implicitly due to an + * unrecoverable error or explicitly when either side closes the stream. + * If you only want to detect a *successful* end, you should use the `end` + * event instead. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after reading a *successful* `end` + * event or after a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + */ +interface ReadableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a readable state (not closed already). + * + * This method can be used to check if the stream still accepts incoming + * data events or if it is ended or closed already. + * Once the stream is non-readable, no further `data` or `end` events SHOULD + * be emitted. + * + * ```php + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * A successfully opened stream always MUST start in readable mode. + * + * Once the stream ends or closes, it MUST switch to non-readable mode. + * This can happen any time, explicitly through `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-readable mode, it MUST NOT transition + * back to readable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements an `isWritable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isReadable(); + /** + * Pauses reading incoming data events. + * + * Removes the data source file descriptor from the event loop. This + * allows you to throttle incoming data. + * + * Unless otherwise noted, a successfully opened stream SHOULD NOT start + * in paused state. + * + * Once the stream is paused, no futher `data` or `end` events SHOULD + * be emitted. + * + * ```php + * $stream->pause(); + * + * $stream->on('data', assertShouldNeverCalled()); + * $stream->on('end', assertShouldNeverCalled()); + * ``` + * + * This method is advisory-only, though generally not recommended, the + * stream MAY continue emitting `data` events. + * + * You can continue processing events by calling `resume()` again. + * + * Note that both methods can be called any number of times, in particular + * calling `pause()` more than once SHOULD NOT have any effect. + * + * @see self::resume() + * @return void + */ + public function pause(); + /** + * Resumes reading incoming data events. + * + * Re-attach the data source after a previous `pause()`. + * + * ```php + * $stream->pause(); + * + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->resume(); + * }); + * ``` + * + * Note that both methods can be called any number of times, in particular + * calling `resume()` without a prior `pause()` SHOULD NOT have any effect. + * + * @see self::pause() + * @return void + */ + public function resume(); + /** + * Pipes all the data from this readable source into the given writable destination. + * + * Automatically sends all incoming data to the destination. + * Automatically throttles the source based on what the destination can handle. + * + * ```php + * $source->pipe($dest); + * ``` + * + * Similarly, you can also pipe an instance implementing `DuplexStreamInterface` + * into itself in order to write back all the data that is received. + * This may be a useful feature for a TCP/IP echo service: + * + * ```php + * $connection->pipe($connection); + * ``` + * + * This method returns the destination stream as-is, which can be used to + * set up chains of piped streams: + * + * ```php + * $source->pipe($decodeGzip)->pipe($filterBadWords)->pipe($dest); + * ``` + * + * By default, this will call `end()` on the destination stream once the + * source stream emits an `end` event. This can be disabled like this: + * + * ```php + * $source->pipe($dest, array('end' => false)); + * ``` + * + * Note that this only applies to the `end` event. + * If an `error` or explicit `close` event happens on the source stream, + * you'll have to manually close the destination stream: + * + * ```php + * $source->pipe($dest); + * $source->on('close', function () use ($dest) { + * $dest->end('BYE!'); + * }); + * ``` + * + * If the source stream is not readable (closed state), then this is a NO-OP. + * + * ```php + * $source->close(); + * $source->pipe($dest); // NO-OP + * ``` + * + * If the destinantion stream is not writable (closed state), then this will simply + * throttle (pause) the source stream: + * + * ```php + * $dest->close(); + * $source->pipe($dest); // calls $source->pause() + * ``` + * + * Similarly, if the destination stream is closed while the pipe is still + * active, it will also throttle (pause) the source stream: + * + * ```php + * $source->pipe($dest); + * $dest->close(); // calls $source->pause() + * ``` + * + * Once the pipe is set up successfully, the destination stream MUST emit + * a `pipe` event with this source stream an event argument. + * + * @param WritableStreamInterface $dest + * @param array $options + * @return WritableStreamInterface $dest stream as-is + */ + public function pipe(WritableStreamInterface $dest, array $options = array()); + /** + * Closes the stream (forcefully). + * + * This method can be used to (forcefully) close the stream. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-readable + * mode, see also `isReadable()`. + * This means that no further `data` or `end` events SHOULD be emitted. + * + * ```php + * $stream->close(); + * assert($stream->isReadable() === false); + * + * $stream->on('data', assertNeverCalled()); + * $stream->on('end', assertNeverCalled()); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the writable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isWritable()`. + * Note that this method should not be confused with the `end()` method. + * + * @return void + * @see WritableStreamInterface::close() + */ + public function close(); +} diff --git a/vendor/react/stream/src/ThroughStream.php b/vendor/react/stream/src/ThroughStream.php new file mode 100644 index 00000000000..428eab8f46b --- /dev/null +++ b/vendor/react/stream/src/ThroughStream.php @@ -0,0 +1,168 @@ +on('data', $this->expectCallableOnceWith('hello')); + * + * $through->write('hello'); + * ``` + * + * Similarly, the [`end()` method](#end) will end the stream and emit an + * [`end` event](#end-event) and then [`close()`](#close-1) the stream. + * The [`close()` method](#close-1) will close the stream and emit a + * [`close` event](#close-event). + * Accordingly, this is can also be used in a [`pipe()`](#pipe) context like this: + * + * ```php + * $through = new ThroughStream(); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Optionally, its constructor accepts any callable function which will then be + * used to *filter* any data written to it. This function receives a single data + * argument as passed to the writable side and must return the data as it will be + * passed to its readable end: + * + * ```php + * $through = new ThroughStream('strtoupper'); + * $source->pipe($through)->pipe($dest); + * ``` + * + * Note that this class makes no assumptions about any data types. This can be + * used to convert data, for example for transforming any structured data into + * a newline-delimited JSON (NDJSON) stream like this: + * + * ```php + * $through = new ThroughStream(function ($data) { + * return json_encode($data) . PHP_EOL; + * }); + * $through->on('data', $this->expectCallableOnceWith("[2, true]\n")); + * + * $through->write(array(2, true)); + * ``` + * + * The callback function is allowed to throw an `Exception`. In this case, + * the stream will emit an `error` event and then [`close()`](#close-1) the stream. + * + * ```php + * $through = new ThroughStream(function ($data) { + * if (!is_string($data)) { + * throw new \UnexpectedValueException('Only strings allowed'); + * } + * return $data; + * }); + * $through->on('error', $this->expectCallableOnce())); + * $through->on('close', $this->expectCallableOnce())); + * $through->on('data', $this->expectCallableNever())); + * + * $through->write(2); + * ``` + * + * @see WritableStreamInterface::write() + * @see WritableStreamInterface::end() + * @see DuplexStreamInterface::close() + * @see WritableStreamInterface::pipe() + */ +final class ThroughStream extends EventEmitter implements DuplexStreamInterface +{ + private $readable = \true; + private $writable = \true; + private $closed = \false; + private $paused = \false; + private $drain = \false; + private $callback; + public function __construct($callback = null) + { + if ($callback !== null && !\is_callable($callback)) { + throw new InvalidArgumentException('Invalid transformation callback given'); + } + $this->callback = $callback; + } + public function pause() + { + $this->paused = \true; + } + public function resume() + { + if ($this->drain) { + $this->drain = \false; + $this->emit('drain'); + } + $this->paused = \false; + } + public function pipe(WritableStreamInterface $dest, array $options = array()) + { + return Util::pipe($this, $dest, $options); + } + public function isReadable() + { + return $this->readable; + } + public function isWritable() + { + return $this->writable; + } + public function write($data) + { + if (!$this->writable) { + return \false; + } + if ($this->callback !== null) { + try { + $data = \call_user_func($this->callback, $data); + } catch (\Exception $e) { + $this->emit('error', array($e)); + $this->close(); + return \false; + } + } + $this->emit('data', array($data)); + if ($this->paused) { + $this->drain = \true; + return \false; + } + return \true; + } + public function end($data = null) + { + if (!$this->writable) { + return; + } + if (null !== $data) { + $this->write($data); + // return if write() already caused the stream to close + if (!$this->writable) { + return; + } + } + $this->readable = \false; + $this->writable = \false; + $this->paused = \true; + $this->drain = \false; + $this->emit('end'); + $this->close(); + } + public function close() + { + if ($this->closed) { + return; + } + $this->readable = \false; + $this->writable = \false; + $this->closed = \true; + $this->paused = \true; + $this->drain = \false; + $this->callback = null; + $this->emit('close'); + $this->removeAllListeners(); + } +} diff --git a/vendor/react/stream/src/Util.php b/vendor/react/stream/src/Util.php new file mode 100644 index 00000000000..5835218dd76 --- /dev/null +++ b/vendor/react/stream/src/Util.php @@ -0,0 +1,66 @@ + NO-OP + if (!$source->isReadable()) { + return $dest; + } + // destination not writable => just pause() source + if (!$dest->isWritable()) { + $source->pause(); + return $dest; + } + $dest->emit('pipe', array($source)); + // forward all source data events as $dest->write() + $source->on('data', $dataer = function ($data) use($source, $dest) { + $feedMore = $dest->write($data); + if (\false === $feedMore) { + $source->pause(); + } + }); + $dest->on('close', function () use($source, $dataer) { + $source->removeListener('data', $dataer); + $source->pause(); + }); + // forward destination drain as $source->resume() + $dest->on('drain', $drainer = function () use($source) { + $source->resume(); + }); + $source->on('close', function () use($dest, $drainer) { + $dest->removeListener('drain', $drainer); + }); + // forward end event from source as $dest->end() + $end = isset($options['end']) ? $options['end'] : \true; + if ($end) { + $source->on('end', $ender = function () use($dest) { + $dest->end(); + }); + $dest->on('close', function () use($source, $ender) { + $source->removeListener('end', $ender); + }); + } + return $dest; + } + public static function forwardEvents($source, $target, array $events) + { + foreach ($events as $event) { + $source->on($event, function () use($event, $target) { + $target->emit($event, \func_get_args()); + }); + } + } +} diff --git a/vendor/react/stream/src/WritableResourceStream.php b/vendor/react/stream/src/WritableResourceStream.php new file mode 100644 index 00000000000..be46d10d711 --- /dev/null +++ b/vendor/react/stream/src/WritableResourceStream.php @@ -0,0 +1,136 @@ +stream = $stream; + $this->loop = $loop ?: Loop::get(); + $this->softLimit = $writeBufferSoftLimit === null ? 65536 : (int) $writeBufferSoftLimit; + $this->writeChunkSize = $writeChunkSize === null ? -1 : (int) $writeChunkSize; + } + public function isWritable() + { + return $this->writable; + } + public function write($data) + { + if (!$this->writable) { + return \false; + } + $this->data .= $data; + if (!$this->listening && $this->data !== '') { + $this->listening = \true; + $this->loop->addWriteStream($this->stream, array($this, 'handleWrite')); + } + return !isset($this->data[$this->softLimit - 1]); + } + public function end($data = null) + { + if (null !== $data) { + $this->write($data); + } + $this->writable = \false; + // close immediately if buffer is already empty + // otherwise wait for buffer to flush first + if ($this->data === '') { + $this->close(); + } + } + public function close() + { + if ($this->closed) { + return; + } + if ($this->listening) { + $this->listening = \false; + $this->loop->removeWriteStream($this->stream); + } + $this->closed = \true; + $this->writable = \false; + $this->data = ''; + $this->emit('close'); + $this->removeAllListeners(); + if (\is_resource($this->stream)) { + \fclose($this->stream); + } + } + /** @internal */ + public function handleWrite() + { + $error = null; + \set_error_handler(function ($_, $errstr) use(&$error) { + $error = $errstr; + }); + if ($this->writeChunkSize === -1) { + $sent = \fwrite($this->stream, $this->data); + } else { + $sent = \fwrite($this->stream, $this->data, $this->writeChunkSize); + } + \restore_error_handler(); + // Only report errors if *nothing* could be sent and an error has been raised. + // Ignore non-fatal warnings if *some* data could be sent. + // Any hard (permanent) error will fail to send any data at all. + // Sending excessive amounts of data will only flush *some* data and then + // report a temporary error (EAGAIN) which we do not raise here in order + // to keep the stream open for further tries to write. + // Should this turn out to be a permanent error later, it will eventually + // send *nothing* and we can detect this. + if (($sent === 0 || $sent === \false) && $error !== null) { + $this->emit('error', array(new \RuntimeException('Unable to write to stream: ' . $error))); + $this->close(); + return; + } + $exceeded = isset($this->data[$this->softLimit - 1]); + $this->data = (string) \substr($this->data, $sent); + // buffer has been above limit and is now below limit + if ($exceeded && !isset($this->data[$this->softLimit - 1])) { + $this->emit('drain'); + } + // buffer is now completely empty => stop trying to write + if ($this->data === '') { + // stop waiting for resource to be writable + if ($this->listening) { + $this->loop->removeWriteStream($this->stream); + $this->listening = \false; + } + // buffer is end()ing and now completely empty => close buffer + if (!$this->writable) { + $this->close(); + } + } + } +} diff --git a/vendor/react/stream/src/WritableStreamInterface.php b/vendor/react/stream/src/WritableStreamInterface.php new file mode 100644 index 00000000000..592938ee8ad --- /dev/null +++ b/vendor/react/stream/src/WritableStreamInterface.php @@ -0,0 +1,343 @@ +on('drain', function () use ($stream) { + * echo 'Stream is now ready to accept more data'; + * }); + * ``` + * + * This event SHOULD be emitted once every time the buffer became full + * previously and is now ready to accept more data. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if the buffer never became full in the first place. + * This event SHOULD NOT be emitted if the buffer has not become full + * previously. + * + * This event is mostly used internally, see also `write()` for more details. + * + * pipe event: + * The `pipe` event will be emitted whenever a readable stream is `pipe()`d + * into this stream. + * The event receives a single `ReadableStreamInterface` argument for the + * source stream. + * + * ```php + * $stream->on('pipe', function (ReadableStreamInterface $source) use ($stream) { + * echo 'Now receiving piped data'; + * + * // explicitly close target if source emits an error + * $source->on('error', function () use ($stream) { + * $stream->close(); + * }); + * }); + * + * $source->pipe($stream); + * ``` + * + * This event MUST be emitted once for each readable stream that is + * successfully piped into this destination stream. + * In other words, this event MAY be emitted any number of times, which may + * be zero times if no stream is ever piped into this stream. + * This event MUST NOT be emitted if either the source is not readable + * (closed already) or this destination is not writable (closed already). + * + * This event is mostly used internally, see also `pipe()` for more details. + * + * error event: + * The `error` event will be emitted once a fatal error occurs, usually while + * trying to write to this stream. + * The event receives a single `Exception` argument for the error instance. + * + * ```php + * $stream->on('error', function (Exception $e) { + * echo 'Error: ' . $e->getMessage() . PHP_EOL; + * }); + * ``` + * + * This event SHOULD be emitted once the stream detects a fatal error, such + * as a fatal transmission error. + * It SHOULD NOT be emitted after a previous `error` or `close` event. + * It MUST NOT be emitted if this is not a fatal error condition, such as + * a temporary network issue that did not cause any data to be lost. + * + * After the stream errors, it MUST close the stream and SHOULD thus be + * followed by a `close` event and then switch to non-writable mode, see + * also `close()` and `isWritable()`. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * only deal with data transmission and may choose + * to only emit this for a fatal transmission error once and will then + * close (terminate) the stream in response. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `error` event. + * In other words, an error may occur while either reading or writing the + * stream which should result in the same error processing. + * + * close event: + * The `close` event will be emitted once the stream closes (terminates). + * + * ```php + * $stream->on('close', function () { + * echo 'CLOSED'; + * }); + * ``` + * + * This event SHOULD be emitted once or never at all, depending on whether + * the stream ever terminates. + * It SHOULD NOT be emitted after a previous `close` event. + * + * After the stream is closed, it MUST switch to non-writable mode, + * see also `isWritable()`. + * + * This event SHOULD be emitted whenever the stream closes, irrespective of + * whether this happens implicitly due to an unrecoverable error or + * explicitly when either side closes the stream. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will likely choose to emit this event after flushing the buffer from + * the `end()` method, after receiving a *successful* `end` event or after + * a fatal transmission `error` event. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close` event. + * In other words, after receiving this event, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * Note that this event should not be confused with the `end` event. + * + * The event callback functions MUST be a valid `callable` that obeys strict + * parameter definitions and MUST accept event parameters exactly as documented. + * The event callback functions MUST NOT throw an `Exception`. + * The return value of the event callback functions will be ignored and has no + * effect, so for performance reasons you're recommended to not return any + * excessive data structures. + * + * Every implementation of this interface MUST follow these event semantics in + * order to be considered a well-behaving stream. + * + * > Note that higher-level implementations of this interface may choose to + * define additional events with dedicated semantics not defined as part of + * this low-level stream specification. Conformance with these event semantics + * is out of scope for this interface, so you may also have to refer to the + * documentation of such a higher-level implementation. + * + * @see EventEmitterInterface + * @see DuplexStreamInterface + */ +interface WritableStreamInterface extends EventEmitterInterface +{ + /** + * Checks whether this stream is in a writable state (not closed already). + * + * This method can be used to check if the stream still accepts writing + * any data or if it is ended or closed already. + * Writing any data to a non-writable stream is a NO-OP: + * + * ```php + * assert($stream->isWritable() === false); + * + * $stream->write('end'); // NO-OP + * $stream->end('end'); // NO-OP + * ``` + * + * A successfully opened stream always MUST start in writable mode. + * + * Once the stream ends or closes, it MUST switch to non-writable mode. + * This can happen any time, explicitly through `end()` or `close()` or + * implicitly due to a remote close or an unrecoverable transmission error. + * Once a stream has switched to non-writable mode, it MUST NOT transition + * back to writable mode. + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements an `isReadable()` + * method. Unless this is a half-open duplex stream, they SHOULD usually + * have the same return value. + * + * @return bool + */ + public function isWritable(); + /** + * Write some data into the stream. + * + * A successful write MUST be confirmed with a boolean `true`, which means + * that either the data was written (flushed) immediately or is buffered and + * scheduled for a future write. Note that this interface gives you no + * control over explicitly flushing the buffered data, as finding the + * appropriate time for this is beyond the scope of this interface and left + * up to the implementation of this interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * If a stream cannot handle writing (or flushing) the data, it SHOULD emit + * an `error` event and MAY `close()` the stream if it can not recover from + * this error. + * + * If the internal buffer is full after adding `$data`, then `write()` + * SHOULD return `false`, indicating that the caller should stop sending + * data until the buffer drains. + * The stream SHOULD send a `drain` event once the buffer is ready to accept + * more data. + * + * Similarly, if the stream is not writable (already in a closed state) + * it MUST NOT process the given `$data` and SHOULD return `false`, + * indicating that the caller should stop sending data. + * + * The given `$data` argument MAY be of mixed type, but it's usually + * recommended it SHOULD be a `string` value or MAY use a type that allows + * representation as a `string` for maximum compatibility. + * + * Many common streams (such as a TCP/IP connection or a file-based stream) + * will only accept the raw (binary) payload data that is transferred over + * the wire as chunks of `string` values. + * + * Due to the stream-based nature of this, the sender may send any number + * of chunks with varying sizes. There are no guarantees that these chunks + * will be received with the exact same framing the sender intended to send. + * In other words, many lower-level protocols (such as TCP/IP) transfer the + * data in chunks that may be anywhere between single-byte values to several + * dozens of kilobytes. You may want to apply a higher-level protocol to + * these low-level data chunks in order to achieve proper message framing. + * + * @param mixed|string $data + * @return bool + */ + public function write($data); + /** + * Successfully ends the stream (after optionally sending some final data). + * + * This method can be used to successfully end the stream, i.e. close + * the stream after sending out all data that is currently buffered. + * + * ```php + * $stream->write('hello'); + * $stream->write('world'); + * $stream->end(); + * ``` + * + * If there's no data currently buffered and nothing to be flushed, then + * this method MAY `close()` the stream immediately. + * + * If there's still data in the buffer that needs to be flushed first, then + * this method SHOULD try to write out this data and only then `close()` + * the stream. + * Once the stream is closed, it SHOULD emit a `close` event. + * + * Note that this interface gives you no control over explicitly flushing + * the buffered data, as finding the appropriate time for this is beyond the + * scope of this interface and left up to the implementation of this + * interface. + * + * Many common streams (such as a TCP/IP connection or file-based stream) + * may choose to buffer all given data and schedule a future flush by using + * an underlying EventLoop to check when the resource is actually writable. + * + * You can optionally pass some final data that is written to the stream + * before ending the stream. If a non-`null` value is given as `$data`, then + * this method will behave just like calling `write($data)` before ending + * with no data. + * + * ```php + * // shorter version + * $stream->end('bye'); + * + * // same as longer version + * $stream->write('bye'); + * $stream->end(); + * ``` + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->end(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * If this stream is a `DuplexStreamInterface`, calling this method SHOULD + * also end its readable side, unless the stream supports half-open mode. + * In other words, after calling this method, these streams SHOULD switch + * into non-writable AND non-readable mode, see also `isReadable()`. + * This implies that in this case, the stream SHOULD NOT emit any `data` + * or `end` events anymore. + * Streams MAY choose to use the `pause()` method logic for this, but + * special care may have to be taken to ensure a following call to the + * `resume()` method SHOULD NOT continue emitting readable events. + * + * Note that this method should not be confused with the `close()` method. + * + * @param mixed|string|null $data + * @return void + */ + public function end($data = null); + /** + * Closes the stream (forcefully). + * + * This method can be used to forcefully close the stream, i.e. close + * the stream without waiting for any buffered data to be flushed. + * If there's still data in the buffer, this data SHOULD be discarded. + * + * ```php + * $stream->close(); + * ``` + * + * Once the stream is closed, it SHOULD emit a `close` event. + * Note that this event SHOULD NOT be emitted more than once, in particular + * if this method is called multiple times. + * + * After calling this method, the stream MUST switch into a non-writable + * mode, see also `isWritable()`. + * This means that no further writes are possible, so any additional + * `write()` or `end()` calls have no effect. + * + * ```php + * $stream->close(); + * assert($stream->isWritable() === false); + * + * $stream->write('nope'); // NO-OP + * $stream->end(); // NO-OP + * ``` + * + * Note that this method should not be confused with the `end()` method. + * Unlike the `end()` method, this method does not take care of any existing + * buffers and simply discards any buffer contents. + * Likewise, this method may also be called after calling `end()` on a + * stream in order to stop waiting for the stream to flush its final data. + * + * ```php + * $stream->end(); + * Loop::addTimer(1.0, function () use ($stream) { + * $stream->close(); + * }); + * ``` + * + * If this stream is a `DuplexStreamInterface`, you should also notice + * how the readable side of the stream also implements a `close()` method. + * In other words, after calling this method, the stream MUST switch into + * non-writable AND non-readable mode, see also `isReadable()`. + * + * @return void + * @see ReadableStreamInterface::close() + */ + public function close(); +} diff --git a/vendor/scoper-autoload.php b/vendor/scoper-autoload.php new file mode 100644 index 00000000000..3f2a2917ba4 --- /dev/null +++ b/vendor/scoper-autoload.php @@ -0,0 +1,15 @@ +=7.3` + +## [4.0.2] - 2020-06-30 + +### Added + +* This component is now supported on PHP 8 + +## [4.0.1] - 2020-05-08 + +### Fixed + +* [#99](https://github.com/sebastianbergmann/diff/pull/99): Regression in unified diff output of identical strings + +## [4.0.0] - 2020-02-07 + +### Removed + +* Removed support for PHP 7.1 and PHP 7.2 + +## [3.0.2] - 2019-02-04 + +### Changed + +* `Chunk::setLines()` now ensures that the `$lines` array only contains `Line` objects + +## [3.0.1] - 2018-06-10 + +### Fixed + +* Removed `"minimum-stability": "dev",` from `composer.json` + +## [3.0.0] - 2018-02-01 + +* The `StrictUnifiedDiffOutputBuilder` implementation of the `DiffOutputBuilderInterface` was added + +### Changed + +* The default `DiffOutputBuilderInterface` implementation now generates context lines (unchanged lines) + +### Removed + +* Removed support for PHP 7.0 + +### Fixed + +* [#70](https://github.com/sebastianbergmann/diff/issues/70): Diffing of arrays no longer works + +## [2.0.1] - 2017-08-03 + +### Fixed + +* [#66](https://github.com/sebastianbergmann/diff/pull/66): Restored backwards compatibility for PHPUnit 6.1.4, 6.2.0, 6.2.1, 6.2.2, and 6.2.3 + +## [2.0.0] - 2017-07-11 [YANKED] + +### Added + +* [#64](https://github.com/sebastianbergmann/diff/pull/64): Show line numbers for chunks of a diff + +### Removed + +* This component is no longer supported on PHP 5.6 + +[5.0.3]: https://github.com/sebastianbergmann/diff/compare/5.0.2...5.0.3 +[5.0.2]: https://github.com/sebastianbergmann/diff/compare/5.0.1...5.0.2 +[5.0.1]: https://github.com/sebastianbergmann/diff/compare/5.0.0...5.0.1 +[5.0.0]: https://github.com/sebastianbergmann/diff/compare/4.0.4...5.0.0 +[4.0.4]: https://github.com/sebastianbergmann/diff/compare/4.0.3...4.0.4 +[4.0.3]: https://github.com/sebastianbergmann/diff/compare/4.0.2...4.0.3 +[4.0.2]: https://github.com/sebastianbergmann/diff/compare/4.0.1...4.0.2 +[4.0.1]: https://github.com/sebastianbergmann/diff/compare/4.0.0...4.0.1 +[4.0.0]: https://github.com/sebastianbergmann/diff/compare/3.0.2...4.0.0 +[3.0.2]: https://github.com/sebastianbergmann/diff/compare/3.0.1...3.0.2 +[3.0.1]: https://github.com/sebastianbergmann/diff/compare/3.0.0...3.0.1 +[3.0.0]: https://github.com/sebastianbergmann/diff/compare/2.0...3.0.0 +[2.0.1]: https://github.com/sebastianbergmann/diff/compare/c341c98ce083db77f896a0aa64f5ee7652915970...2.0.1 +[2.0.0]: https://github.com/sebastianbergmann/diff/compare/1.4...c341c98ce083db77f896a0aa64f5ee7652915970 diff --git a/vendor/sebastian/diff/LICENSE b/vendor/sebastian/diff/LICENSE new file mode 100644 index 00000000000..a453252d525 --- /dev/null +++ b/vendor/sebastian/diff/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2002-2023, Sebastian Bergmann +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/sebastian/diff/README.md b/vendor/sebastian/diff/README.md new file mode 100644 index 00000000000..539dc59edeb --- /dev/null +++ b/vendor/sebastian/diff/README.md @@ -0,0 +1,206 @@ +[![Latest Stable Version](https://poser.pugx.org/sebastian/diff/v/stable.png)](https://packagist.org/packages/sebastian/diff) +[![CI Status](https://github.com/sebastianbergmann/diff/workflows/CI/badge.svg)](https://github.com/sebastianbergmann/diff/actions) +[![Type Coverage](https://shepherd.dev/github/sebastianbergmann/diff/coverage.svg)](https://shepherd.dev/github/sebastianbergmann/diff) +[![codecov](https://codecov.io/gh/sebastianbergmann/diff/branch/main/graph/badge.svg)](https://codecov.io/gh/sebastianbergmann/diff) + +# sebastian/diff + +Diff implementation for PHP, factored out of PHPUnit into a stand-alone component. + +## Installation + +You can add this library as a local, per-project dependency to your project using [Composer](https://getcomposer.org/): + +``` +composer require sebastian/diff +``` + +If you only need this library during development, for instance to run your project's test suite, then you should add it as a development-time dependency: + +``` +composer require --dev sebastian/diff +``` + +### Usage + +#### Generating diff + +The `Differ` class can be used to generate a textual representation of the difference between two strings: + +```php +diff('foo', 'bar'); +``` + +The code above yields the output below: +```diff +--- Original ++++ New +@@ @@ +-foo ++bar +``` + +There are three output builders available in this package: + +#### UnifiedDiffOutputBuilder + +This is default builder, which generates the output close to udiff and is used by PHPUnit. + +```php +diff('foo', 'bar'); +``` + +#### StrictUnifiedDiffOutputBuilder + +Generates (strict) Unified diff's (unidiffs) with hunks, +similar to `diff -u` and compatible with `patch` and `git apply`. + +```php + true, // ranges of length one are rendered with the trailing `,1` + 'commonLineThreshold' => 6, // number of same lines before ending a new hunk and creating a new one (if needed) + 'contextLines' => 3, // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3 + 'fromFile' => '', + 'fromFileDate' => null, + 'toFile' => '', + 'toFileDate' => null, +]); + +$differ = new Differ($builder); +print $differ->diff('foo', 'bar'); +``` + +#### DiffOnlyOutputBuilder + +Output only the lines that differ. + +```php +diff('foo', 'bar'); +``` + +#### DiffOutputBuilderInterface + +You can pass any output builder to the `Differ` class as longs as it implements the `DiffOutputBuilderInterface`. + +#### Parsing diff + +The `Parser` class can be used to parse a unified diff into an object graph: + +```php +use SebastianBergmann\Diff\Parser; +use SebastianBergmann\Git; + +$git = new Git('/usr/local/src/money'); + +$diff = $git->getDiff( + '948a1a07768d8edd10dcefa8315c1cbeffb31833', + 'c07a373d2399f3e686234c4f7f088d635eb9641b' +); + +$parser = new Parser; + +print_r($parser->parse($diff)); +``` + +The code above yields the output below: + + Array + ( + [0] => SebastianBergmann\Diff\Diff Object + ( + [from:SebastianBergmann\Diff\Diff:private] => a/tests/MoneyTest.php + [to:SebastianBergmann\Diff\Diff:private] => b/tests/MoneyTest.php + [chunks:SebastianBergmann\Diff\Diff:private] => Array + ( + [0] => SebastianBergmann\Diff\Chunk Object + ( + [start:SebastianBergmann\Diff\Chunk:private] => 87 + [startRange:SebastianBergmann\Diff\Chunk:private] => 7 + [end:SebastianBergmann\Diff\Chunk:private] => 87 + [endRange:SebastianBergmann\Diff\Chunk:private] => 7 + [lines:SebastianBergmann\Diff\Chunk:private] => Array + ( + [0] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::add + ) + + [1] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => * @covers SebastianBergmann\Money\Money::newMoney + ) + + [2] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => */ + ) + + [3] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 2 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyWithSameCurrencyObjectCanBeAdded() + ) + + [4] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 1 + [content:SebastianBergmann\Diff\Line:private] => public function testAnotherMoneyObjectWithSameCurrencyCanBeAdded() + ) + + [5] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => { + ) + + [6] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $a = new Money(1, new Currency('EUR')); + ) + + [7] => SebastianBergmann\Diff\Line Object + ( + [type:SebastianBergmann\Diff\Line:private] => 3 + [content:SebastianBergmann\Diff\Line:private] => $b = new Money(2, new Currency('EUR')); + ) + ) + ) + ) + ) + ) + +Note: If the chunk size is 0 lines, i.e., `getStartRange()` or `getEndRange()` return 0, the number of line returned by `getStart()` or `getEnd()` is one lower than one would expect. It is the line number after which the chunk should be inserted or deleted; in all other cases, it gives the first line number of the replaced range of lines. diff --git a/vendor/sebastian/diff/SECURITY.md b/vendor/sebastian/diff/SECURITY.md new file mode 100644 index 00000000000..d88ff0019ab --- /dev/null +++ b/vendor/sebastian/diff/SECURITY.md @@ -0,0 +1,30 @@ +# Security Policy + +If you believe you have found a security vulnerability in the library that is developed in this repository, please report it to us through coordinated disclosure. + +**Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.** + +Instead, please email `sebastian@phpunit.de`. + +Please include as much of the information listed below as you can to help us better understand and resolve the issue: + +* The type of issue +* Full paths of source file(s) related to the manifestation of the issue +* The location of the affected source code (tag/branch/commit or direct URL) +* Any special configuration required to reproduce the issue +* Step-by-step instructions to reproduce the issue +* Proof-of-concept or exploit code (if possible) +* Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +## Web Context + +The library that is developed in this repository was either extracted from [PHPUnit](https://github.com/sebastianbergmann/phpunit) or developed specifically as a dependency for PHPUnit. + +The library is developed with a focus on development environments and the command-line. No specific testing or hardening with regard to using the library in an HTTP or web context or with untrusted input data is performed. The library might also contain functionality that intentionally exposes internal application data for debugging purposes. + +If the library is used in a web application, the application developer is responsible for filtering inputs or escaping outputs as necessary and for verifying that the used functionality is safe for use within the intended context. + +Vulnerabilities specific to the use outside a development context will be fixed as applicable, provided that the fix does not have an averse effect on the primary use case for development purposes. + diff --git a/vendor/sebastian/diff/composer.json b/vendor/sebastian/diff/composer.json new file mode 100644 index 00000000000..acc5769f7ef --- /dev/null +++ b/vendor/sebastian/diff/composer.json @@ -0,0 +1,56 @@ +{ + "name": "sebastian\/diff", + "description": "Diff implementation", + "keywords": [ + "diff", + "udiff", + "unidiff", + "unified diff" + ], + "homepage": "https:\/\/github.com\/sebastianbergmann\/diff", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Sebastian Bergmann", + "email": "sebastian@phpunit.de" + }, + { + "name": "Kore Nordmann", + "email": "mail@kore-nordmann.de" + } + ], + "support": { + "issues": "https:\/\/github.com\/sebastianbergmann\/diff\/issues", + "security": "https:\/\/github.com\/sebastianbergmann\/diff\/security\/policy" + }, + "prefer-stable": true, + "config": { + "platform": { + "php": "8.1.0" + }, + "optimize-autoloader": true, + "sort-packages": true + }, + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit\/phpunit": "^10.0", + "symfony\/process": "^4.2 || ^5" + }, + "autoload": { + "classmap": [ + "src\/" + ] + }, + "autoload-dev": { + "classmap": [ + "tests\/" + ] + }, + "extra": { + "branch-alias": { + "dev-main": "5.0-dev" + } + } +} \ No newline at end of file diff --git a/vendor/sebastian/diff/src/Chunk.php b/vendor/sebastian/diff/src/Chunk.php new file mode 100644 index 00000000000..7e464272a75 --- /dev/null +++ b/vendor/sebastian/diff/src/Chunk.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +final class Chunk +{ + /** + * @var int + */ + private $start; + /** + * @var int + */ + private $startRange; + /** + * @var int + */ + private $end; + /** + * @var int + */ + private $endRange; + /** + * @var mixed[] + */ + private $lines; + public function __construct(int $start = 0, int $startRange = 1, int $end = 0, int $endRange = 1, array $lines = []) + { + $this->start = $start; + $this->startRange = $startRange; + $this->end = $end; + $this->endRange = $endRange; + $this->lines = $lines; + } + public function getStart() : int + { + return $this->start; + } + public function getStartRange() : int + { + return $this->startRange; + } + public function getEnd() : int + { + return $this->end; + } + public function getEndRange() : int + { + return $this->endRange; + } + /** + * @psalm-return list + */ + public function getLines() : array + { + return $this->lines; + } + /** + * @psalm-param list $lines + */ + public function setLines(array $lines) : void + { + foreach ($lines as $line) { + if (!$line instanceof Line) { + throw new InvalidArgumentException(); + } + } + $this->lines = $lines; + } +} diff --git a/vendor/sebastian/diff/src/Diff.php b/vendor/sebastian/diff/src/Diff.php new file mode 100644 index 00000000000..06ca3fa7948 --- /dev/null +++ b/vendor/sebastian/diff/src/Diff.php @@ -0,0 +1,60 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +final class Diff +{ + /** + * @var string + */ + private $from; + /** + * @var string + */ + private $to; + /** + * @psalm-var list + * @var mixed[] + */ + private $chunks; + /** + * @psalm-param list $chunks + */ + public function __construct(string $from, string $to, array $chunks = []) + { + $this->from = $from; + $this->to = $to; + $this->chunks = $chunks; + } + public function getFrom() : string + { + return $this->from; + } + public function getTo() : string + { + return $this->to; + } + /** + * @psalm-return list + */ + public function getChunks() : array + { + return $this->chunks; + } + /** + * @psalm-param list $chunks + */ + public function setChunks(array $chunks) : void + { + $this->chunks = $chunks; + } +} diff --git a/vendor/sebastian/diff/src/Differ.php b/vendor/sebastian/diff/src/Differ.php new file mode 100644 index 00000000000..6ba2f89c49a --- /dev/null +++ b/vendor/sebastian/diff/src/Differ.php @@ -0,0 +1,206 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use const PHP_INT_SIZE; +use const PREG_SPLIT_DELIM_CAPTURE; +use const PREG_SPLIT_NO_EMPTY; +use function array_shift; +use function array_unshift; +use function array_values; +use function count; +use function current; +use function end; +use function is_string; +use function key; +use function min; +use function preg_split; +use function prev; +use function reset; +use function str_ends_with; +use function substr; +use ECSPrefix202307\SebastianBergmann\Diff\Output\DiffOutputBuilderInterface; +final class Differ +{ + public const OLD = 0; + public const ADDED = 1; + public const REMOVED = 2; + public const DIFF_LINE_END_WARNING = 3; + public const NO_LINE_END_EOF_WARNING = 4; + /** + * @var \SebastianBergmann\Diff\Output\DiffOutputBuilderInterface + */ + private $outputBuilder; + public function __construct(DiffOutputBuilderInterface $outputBuilder) + { + $this->outputBuilder = $outputBuilder; + } + /** + * @param mixed[]|string $from + * @param mixed[]|string $to + */ + public function diff($from, $to, LongestCommonSubsequenceCalculator $lcs = null) : string + { + $diff = $this->diffToArray($from, $to, $lcs); + return $this->outputBuilder->getDiff($diff); + } + /** + * @param mixed[]|string $from + * @param mixed[]|string $to + */ + public function diffToArray($from, $to, LongestCommonSubsequenceCalculator $lcs = null) : array + { + if (is_string($from)) { + $from = $this->splitStringByLines($from); + } + if (is_string($to)) { + $to = $this->splitStringByLines($to); + } + [$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, ["#Warning: Strings contain different line endings!\n", self::DIFF_LINE_END_WARNING]); + } + return $diff; + } + private function splitStringByLines(string $input) : array + { + return preg_split('/(.*\\R)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + } + private function selectLcsImplementation(array $from, array $to) : LongestCommonSubsequenceCalculator + { + // We do not want to use the time-efficient implementation if its memory + // footprint will probably exceed this value. Note that the footprint + // calculation is only an estimation for the matrix and the LCS method + // will typically allocate a bit more memory than this. + $memoryLimit = 100 * 1024 * 1024; + if ($this->calculateEstimatedFootprint($from, $to) > $memoryLimit) { + return new MemoryEfficientLongestCommonSubsequenceCalculator(); + } + return new TimeEfficientLongestCommonSubsequenceCalculator(); + } + /** + * @return float|int + */ + 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) : bool + { + $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 either input or output is a single line without breaks than no warning should be raised + if (['' => \true] === $newLineBreaks || ['' => \true] === $oldLineBreaks) { + return \false; + } + // two-way compare + 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) : string + { + if (!is_string($line)) { + return ''; + } + $lc = substr($line, -1); + if ("\r" === $lc) { + return "\r"; + } + if ("\n" !== $lc) { + return ''; + } + if (\substr_compare($line, "\r\n", -\strlen("\r\n")) === 0) { + return "\r\n"; + } + return "\n"; + } + private static function getArrayDiffParted(array &$from, array &$to) : array + { + $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]; + } +} diff --git a/vendor/sebastian/diff/src/Exception/ConfigurationException.php b/vendor/sebastian/diff/src/Exception/ConfigurationException.php new file mode 100644 index 00000000000..6b64bd44be9 --- /dev/null +++ b/vendor/sebastian/diff/src/Exception/ConfigurationException.php @@ -0,0 +1,24 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use function gettype; +use function is_object; +use function sprintf; +use Exception; +final class ConfigurationException extends InvalidArgumentException +{ + public function __construct(string $option, string $expected, $value, int $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 ? '' : gettype($value) . '#' . $value)), $code, $previous); + } +} diff --git a/vendor/sebastian/diff/src/Exception/Exception.php b/vendor/sebastian/diff/src/Exception/Exception.php new file mode 100644 index 00000000000..5d3a49ff75c --- /dev/null +++ b/vendor/sebastian/diff/src/Exception/Exception.php @@ -0,0 +1,17 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use Throwable; +interface Exception extends Throwable +{ +} diff --git a/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php b/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php new file mode 100644 index 00000000000..a3c8fd3232c --- /dev/null +++ b/vendor/sebastian/diff/src/Exception/InvalidArgumentException.php @@ -0,0 +1,16 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +class InvalidArgumentException extends \InvalidArgumentException implements Exception +{ +} diff --git a/vendor/sebastian/diff/src/Line.php b/vendor/sebastian/diff/src/Line.php new file mode 100644 index 00000000000..57b6e1f80a5 --- /dev/null +++ b/vendor/sebastian/diff/src/Line.php @@ -0,0 +1,40 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +final class Line +{ + public const ADDED = 1; + public const REMOVED = 2; + public const UNCHANGED = 3; + /** + * @var int + */ + private $type; + /** + * @var string + */ + private $content; + public function __construct(int $type = self::UNCHANGED, string $content = '') + { + $this->type = $type; + $this->content = $content; + } + public function getContent() : string + { + return $this->content; + } + public function getType() : int + { + return $this->type; + } +} diff --git a/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php b/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000000..f851a6a75df --- /dev/null +++ b/vendor/sebastian/diff/src/LongestCommonSubsequenceCalculator.php @@ -0,0 +1,20 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +interface LongestCommonSubsequenceCalculator +{ + /** + * Calculates the longest common subsequence of two arrays. + */ + public function calculate(array $from, array $to) : array; +} diff --git a/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php b/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000000..696a1bfdc89 --- /dev/null +++ b/vendor/sebastian/diff/src/MemoryEfficientLongestCommonSubsequenceCalculator.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use function array_fill; +use function array_merge; +use function array_reverse; +use function array_slice; +use function count; +use function in_array; +use function max; +final class MemoryEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator +{ + /** + * @inheritDoc + */ + public function calculate(array $from, array $to) : array + { + $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) : array + { + $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 { + // don't use max() to avoid function call overhead + if ($current[$j] > $prev[$j + 1]) { + $current[$j + 1] = $current[$j]; + } else { + $current[$j + 1] = $prev[$j + 1]; + } + } + } + } + return $current; + } +} diff --git a/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php b/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php new file mode 100644 index 00000000000..19716cb80bf --- /dev/null +++ b/vendor/sebastian/diff/src/Output/AbstractChunkOutputBuilder.php @@ -0,0 +1,49 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff\Output; + +use function count; +abstract class AbstractChunkOutputBuilder implements DiffOutputBuilderInterface +{ + /** + * Takes input of the diff array and returns the common parts. + * Iterates through diff line by line. + */ + protected function getCommonChunks(array $diff, int $lineThreshold = 5) : array + { + $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; + } +} diff --git a/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php b/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php new file mode 100644 index 00000000000..3b10150bb11 --- /dev/null +++ b/vendor/sebastian/diff/src/Output/DiffOnlyOutputBuilder.php @@ -0,0 +1,68 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff\Output; + +use function fclose; +use function fopen; +use function fwrite; +use function str_ends_with; +use function stream_get_contents; +use function substr; +use ECSPrefix202307\SebastianBergmann\Diff\Differ; +/** + * Builds a diff string representation in a loose unified diff format + * listing only changes lines. Does not include line numbers. + */ +final class DiffOnlyOutputBuilder implements DiffOutputBuilderInterface +{ + /** + * @var string + */ + private $header; + public function __construct(string $header = "--- Original\n+++ New\n") + { + $this->header = $header; + } + public function getDiff(array $diff) : string + { + $buffer = fopen('php://memory', 'r+b'); + if ('' !== $this->header) { + fwrite($buffer, $this->header); + if (\substr_compare($this->header, "\n", -\strlen("\n")) !== 0) { + 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; + // Warnings should not be tested for line break, it will always be there + } else { + /* Not changed (old) 0 */ + continue; + // we didn't write the not-changed line, so do not add a line break either + } + $lc = substr($diffEntry[0], -1); + if ($lc !== "\n" && $lc !== "\r") { + fwrite($buffer, "\n"); + // \No newline at end of file + } + } + $diff = stream_get_contents($buffer, -1, 0); + fclose($buffer); + return $diff; + } +} diff --git a/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php b/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php new file mode 100644 index 00000000000..23e804d77d1 --- /dev/null +++ b/vendor/sebastian/diff/src/Output/DiffOutputBuilderInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff\Output; + +/** + * Defines how an output builder should take a generated + * diff array and return a string representation of that diff. + */ +interface DiffOutputBuilderInterface +{ + public function getDiff(array $diff) : string; +} diff --git a/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php b/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php new file mode 100644 index 00000000000..c054dc40824 --- /dev/null +++ b/vendor/sebastian/diff/src/Output/StrictUnifiedDiffOutputBuilder.php @@ -0,0 +1,252 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff\Output; + +use function array_merge; +use function array_splice; +use function count; +use function fclose; +use function fopen; +use function fwrite; +use function is_bool; +use function is_int; +use function is_string; +use function max; +use function min; +use function sprintf; +use function stream_get_contents; +use function substr; +use ECSPrefix202307\SebastianBergmann\Diff\ConfigurationException; +use ECSPrefix202307\SebastianBergmann\Diff\Differ; +/** + * Strict Unified diff output builder. + * + * Generates (strict) Unified diff's (unidiffs) with hunks. + */ +final class StrictUnifiedDiffOutputBuilder implements DiffOutputBuilderInterface +{ + /** + * @var mixed[] + */ + private static $default = [ + 'collapseRanges' => \true, + // ranges of length one are rendered with the trailing `,1` + 'commonLineThreshold' => 6, + // number of same lines before ending a new hunk and creating a new one (if needed) + 'contextLines' => 3, + // like `diff: -u, -U NUM, --unified[=NUM]`, for patch/git apply compatibility best to keep at least @ 3 + 'fromFile' => null, + 'fromFileDate' => null, + 'toFile' => null, + 'toFileDate' => null, + ]; + /** + * @var bool + */ + private $changed; + /** + * @var bool + */ + private $collapseRanges; + /** + * @psalm-var positive-int + * @var int + */ + private $commonLineThreshold; + /** + * @var string + */ + private $header; + /** + * @psalm-var positive-int + * @var int + */ + private $contextLines; + 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']); + } + $this->assertString($options, 'fromFile'); + $this->assertString($options, 'toFile'); + $this->assertStringOrNull($options, 'fromFileDate'); + $this->assertStringOrNull($options, 'toFileDate'); + $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) : string + { + 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); + // If the last char is not a linebreak: add it. + // This might happen when both the `from` and `to` do not have a trailing linebreak + $last = substr($diff, -1); + return "\n" !== $last && "\r" !== $last ? $diff . "\n" : $diff; + } + private function writeDiffHunks($output, array $diff) : void + { + // detect "No newline at end of file" and insert into `$diff` if needed + $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 { + // search back for the last `+` and `-` line, + // check if it has a trailing linebreak, else add a warning under it + $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; + } + } + } + } + // write hunks to output buffer + $cutOff = max($this->commonLineThreshold, $this->contextLines); + $hunkCapture = \false; + $sameCount = $toRange = $fromRange = 0; + $toStart = $fromStart = 1; + $i = 0; + /** @var int $i */ + foreach ($diff as $i => $entry) { + if (0 === $entry[1]) { + // same + if (\false === $hunkCapture) { + $fromStart++; + $toStart++; + continue; + } + $sameCount++; + $toRange++; + $fromRange++; + if ($sameCount === $cutOff) { + $contextStartOffset = $hunkCapture - $this->contextLines < 0 ? $hunkCapture : $this->contextLines; + // note: $contextEndOffset = $this->contextLines; + // + // because we never go beyond the end of the diff. + // with the cutoff/contextlines here the follow is never true; + // + // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) { + // $contextEndOffset = count($diff) - 1; + // } + // + // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop + $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]) { + // added + $toRange++; + } + if (Differ::REMOVED === $entry[1]) { + // removed + $fromRange++; + } + } + if (\false === $hunkCapture) { + return; + } + // we end here when cutoff (commonLineThreshold) was not reached, but we were capturing a hunk, + // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold + $contextStartOffset = $hunkCapture - $this->contextLines < 0 ? $hunkCapture : $this->contextLines; + // prevent trying to write out more common lines than there are in the diff _and_ + // do not write more than configured through the context lines + $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, int $diffStartIndex, int $diffEndIndex, int $fromStart, int $fromRange, int $toStart, int $toRange, $output) : void + { + 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]); + } + //} elseif ($diff[$i][1] === Differ::DIFF_LINE_END_WARNING) { // custom comment inserted by PHPUnit/diff package + // skip + //} else { + // unknown/invalid + //} + } + } + private function assertString(array $options, string $option) : void + { + if (!is_string($options[$option])) { + throw new ConfigurationException($option, 'a string', $options[$option]); + } + } + private function assertStringOrNull(array $options, string $option) : void + { + if (null !== $options[$option] && !is_string($options[$option])) { + throw new ConfigurationException($option, 'a string or ', $options[$option]); + } + } +} diff --git a/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php b/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php new file mode 100644 index 00000000000..6a8e7413cbe --- /dev/null +++ b/vendor/sebastian/diff/src/Output/UnifiedDiffOutputBuilder.php @@ -0,0 +1,198 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff\Output; + +use function array_splice; +use function count; +use function fclose; +use function fopen; +use function fwrite; +use function max; +use function min; +use function str_ends_with; +use function stream_get_contents; +use function strlen; +use function substr; +use ECSPrefix202307\SebastianBergmann\Diff\Differ; +/** + * Builds a diff string representation in unified diff format in chunks. + */ +final class UnifiedDiffOutputBuilder extends AbstractChunkOutputBuilder +{ + /** + * @var bool + */ + private $collapseRanges = \true; + /** + * @var int + */ + private $commonLineThreshold = 6; + /** + * @psalm-var positive-int + * @var int + */ + private $contextLines = 3; + /** + * @var string + */ + private $header; + /** + * @var bool + */ + private $addLineNumbers; + public function __construct(string $header = "--- Original\n+++ New\n", bool $addLineNumbers = \false) + { + $this->header = $header; + $this->addLineNumbers = $addLineNumbers; + } + public function getDiff(array $diff) : string + { + $buffer = fopen('php://memory', 'r+b'); + if ('' !== $this->header) { + fwrite($buffer, $this->header); + if (\substr_compare($this->header, "\n", -strlen("\n")) !== 0) { + fwrite($buffer, "\n"); + } + } + if (0 !== count($diff)) { + $this->writeDiffHunks($buffer, $diff); + } + $diff = stream_get_contents($buffer, -1, 0); + fclose($buffer); + // If the diff is non-empty and last char is not a linebreak: add it. + // This might happen when both the `from` and `to` do not have a trailing linebreak + $last = substr($diff, -1); + return 0 !== strlen($diff) && "\n" !== $last && "\r" !== $last ? $diff . "\n" : $diff; + } + private function writeDiffHunks($output, array $diff) : void + { + // detect "No newline at end of file" and insert into `$diff` if needed + $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 { + // search back for the last `+` and `-` line, + // check if it has trailing linebreak, else add a warning under it + $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; + } + } + } + } + // write hunks to output buffer + $cutOff = max($this->commonLineThreshold, $this->contextLines); + $hunkCapture = \false; + $sameCount = $toRange = $fromRange = 0; + $toStart = $fromStart = 1; + $i = 0; + /** @var int $i */ + foreach ($diff as $i => $entry) { + if (0 === $entry[1]) { + // same + if (\false === $hunkCapture) { + $fromStart++; + $toStart++; + continue; + } + $sameCount++; + $toRange++; + $fromRange++; + if ($sameCount === $cutOff) { + $contextStartOffset = $hunkCapture - $this->contextLines < 0 ? $hunkCapture : $this->contextLines; + // note: $contextEndOffset = $this->contextLines; + // + // because we never go beyond the end of the diff. + // with the cutoff/contextlines here the follow is never true; + // + // if ($i - $cutOff + $this->contextLines + 1 > \count($diff)) { + // $contextEndOffset = count($diff) - 1; + // } + // + // ; that would be true for a trailing incomplete hunk case which is dealt with after this loop + $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; + } + // we end here when cutoff (commonLineThreshold) was not reached, but we were capturing a hunk, + // do not render hunk till end automatically because the number of context lines might be less than the commonLineThreshold + $contextStartOffset = $hunkCapture - $this->contextLines < 0 ? $hunkCapture : $this->contextLines; + // prevent trying to write out more common lines than there are in the diff _and_ + // do not write more than configured through the context lines + $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, int $diffStartIndex, int $diffEndIndex, int $fromStart, int $fromRange, int $toStart, int $toRange, $output) : void + { + 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"); + // $diff[$i][0] + } else { + /* Not changed (old) Differ::OLD or Warning Differ::DIFF_LINE_END_WARNING */ + fwrite($output, ' ' . $diff[$i][0]); + } + } + } +} diff --git a/vendor/sebastian/diff/src/Parser.php b/vendor/sebastian/diff/src/Parser.php new file mode 100644 index 00000000000..143ffd74b38 --- /dev/null +++ b/vendor/sebastian/diff/src/Parser.php @@ -0,0 +1,84 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use function array_pop; +use function count; +use function max; +use function preg_match; +use function preg_split; +/** + * Unified diff parser. + */ +final class Parser +{ + /** + * @return Diff[] + */ + public function parse(string $string) : array + { + $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('#^---\\h+"?(?P[^\\v\\t"]+)#', $lines[$i], $fromMatch) && preg_match('#^\\+\\+\\+\\h+"?(?P[^\\v\\t"]+)#', $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) : void + { + $chunks = []; + $chunk = null; + $diffLines = []; + foreach ($lines as $line) { + if (preg_match('/^@@\\s+-(?P\\d+)(?:,\\s*(?P\\d+))?\\s+\\+(?P\\d+)(?:,\\s*(?P\\d+))?\\s+@@/', $line, $match, \PREG_UNMATCHED_AS_NULL)) { + $chunk = new Chunk((int) $match['start'], isset($match['startrange']) ? max(0, (int) $match['startrange']) : 1, (int) $match['end'], isset($match['endrange']) ? max(0, (int) $match['endrange']) : 1); + $chunks[] = $chunk; + $diffLines = []; + continue; + } + if (preg_match('/^(?P[+ -])?(?P.*)/', $line, $match)) { + $type = Line::UNCHANGED; + if ($match['type'] === '+') { + $type = Line::ADDED; + } elseif ($match['type'] === '-') { + $type = Line::REMOVED; + } + $diffLines[] = new Line($type, $match['line']); + ($chunk2 = $chunk) ? $chunk2->setLines($diffLines) : null; + } + } + $diff->setChunks($chunks); + } +} diff --git a/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php b/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php new file mode 100644 index 00000000000..632f111e116 --- /dev/null +++ b/vendor/sebastian/diff/src/TimeEfficientLongestCommonSubsequenceCalculator.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +namespace ECSPrefix202307\SebastianBergmann\Diff; + +use function array_reverse; +use function count; +use function max; +use SplFixedArray; +final class TimeEfficientLongestCommonSubsequenceCalculator implements LongestCommonSubsequenceCalculator +{ + /** + * @inheritDoc + */ + public function calculate(array $from, array $to) : array + { + $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; + // don't use max() to avoid function call overhead + $firstOrLast = $from[$i - 1] === $to[$j - 1] ? $matrix[$o - $width - 1] + 1 : 0; + if ($matrix[$o - 1] > $matrix[$o - $width]) { + if ($firstOrLast > $matrix[$o - 1]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - 1]; + } + } else { + if ($firstOrLast > $matrix[$o - $width]) { + $matrix[$o] = $firstOrLast; + } else { + $matrix[$o] = $matrix[$o - $width]; + } + } + } + } + $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); + } +} diff --git a/vendor/squizlabs/php_codesniffer/CONTRIBUTING.md b/vendor/squizlabs/php_codesniffer/CONTRIBUTING.md new file mode 100644 index 00000000000..5cc7363530b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/CONTRIBUTING.md @@ -0,0 +1,13 @@ +Contributing +------------- + +Before you contribute code to PHP\_CodeSniffer, please make sure it conforms to the PHPCS coding standard and that the PHP\_CodeSniffer unit tests still pass. The easiest way to contribute is to work on a checkout of the repository, or your own fork, rather than an installed PEAR version. If you do this, you can run the following commands to check if everything is ready to submit: + + cd PHP_CodeSniffer + php bin/phpcs + +Which should display no coding standard errors. And then: + + phpunit + +Which should give you no failures or errors. You can ignore any skipped tests as these are for external tools. diff --git a/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist b/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist new file mode 100644 index 00000000000..f95058faa75 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/CodeSniffer.conf.dist @@ -0,0 +1,9 @@ + 'PSR2', + 'report_format' => 'summary', + 'show_warnings' => '0', + 'show_progress' => '1', + 'report_width' => '120', +); +?> diff --git a/vendor/squizlabs/php_codesniffer/README.md b/vendor/squizlabs/php_codesniffer/README.md new file mode 100644 index 00000000000..859de432c6e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/README.md @@ -0,0 +1,134 @@ +## About + +PHP_CodeSniffer is a set of two PHP scripts; the main `phpcs` script that tokenizes PHP, JavaScript and CSS files to detect violations of a defined coding standard, and a second `phpcbf` script to automatically correct coding standard violations. PHP_CodeSniffer is an essential development tool that ensures your code remains clean and consistent. + +[![Build Status](https://github.com/squizlabs/PHP_CodeSniffer/workflows/Validate/badge.svg?branch=master)](https://github.com/squizlabs/PHP_CodeSniffer/actions) +[![Build Status](https://github.com/squizlabs/PHP_CodeSniffer/workflows/Test/badge.svg?branch=master)](https://github.com/squizlabs/PHP_CodeSniffer/actions) +[![Code consistency](http://squizlabs.github.io/PHP_CodeSniffer/analysis/squizlabs/PHP_CodeSniffer/grade.svg)](http://squizlabs.github.io/PHP_CodeSniffer/analysis/squizlabs/PHP_CodeSniffer) +[![Join the chat at https://gitter.im/squizlabs/PHP_CodeSniffer](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/squizlabs/PHP_CodeSniffer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +## Requirements + +PHP_CodeSniffer requires PHP version 5.4.0 or greater, although individual sniffs may have additional requirements such as external applications and scripts. See the [Configuration Options manual page](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Configuration-Options) for a list of these requirements. + +If you're using PHP_CodeSniffer as part of a team, or you're running it on a [CI](https://en.wikipedia.org/wiki/Continuous_integration) server, you may want to configure your project's settings [using a configuration file](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Advanced-Usage#using-a-default-configuration-file). + + +## Installation + +The easiest way to get started with PHP_CodeSniffer is to download the Phar files for each of the commands: +``` +# Download using curl +curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar +curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar + +# Or download using wget +wget https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar +wget https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar + +# Then test the downloaded PHARs +php phpcs.phar -h +php phpcbf.phar -h +``` + +### Composer +If you use Composer, you can install PHP_CodeSniffer system-wide with the following command: +```bash +composer global require "squizlabs/php_codesniffer=*" +``` +Make sure you have the composer bin dir in your PATH. The default value is `~/.composer/vendor/bin/`, but you can check the value that you need to use by running `composer global config bin-dir --absolute`. + +Or alternatively, include a dependency for `squizlabs/php_codesniffer` in your `composer.json` file. For example: + +```json +{ + "require-dev": { + "squizlabs/php_codesniffer": "3.*" + } +} +``` + +You will then be able to run PHP_CodeSniffer from the vendor bin directory: +```bash +./vendor/bin/phpcs -h +./vendor/bin/phpcbf -h +``` +### Phive +If you use Phive, you can install PHP_CodeSniffer as a project tool using the following commands: +```bash +phive install phpcs +phive install phpcbf +``` +You will then be able to run PHP_CodeSniffer from the tools directory: +```bash +./tools/phpcs -h +./tools/phpcbf -h +``` +### PEAR +If you use PEAR, you can install PHP_CodeSniffer using the PEAR installer. This will make the `phpcs` and `phpcbf` commands immediately available for use. To install PHP_CodeSniffer using the PEAR installer, first ensure you have [installed PEAR](http://pear.php.net/manual/en/installation.getting.php) and then run the following command: +```bash +pear install PHP_CodeSniffer +``` +### Git Clone +You can also download the PHP_CodeSniffer source and run the `phpcs` and `phpcbf` commands directly from the Git clone: +```bash +git clone https://github.com/squizlabs/PHP_CodeSniffer.git +cd PHP_CodeSniffer +php bin/phpcs -h +php bin/phpcbf -h +``` +## Getting Started + +The default coding standard used by PHP_CodeSniffer is the PEAR coding standard. To check a file against the PEAR coding standard, simply specify the file's location: +```bash +phpcs /path/to/code/myfile.php +``` +Or if you wish to check an entire directory you can specify the directory location instead of a file. +```bash +phpcs /path/to/code-directory +``` +If you wish to check your code against the PSR-12 coding standard, use the `--standard` command line argument: +```bash +phpcs --standard=PSR12 /path/to/code-directory +``` + +If PHP_CodeSniffer finds any coding standard errors, a report will be shown after running the command. + +Full usage information and example reports are available on the [usage page](https://github.com/squizlabs/PHP_CodeSniffer/wiki/Usage). + +## Documentation + +The documentation for PHP_CodeSniffer is available on the [Github wiki](https://github.com/squizlabs/PHP_CodeSniffer/wiki). + +## Issues + +Bug reports and feature requests can be submitted on the [Github Issue Tracker](https://github.com/squizlabs/PHP_CodeSniffer/issues). + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md) for information. + +## Versioning + +PHP_CodeSniffer uses a `MAJOR.MINOR.PATCH` version number format. + +The `MAJOR` version is incremented when: +- backwards-incompatible changes are made to how the `phpcs` or `phpcbf` commands are used, or +- backwards-incompatible changes are made to the `ruleset.xml` format, or +- backwards-incompatible changes are made to the API used by sniff developers, or +- custom PHP_CodeSniffer token types are removed, or +- existing sniffs are removed from PHP_CodeSniffer entirely + +The `MINOR` version is incremented when: +- new backwards-compatible features are added to the `phpcs` and `phpcbf` commands, or +- backwards-compatible changes are made to the `ruleset.xml` format, or +- backwards-compatible changes are made to the API used by sniff developers, or +- new sniffs are added to an included standard, or +- existing sniffs are removed from an included standard + +> NOTE: Backwards-compatible changes to the API used by sniff developers will allow an existing sniff to continue running without producing fatal errors but may not result in the sniff reporting the same errors as it did previously without changes being required. + +The `PATCH` version is incremented when: +- backwards-compatible bug fixes are made + +> NOTE: As PHP_CodeSniffer exists to report and fix issues, most bugs are the result of coding standard errors being incorrectly reported or coding standard errors not being reported when they should be. This means that the messages produced by PHP_CodeSniffer, and the fixes it makes, are likely to be different between PATCH versions. diff --git a/vendor/squizlabs/php_codesniffer/autoload.php b/vendor/squizlabs/php_codesniffer/autoload.php new file mode 100644 index 00000000000..2721184d2fc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/autoload.php @@ -0,0 +1,282 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +if (\class_exists('PHP_CodeSniffer\\Autoload', \false) === \false) { + class Autoload + { + /** + * The composer autoloader. + * + * @var \Composer\Autoload\ClassLoader + */ + private static $composerAutoloader = null; + /** + * A mapping of file names to class names. + * + * @var array + */ + private static $loadedClasses = []; + /** + * A mapping of class names to file names. + * + * @var array + */ + private static $loadedFiles = []; + /** + * A list of additional directories to search during autoloading. + * + * This is typically a list of coding standard directories. + * + * @var string[] + */ + private static $searchPaths = []; + /** + * Loads a class. + * + * This method only loads classes that exist in the PHP_CodeSniffer namespace. + * All other classes are ignored and loaded by subsequent autoloaders. + * + * @param string $class The name of the class to load. + * + * @return bool + */ + public static function load($class) + { + // Include the composer autoloader if there is one, but re-register it + // so this autoloader runs before the composer one as we need to include + // all files so we can figure out what the class/interface/trait name is. + if (self::$composerAutoloader === null) { + // Make sure we don't try to load any of Composer's classes + // while the autoloader is being setup. + if (\strpos($class, 'Composer\\') === 0) { + return; + } + if (\strpos(__DIR__, 'phar://') !== 0 && @\file_exists(__DIR__ . '/../../autoload.php') === \true) { + self::$composerAutoloader = (include __DIR__ . '/../../autoload.php'); + if (self::$composerAutoloader instanceof \ECSPrefix202307\Composer\Autoload\ClassLoader) { + self::$composerAutoloader->unregister(); + self::$composerAutoloader->register(); + } else { + // Something went wrong, so keep going without the autoloader + // although namespaced sniffs might error. + self::$composerAutoloader = \false; + } + } else { + self::$composerAutoloader = \false; + } + } + //end if + $ds = \DIRECTORY_SEPARATOR; + $path = \false; + if (\substr($class, 0, 16) === 'PHP_CodeSniffer\\') { + if (\substr($class, 0, 22) === 'PHP_CodeSniffer\\Tests\\') { + $isInstalled = !\is_dir(__DIR__ . $ds . 'tests'); + if ($isInstalled === \false) { + $path = __DIR__ . $ds . 'tests'; + } else { + $path = '@test_dir@' . $ds . 'PHP_CodeSniffer' . $ds . 'CodeSniffer'; + } + $path .= $ds . \substr(\str_replace('\\', $ds, $class), 22) . '.php'; + } else { + $path = __DIR__ . $ds . 'src' . $ds . \substr(\str_replace('\\', $ds, $class), 16) . '.php'; + } + } + // See if the composer autoloader knows where the class is. + if ($path === \false && self::$composerAutoloader !== \false) { + $path = self::$composerAutoloader->findFile($class); + } + // See if the class is inside one of our alternate search paths. + if ($path === \false) { + foreach (self::$searchPaths as $searchPath => $nsPrefix) { + $className = $class; + if ($nsPrefix !== '' && \substr($class, 0, \strlen($nsPrefix)) === $nsPrefix) { + $className = \substr($class, \strlen($nsPrefix) + 1); + } + $path = $searchPath . $ds . \str_replace('\\', $ds, $className) . '.php'; + if (\is_file($path) === \true) { + break; + } + $path = \false; + } + } + if ($path !== \false && \is_file($path) === \true) { + self::loadFile($path); + return \true; + } + return \false; + } + //end load() + /** + * Includes a file and tracks what class or interface was loaded as a result. + * + * @param string $path The path of the file to load. + * + * @return string The fully qualified name of the class in the loaded file. + */ + public static function loadFile($path) + { + if (\strpos(__DIR__, 'phar://') !== 0) { + $path = \realpath($path); + if ($path === \false) { + return \false; + } + } + if (isset(self::$loadedClasses[$path]) === \true) { + return self::$loadedClasses[$path]; + } + $classesBeforeLoad = ['classes' => \get_declared_classes(), 'interfaces' => \get_declared_interfaces(), 'traits' => \get_declared_traits()]; + include $path; + $classesAfterLoad = ['classes' => \get_declared_classes(), 'interfaces' => \get_declared_interfaces(), 'traits' => \get_declared_traits()]; + $className = self::determineLoadedClass($classesBeforeLoad, $classesAfterLoad); + self::$loadedClasses[$path] = $className; + self::$loadedFiles[$className] = $path; + return self::$loadedClasses[$path]; + } + //end loadFile() + /** + * Determine which class was loaded based on the before and after lists of loaded classes. + * + * @param array $classesBeforeLoad The classes/interfaces/traits before the file was included. + * @param array $classesAfterLoad The classes/interfaces/traits after the file was included. + * + * @return string The fully qualified name of the class in the loaded file. + */ + public static function determineLoadedClass($classesBeforeLoad, $classesAfterLoad) + { + $className = null; + $newClasses = \array_diff($classesAfterLoad['classes'], $classesBeforeLoad['classes']); + if (\PHP_VERSION_ID < 70400) { + $newClasses = \array_reverse($newClasses); + } + // Since PHP 7.4 get_declared_classes() does not guarantee any order, making + // it impossible to use order to determine which is the parent an which is the child. + // Let's reduce the list of candidates by removing all the classes known to be "parents". + // That way, at the end, only the "main" class just included will remain. + $newClasses = \array_reduce($newClasses, function ($remaining, $current) { + return \array_diff($remaining, \class_parents($current)); + }, $newClasses); + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === \false) { + $className = $name; + break; + } + } + if ($className === null) { + $newClasses = \array_reverse(\array_diff($classesAfterLoad['interfaces'], $classesBeforeLoad['interfaces'])); + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === \false) { + $className = $name; + break; + } + } + } + if ($className === null) { + $newClasses = \array_reverse(\array_diff($classesAfterLoad['traits'], $classesBeforeLoad['traits'])); + foreach ($newClasses as $name) { + if (isset(self::$loadedFiles[$name]) === \false) { + $className = $name; + break; + } + } + } + return $className; + } + //end determineLoadedClass() + /** + * Adds a directory to search during autoloading. + * + * @param string $path The path to the directory to search. + * @param string $nsPrefix The namespace prefix used by files under this path. + * + * @return void + */ + public static function addSearchPath($path, $nsPrefix = '') + { + self::$searchPaths[$path] = \rtrim(\trim((string) $nsPrefix), '\\'); + } + //end addSearchPath() + /** + * Retrieve the namespaces and paths registered by external standards. + * + * @return array + */ + public static function getSearchPaths() + { + return self::$searchPaths; + } + //end getSearchPaths() + /** + * Gets the class name for the given file path. + * + * @param string $path The name of the file. + * + * @throws \Exception If the file path has not been loaded. + * @return string + */ + public static function getLoadedClassName($path) + { + if (isset(self::$loadedClasses[$path]) === \false) { + throw new \Exception("Cannot get class name for {$path}; file has not been included"); + } + return self::$loadedClasses[$path]; + } + //end getLoadedClassName() + /** + * Gets the file path for the given class name. + * + * @param string $class The name of the class. + * + * @throws \Exception If the class name has not been loaded + * @return string + */ + public static function getLoadedFileName($class) + { + if (isset(self::$loadedFiles[$class]) === \false) { + throw new \Exception("Cannot get file name for {$class}; class has not been included"); + } + return self::$loadedFiles[$class]; + } + //end getLoadedFileName() + /** + * Gets the mapping of file names to class names. + * + * @return array + */ + public static function getLoadedClasses() + { + return self::$loadedClasses; + } + //end getLoadedClasses() + /** + * Gets the mapping of class names to file names. + * + * @return array + */ + public static function getLoadedFiles() + { + return self::$loadedFiles; + } + //end getLoadedFiles() + } + //end class + // Register the autoloader before any existing autoloaders to ensure + // it gets a chance to hear about every autoload request, and record + // the file and class name for it. + \spl_autoload_register(__NAMESPACE__ . '\\Autoload::load', \true, \true); +} +//end if diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcbf b/vendor/squizlabs/php_codesniffer/bin/phpcbf new file mode 100644 index 00000000000..2e3eb1b3ce4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcbf @@ -0,0 +1,19 @@ +#!/usr/bin/env php + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +if (\is_file(__DIR__ . '/../autoload.php') === \true) { + include_once __DIR__ . '/../autoload.php'; +} else { + include_once 'PHP/CodeSniffer/autoload.php'; +} +$runner = new \PHP_CodeSniffer\Runner(); +$exitCode = $runner->runPHPCBF(); +exit($exitCode); diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat b/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat new file mode 100644 index 00000000000..5b07a7d9249 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcbf.bat @@ -0,0 +1,12 @@ +@echo off +REM PHP Code Beautifier and Fixer fixes violations of a defined coding standard. +REM +REM @author Greg Sherwood +REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) +REM @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + +if "%PHP_PEAR_PHP_BIN%" neq "" ( + set PHPBIN=%PHP_PEAR_PHP_BIN% +) else set PHPBIN=php + +"%PHPBIN%" "%~dp0\phpcbf" %* diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcs b/vendor/squizlabs/php_codesniffer/bin/phpcs new file mode 100644 index 00000000000..6dbade32775 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcs @@ -0,0 +1,19 @@ +#!/usr/bin/env php + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +if (\is_file(__DIR__ . '/../autoload.php') === \true) { + include_once __DIR__ . '/../autoload.php'; +} else { + include_once 'PHP/CodeSniffer/autoload.php'; +} +$runner = new \PHP_CodeSniffer\Runner(); +$exitCode = $runner->runPHPCS(); +exit($exitCode); diff --git a/vendor/squizlabs/php_codesniffer/bin/phpcs.bat b/vendor/squizlabs/php_codesniffer/bin/phpcs.bat new file mode 100644 index 00000000000..9f9be720336 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/bin/phpcs.bat @@ -0,0 +1,12 @@ +@echo off +REM PHP_CodeSniffer detects violations of a defined coding standard. +REM +REM @author Greg Sherwood +REM @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) +REM @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + +if "%PHP_PEAR_PHP_BIN%" neq "" ( + set PHPBIN=%PHP_PEAR_PHP_BIN% +) else set PHPBIN=php + +"%PHPBIN%" "%~dp0\phpcs" %* diff --git a/vendor/squizlabs/php_codesniffer/composer.json b/vendor/squizlabs/php_codesniffer/composer.json new file mode 100644 index 00000000000..c47f3ae6692 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/composer.json @@ -0,0 +1,41 @@ +{ + "name": "squizlabs\/php_codesniffer", + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "type": "library", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "homepage": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Greg Sherwood", + "role": "lead" + } + ], + "support": { + "issues": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer\/issues", + "wiki": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer\/wiki", + "source": "https:\/\/github.com\/squizlabs\/PHP_CodeSniffer" + }, + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "require": { + "php": ">=5.4.0", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "ext-simplexml": "*" + }, + "require-dev": { + "phpunit\/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0" + }, + "bin": [ + "bin\/phpcs", + "bin\/phpcbf" + ] +} \ No newline at end of file diff --git a/vendor/squizlabs/php_codesniffer/licence.txt b/vendor/squizlabs/php_codesniffer/licence.txt new file mode 100644 index 00000000000..9f95b67713c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/licence.txt @@ -0,0 +1,24 @@ +Copyright (c) 2012, Squiz Pty Ltd (ABN 77 084 670 600) +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/squizlabs/php_codesniffer/phpcs.xsd b/vendor/squizlabs/php_codesniffer/phpcs.xsd new file mode 100644 index 00000000000..d93dd868c07 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/phpcs.xsd @@ -0,0 +1,136 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Config.php b/vendor/squizlabs/php_codesniffer/src/Config.php new file mode 100644 index 00000000000..47a7ab26662 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Config.php @@ -0,0 +1,1483 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Util\Common; +/** + * Stores the configuration used to run PHPCS and PHPCBF. + * + * @property string[] $files The files and directories to check. + * @property string[] $standards The standards being used for checking. + * @property int $verbosity How verbose the output should be. + * 0: no unnecessary output + * 1: basic output for files being checked + * 2: ruleset and file parsing output + * 3: sniff execution output + * @property bool $interactive Enable interactive checking mode. + * @property bool $parallel Check files in parallel. + * @property bool $cache Enable the use of the file cache. + * @property bool $cacheFile A file where the cache data should be written + * @property bool $colors Display colours in output. + * @property bool $explain Explain the coding standards. + * @property bool $local Process local files in directories only (no recursion). + * @property bool $showSources Show sniff source codes in report output. + * @property bool $showProgress Show basic progress information while running. + * @property bool $quiet Quiet mode; disables progress and verbose output. + * @property bool $annotations Process phpcs: annotations. + * @property int $tabWidth How many spaces each tab is worth. + * @property string $encoding The encoding of the files being checked. + * @property string[] $sniffs The sniffs that should be used for checking. + * If empty, all sniffs in the supplied standards will be used. + * @property string[] $exclude The sniffs that should be excluded from checking. + * If empty, all sniffs in the supplied standards will be used. + * @property string[] $ignored Regular expressions used to ignore files and folders during checking. + * @property string $reportFile A file where the report output should be written. + * @property string $generator The documentation generator to use. + * @property string $filter The filter to use for the run. + * @property string[] $bootstrap One of more files to include before the run begins. + * @property int $reportWidth The maximum number of columns that reports should use for output. + * Set to "auto" for have this value changed to the width of the terminal. + * @property int $errorSeverity The minimum severity an error must have to be displayed. + * @property int $warningSeverity The minimum severity a warning must have to be displayed. + * @property bool $recordErrors Record the content of error messages as well as error counts. + * @property string $suffix A suffix to add to fixed files. + * @property string $basepath A file system location to strip from the paths of files shown in reports. + * @property bool $stdin Read content from STDIN instead of supplied files. + * @property string $stdinContent Content passed directly to PHPCS on STDIN. + * @property string $stdinPath The path to use for content passed on STDIN. + * + * @property array $extensions File extensions that should be checked, and what tokenizer to use. + * E.g., array('inc' => 'PHP'); + * @property array $reports The reports to use for printing output after the run. + * The format of the array is: + * array( + * 'reportName1' => 'outputFile', + * 'reportName2' => null, + * ); + * If the array value is NULL, the report will be written to the screen. + * + * @property string[] $unknown Any arguments gathered on the command line that are unknown to us. + * E.g., using `phpcs -c` will give array('c'); + */ +class Config +{ + /** + * The current version. + * + * @var string + */ + const VERSION = '3.7.2'; + /** + * Package stability; either stable, beta or alpha. + * + * @var string + */ + const STABILITY = 'stable'; + /** + * An array of settings that PHPCS and PHPCBF accept. + * + * This array is not meant to be accessed directly. Instead, use the settings + * as if they are class member vars so the __get() and __set() magic methods + * can be used to validate the values. For example, to set the verbosity level to + * level 2, use $this->verbosity = 2; instead of accessing this property directly. + * + * Each of these settings is described in the class comment property list. + * + * @var array + */ + private $settings = ['files' => null, 'standards' => null, 'verbosity' => null, 'interactive' => null, 'parallel' => null, 'cache' => null, 'cacheFile' => null, 'colors' => null, 'explain' => null, 'local' => null, 'showSources' => null, 'showProgress' => null, 'quiet' => null, 'annotations' => null, 'tabWidth' => null, 'encoding' => null, 'extensions' => null, 'sniffs' => null, 'exclude' => null, 'ignored' => null, 'reportFile' => null, 'generator' => null, 'filter' => null, 'bootstrap' => null, 'reports' => null, 'basepath' => null, 'reportWidth' => null, 'errorSeverity' => null, 'warningSeverity' => null, 'recordErrors' => null, 'suffix' => null, 'stdin' => null, 'stdinContent' => null, 'stdinPath' => null, 'unknown' => null]; + /** + * Whether or not to kill the process when an unknown command line arg is found. + * + * If FALSE, arguments that are not command line options or file/directory paths + * will be ignored and execution will continue. These values will be stored in + * $this->unknown. + * + * @var boolean + */ + public $dieOnUnknownArg; + /** + * The current command line arguments we are processing. + * + * @var string[] + */ + private $cliArgs = []; + /** + * Command line values that the user has supplied directly. + * + * @var array + */ + private static $overriddenDefaults = []; + /** + * Config file data that has been loaded for the run. + * + * @var array + */ + private static $configData = null; + /** + * The full path to the config data file that has been loaded. + * + * @var string + */ + private static $configDataFile = null; + /** + * Automatically discovered executable utility paths. + * + * @var array + */ + private static $executablePaths = []; + /** + * Get the value of an inaccessible property. + * + * @param string $name The name of the property. + * + * @return mixed + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid. + */ + public function __get($name) + { + if (\array_key_exists($name, $this->settings) === \false) { + throw new RuntimeException("ERROR: unable to get value of property \"{$name}\""); + } + return $this->settings[$name]; + } + //end __get() + /** + * Set the value of an inaccessible property. + * + * @param string $name The name of the property. + * @param mixed $value The value of the property. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the setting name is invalid. + */ + public function __set($name, $value) + { + if (\array_key_exists($name, $this->settings) === \false) { + throw new RuntimeException("Can't __set() {$name}; setting doesn't exist"); + } + switch ($name) { + case 'reportWidth': + // Support auto terminal width. + if ($value === 'auto' && \function_exists('shell_exec') === \true && \preg_match('|\\d+ (\\d+)|', \shell_exec('stty size 2>&1'), $matches) === 1) { + $value = (int) $matches[1]; + } else { + $value = (int) $value; + } + break; + case 'standards': + $cleaned = []; + // Check if the standard name is valid, or if the case is invalid. + $installedStandards = \PHP_CodeSniffer\Util\Standards::getInstalledStandards(); + foreach ($value as $standard) { + foreach ($installedStandards as $validStandard) { + if (\strtolower($standard) === \strtolower($validStandard)) { + $standard = $validStandard; + break; + } + } + $cleaned[] = $standard; + } + $value = $cleaned; + break; + default: + // No validation required. + break; + } + //end switch + $this->settings[$name] = $value; + } + //end __set() + /** + * Check if the value of an inaccessible property is set. + * + * @param string $name The name of the property. + * + * @return bool + */ + public function __isset($name) + { + return isset($this->settings[$name]); + } + //end __isset() + /** + * Unset the value of an inaccessible property. + * + * @param string $name The name of the property. + * + * @return void + */ + public function __unset($name) + { + $this->settings[$name] = null; + } + //end __unset() + /** + * Get the array of all config settings. + * + * @return array + */ + public function getSettings() + { + return $this->settings; + } + //end getSettings() + /** + * Set the array of all config settings. + * + * @param array $settings The array of config settings. + * + * @return void + */ + public function setSettings($settings) + { + return $this->settings = $settings; + } + //end setSettings() + /** + * Creates a Config object and populates it with command line values. + * + * @param array $cliArgs An array of values gathered from CLI args. + * @param bool $dieOnUnknownArg Whether or not to kill the process when an + * unknown command line arg is found. + * + * @return void + */ + public function __construct(array $cliArgs = [], $dieOnUnknownArg = \true) + { + if (\defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS') === \true) { + // Let everything through during testing so that we can + // make use of PHPUnit command line arguments as well. + $this->dieOnUnknownArg = \false; + } else { + $this->dieOnUnknownArg = $dieOnUnknownArg; + } + if (empty($cliArgs) === \true) { + $cliArgs = $_SERVER['argv']; + \array_shift($cliArgs); + } + $this->restoreDefaults(); + $this->setCommandLineValues($cliArgs); + if (isset(self::$overriddenDefaults['standards']) === \false) { + // They did not supply a standard to use. + // Look for a default ruleset in the current directory or higher. + $currentDir = \getcwd(); + $defaultFiles = ['.phpcs.xml', 'phpcs.xml', '.phpcs.xml.dist', 'phpcs.xml.dist']; + do { + foreach ($defaultFiles as $defaultFilename) { + $default = $currentDir . \DIRECTORY_SEPARATOR . $defaultFilename; + if (\is_file($default) === \true) { + $this->standards = [$default]; + break 2; + } + } + $lastDir = $currentDir; + $currentDir = \dirname($currentDir); + } while ($currentDir !== '.' && $currentDir !== $lastDir && Common::isReadable($currentDir) === \true); + } + //end if + if (\defined('STDIN') === \false || \stripos(\PHP_OS, 'WIN') === 0) { + return; + } + $handle = \fopen('php://stdin', 'r'); + // Check for content on STDIN. + if ($this->stdin === \true || \PHP_CodeSniffer\Util\Common::isStdinATTY() === \false && \feof($handle) === \false) { + $readStreams = [$handle]; + $writeSteams = null; + $fileContents = ''; + while (\is_resource($handle) === \true && \feof($handle) === \false) { + // Set a timeout of 200ms. + if (\stream_select($readStreams, $writeSteams, $writeSteams, 0, 200000) === 0) { + break; + } + $fileContents .= \fgets($handle); + } + if (\trim($fileContents) !== '') { + $this->stdin = \true; + $this->stdinContent = $fileContents; + self::$overriddenDefaults['stdin'] = \true; + self::$overriddenDefaults['stdinContent'] = \true; + } + } + //end if + \fclose($handle); + } + //end __construct() + /** + * Set the command line values. + * + * @param array $args An array of command line arguments to set. + * + * @return void + */ + public function setCommandLineValues($args) + { + $this->cliArgs = $args; + $numArgs = \count($args); + for ($i = 0; $i < $numArgs; $i++) { + $arg = $this->cliArgs[$i]; + if ($arg === '') { + continue; + } + if ($arg[0] === '-') { + if ($arg === '-') { + // Asking to read from STDIN. + $this->stdin = \true; + self::$overriddenDefaults['stdin'] = \true; + continue; + } + if ($arg === '--') { + // Empty argument, ignore it. + continue; + } + if ($arg[1] === '-') { + $this->processLongArgument(\substr($arg, 2), $i); + } else { + $switches = \str_split($arg); + foreach ($switches as $switch) { + if ($switch === '-') { + continue; + } + $this->processShortArgument($switch, $i); + } + } + } else { + $this->processUnknownArgument($arg, $i); + } + //end if + } + //end for + } + //end setCommandLineValues() + /** + * Restore default values for all possible command line arguments. + * + * @return void + */ + public function restoreDefaults() + { + $this->files = []; + $this->standards = ['PEAR']; + $this->verbosity = 0; + $this->interactive = \false; + $this->cache = \false; + $this->cacheFile = null; + $this->colors = \false; + $this->explain = \false; + $this->local = \false; + $this->showSources = \false; + $this->showProgress = \false; + $this->quiet = \false; + $this->annotations = \true; + $this->parallel = 1; + $this->tabWidth = 0; + $this->encoding = 'utf-8'; + $this->extensions = ['php' => 'PHP', 'inc' => 'PHP', 'js' => 'JS', 'css' => 'CSS']; + $this->sniffs = []; + $this->exclude = []; + $this->ignored = []; + $this->reportFile = null; + $this->generator = null; + $this->filter = null; + $this->bootstrap = []; + $this->basepath = null; + $this->reports = ['full' => null]; + $this->reportWidth = 'auto'; + $this->errorSeverity = 5; + $this->warningSeverity = 5; + $this->recordErrors = \true; + $this->suffix = ''; + $this->stdin = \false; + $this->stdinContent = null; + $this->stdinPath = null; + $this->unknown = []; + $standard = self::getConfigData('default_standard'); + if ($standard !== null) { + $this->standards = \explode(',', $standard); + } + $reportFormat = self::getConfigData('report_format'); + if ($reportFormat !== null) { + $this->reports = [$reportFormat => null]; + } + $tabWidth = self::getConfigData('tab_width'); + if ($tabWidth !== null) { + $this->tabWidth = (int) $tabWidth; + } + $encoding = self::getConfigData('encoding'); + if ($encoding !== null) { + $this->encoding = \strtolower($encoding); + } + $severity = self::getConfigData('severity'); + if ($severity !== null) { + $this->errorSeverity = (int) $severity; + $this->warningSeverity = (int) $severity; + } + $severity = self::getConfigData('error_severity'); + if ($severity !== null) { + $this->errorSeverity = (int) $severity; + } + $severity = self::getConfigData('warning_severity'); + if ($severity !== null) { + $this->warningSeverity = (int) $severity; + } + $showWarnings = self::getConfigData('show_warnings'); + if ($showWarnings !== null) { + $showWarnings = (bool) $showWarnings; + if ($showWarnings === \false) { + $this->warningSeverity = 0; + } + } + $reportWidth = self::getConfigData('report_width'); + if ($reportWidth !== null) { + $this->reportWidth = $reportWidth; + } + $showProgress = self::getConfigData('show_progress'); + if ($showProgress !== null) { + $this->showProgress = (bool) $showProgress; + } + $quiet = self::getConfigData('quiet'); + if ($quiet !== null) { + $this->quiet = (bool) $quiet; + } + $colors = self::getConfigData('colors'); + if ($colors !== null) { + $this->colors = (bool) $colors; + } + if (\defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS') === \false) { + $cache = self::getConfigData('cache'); + if ($cache !== null) { + $this->cache = (bool) $cache; + } + $parallel = self::getConfigData('parallel'); + if ($parallel !== null) { + $this->parallel = \max((int) $parallel, 1); + } + } + } + //end restoreDefaults() + /** + * Processes a short (-e) command line argument. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processShortArgument($arg, $pos) + { + switch ($arg) { + case 'h': + case '?': + \ob_start(); + $this->printUsage(); + $output = \ob_get_contents(); + \ob_end_clean(); + throw new DeepExitException($output, 0); + case 'i': + \ob_start(); + \PHP_CodeSniffer\Util\Standards::printInstalledStandards(); + $output = \ob_get_contents(); + \ob_end_clean(); + throw new DeepExitException($output, 0); + case 'v': + if ($this->quiet === \true) { + // Ignore when quiet mode is enabled. + break; + } + $this->verbosity++; + self::$overriddenDefaults['verbosity'] = \true; + break; + case 'l': + $this->local = \true; + self::$overriddenDefaults['local'] = \true; + break; + case 's': + $this->showSources = \true; + self::$overriddenDefaults['showSources'] = \true; + break; + case 'a': + $this->interactive = \true; + self::$overriddenDefaults['interactive'] = \true; + break; + case 'e': + $this->explain = \true; + self::$overriddenDefaults['explain'] = \true; + break; + case 'p': + if ($this->quiet === \true) { + // Ignore when quiet mode is enabled. + break; + } + $this->showProgress = \true; + self::$overriddenDefaults['showProgress'] = \true; + break; + case 'q': + // Quiet mode disables a few other settings as well. + $this->quiet = \true; + $this->showProgress = \false; + $this->verbosity = 0; + self::$overriddenDefaults['quiet'] = \true; + break; + case 'm': + $this->recordErrors = \false; + self::$overriddenDefaults['recordErrors'] = \true; + break; + case 'd': + $ini = \explode('=', $this->cliArgs[$pos + 1]); + $this->cliArgs[$pos + 1] = ''; + if (isset($ini[1]) === \true) { + \ini_set($ini[0], $ini[1]); + } else { + \ini_set($ini[0], \true); + } + break; + case 'n': + if (isset(self::$overriddenDefaults['warningSeverity']) === \false) { + $this->warningSeverity = 0; + self::$overriddenDefaults['warningSeverity'] = \true; + } + break; + case 'w': + if (isset(self::$overriddenDefaults['warningSeverity']) === \false) { + $this->warningSeverity = $this->errorSeverity; + self::$overriddenDefaults['warningSeverity'] = \true; + } + break; + default: + if ($this->dieOnUnknownArg === \false) { + $unknown = $this->unknown; + $unknown[] = $arg; + $this->unknown = $unknown; + } else { + $this->processUnknownArgument('-' . $arg, $pos); + } + } + //end switch + } + //end processShortArgument() + /** + * Processes a long (--example) command line argument. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processLongArgument($arg, $pos) + { + switch ($arg) { + case 'help': + \ob_start(); + $this->printUsage(); + $output = \ob_get_contents(); + \ob_end_clean(); + throw new DeepExitException($output, 0); + case 'version': + $output = 'PHP_CodeSniffer version ' . self::VERSION . ' (' . self::STABILITY . ') '; + $output .= 'by Squiz (http://www.squiz.net)' . \PHP_EOL; + throw new DeepExitException($output, 0); + case 'colors': + if (isset(self::$overriddenDefaults['colors']) === \true) { + break; + } + $this->colors = \true; + self::$overriddenDefaults['colors'] = \true; + break; + case 'no-colors': + if (isset(self::$overriddenDefaults['colors']) === \true) { + break; + } + $this->colors = \false; + self::$overriddenDefaults['colors'] = \true; + break; + case 'cache': + if (isset(self::$overriddenDefaults['cache']) === \true) { + break; + } + if (\defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS') === \false) { + $this->cache = \true; + self::$overriddenDefaults['cache'] = \true; + } + break; + case 'no-cache': + if (isset(self::$overriddenDefaults['cache']) === \true) { + break; + } + $this->cache = \false; + self::$overriddenDefaults['cache'] = \true; + break; + case 'ignore-annotations': + if (isset(self::$overriddenDefaults['annotations']) === \true) { + break; + } + $this->annotations = \false; + self::$overriddenDefaults['annotations'] = \true; + break; + case 'config-set': + if (isset($this->cliArgs[$pos + 1]) === \false || isset($this->cliArgs[$pos + 2]) === \false) { + $error = 'ERROR: Setting a config option requires a name and value' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $key = $this->cliArgs[$pos + 1]; + $value = $this->cliArgs[$pos + 2]; + $current = self::getConfigData($key); + try { + $this->setConfigData($key, $value); + } catch (\Exception $e) { + throw new DeepExitException($e->getMessage() . \PHP_EOL, 3); + } + $output = 'Using config file: ' . self::$configDataFile . \PHP_EOL . \PHP_EOL; + if ($current === null) { + $output .= "Config value \"{$key}\" added successfully" . \PHP_EOL; + } else { + $output .= "Config value \"{$key}\" updated successfully; old value was \"{$current}\"" . \PHP_EOL; + } + throw new DeepExitException($output, 0); + case 'config-delete': + if (isset($this->cliArgs[$pos + 1]) === \false) { + $error = 'ERROR: Deleting a config option requires the name of the option' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $output = 'Using config file: ' . self::$configDataFile . \PHP_EOL . \PHP_EOL; + $key = $this->cliArgs[$pos + 1]; + $current = self::getConfigData($key); + if ($current === null) { + $output .= "Config value \"{$key}\" has not been set" . \PHP_EOL; + } else { + try { + $this->setConfigData($key, null); + } catch (\Exception $e) { + throw new DeepExitException($e->getMessage() . \PHP_EOL, 3); + } + $output .= "Config value \"{$key}\" removed successfully; old value was \"{$current}\"" . \PHP_EOL; + } + throw new DeepExitException($output, 0); + case 'config-show': + \ob_start(); + $data = self::getAllConfigData(); + echo 'Using config file: ' . self::$configDataFile . \PHP_EOL . \PHP_EOL; + $this->printConfigData($data); + $output = \ob_get_contents(); + \ob_end_clean(); + throw new DeepExitException($output, 0); + case 'runtime-set': + if (isset($this->cliArgs[$pos + 1]) === \false || isset($this->cliArgs[$pos + 2]) === \false) { + $error = 'ERROR: Setting a runtime config option requires a name and value' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $key = $this->cliArgs[$pos + 1]; + $value = $this->cliArgs[$pos + 2]; + $this->cliArgs[$pos + 1] = ''; + $this->cliArgs[$pos + 2] = ''; + self::setConfigData($key, $value, \true); + if (isset(self::$overriddenDefaults['runtime-set']) === \false) { + self::$overriddenDefaults['runtime-set'] = []; + } + self::$overriddenDefaults['runtime-set'][$key] = \true; + break; + default: + if (\substr($arg, 0, 7) === 'sniffs=') { + if (isset(self::$overriddenDefaults['sniffs']) === \true) { + break; + } + $sniffs = \explode(',', \substr($arg, 7)); + foreach ($sniffs as $sniff) { + if (\substr_count($sniff, '.') !== 2) { + $error = 'ERROR: The specified sniff code "' . $sniff . '" is invalid' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } + $this->sniffs = $sniffs; + self::$overriddenDefaults['sniffs'] = \true; + } else { + if (\substr($arg, 0, 8) === 'exclude=') { + if (isset(self::$overriddenDefaults['exclude']) === \true) { + break; + } + $sniffs = \explode(',', \substr($arg, 8)); + foreach ($sniffs as $sniff) { + if (\substr_count($sniff, '.') !== 2) { + $error = 'ERROR: The specified sniff code "' . $sniff . '" is invalid' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } + $this->exclude = $sniffs; + self::$overriddenDefaults['exclude'] = \true; + } else { + if (\defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS') === \false && \substr($arg, 0, 6) === 'cache=') { + if (isset(self::$overriddenDefaults['cache']) === \true && $this->cache === \false || isset(self::$overriddenDefaults['cacheFile']) === \true) { + break; + } + // Turn caching on. + $this->cache = \true; + self::$overriddenDefaults['cache'] = \true; + $this->cacheFile = \PHP_CodeSniffer\Util\Common::realpath(\substr($arg, 6)); + // It may not exist and return false instead. + if ($this->cacheFile === \false) { + $this->cacheFile = \substr($arg, 6); + $dir = \dirname($this->cacheFile); + if (\is_dir($dir) === \false) { + $error = 'ERROR: The specified cache file path "' . $this->cacheFile . '" points to a non-existent directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + if ($dir === '.') { + // Passed cache file is a file in the current directory. + $this->cacheFile = \getcwd() . '/' . \basename($this->cacheFile); + } else { + if ($dir[0] === '/') { + // An absolute path. + $dir = \PHP_CodeSniffer\Util\Common::realpath($dir); + } else { + $dir = \PHP_CodeSniffer\Util\Common::realpath(\getcwd() . '/' . $dir); + } + if ($dir !== \false) { + // Cache file path is relative. + $this->cacheFile = $dir . '/' . \basename($this->cacheFile); + } + } + } + //end if + self::$overriddenDefaults['cacheFile'] = \true; + if (\is_dir($this->cacheFile) === \true) { + $error = 'ERROR: The specified cache file path "' . $this->cacheFile . '" is a directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } else { + if (\substr($arg, 0, 10) === 'bootstrap=') { + $files = \explode(',', \substr($arg, 10)); + $bootstrap = []; + foreach ($files as $file) { + $path = \PHP_CodeSniffer\Util\Common::realpath($file); + if ($path === \false) { + $error = 'ERROR: The specified bootstrap file "' . $file . '" does not exist' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $bootstrap[] = $path; + } + $this->bootstrap = \array_merge($this->bootstrap, $bootstrap); + self::$overriddenDefaults['bootstrap'] = \true; + } else { + if (\substr($arg, 0, 10) === 'file-list=') { + $fileList = \substr($arg, 10); + $path = \PHP_CodeSniffer\Util\Common::realpath($fileList); + if ($path === \false) { + $error = 'ERROR: The specified file list "' . $fileList . '" does not exist' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $files = \file($path); + foreach ($files as $inputFile) { + $inputFile = \trim($inputFile); + // Skip empty lines. + if ($inputFile === '') { + continue; + } + $this->processFilePath($inputFile); + } + } else { + if (\substr($arg, 0, 11) === 'stdin-path=') { + if (isset(self::$overriddenDefaults['stdinPath']) === \true) { + break; + } + $this->stdinPath = \PHP_CodeSniffer\Util\Common::realpath(\substr($arg, 11)); + // It may not exist and return false instead, so use whatever they gave us. + if ($this->stdinPath === \false) { + $this->stdinPath = \trim(\substr($arg, 11)); + } + self::$overriddenDefaults['stdinPath'] = \true; + } else { + if (\PHP_CODESNIFFER_CBF === \false && \substr($arg, 0, 12) === 'report-file=') { + if (isset(self::$overriddenDefaults['reportFile']) === \true) { + break; + } + $this->reportFile = \PHP_CodeSniffer\Util\Common::realpath(\substr($arg, 12)); + // It may not exist and return false instead. + if ($this->reportFile === \false) { + $this->reportFile = \substr($arg, 12); + $dir = \PHP_CodeSniffer\Util\Common::realpath(\dirname($this->reportFile)); + if (\is_dir($dir) === \false) { + $error = 'ERROR: The specified report file path "' . $this->reportFile . '" points to a non-existent directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $this->reportFile = $dir . '/' . \basename($this->reportFile); + } + //end if + self::$overriddenDefaults['reportFile'] = \true; + if (\is_dir($this->reportFile) === \true) { + $error = 'ERROR: The specified report file path "' . $this->reportFile . '" is a directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } else { + if (\substr($arg, 0, 13) === 'report-width=') { + if (isset(self::$overriddenDefaults['reportWidth']) === \true) { + break; + } + $this->reportWidth = \substr($arg, 13); + self::$overriddenDefaults['reportWidth'] = \true; + } else { + if (\substr($arg, 0, 9) === 'basepath=') { + if (isset(self::$overriddenDefaults['basepath']) === \true) { + break; + } + self::$overriddenDefaults['basepath'] = \true; + if (\substr($arg, 9) === '') { + $this->basepath = null; + break; + } + $this->basepath = \PHP_CodeSniffer\Util\Common::realpath(\substr($arg, 9)); + // It may not exist and return false instead. + if ($this->basepath === \false) { + $this->basepath = \substr($arg, 9); + } + if (\is_dir($this->basepath) === \false) { + $error = 'ERROR: The specified basepath "' . $this->basepath . '" points to a non-existent directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } else { + if (\substr($arg, 0, 7) === 'report=' || \substr($arg, 0, 7) === 'report-') { + $reports = []; + if ($arg[6] === '-') { + // This is a report with file output. + $split = \strpos($arg, '='); + if ($split === \false) { + $report = \substr($arg, 7); + $output = null; + } else { + $report = \substr($arg, 7, $split - 7); + $output = \substr($arg, $split + 1); + if ($output === \false) { + $output = null; + } else { + $dir = \PHP_CodeSniffer\Util\Common::realpath(\dirname($output)); + if (\is_dir($dir) === \false) { + $error = 'ERROR: The specified ' . $report . ' report file path "' . $output . '" points to a non-existent directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $output = $dir . '/' . \basename($output); + if (\is_dir($output) === \true) { + $error = 'ERROR: The specified ' . $report . ' report file path "' . $output . '" is a directory' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } + //end if + } + //end if + $reports[$report] = $output; + } else { + // This is a single report. + if (isset(self::$overriddenDefaults['reports']) === \true) { + break; + } + $reportNames = \explode(',', \substr($arg, 7)); + foreach ($reportNames as $report) { + $reports[$report] = null; + } + } + //end if + // Remove the default value so the CLI value overrides it. + if (isset(self::$overriddenDefaults['reports']) === \false) { + $this->reports = $reports; + } else { + $this->reports = \array_merge($this->reports, $reports); + } + self::$overriddenDefaults['reports'] = \true; + } else { + if (\substr($arg, 0, 7) === 'filter=') { + if (isset(self::$overriddenDefaults['filter']) === \true) { + break; + } + $this->filter = \substr($arg, 7); + self::$overriddenDefaults['filter'] = \true; + } else { + if (\substr($arg, 0, 9) === 'standard=') { + $standards = \trim(\substr($arg, 9)); + if ($standards !== '') { + $this->standards = \explode(',', $standards); + } + self::$overriddenDefaults['standards'] = \true; + } else { + if (\substr($arg, 0, 11) === 'extensions=') { + if (isset(self::$overriddenDefaults['extensions']) === \true) { + break; + } + $extensions = \explode(',', \substr($arg, 11)); + $newExtensions = []; + foreach ($extensions as $ext) { + $slash = \strpos($ext, '/'); + if ($slash !== \false) { + // They specified the tokenizer too. + list($ext, $tokenizer) = \explode('/', $ext); + $newExtensions[$ext] = \strtoupper($tokenizer); + continue; + } + if (isset($this->extensions[$ext]) === \true) { + $newExtensions[$ext] = $this->extensions[$ext]; + } else { + $newExtensions[$ext] = 'PHP'; + } + } + $this->extensions = $newExtensions; + self::$overriddenDefaults['extensions'] = \true; + } else { + if (\substr($arg, 0, 7) === 'suffix=') { + if (isset(self::$overriddenDefaults['suffix']) === \true) { + break; + } + $this->suffix = \substr($arg, 7); + self::$overriddenDefaults['suffix'] = \true; + } else { + if (\substr($arg, 0, 9) === 'parallel=') { + if (isset(self::$overriddenDefaults['parallel']) === \true) { + break; + } + $this->parallel = \max((int) \substr($arg, 9), 1); + self::$overriddenDefaults['parallel'] = \true; + } else { + if (\substr($arg, 0, 9) === 'severity=') { + $this->errorSeverity = (int) \substr($arg, 9); + $this->warningSeverity = $this->errorSeverity; + if (isset(self::$overriddenDefaults['errorSeverity']) === \false) { + self::$overriddenDefaults['errorSeverity'] = \true; + } + if (isset(self::$overriddenDefaults['warningSeverity']) === \false) { + self::$overriddenDefaults['warningSeverity'] = \true; + } + } else { + if (\substr($arg, 0, 15) === 'error-severity=') { + if (isset(self::$overriddenDefaults['errorSeverity']) === \true) { + break; + } + $this->errorSeverity = (int) \substr($arg, 15); + self::$overriddenDefaults['errorSeverity'] = \true; + } else { + if (\substr($arg, 0, 17) === 'warning-severity=') { + if (isset(self::$overriddenDefaults['warningSeverity']) === \true) { + break; + } + $this->warningSeverity = (int) \substr($arg, 17); + self::$overriddenDefaults['warningSeverity'] = \true; + } else { + if (\substr($arg, 0, 7) === 'ignore=') { + if (isset(self::$overriddenDefaults['ignored']) === \true) { + break; + } + // Split the ignore string on commas, unless the comma is escaped + // using 1 or 3 slashes (\, or \\\,). + $patterns = \preg_split('/(?<=(?ignored = $ignored; + self::$overriddenDefaults['ignored'] = \true; + } else { + if (\substr($arg, 0, 10) === 'generator=' && \PHP_CODESNIFFER_CBF === \false) { + if (isset(self::$overriddenDefaults['generator']) === \true) { + break; + } + $this->generator = \substr($arg, 10); + self::$overriddenDefaults['generator'] = \true; + } else { + if (\substr($arg, 0, 9) === 'encoding=') { + if (isset(self::$overriddenDefaults['encoding']) === \true) { + break; + } + $this->encoding = \strtolower(\substr($arg, 9)); + self::$overriddenDefaults['encoding'] = \true; + } else { + if (\substr($arg, 0, 10) === 'tab-width=') { + if (isset(self::$overriddenDefaults['tabWidth']) === \true) { + break; + } + $this->tabWidth = (int) \substr($arg, 10); + self::$overriddenDefaults['tabWidth'] = \true; + } else { + if ($this->dieOnUnknownArg === \false) { + $eqPos = \strpos($arg, '='); + try { + if ($eqPos === \false) { + $this->values[$arg] = $arg; + } else { + $value = \substr($arg, $eqPos + 1); + $arg = \substr($arg, 0, $eqPos); + $this->values[$arg] = $value; + } + } catch (RuntimeException $e) { + // Value is not valid, so just ignore it. + } + } else { + $this->processUnknownArgument('--' . $arg, $pos); + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + } + //end if + break; + } + //end switch + } + //end processLongArgument() + /** + * Processes an unknown command line argument. + * + * Assumes all unknown arguments are files and folders to check. + * + * @param string $arg The command line argument. + * @param int $pos The position of the argument on the command line. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processUnknownArgument($arg, $pos) + { + // We don't know about any additional switches; just files. + if ($arg[0] === '-') { + if ($this->dieOnUnknownArg === \false) { + return; + } + $error = "ERROR: option \"{$arg}\" not known" . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + $this->processFilePath($arg); + } + //end processUnknownArgument() + /** + * Processes a file path and add it to the file list. + * + * @param string $path The path to the file to add. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processFilePath($path) + { + // If we are processing STDIN, don't record any files to check. + if ($this->stdin === \true) { + return; + } + $file = \PHP_CodeSniffer\Util\Common::realpath($path); + if (\file_exists($file) === \false) { + if ($this->dieOnUnknownArg === \false) { + return; + } + $error = 'ERROR: The file "' . $path . '" does not exist.' . \PHP_EOL . \PHP_EOL; + $error .= $this->printShortUsage(\true); + throw new DeepExitException($error, 3); + } else { + // Can't modify the files array directly because it's not a real + // class member, so need to use this little get/modify/set trick. + $files = $this->files; + $files[] = $file; + $this->files = $files; + self::$overriddenDefaults['files'] = \true; + } + } + //end processFilePath() + /** + * Prints out the usage information for this script. + * + * @return void + */ + public function printUsage() + { + echo \PHP_EOL; + if (\PHP_CODESNIFFER_CBF === \true) { + $this->printPHPCBFUsage(); + } else { + $this->printPHPCSUsage(); + } + echo \PHP_EOL; + } + //end printUsage() + /** + * Prints out the short usage information for this script. + * + * @param bool $return If TRUE, the usage string is returned + * instead of output to screen. + * + * @return string|void + */ + public function printShortUsage($return = \false) + { + if (\PHP_CODESNIFFER_CBF === \true) { + $usage = 'Run "phpcbf --help" for usage information'; + } else { + $usage = 'Run "phpcs --help" for usage information'; + } + $usage .= \PHP_EOL . \PHP_EOL; + if ($return === \true) { + return $usage; + } + echo $usage; + } + //end printShortUsage() + /** + * Prints out the usage information for PHPCS. + * + * @return void + */ + public function printPHPCSUsage() + { + echo 'Usage: phpcs [-nwlsaepqvi] [-d key[=value]] [--colors] [--no-colors]' . \PHP_EOL; + echo ' [--cache[=]] [--no-cache] [--tab-width=]' . \PHP_EOL; + echo ' [--report=] [--report-file=] [--report-=]' . \PHP_EOL; + echo ' [--report-width=] [--basepath=] [--bootstrap=]' . \PHP_EOL; + echo ' [--severity=] [--error-severity=] [--warning-severity=]' . \PHP_EOL; + echo ' [--runtime-set key value] [--config-set key value] [--config-delete key] [--config-show]' . \PHP_EOL; + echo ' [--standard=] [--sniffs=] [--exclude=]' . \PHP_EOL; + echo ' [--encoding=] [--parallel=] [--generator=]' . \PHP_EOL; + echo ' [--extensions=] [--ignore=] [--ignore-annotations]' . \PHP_EOL; + echo ' [--stdin-path=] [--file-list=] [--filter=] - ...' . \PHP_EOL; + echo \PHP_EOL; + echo ' - Check STDIN instead of local files and directories' . \PHP_EOL; + echo ' -n Do not print warnings (shortcut for --warning-severity=0)' . \PHP_EOL; + echo ' -w Print both warnings and errors (this is the default)' . \PHP_EOL; + echo ' -l Local directory only, no recursion' . \PHP_EOL; + echo ' -s Show sniff codes in all reports' . \PHP_EOL; + echo ' -a Run interactively' . \PHP_EOL; + echo ' -e Explain a standard by showing the sniffs it includes' . \PHP_EOL; + echo ' -p Show progress of the run' . \PHP_EOL; + echo ' -q Quiet mode; disables progress and verbose output' . \PHP_EOL; + echo ' -m Stop error messages from being recorded' . \PHP_EOL; + echo ' (saves a lot of memory, but stops many reports from being used)' . \PHP_EOL; + echo ' -v Print processed files' . \PHP_EOL; + echo ' -vv Print ruleset and token output' . \PHP_EOL; + echo ' -vvv Print sniff processing information' . \PHP_EOL; + echo ' -i Show a list of installed coding standards' . \PHP_EOL; + echo ' -d Set the [key] php.ini value to [value] or [true] if value is omitted' . \PHP_EOL; + echo \PHP_EOL; + echo ' --help Print this help message' . \PHP_EOL; + echo ' --version Print version information' . \PHP_EOL; + echo ' --colors Use colors in output' . \PHP_EOL; + echo ' --no-colors Do not use colors in output (this is the default)' . \PHP_EOL; + echo ' --cache Cache results between runs' . \PHP_EOL; + echo ' --no-cache Do not cache results between runs (this is the default)' . \PHP_EOL; + echo ' --ignore-annotations Ignore all phpcs: annotations in code comments' . \PHP_EOL; + echo \PHP_EOL; + echo ' Use a specific file for caching (uses a temporary file by default)' . \PHP_EOL; + echo ' A path to strip from the front of file paths inside reports' . \PHP_EOL; + echo ' A comma separated list of files to run before processing begins' . \PHP_EOL; + echo ' The encoding of the files being checked (default is utf-8)' . \PHP_EOL; + echo ' A comma separated list of file extensions to check' . \PHP_EOL; + echo ' The type of the file can be specified using: ext/type' . \PHP_EOL; + echo ' e.g., module/php,es/js' . \PHP_EOL; + echo ' One or more files and/or directories to check' . \PHP_EOL; + echo ' A file containing a list of files and/or directories to check (one per line)' . \PHP_EOL; + echo ' Use either the "gitmodified" or "gitstaged" filter,' . \PHP_EOL; + echo ' or specify the path to a custom filter class' . \PHP_EOL; + echo ' Use either the "HTML", "Markdown" or "Text" generator' . \PHP_EOL; + echo ' (forces documentation generation instead of checking)' . \PHP_EOL; + echo ' A comma separated list of patterns to ignore files and directories' . \PHP_EOL; + echo ' How many files should be checked simultaneously (default is 1)' . \PHP_EOL; + echo ' Print either the "full", "xml", "checkstyle", "csv"' . \PHP_EOL; + echo ' "json", "junit", "emacs", "source", "summary", "diff"' . \PHP_EOL; + echo ' "svnblame", "gitblame", "hgblame" or "notifysend" report,' . \PHP_EOL; + echo ' or specify the path to a custom report class' . \PHP_EOL; + echo ' (the "full" report is printed by default)' . \PHP_EOL; + echo ' Write the report to the specified file path' . \PHP_EOL; + echo ' How many columns wide screen reports should be printed' . \PHP_EOL; + echo ' or set to "auto" to use current screen width, where supported' . \PHP_EOL; + echo ' The minimum severity required to display an error or warning' . \PHP_EOL; + echo ' A comma separated list of sniff codes to include or exclude from checking' . \PHP_EOL; + echo ' (all sniffs must be part of the specified standard)' . \PHP_EOL; + echo ' The name or path of the coding standard to use' . \PHP_EOL; + echo ' If processing STDIN, the file path that STDIN will be processed as' . \PHP_EOL; + echo ' The number of spaces each tab represents' . \PHP_EOL; + } + //end printPHPCSUsage() + /** + * Prints out the usage information for PHPCBF. + * + * @return void + */ + public function printPHPCBFUsage() + { + echo 'Usage: phpcbf [-nwli] [-d key[=value]] [--ignore-annotations] [--bootstrap=]' . \PHP_EOL; + echo ' [--standard=] [--sniffs=] [--exclude=] [--suffix=]' . \PHP_EOL; + echo ' [--severity=] [--error-severity=] [--warning-severity=]' . \PHP_EOL; + echo ' [--tab-width=] [--encoding=] [--parallel=]' . \PHP_EOL; + echo ' [--basepath=] [--extensions=] [--ignore=]' . \PHP_EOL; + echo ' [--stdin-path=] [--file-list=] [--filter=] - ...' . \PHP_EOL; + echo \PHP_EOL; + echo ' - Fix STDIN instead of local files and directories' . \PHP_EOL; + echo ' -n Do not fix warnings (shortcut for --warning-severity=0)' . \PHP_EOL; + echo ' -w Fix both warnings and errors (on by default)' . \PHP_EOL; + echo ' -l Local directory only, no recursion' . \PHP_EOL; + echo ' -p Show progress of the run' . \PHP_EOL; + echo ' -q Quiet mode; disables progress and verbose output' . \PHP_EOL; + echo ' -v Print processed files' . \PHP_EOL; + echo ' -vv Print ruleset and token output' . \PHP_EOL; + echo ' -vvv Print sniff processing information' . \PHP_EOL; + echo ' -i Show a list of installed coding standards' . \PHP_EOL; + echo ' -d Set the [key] php.ini value to [value] or [true] if value is omitted' . \PHP_EOL; + echo \PHP_EOL; + echo ' --help Print this help message' . \PHP_EOL; + echo ' --version Print version information' . \PHP_EOL; + echo ' --ignore-annotations Ignore all phpcs: annotations in code comments' . \PHP_EOL; + echo \PHP_EOL; + echo ' A path to strip from the front of file paths inside reports' . \PHP_EOL; + echo ' A comma separated list of files to run before processing begins' . \PHP_EOL; + echo ' The encoding of the files being fixed (default is utf-8)' . \PHP_EOL; + echo ' A comma separated list of file extensions to fix' . \PHP_EOL; + echo ' The type of the file can be specified using: ext/type' . \PHP_EOL; + echo ' e.g., module/php,es/js' . \PHP_EOL; + echo ' One or more files and/or directories to fix' . \PHP_EOL; + echo ' A file containing a list of files and/or directories to fix (one per line)' . \PHP_EOL; + echo ' Use either the "gitmodified" or "gitstaged" filter,' . \PHP_EOL; + echo ' or specify the path to a custom filter class' . \PHP_EOL; + echo ' A comma separated list of patterns to ignore files and directories' . \PHP_EOL; + echo ' How many files should be fixed simultaneously (default is 1)' . \PHP_EOL; + echo ' The minimum severity required to fix an error or warning' . \PHP_EOL; + echo ' A comma separated list of sniff codes to include or exclude from fixing' . \PHP_EOL; + echo ' (all sniffs must be part of the specified standard)' . \PHP_EOL; + echo ' The name or path of the coding standard to use' . \PHP_EOL; + echo ' If processing STDIN, the file path that STDIN will be processed as' . \PHP_EOL; + echo ' Write modified files to a filename using this suffix' . \PHP_EOL; + echo ' ("diff" and "patch" are not used in this mode)' . \PHP_EOL; + echo ' The number of spaces each tab represents' . \PHP_EOL; + } + //end printPHPCBFUsage() + /** + * Get a single config value. + * + * @param string $key The name of the config value. + * + * @return string|null + * @see setConfigData() + * @see getAllConfigData() + */ + public static function getConfigData($key) + { + $phpCodeSnifferConfig = self::getAllConfigData(); + if ($phpCodeSnifferConfig === null) { + return null; + } + if (isset($phpCodeSnifferConfig[$key]) === \false) { + return null; + } + return $phpCodeSnifferConfig[$key]; + } + //end getConfigData() + /** + * Get the path to an executable utility. + * + * @param string $name The name of the executable utility. + * + * @return string|null + * @see getConfigData() + */ + public static function getExecutablePath($name) + { + $data = self::getConfigData($name . '_path'); + if ($data !== null) { + return $data; + } + if ($name === "php") { + // For php, we know the executable path. There's no need to look it up. + return \PHP_BINARY; + } + if (\array_key_exists($name, self::$executablePaths) === \true) { + return self::$executablePaths[$name]; + } + if (\stripos(\PHP_OS, 'WIN') === 0) { + $cmd = 'where ' . \escapeshellarg($name) . ' 2> nul'; + } else { + $cmd = 'which ' . \escapeshellarg($name) . ' 2> /dev/null'; + } + $result = \exec($cmd, $output, $retVal); + if ($retVal !== 0) { + $result = null; + } + self::$executablePaths[$name] = $result; + return $result; + } + //end getExecutablePath() + /** + * Set a single config value. + * + * @param string $key The name of the config value. + * @param string|null $value The value to set. If null, the config + * entry is deleted, reverting it to the + * default value. + * @param boolean $temp Set this config data temporarily for this + * script run. This will not write the config + * data to the config file. + * + * @return bool + * @see getConfigData() + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file can not be written. + */ + public static function setConfigData($key, $value, $temp = \false) + { + if (isset(self::$overriddenDefaults['runtime-set']) === \true && isset(self::$overriddenDefaults['runtime-set'][$key]) === \true) { + return \false; + } + if ($temp === \false) { + $path = ''; + if (\is_callable('\\Phar::running') === \true) { + $path = \Phar::running(\false); + } + if ($path !== '') { + $configFile = \dirname($path) . \DIRECTORY_SEPARATOR . 'CodeSniffer.conf'; + } else { + $configFile = \dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'CodeSniffer.conf'; + if (\is_file($configFile) === \false && \strpos('@data_dir@', '@data_dir') === \false) { + // If data_dir was replaced, this is a PEAR install and we can + // use the PEAR data dir to store the conf file. + $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf'; + } + } + if (\is_file($configFile) === \true && \is_writable($configFile) === \false) { + $error = 'ERROR: Config file ' . $configFile . ' is not writable' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + } + //end if + $phpCodeSnifferConfig = self::getAllConfigData(); + if ($value === null) { + if (isset($phpCodeSnifferConfig[$key]) === \true) { + unset($phpCodeSnifferConfig[$key]); + } + } else { + $phpCodeSnifferConfig[$key] = $value; + } + if ($temp === \false) { + $output = '<' . '?php' . "\n" . ' $phpCodeSnifferConfig = '; + $output .= \var_export($phpCodeSnifferConfig, \true); + $output .= ";\n?" . '>'; + if (\file_put_contents($configFile, $output) === \false) { + $error = 'ERROR: Config file ' . $configFile . ' could not be written' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + self::$configDataFile = $configFile; + } + self::$configData = $phpCodeSnifferConfig; + // If the installed paths are being set, make sure all known + // standards paths are added to the autoloader. + if ($key === 'installed_paths') { + $installedStandards = \PHP_CodeSniffer\Util\Standards::getInstalledStandardDetails(); + foreach ($installedStandards as $name => $details) { + \PHP_CodeSniffer\Autoload::addSearchPath($details['path'], $details['namespace']); + } + } + return \true; + } + //end setConfigData() + /** + * Get all config data. + * + * @return array + * @see getConfigData() + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the config file could not be read. + */ + public static function getAllConfigData() + { + if (self::$configData !== null) { + return self::$configData; + } + $path = ''; + if (\is_callable('\\Phar::running') === \true) { + $path = \Phar::running(\false); + } + if ($path !== '') { + $configFile = \dirname($path) . \DIRECTORY_SEPARATOR . 'CodeSniffer.conf'; + } else { + $configFile = \dirname(__DIR__) . \DIRECTORY_SEPARATOR . 'CodeSniffer.conf'; + if (\is_file($configFile) === \false && \strpos('@data_dir@', '@data_dir') === \false) { + $configFile = '@data_dir@/PHP_CodeSniffer/CodeSniffer.conf'; + } + } + if (\is_file($configFile) === \false) { + self::$configData = []; + return []; + } + if (Common::isReadable($configFile) === \false) { + $error = 'ERROR: Config file ' . $configFile . ' is not readable' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + include $configFile; + self::$configDataFile = $configFile; + self::$configData = $phpCodeSnifferConfig; + return self::$configData; + } + //end getAllConfigData() + /** + * Prints out the gathered config data. + * + * @param array $data The config data to print. + * + * @return void + */ + public function printConfigData($data) + { + $max = 0; + $keys = \array_keys($data); + foreach ($keys as $key) { + $len = \strlen($key); + if (\strlen($key) > $max) { + $max = $len; + } + } + if ($max === 0) { + return; + } + $max += 2; + \ksort($data); + foreach ($data as $name => $value) { + echo \str_pad($name . ': ', $max) . $value . \PHP_EOL; + } + } + //end printConfigData() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php new file mode 100644 index 00000000000..d65926ca98b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/DeepExitException.php @@ -0,0 +1,18 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Exceptions; + +class DeepExitException extends \Exception +{ +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php new file mode 100644 index 00000000000..622cd427dea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/RuntimeException.php @@ -0,0 +1,15 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Exceptions; + +class RuntimeException extends \RuntimeException +{ +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php b/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php new file mode 100644 index 00000000000..6824d5fb3bc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Exceptions/TokenizerException.php @@ -0,0 +1,15 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Exceptions; + +class TokenizerException extends \Exception +{ +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php b/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php new file mode 100644 index 00000000000..6869cbe064d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/DummyFile.php @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +class DummyFile extends \PHP_CodeSniffer\Files\File +{ + /** + * Creates a DummyFile object and sets the content. + * + * @param string $content The content of the file. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($content, Ruleset $ruleset, Config $config) + { + $this->setContent($content); + // See if a filename was defined in the content. + // This is done by including: phpcs_input_file: [file path] + // as the first line of content. + $path = 'STDIN'; + if ($content !== '') { + if (\substr($content, 0, 17) === 'phpcs_input_file:') { + $eolPos = \strpos($content, $this->eolChar); + $filename = \trim(\substr($content, 17, $eolPos - 17)); + $content = \substr($content, $eolPos + \strlen($this->eolChar)); + $path = $filename; + $this->setContent($content); + } + } + // The CLI arg overrides anything passed in the content. + if ($config->stdinPath !== null) { + $path = $config->stdinPath; + } + parent::__construct($path, $ruleset, $config); + } + //end __construct() + /** + * Set the error, warning, and fixable counts for the file. + * + * @param int $errorCount The number of errors found. + * @param int $warningCount The number of warnings found. + * @param int $fixableCount The number of fixable errors found. + * @param int $fixedCount The number of errors that were fixed. + * + * @return void + */ + public function setErrorCounts($errorCount, $warningCount, $fixableCount, $fixedCount) + { + $this->errorCount = $errorCount; + $this->warningCount = $warningCount; + $this->fixableCount = $fixableCount; + $this->fixedCount = $fixedCount; + } + //end setErrorCounts() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/File.php b/vendor/squizlabs/php_codesniffer/src/Files/File.php new file mode 100644 index 00000000000..5e9765fe045 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/File.php @@ -0,0 +1,2263 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Fixer; +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Exceptions\TokenizerException; +class File +{ + /** + * The absolute path to the file associated with this object. + * + * @var string + */ + public $path = ''; + /** + * The content of the file. + * + * @var string + */ + protected $content = ''; + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + /** + * If TRUE, the entire file is being ignored. + * + * @var boolean + */ + public $ignored = \false; + /** + * The EOL character this file uses. + * + * @var string + */ + public $eolChar = ''; + /** + * The Fixer object to control fixing errors. + * + * @var \PHP_CodeSniffer\Fixer + */ + public $fixer = null; + /** + * The tokenizer being used for this file. + * + * @var \PHP_CodeSniffer\Tokenizers\Tokenizer + */ + public $tokenizer = null; + /** + * The name of the tokenizer being used for this file. + * + * @var string + */ + public $tokenizerType = 'PHP'; + /** + * Was the file loaded from cache? + * + * If TRUE, the file was loaded from a local cache. + * If FALSE, the file was tokenized and processed fully. + * + * @var boolean + */ + public $fromCache = \false; + /** + * The number of tokens in this file. + * + * Stored here to save calling count() everywhere. + * + * @var integer + */ + public $numTokens = 0; + /** + * The tokens stack map. + * + * @var array + */ + protected $tokens = []; + /** + * The errors raised from sniffs. + * + * @var array + * @see getErrors() + */ + protected $errors = []; + /** + * The warnings raised from sniffs. + * + * @var array + * @see getWarnings() + */ + protected $warnings = []; + /** + * The metrics recorded by sniffs. + * + * @var array + * @see getMetrics() + */ + protected $metrics = []; + /** + * The metrics recorded for each token. + * + * Stops the same metric being recorded for the same token twice. + * + * @var array + * @see getMetrics() + */ + private $metricTokens = []; + /** + * The total number of errors raised. + * + * @var integer + */ + protected $errorCount = 0; + /** + * The total number of warnings raised. + * + * @var integer + */ + protected $warningCount = 0; + /** + * The total number of errors and warnings that can be fixed. + * + * @var integer + */ + protected $fixableCount = 0; + /** + * The total number of errors and warnings that were fixed. + * + * @var integer + */ + protected $fixedCount = 0; + /** + * TRUE if errors are being replayed from the cache. + * + * @var boolean + */ + protected $replayingErrors = \false; + /** + * An array of sniffs that are being ignored. + * + * @var array + */ + protected $ignoredListeners = []; + /** + * An array of message codes that are being ignored. + * + * @var array + */ + protected $ignoredCodes = []; + /** + * An array of sniffs listening to this file's processing. + * + * @var \PHP_CodeSniffer\Sniffs\Sniff[] + */ + protected $listeners = []; + /** + * The class name of the sniff currently processing the file. + * + * @var string + */ + protected $activeListener = ''; + /** + * An array of sniffs being processed and how long they took. + * + * @var array + */ + protected $listenerTimes = []; + /** + * A cache of often used config settings to improve performance. + * + * Storing them here saves 10k+ calls to __get() in the Config class. + * + * @var array + */ + protected $configCache = []; + /** + * Constructs a file. + * + * @param string $path The absolute path to the file to process. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($path, Ruleset $ruleset, Config $config) + { + $this->path = $path; + $this->ruleset = $ruleset; + $this->config = $config; + $this->fixer = new Fixer(); + $parts = \explode('.', $path); + $extension = \array_pop($parts); + if (isset($config->extensions[$extension]) === \true) { + $this->tokenizerType = $config->extensions[$extension]; + } else { + // Revert to default. + $this->tokenizerType = 'PHP'; + } + $this->configCache['cache'] = $this->config->cache; + $this->configCache['sniffs'] = \array_map('strtolower', $this->config->sniffs); + $this->configCache['exclude'] = \array_map('strtolower', $this->config->exclude); + $this->configCache['errorSeverity'] = $this->config->errorSeverity; + $this->configCache['warningSeverity'] = $this->config->warningSeverity; + $this->configCache['recordErrors'] = $this->config->recordErrors; + $this->configCache['ignorePatterns'] = $this->ruleset->ignorePatterns; + $this->configCache['includePatterns'] = $this->ruleset->includePatterns; + } + //end __construct() + /** + * Set the content of the file. + * + * Setting the content also calculates the EOL char being used. + * + * @param string $content The file content. + * + * @return void + */ + public function setContent($content) + { + $this->content = $content; + $this->tokens = []; + try { + $this->eolChar = Util\Common::detectLineEndings($content); + } catch (RuntimeException $e) { + $this->addWarningOnLine($e->getMessage(), 1, 'Internal.DetectLineEndings'); + return; + } + } + //end setContent() + /** + * Reloads the content of the file. + * + * By default, we have no idea where our content comes from, + * so we can't do anything. + * + * @return void + */ + public function reloadContent() + { + } + //end reloadContent() + /** + * Disables caching of this file. + * + * @return void + */ + public function disableCaching() + { + $this->configCache['cache'] = \false; + } + //end disableCaching() + /** + * Starts the stack traversal and tells listeners when tokens are found. + * + * @return void + */ + public function process() + { + if ($this->ignored === \true) { + return; + } + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + $this->parse(); + // Check if tokenizer errors cause this file to be ignored. + if ($this->ignored === \true) { + return; + } + $this->fixer->startFile($this); + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + echo "\t*** START TOKEN PROCESSING ***" . \PHP_EOL; + } + $foundCode = \false; + $listenerIgnoreTo = []; + $inTests = \defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS'); + $checkAnnotations = $this->config->annotations; + // Foreach of the listeners that have registered to listen for this + // token, get them to process it. + foreach ($this->tokens as $stackPtr => $token) { + // Check for ignored lines. + if ($checkAnnotations === \true && ($token['code'] === \T_COMMENT || $token['code'] === \T_PHPCS_IGNORE_FILE || $token['code'] === \T_PHPCS_SET || $token['code'] === \T_DOC_COMMENT_STRING || $token['code'] === \T_DOC_COMMENT_TAG || $inTests === \true && $token['code'] === \T_INLINE_HTML)) { + $commentText = \ltrim($this->tokens[$stackPtr]['content'], " \t/*#"); + $commentTextLower = \strtolower($commentText); + if (\strpos($commentText, '@codingStandards') !== \false) { + if (\strpos($commentText, '@codingStandardsIgnoreFile') !== \false) { + // Ignoring the whole file, just a little late. + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + return; + } else { + if (\strpos($commentText, '@codingStandardsChangeSetting') !== \false) { + $start = \strpos($commentText, '@codingStandardsChangeSetting'); + $comment = \substr($commentText, $start + 30); + $parts = \explode(' ', $comment); + if (\count($parts) >= 2) { + $sniffParts = \explode('.', $parts[0]); + if (\count($sniffParts) >= 3) { + // If the sniff code is not known to us, it has not been registered in this run. + // But don't throw an error as it could be there for a different standard to use. + if (isset($this->ruleset->sniffCodes[$parts[0]]) === \true) { + $listenerCode = \array_shift($parts); + $propertyCode = \array_shift($parts); + $propertyValue = \rtrim(\implode(' ', $parts), " */\r\n"); + $listenerClass = $this->ruleset->sniffCodes[$listenerCode]; + $this->ruleset->setSniffProperty($listenerClass, $propertyCode, $propertyValue); + } + } + } + } + } + //end if + } else { + if (\substr($commentTextLower, 0, 16) === 'phpcs:ignorefile' || \substr($commentTextLower, 0, 17) === '@phpcs:ignorefile') { + // Ignoring the whole file, just a little late. + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + return; + } else { + if (\substr($commentTextLower, 0, 9) === 'phpcs:set' || \substr($commentTextLower, 0, 10) === '@phpcs:set') { + if (isset($token['sniffCode']) === \true) { + $listenerCode = $token['sniffCode']; + if (isset($this->ruleset->sniffCodes[$listenerCode]) === \true) { + $propertyCode = $token['sniffProperty']; + $propertyValue = $token['sniffPropertyValue']; + $listenerClass = $this->ruleset->sniffCodes[$listenerCode]; + $this->ruleset->setSniffProperty($listenerClass, $propertyCode, $propertyValue); + } + } + } + } + } + //end if + } + //end if + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + $type = $token['type']; + $content = Util\Common::prepareForOutput($token['content']); + echo "\t\tProcess token {$stackPtr}: {$type} => {$content}" . \PHP_EOL; + } + if ($token['code'] !== \T_INLINE_HTML) { + $foundCode = \true; + } + if (isset($this->ruleset->tokenListeners[$token['code']]) === \false) { + continue; + } + foreach ($this->ruleset->tokenListeners[$token['code']] as $listenerData) { + if (isset($this->ignoredListeners[$listenerData['class']]) === \true || isset($listenerIgnoreTo[$listenerData['class']]) === \true && $listenerIgnoreTo[$listenerData['class']] > $stackPtr) { + // This sniff is ignoring past this token, or the whole file. + continue; + } + // Make sure this sniff supports the tokenizer + // we are currently using. + $class = $listenerData['class']; + if (isset($listenerData['tokenizers'][$this->tokenizerType]) === \false) { + continue; + } + if (\trim($this->path, '\'"') !== 'STDIN') { + // If the file path matches one of our ignore patterns, skip it. + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + foreach ($listenerData['ignore'] as $pattern) { + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (\DIRECTORY_SEPARATOR === '\\') { + $pattern = \str_replace('/', '\\\\', $pattern); + } + $pattern = '`' . $pattern . '`i'; + if (\preg_match($pattern, $this->path) === 1) { + $this->ignoredListeners[$class] = \true; + continue 2; + } + } + // If the file path does not match one of our include patterns, skip it. + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + if (empty($listenerData['include']) === \false) { + $included = \false; + foreach ($listenerData['include'] as $pattern) { + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (\DIRECTORY_SEPARATOR === '\\') { + $pattern = \str_replace('/', '\\\\', $pattern); + } + $pattern = '`' . $pattern . '`i'; + if (\preg_match($pattern, $this->path) === 1) { + $included = \true; + break; + } + } + if ($included === \false) { + $this->ignoredListeners[$class] = \true; + continue; + } + } + //end if + } + //end if + $this->activeListener = $class; + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + $startTime = \microtime(\true); + echo "\t\t\tProcessing " . $this->activeListener . '... '; + } + $ignoreTo = $this->ruleset->sniffs[$class]->process($this, $stackPtr); + if ($ignoreTo !== null) { + $listenerIgnoreTo[$this->activeListener] = $ignoreTo; + } + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + $timeTaken = \microtime(\true) - $startTime; + if (isset($this->listenerTimes[$this->activeListener]) === \false) { + $this->listenerTimes[$this->activeListener] = 0; + } + $this->listenerTimes[$this->activeListener] += $timeTaken; + $timeTaken = \round($timeTaken, 4); + echo "DONE in {$timeTaken} seconds" . \PHP_EOL; + } + $this->activeListener = ''; + } + //end foreach + } + //end foreach + // If short open tags are off but the file being checked uses + // short open tags, the whole content will be inline HTML + // and nothing will be checked. So try and handle this case. + // We don't show this error for STDIN because we can't be sure the content + // actually came directly from the user. It could be something like + // refs from a Git pre-push hook. + if ($foundCode === \false && $this->tokenizerType === 'PHP' && $this->path !== 'STDIN') { + $shortTags = (bool) \ini_get('short_open_tag'); + if ($shortTags === \false) { + $error = 'No PHP code was found in this file and short open tags are not allowed by this install of PHP. This file may be using short open tags but PHP does not allow them.'; + $this->addWarning($error, null, 'Internal.NoCodeFound'); + } + } + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + echo "\t*** END TOKEN PROCESSING ***" . \PHP_EOL; + echo "\t*** START SNIFF PROCESSING REPORT ***" . \PHP_EOL; + \asort($this->listenerTimes, \SORT_NUMERIC); + $this->listenerTimes = \array_reverse($this->listenerTimes, \true); + foreach ($this->listenerTimes as $listener => $timeTaken) { + echo "\t{$listener}: " . \round($timeTaken, 4) . ' secs' . \PHP_EOL; + } + echo "\t*** END SNIFF PROCESSING REPORT ***" . \PHP_EOL; + } + $this->fixedCount += $this->fixer->getFixCount(); + } + //end process() + /** + * Tokenizes the file and prepares it for the test run. + * + * @return void + */ + public function parse() + { + if (empty($this->tokens) === \false) { + // File has already been parsed. + return; + } + try { + $tokenizerClass = 'PHP_CodeSniffer\\Tokenizers\\' . $this->tokenizerType; + $this->tokenizer = new $tokenizerClass($this->content, $this->config, $this->eolChar); + $this->tokens = $this->tokenizer->getTokens(); + } catch (TokenizerException $e) { + $this->ignored = \true; + $this->addWarning($e->getMessage(), null, 'Internal.Tokenizer.Exception'); + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo "[{$this->tokenizerType} => tokenizer error]... "; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + } + return; + } + $this->numTokens = \count($this->tokens); + // Check for mixed line endings as these can cause tokenizer errors and we + // should let the user know that the results they get may be incorrect. + // This is done by removing all backslashes, removing the newline char we + // detected, then converting newlines chars into text. If any backslashes + // are left at the end, we have additional newline chars in use. + $contents = \str_replace('\\', '', $this->content); + $contents = \str_replace($this->eolChar, '', $contents); + $contents = \str_replace("\n", '\\n', $contents); + $contents = \str_replace("\r", '\\r', $contents); + if (\strpos($contents, '\\') !== \false) { + $error = 'File has mixed line endings; this may cause incorrect results'; + $this->addWarningOnLine($error, 1, 'Internal.LineEndings.Mixed'); + } + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + if ($this->numTokens === 0) { + $numLines = 0; + } else { + $numLines = $this->tokens[$this->numTokens - 1]['line']; + } + echo "[{$this->tokenizerType} => {$this->numTokens} tokens in {$numLines} lines]... "; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + } + } + //end parse() + /** + * Returns the token stack for this file. + * + * @return array + */ + public function getTokens() + { + return $this->tokens; + } + //end getTokens() + /** + * Remove vars stored in this file that are no longer required. + * + * @return void + */ + public function cleanUp() + { + $this->listenerTimes = null; + $this->content = null; + $this->tokens = null; + $this->metricTokens = null; + $this->tokenizer = null; + $this->fixer = null; + $this->config = null; + $this->ruleset = null; + } + //end cleanUp() + /** + * Records an error against a specific token in the file. + * + * @param string $error The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the error be fixed by the sniff? + * + * @return boolean + */ + public function addError($error, $stackPtr, $code, $data = [], $severity = 0, $fixable = \false) + { + if ($stackPtr === null) { + $line = 1; + $column = 1; + } else { + $line = $this->tokens[$stackPtr]['line']; + $column = $this->tokens[$stackPtr]['column']; + } + return $this->addMessage(\true, $error, $line, $column, $code, $data, $severity, $fixable); + } + //end addError() + /** + * Records a warning against a specific token in the file. + * + * @param string $warning The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the warning be fixed by the sniff? + * + * @return boolean + */ + public function addWarning($warning, $stackPtr, $code, $data = [], $severity = 0, $fixable = \false) + { + if ($stackPtr === null) { + $line = 1; + $column = 1; + } else { + $line = $this->tokens[$stackPtr]['line']; + $column = $this->tokens[$stackPtr]['column']; + } + return $this->addMessage(\false, $warning, $line, $column, $code, $data, $severity, $fixable); + } + //end addWarning() + /** + * Records an error against a specific line in the file. + * + * @param string $error The error message. + * @param int $line The line on which the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addErrorOnLine($error, $line, $code, $data = [], $severity = 0) + { + return $this->addMessage(\true, $error, $line, 1, $code, $data, $severity, \false); + } + //end addErrorOnLine() + /** + * Records a warning against a specific token in the file. + * + * @param string $warning The error message. + * @param int $line The line on which the warning occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 will + * will be converted into the default severity level. + * + * @return boolean + */ + public function addWarningOnLine($warning, $line, $code, $data = [], $severity = 0) + { + return $this->addMessage(\false, $warning, $line, 1, $code, $data, $severity, \false); + } + //end addWarningOnLine() + /** + * Records a fixable error against a specific token in the file. + * + * Returns true if the error was recorded and should be fixed. + * + * @param string $error The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the error message. + * @param int $severity The severity level for this error. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addFixableError($error, $stackPtr, $code, $data = [], $severity = 0) + { + $recorded = $this->addError($error, $stackPtr, $code, $data, $severity, \true); + if ($recorded === \true && $this->fixer->enabled === \true) { + return \true; + } + return \false; + } + //end addFixableError() + /** + * Records a fixable warning against a specific token in the file. + * + * Returns true if the warning was recorded and should be fixed. + * + * @param string $warning The error message. + * @param int $stackPtr The stack position where the error occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the warning message. + * @param int $severity The severity level for this warning. A value of 0 + * will be converted into the default severity level. + * + * @return boolean + */ + public function addFixableWarning($warning, $stackPtr, $code, $data = [], $severity = 0) + { + $recorded = $this->addWarning($warning, $stackPtr, $code, $data, $severity, \true); + if ($recorded === \true && $this->fixer->enabled === \true) { + return \true; + } + return \false; + } + //end addFixableWarning() + /** + * Adds an error to the error stack. + * + * @param boolean $error Is this an error message? + * @param string $message The text of the message. + * @param int $line The line on which the message occurred. + * @param int $column The column at which the message occurred. + * @param string $code A violation code unique to the sniff message. + * @param array $data Replacements for the message. + * @param int $severity The severity level for this message. A value of 0 + * will be converted into the default severity level. + * @param boolean $fixable Can the problem be fixed by the sniff? + * + * @return boolean + */ + protected function addMessage($error, $message, $line, $column, $code, $data, $severity, $fixable) + { + // Check if this line is ignoring all message codes. + if (isset($this->tokenizer->ignoredLines[$line]['.all']) === \true) { + return \false; + } + // Work out which sniff generated the message. + $parts = \explode('.', $code); + if ($parts[0] === 'Internal') { + // An internal message. + $listenerCode = Util\Common::getSniffCode($this->activeListener); + $sniffCode = $code; + $checkCodes = [$sniffCode]; + } else { + if ($parts[0] !== $code) { + // The full message code has been passed in. + $sniffCode = $code; + $listenerCode = \substr($sniffCode, 0, \strrpos($sniffCode, '.')); + } else { + $listenerCode = Util\Common::getSniffCode($this->activeListener); + $sniffCode = $listenerCode . '.' . $code; + $parts = \explode('.', $sniffCode); + } + $checkCodes = [$sniffCode, $parts[0] . '.' . $parts[1] . '.' . $parts[2], $parts[0] . '.' . $parts[1], $parts[0]]; + } + //end if + if (isset($this->tokenizer->ignoredLines[$line]) === \true) { + // Check if this line is ignoring this specific message. + $ignored = \false; + foreach ($checkCodes as $checkCode) { + if (isset($this->tokenizer->ignoredLines[$line][$checkCode]) === \true) { + $ignored = \true; + break; + } + } + // If it is ignored, make sure it's not whitelisted. + if ($ignored === \true && isset($this->tokenizer->ignoredLines[$line]['.except']) === \true) { + foreach ($checkCodes as $checkCode) { + if (isset($this->tokenizer->ignoredLines[$line]['.except'][$checkCode]) === \true) { + $ignored = \false; + break; + } + } + } + if ($ignored === \true) { + return \false; + } + } + //end if + $includeAll = \true; + if ($this->configCache['cache'] === \false || $this->configCache['recordErrors'] === \false) { + $includeAll = \false; + } + // Filter out any messages for sniffs that shouldn't have run + // due to the use of the --sniffs command line argument. + if ($includeAll === \false && (empty($this->configCache['sniffs']) === \false && \in_array(\strtolower($listenerCode), $this->configCache['sniffs'], \true) === \false || empty($this->configCache['exclude']) === \false && \in_array(\strtolower($listenerCode), $this->configCache['exclude'], \true) === \true)) { + return \false; + } + // If we know this sniff code is being ignored for this file, return early. + foreach ($checkCodes as $checkCode) { + if (isset($this->ignoredCodes[$checkCode]) === \true) { + return \false; + } + } + $oppositeType = 'warning'; + if ($error === \false) { + $oppositeType = 'error'; + } + foreach ($checkCodes as $checkCode) { + // Make sure this message type has not been set to the opposite message type. + if (isset($this->ruleset->ruleset[$checkCode]['type']) === \true && $this->ruleset->ruleset[$checkCode]['type'] === $oppositeType) { + $error = !$error; + break; + } + } + if ($error === \true) { + $configSeverity = $this->configCache['errorSeverity']; + $messageCount =& $this->errorCount; + $messages =& $this->errors; + } else { + $configSeverity = $this->configCache['warningSeverity']; + $messageCount =& $this->warningCount; + $messages =& $this->warnings; + } + if ($includeAll === \false && $configSeverity === 0) { + // Don't bother doing any processing as these messages are just going to + // be hidden in the reports anyway. + return \false; + } + if ($severity === 0) { + $severity = 5; + } + foreach ($checkCodes as $checkCode) { + // Make sure we are interested in this severity level. + if (isset($this->ruleset->ruleset[$checkCode]['severity']) === \true) { + $severity = $this->ruleset->ruleset[$checkCode]['severity']; + break; + } + } + if ($includeAll === \false && $configSeverity > $severity) { + return \false; + } + // Make sure we are not ignoring this file. + $included = null; + if (\trim($this->path, '\'"') === 'STDIN') { + $included = \true; + } else { + foreach ($checkCodes as $checkCode) { + $patterns = null; + if (isset($this->configCache['includePatterns'][$checkCode]) === \true) { + $patterns = $this->configCache['includePatterns'][$checkCode]; + $excluding = \false; + } else { + if (isset($this->configCache['ignorePatterns'][$checkCode]) === \true) { + $patterns = $this->configCache['ignorePatterns'][$checkCode]; + $excluding = \true; + } + } + if ($patterns === null) { + continue; + } + foreach ($patterns as $pattern => $type) { + // While there is support for a type of each pattern + // (absolute or relative) we don't actually support it here. + $replacements = ['\\,' => ',', '*' => '.*']; + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (\DIRECTORY_SEPARATOR === '\\') { + $replacements['/'] = '\\\\'; + } + $pattern = '`' . \strtr($pattern, $replacements) . '`i'; + $matched = \preg_match($pattern, $this->path); + if ($matched === 0) { + if ($excluding === \false && $included === null) { + // This file path is not being included. + $included = \false; + } + continue; + } + if ($excluding === \true) { + // This file path is being excluded. + $this->ignoredCodes[$checkCode] = \true; + return \false; + } + // This file path is being included. + $included = \true; + break; + } + //end foreach + } + //end foreach + } + //end if + if ($included === \false) { + // There were include rules set, but this file + // path didn't match any of them. + return \false; + } + $messageCount++; + if ($fixable === \true) { + $this->fixableCount++; + } + if ($this->configCache['recordErrors'] === \false && $includeAll === \false) { + return \true; + } + // See if there is a custom error message format to use. + // But don't do this if we are replaying errors because replayed + // errors have already used the custom format and have had their + // data replaced. + if ($this->replayingErrors === \false && isset($this->ruleset->ruleset[$sniffCode]['message']) === \true) { + $message = $this->ruleset->ruleset[$sniffCode]['message']; + } + if (empty($data) === \false) { + $message = \vsprintf($message, $data); + } + if (isset($messages[$line]) === \false) { + $messages[$line] = []; + } + if (isset($messages[$line][$column]) === \false) { + $messages[$line][$column] = []; + } + $messages[$line][$column][] = ['message' => $message, 'source' => $sniffCode, 'listener' => $this->activeListener, 'severity' => $severity, 'fixable' => $fixable]; + if (\PHP_CODESNIFFER_VERBOSITY > 1 && $this->fixer->enabled === \true && $fixable === \true) { + @\ob_end_clean(); + echo "\tE: [Line {$line}] {$message} ({$sniffCode})" . \PHP_EOL; + \ob_start(); + } + return \true; + } + //end addMessage() + /** + * Record a metric about the file being examined. + * + * @param int $stackPtr The stack position where the metric was recorded. + * @param string $metric The name of the metric being recorded. + * @param string $value The value of the metric being recorded. + * + * @return boolean + */ + public function recordMetric($stackPtr, $metric, $value) + { + if (isset($this->metrics[$metric]) === \false) { + $this->metrics[$metric] = ['values' => [$value => 1]]; + $this->metricTokens[$metric][$stackPtr] = \true; + } else { + if (isset($this->metricTokens[$metric][$stackPtr]) === \false) { + $this->metricTokens[$metric][$stackPtr] = \true; + if (isset($this->metrics[$metric]['values'][$value]) === \false) { + $this->metrics[$metric]['values'][$value] = 1; + } else { + $this->metrics[$metric]['values'][$value]++; + } + } + } + return \true; + } + //end recordMetric() + /** + * Returns the number of errors raised. + * + * @return int + */ + public function getErrorCount() + { + return $this->errorCount; + } + //end getErrorCount() + /** + * Returns the number of warnings raised. + * + * @return int + */ + public function getWarningCount() + { + return $this->warningCount; + } + //end getWarningCount() + /** + * Returns the number of fixable errors/warnings raised. + * + * @return int + */ + public function getFixableCount() + { + return $this->fixableCount; + } + //end getFixableCount() + /** + * Returns the number of fixed errors/warnings. + * + * @return int + */ + public function getFixedCount() + { + return $this->fixedCount; + } + //end getFixedCount() + /** + * Returns the list of ignored lines. + * + * @return array + */ + public function getIgnoredLines() + { + return $this->tokenizer->ignoredLines; + } + //end getIgnoredLines() + /** + * Returns the errors raised from processing this file. + * + * @return array + */ + public function getErrors() + { + return $this->errors; + } + //end getErrors() + /** + * Returns the warnings raised from processing this file. + * + * @return array + */ + public function getWarnings() + { + return $this->warnings; + } + //end getWarnings() + /** + * Returns the metrics found while processing this file. + * + * @return array + */ + public function getMetrics() + { + return $this->metrics; + } + //end getMetrics() + /** + * Returns the absolute filename of this file. + * + * @return string + */ + public function getFilename() + { + return $this->path; + } + //end getFilename() + /** + * Returns the declaration name for classes, interfaces, traits, enums, and functions. + * + * @param int $stackPtr The position of the declaration token which + * declared the class, interface, trait, or function. + * + * @return string|null The name of the class, interface, trait, or function; + * or NULL if the function or class is anonymous. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified token is not of type + * T_FUNCTION, T_CLASS, T_ANON_CLASS, + * T_CLOSURE, T_TRAIT, T_ENUM, or T_INTERFACE. + */ + public function getDeclarationName($stackPtr) + { + $tokenCode = $this->tokens[$stackPtr]['code']; + if ($tokenCode === \T_ANON_CLASS || $tokenCode === \T_CLOSURE) { + return null; + } + if ($tokenCode !== \T_FUNCTION && $tokenCode !== \T_CLASS && $tokenCode !== \T_INTERFACE && $tokenCode !== \T_TRAIT && $tokenCode !== \T_ENUM) { + throw new RuntimeException('Token type "' . $this->tokens[$stackPtr]['type'] . '" is not T_FUNCTION, T_CLASS, T_INTERFACE, T_TRAIT or T_ENUM'); + } + if ($tokenCode === \T_FUNCTION && \strtolower($this->tokens[$stackPtr]['content']) !== 'function') { + // This is a function declared without the "function" keyword. + // So this token is the function name. + return $this->tokens[$stackPtr]['content']; + } + $content = null; + for ($i = $stackPtr; $i < $this->numTokens; $i++) { + if ($this->tokens[$i]['code'] === \T_STRING) { + $content = $this->tokens[$i]['content']; + break; + } + } + return $content; + } + //end getDeclarationName() + /** + * Returns the method parameters for the specified function token. + * + * Also supports passing in a USE token for a closure use group. + * + * Each parameter is in the following format: + * + * + * 0 => array( + * 'name' => '$var', // The variable name. + * 'token' => integer, // The stack pointer to the variable name. + * 'content' => string, // The full content of the variable definition. + * 'has_attributes' => boolean, // Does the parameter have one or more attributes attached ? + * 'pass_by_reference' => boolean, // Is the variable passed by reference? + * 'reference_token' => integer, // The stack pointer to the reference operator + * // or FALSE if the param is not passed by reference. + * 'variable_length' => boolean, // Is the param of variable length through use of `...` ? + * 'variadic_token' => integer, // The stack pointer to the ... operator + * // or FALSE if the param is not variable length. + * 'type_hint' => string, // The type hint for the variable. + * 'type_hint_token' => integer, // The stack pointer to the start of the type hint + * // or FALSE if there is no type hint. + * 'type_hint_end_token' => integer, // The stack pointer to the end of the type hint + * // or FALSE if there is no type hint. + * 'nullable_type' => boolean, // TRUE if the type is preceded by the nullability + * // operator. + * 'comma_token' => integer, // The stack pointer to the comma after the param + * // or FALSE if this is the last param. + * ) + * + * + * Parameters with default values have additional array indexes of: + * 'default' => string, // The full content of the default value. + * 'default_token' => integer, // The stack pointer to the start of the default value. + * 'default_equal_token' => integer, // The stack pointer to the equals sign. + * + * Parameters declared using PHP 8 constructor property promotion, have these additional array indexes: + * 'property_visibility' => string, // The property visibility as declared. + * 'visibility_token' => integer, // The stack pointer to the visibility modifier token. + * 'property_readonly' => bool, // TRUE if the readonly keyword was found. + * 'readonly_token' => integer, // The stack pointer to the readonly modifier token. + * + * @param int $stackPtr The position in the stack of the function token + * to acquire the parameters for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified $stackPtr is not of + * type T_FUNCTION, T_CLOSURE, T_USE, + * or T_FN. + */ + public function getMethodParameters($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== \T_FUNCTION && $this->tokens[$stackPtr]['code'] !== \T_CLOSURE && $this->tokens[$stackPtr]['code'] !== \T_USE && $this->tokens[$stackPtr]['code'] !== \T_FN) { + throw new RuntimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_USE or T_FN'); + } + if ($this->tokens[$stackPtr]['code'] === \T_USE) { + $opener = $this->findNext(\T_OPEN_PARENTHESIS, $stackPtr + 1); + if ($opener === \false || isset($this->tokens[$opener]['parenthesis_owner']) === \true) { + throw new RuntimeException('$stackPtr was not a valid T_USE'); + } + } else { + if (isset($this->tokens[$stackPtr]['parenthesis_opener']) === \false) { + // Live coding or syntax error, so no params to find. + return []; + } + $opener = $this->tokens[$stackPtr]['parenthesis_opener']; + } + if (isset($this->tokens[$opener]['parenthesis_closer']) === \false) { + // Live coding or syntax error, so no params to find. + return []; + } + $closer = $this->tokens[$opener]['parenthesis_closer']; + $vars = []; + $currVar = null; + $paramStart = $opener + 1; + $defaultStart = null; + $equalToken = null; + $paramCount = 0; + $hasAttributes = \false; + $passByReference = \false; + $referenceToken = \false; + $variableLength = \false; + $variadicToken = \false; + $typeHint = ''; + $typeHintToken = \false; + $typeHintEndToken = \false; + $nullableType = \false; + $visibilityToken = null; + $readonlyToken = null; + for ($i = $paramStart; $i <= $closer; $i++) { + // Check to see if this token has a parenthesis or bracket opener. If it does + // it's likely to be an array which might have arguments in it. This + // could cause problems in our parsing below, so lets just skip to the + // end of it. + if (isset($this->tokens[$i]['parenthesis_opener']) === \true) { + // Don't do this if it's the close parenthesis for the method. + if ($i !== $this->tokens[$i]['parenthesis_closer']) { + $i = $this->tokens[$i]['parenthesis_closer']; + continue; + } + } + if (isset($this->tokens[$i]['bracket_opener']) === \true) { + if ($i !== $this->tokens[$i]['bracket_closer']) { + $i = $this->tokens[$i]['bracket_closer']; + continue; + } + } + switch ($this->tokens[$i]['code']) { + case \T_ATTRIBUTE: + $hasAttributes = \true; + // Skip to the end of the attribute. + $i = $this->tokens[$i]['attribute_closer']; + break; + case \T_BITWISE_AND: + if ($defaultStart === null) { + $passByReference = \true; + $referenceToken = $i; + } + break; + case \T_VARIABLE: + $currVar = $i; + break; + case \T_ELLIPSIS: + $variableLength = \true; + $variadicToken = $i; + break; + case \T_CALLABLE: + if ($typeHintToken === \false) { + $typeHintToken = $i; + } + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + break; + case \T_SELF: + case \T_PARENT: + case \T_STATIC: + // Self and parent are valid, static invalid, but was probably intended as type hint. + if (isset($defaultStart) === \false) { + if ($typeHintToken === \false) { + $typeHintToken = $i; + } + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case \T_STRING: + // This is a string, so it may be a type hint, but it could + // also be a constant used as a default value. + $prevComma = \false; + for ($t = $i; $t >= $opener; $t--) { + if ($this->tokens[$t]['code'] === \T_COMMA) { + $prevComma = $t; + break; + } + } + if ($prevComma !== \false) { + $nextEquals = \false; + for ($t = $prevComma; $t < $i; $t++) { + if ($this->tokens[$t]['code'] === \T_EQUAL) { + $nextEquals = $t; + break; + } + } + if ($nextEquals !== \false) { + break; + } + } + if ($defaultStart === null) { + if ($typeHintToken === \false) { + $typeHintToken = $i; + } + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case \T_NAMESPACE: + case \T_NS_SEPARATOR: + case \T_TYPE_UNION: + case \T_TYPE_INTERSECTION: + case \T_FALSE: + case \T_NULL: + // Part of a type hint or default value. + if ($defaultStart === null) { + if ($typeHintToken === \false) { + $typeHintToken = $i; + } + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case \T_NULLABLE: + if ($defaultStart === null) { + $nullableType = \true; + $typeHint .= $this->tokens[$i]['content']; + $typeHintEndToken = $i; + } + break; + case \T_PUBLIC: + case \T_PROTECTED: + case \T_PRIVATE: + if ($defaultStart === null) { + $visibilityToken = $i; + } + break; + case \T_READONLY: + if ($defaultStart === null) { + $readonlyToken = $i; + } + break; + case \T_CLOSE_PARENTHESIS: + case \T_COMMA: + // If it's null, then there must be no parameters for this + // method. + if ($currVar === null) { + continue 2; + } + $vars[$paramCount] = []; + $vars[$paramCount]['token'] = $currVar; + $vars[$paramCount]['name'] = $this->tokens[$currVar]['content']; + $vars[$paramCount]['content'] = \trim($this->getTokensAsString($paramStart, $i - $paramStart)); + if ($defaultStart !== null) { + $vars[$paramCount]['default'] = \trim($this->getTokensAsString($defaultStart, $i - $defaultStart)); + $vars[$paramCount]['default_token'] = $defaultStart; + $vars[$paramCount]['default_equal_token'] = $equalToken; + } + $vars[$paramCount]['has_attributes'] = $hasAttributes; + $vars[$paramCount]['pass_by_reference'] = $passByReference; + $vars[$paramCount]['reference_token'] = $referenceToken; + $vars[$paramCount]['variable_length'] = $variableLength; + $vars[$paramCount]['variadic_token'] = $variadicToken; + $vars[$paramCount]['type_hint'] = $typeHint; + $vars[$paramCount]['type_hint_token'] = $typeHintToken; + $vars[$paramCount]['type_hint_end_token'] = $typeHintEndToken; + $vars[$paramCount]['nullable_type'] = $nullableType; + if ($visibilityToken !== null) { + $vars[$paramCount]['property_visibility'] = $this->tokens[$visibilityToken]['content']; + $vars[$paramCount]['visibility_token'] = $visibilityToken; + $vars[$paramCount]['property_readonly'] = \false; + } + if ($readonlyToken !== null) { + $vars[$paramCount]['property_readonly'] = \true; + $vars[$paramCount]['readonly_token'] = $readonlyToken; + } + if ($this->tokens[$i]['code'] === \T_COMMA) { + $vars[$paramCount]['comma_token'] = $i; + } else { + $vars[$paramCount]['comma_token'] = \false; + } + // Reset the vars, as we are about to process the next parameter. + $currVar = null; + $paramStart = $i + 1; + $defaultStart = null; + $equalToken = null; + $hasAttributes = \false; + $passByReference = \false; + $referenceToken = \false; + $variableLength = \false; + $variadicToken = \false; + $typeHint = ''; + $typeHintToken = \false; + $typeHintEndToken = \false; + $nullableType = \false; + $visibilityToken = null; + $readonlyToken = null; + $paramCount++; + break; + case \T_EQUAL: + $defaultStart = $this->findNext(Util\Tokens::$emptyTokens, $i + 1, null, \true); + $equalToken = $i; + break; + } + //end switch + } + //end for + return $vars; + } + //end getMethodParameters() + /** + * Returns the visibility and implementation properties of a method. + * + * The format of the return value is: + * + * array( + * 'scope' => 'public', // Public, private, or protected + * 'scope_specified' => true, // TRUE if the scope keyword was found. + * 'return_type' => '', // The return type of the method. + * 'return_type_token' => integer, // The stack pointer to the start of the return type + * // or FALSE if there is no return type. + * 'return_type_end_token' => integer, // The stack pointer to the end of the return type + * // or FALSE if there is no return type. + * 'nullable_return_type' => false, // TRUE if the return type is preceded by the + * // nullability operator. + * 'is_abstract' => false, // TRUE if the abstract keyword was found. + * 'is_final' => false, // TRUE if the final keyword was found. + * 'is_static' => false, // TRUE if the static keyword was found. + * 'has_body' => false, // TRUE if the method has a body + * ); + * + * + * @param int $stackPtr The position in the stack of the function token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_FUNCTION, T_CLOSURE, or T_FN token. + */ + public function getMethodProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== \T_FUNCTION && $this->tokens[$stackPtr]['code'] !== \T_CLOSURE && $this->tokens[$stackPtr]['code'] !== \T_FN) { + throw new RuntimeException('$stackPtr must be of type T_FUNCTION or T_CLOSURE or T_FN'); + } + if ($this->tokens[$stackPtr]['code'] === \T_FUNCTION) { + $valid = [\T_PUBLIC => \T_PUBLIC, \T_PRIVATE => \T_PRIVATE, \T_PROTECTED => \T_PROTECTED, \T_STATIC => \T_STATIC, \T_FINAL => \T_FINAL, \T_ABSTRACT => \T_ABSTRACT, \T_WHITESPACE => \T_WHITESPACE, \T_COMMENT => \T_COMMENT, \T_DOC_COMMENT => \T_DOC_COMMENT]; + } else { + $valid = [\T_STATIC => \T_STATIC, \T_WHITESPACE => \T_WHITESPACE, \T_COMMENT => \T_COMMENT, \T_DOC_COMMENT => \T_DOC_COMMENT]; + } + $scope = 'public'; + $scopeSpecified = \false; + $isAbstract = \false; + $isFinal = \false; + $isStatic = \false; + for ($i = $stackPtr - 1; $i > 0; $i--) { + if (isset($valid[$this->tokens[$i]['code']]) === \false) { + break; + } + switch ($this->tokens[$i]['code']) { + case \T_PUBLIC: + $scope = 'public'; + $scopeSpecified = \true; + break; + case \T_PRIVATE: + $scope = 'private'; + $scopeSpecified = \true; + break; + case \T_PROTECTED: + $scope = 'protected'; + $scopeSpecified = \true; + break; + case \T_ABSTRACT: + $isAbstract = \true; + break; + case \T_FINAL: + $isFinal = \true; + break; + case \T_STATIC: + $isStatic = \true; + break; + } + //end switch + } + //end for + $returnType = ''; + $returnTypeToken = \false; + $returnTypeEndToken = \false; + $nullableReturnType = \false; + $hasBody = \true; + if (isset($this->tokens[$stackPtr]['parenthesis_closer']) === \true) { + $scopeOpener = null; + if (isset($this->tokens[$stackPtr]['scope_opener']) === \true) { + $scopeOpener = $this->tokens[$stackPtr]['scope_opener']; + } + $valid = [\T_STRING => \T_STRING, \T_CALLABLE => \T_CALLABLE, \T_SELF => \T_SELF, \T_PARENT => \T_PARENT, \T_STATIC => \T_STATIC, \T_FALSE => \T_FALSE, \T_NULL => \T_NULL, \T_NAMESPACE => \T_NAMESPACE, \T_NS_SEPARATOR => \T_NS_SEPARATOR, \T_TYPE_UNION => \T_TYPE_UNION, \T_TYPE_INTERSECTION => \T_TYPE_INTERSECTION]; + for ($i = $this->tokens[$stackPtr]['parenthesis_closer']; $i < $this->numTokens; $i++) { + if ($scopeOpener === null && $this->tokens[$i]['code'] === \T_SEMICOLON || $scopeOpener !== null && $i === $scopeOpener) { + // End of function definition. + break; + } + if ($this->tokens[$i]['code'] === \T_NULLABLE) { + $nullableReturnType = \true; + } + if (isset($valid[$this->tokens[$i]['code']]) === \true) { + if ($returnTypeToken === \false) { + $returnTypeToken = $i; + } + $returnType .= $this->tokens[$i]['content']; + $returnTypeEndToken = $i; + } + } + //end for + if ($this->tokens[$stackPtr]['code'] === \T_FN) { + $bodyToken = \T_FN_ARROW; + } else { + $bodyToken = \T_OPEN_CURLY_BRACKET; + } + $end = $this->findNext([$bodyToken, \T_SEMICOLON], $this->tokens[$stackPtr]['parenthesis_closer']); + $hasBody = $this->tokens[$end]['code'] === $bodyToken; + } + //end if + if ($returnType !== '' && $nullableReturnType === \true) { + $returnType = '?' . $returnType; + } + return ['scope' => $scope, 'scope_specified' => $scopeSpecified, 'return_type' => $returnType, 'return_type_token' => $returnTypeToken, 'return_type_end_token' => $returnTypeEndToken, 'nullable_return_type' => $nullableReturnType, 'is_abstract' => $isAbstract, 'is_final' => $isFinal, 'is_static' => $isStatic, 'has_body' => $hasBody]; + } + //end getMethodProperties() + /** + * Returns the visibility and implementation properties of a class member var. + * + * The format of the return value is: + * + * + * array( + * 'scope' => string, // Public, private, or protected. + * 'scope_specified' => boolean, // TRUE if the scope was explicitly specified. + * 'is_static' => boolean, // TRUE if the static keyword was found. + * 'is_readonly' => boolean, // TRUE if the readonly keyword was found. + * 'type' => string, // The type of the var (empty if no type specified). + * 'type_token' => integer, // The stack pointer to the start of the type + * // or FALSE if there is no type. + * 'type_end_token' => integer, // The stack pointer to the end of the type + * // or FALSE if there is no type. + * 'nullable_type' => boolean, // TRUE if the type is preceded by the nullability + * // operator. + * ); + * + * + * @param int $stackPtr The position in the stack of the T_VARIABLE token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_VARIABLE token, or if the position is not + * a class member variable. + */ + public function getMemberProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== \T_VARIABLE) { + throw new RuntimeException('$stackPtr must be of type T_VARIABLE'); + } + $conditions = \array_keys($this->tokens[$stackPtr]['conditions']); + $ptr = \array_pop($conditions); + if (isset($this->tokens[$ptr]) === \false || $this->tokens[$ptr]['code'] !== \T_CLASS && $this->tokens[$ptr]['code'] !== \T_ANON_CLASS && $this->tokens[$ptr]['code'] !== \T_TRAIT) { + if (isset($this->tokens[$ptr]) === \true && ($this->tokens[$ptr]['code'] === \T_INTERFACE || $this->tokens[$ptr]['code'] === \T_ENUM)) { + // T_VARIABLEs in interfaces/enums can actually be method arguments + // but they won't be seen as being inside the method because there + // are no scope openers and closers for abstract methods. If it is in + // parentheses, we can be pretty sure it is a method argument. + if (isset($this->tokens[$stackPtr]['nested_parenthesis']) === \false || empty($this->tokens[$stackPtr]['nested_parenthesis']) === \true) { + $error = 'Possible parse error: %ss may not include member vars'; + $code = \sprintf('Internal.ParseError.%sHasMemberVar', \ucfirst($this->tokens[$ptr]['content'])); + $data = [\strtolower($this->tokens[$ptr]['content'])]; + $this->addWarning($error, $stackPtr, $code, $data); + return []; + } + } else { + throw new RuntimeException('$stackPtr is not a class member var'); + } + } + //end if + // Make sure it's not a method parameter. + if (empty($this->tokens[$stackPtr]['nested_parenthesis']) === \false) { + $parenthesis = \array_keys($this->tokens[$stackPtr]['nested_parenthesis']); + $deepestOpen = \array_pop($parenthesis); + if ($deepestOpen > $ptr && isset($this->tokens[$deepestOpen]['parenthesis_owner']) === \true && $this->tokens[$this->tokens[$deepestOpen]['parenthesis_owner']]['code'] === \T_FUNCTION) { + throw new RuntimeException('$stackPtr is not a class member var'); + } + } + $valid = [\T_PUBLIC => \T_PUBLIC, \T_PRIVATE => \T_PRIVATE, \T_PROTECTED => \T_PROTECTED, \T_STATIC => \T_STATIC, \T_VAR => \T_VAR, \T_READONLY => \T_READONLY]; + $valid += Util\Tokens::$emptyTokens; + $scope = 'public'; + $scopeSpecified = \false; + $isStatic = \false; + $isReadonly = \false; + $startOfStatement = $this->findPrevious([\T_SEMICOLON, \T_OPEN_CURLY_BRACKET, \T_CLOSE_CURLY_BRACKET, \T_ATTRIBUTE_END], $stackPtr - 1); + for ($i = $startOfStatement + 1; $i < $stackPtr; $i++) { + if (isset($valid[$this->tokens[$i]['code']]) === \false) { + break; + } + switch ($this->tokens[$i]['code']) { + case \T_PUBLIC: + $scope = 'public'; + $scopeSpecified = \true; + break; + case \T_PRIVATE: + $scope = 'private'; + $scopeSpecified = \true; + break; + case \T_PROTECTED: + $scope = 'protected'; + $scopeSpecified = \true; + break; + case \T_STATIC: + $isStatic = \true; + break; + case \T_READONLY: + $isReadonly = \true; + break; + } + } + //end for + $type = ''; + $typeToken = \false; + $typeEndToken = \false; + $nullableType = \false; + if ($i < $stackPtr) { + // We've found a type. + $valid = [\T_STRING => \T_STRING, \T_CALLABLE => \T_CALLABLE, \T_SELF => \T_SELF, \T_PARENT => \T_PARENT, \T_FALSE => \T_FALSE, \T_NULL => \T_NULL, \T_NAMESPACE => \T_NAMESPACE, \T_NS_SEPARATOR => \T_NS_SEPARATOR, \T_TYPE_UNION => \T_TYPE_UNION, \T_TYPE_INTERSECTION => \T_TYPE_INTERSECTION]; + for ($i; $i < $stackPtr; $i++) { + if ($this->tokens[$i]['code'] === \T_VARIABLE) { + // Hit another variable in a group definition. + break; + } + if ($this->tokens[$i]['code'] === \T_NULLABLE) { + $nullableType = \true; + } + if (isset($valid[$this->tokens[$i]['code']]) === \true) { + $typeEndToken = $i; + if ($typeToken === \false) { + $typeToken = $i; + } + $type .= $this->tokens[$i]['content']; + } + } + if ($type !== '' && $nullableType === \true) { + $type = '?' . $type; + } + } + //end if + return ['scope' => $scope, 'scope_specified' => $scopeSpecified, 'is_static' => $isStatic, 'is_readonly' => $isReadonly, 'type' => $type, 'type_token' => $typeToken, 'type_end_token' => $typeEndToken, 'nullable_type' => $nullableType]; + } + //end getMemberProperties() + /** + * Returns the visibility and implementation properties of a class. + * + * The format of the return value is: + * + * array( + * 'is_abstract' => false, // true if the abstract keyword was found. + * 'is_final' => false, // true if the final keyword was found. + * ); + * + * + * @param int $stackPtr The position in the stack of the T_CLASS token to + * acquire the properties for. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position is not a + * T_CLASS token. + */ + public function getClassProperties($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== \T_CLASS) { + throw new RuntimeException('$stackPtr must be of type T_CLASS'); + } + $valid = [\T_FINAL => \T_FINAL, \T_ABSTRACT => \T_ABSTRACT, \T_WHITESPACE => \T_WHITESPACE, \T_COMMENT => \T_COMMENT, \T_DOC_COMMENT => \T_DOC_COMMENT]; + $isAbstract = \false; + $isFinal = \false; + for ($i = $stackPtr - 1; $i > 0; $i--) { + if (isset($valid[$this->tokens[$i]['code']]) === \false) { + break; + } + switch ($this->tokens[$i]['code']) { + case \T_ABSTRACT: + $isAbstract = \true; + break; + case \T_FINAL: + $isFinal = \true; + break; + } + } + //end for + return ['is_abstract' => $isAbstract, 'is_final' => $isFinal]; + } + //end getClassProperties() + /** + * Determine if the passed token is a reference operator. + * + * Returns true if the specified token position represents a reference. + * Returns false if the token represents a bitwise operator. + * + * @param int $stackPtr The position of the T_BITWISE_AND token. + * + * @return boolean + */ + public function isReference($stackPtr) + { + if ($this->tokens[$stackPtr]['code'] !== \T_BITWISE_AND) { + return \false; + } + $tokenBefore = $this->findPrevious(Util\Tokens::$emptyTokens, $stackPtr - 1, null, \true); + if ($this->tokens[$tokenBefore]['code'] === \T_FUNCTION || $this->tokens[$tokenBefore]['code'] === \T_CLOSURE || $this->tokens[$tokenBefore]['code'] === \T_FN) { + // Function returns a reference. + return \true; + } + if ($this->tokens[$tokenBefore]['code'] === \T_DOUBLE_ARROW) { + // Inside a foreach loop or array assignment, this is a reference. + return \true; + } + if ($this->tokens[$tokenBefore]['code'] === \T_AS) { + // Inside a foreach loop, this is a reference. + return \true; + } + if (isset(Util\Tokens::$assignmentTokens[$this->tokens[$tokenBefore]['code']]) === \true) { + // This is directly after an assignment. It's a reference. Even if + // it is part of an operation, the other tests will handle it. + return \true; + } + $tokenAfter = $this->findNext(Util\Tokens::$emptyTokens, $stackPtr + 1, null, \true); + if ($this->tokens[$tokenAfter]['code'] === \T_NEW) { + return \true; + } + if (isset($this->tokens[$stackPtr]['nested_parenthesis']) === \true) { + $brackets = $this->tokens[$stackPtr]['nested_parenthesis']; + $lastBracket = \array_pop($brackets); + if (isset($this->tokens[$lastBracket]['parenthesis_owner']) === \true) { + $owner = $this->tokens[$this->tokens[$lastBracket]['parenthesis_owner']]; + if ($owner['code'] === \T_FUNCTION || $owner['code'] === \T_CLOSURE || $owner['code'] === \T_FN) { + $params = $this->getMethodParameters($this->tokens[$lastBracket]['parenthesis_owner']); + foreach ($params as $param) { + if ($param['reference_token'] === $stackPtr) { + // Function parameter declared to be passed by reference. + return \true; + } + } + } + //end if + } else { + $prev = \false; + for ($t = $this->tokens[$lastBracket]['parenthesis_opener'] - 1; $t >= 0; $t--) { + if ($this->tokens[$t]['code'] !== \T_WHITESPACE) { + $prev = $t; + break; + } + } + if ($prev !== \false && $this->tokens[$prev]['code'] === \T_USE) { + // Closure use by reference. + return \true; + } + } + //end if + } + //end if + // Pass by reference in function calls and assign by reference in arrays. + if ($this->tokens[$tokenBefore]['code'] === \T_OPEN_PARENTHESIS || $this->tokens[$tokenBefore]['code'] === \T_COMMA || $this->tokens[$tokenBefore]['code'] === \T_OPEN_SHORT_ARRAY) { + if ($this->tokens[$tokenAfter]['code'] === \T_VARIABLE) { + return \true; + } else { + $skip = Util\Tokens::$emptyTokens; + $skip[] = \T_NS_SEPARATOR; + $skip[] = \T_SELF; + $skip[] = \T_PARENT; + $skip[] = \T_STATIC; + $skip[] = \T_STRING; + $skip[] = \T_NAMESPACE; + $skip[] = \T_DOUBLE_COLON; + $nextSignificantAfter = $this->findNext($skip, $stackPtr + 1, null, \true); + if ($this->tokens[$nextSignificantAfter]['code'] === \T_VARIABLE) { + return \true; + } + } + //end if + } + //end if + return \false; + } + //end isReference() + /** + * Returns the content of the tokens from the specified start position in + * the token stack for the specified length. + * + * @param int $start The position to start from in the token stack. + * @param int $length The length of tokens to traverse from the start pos. + * @param bool $origContent Whether the original content or the tab replaced + * content should be used. + * + * @return string The token contents. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified position does not exist. + */ + public function getTokensAsString($start, $length, $origContent = \false) + { + if (\is_int($start) === \false || isset($this->tokens[$start]) === \false) { + throw new RuntimeException('The $start position for getTokensAsString() must exist in the token stack'); + } + if (\is_int($length) === \false || $length <= 0) { + return ''; + } + $str = ''; + $end = $start + $length; + if ($end > $this->numTokens) { + $end = $this->numTokens; + } + for ($i = $start; $i < $end; $i++) { + // If tabs are being converted to spaces by the tokeniser, the + // original content should be used instead of the converted content. + if ($origContent === \true && isset($this->tokens[$i]['orig_content']) === \true) { + $str .= $this->tokens[$i]['orig_content']; + } else { + $str .= $this->tokens[$i]['content']; + } + } + return $str; + } + //end getTokensAsString() + /** + * Returns the position of the previous specified token(s). + * + * If a value is specified, the previous token of the specified type(s) + * containing the specified value will be returned. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. + * @param int|null $end The end position to fail if no token is found. + * if not specified or null, end will default to + * the start of the token stack. + * @param bool $exclude If true, find the previous token that is NOT of + * the types specified in $types. + * @param string|null $value The value that the token(s) must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * @param bool $local If true, tokens outside the current statement + * will not be checked. IE. checking will stop + * at the previous semi-colon found. + * + * @return int|false + * @see findNext() + */ + public function findPrevious($types, $start, $end = null, $exclude = \false, $value = null, $local = \false) + { + $types = (array) $types; + if ($end === null) { + $end = 0; + } + for ($i = $start; $i >= $end; $i--) { + $found = (bool) $exclude; + foreach ($types as $type) { + if ($this->tokens[$i]['code'] === $type) { + $found = !$exclude; + break; + } + } + if ($found === \true) { + if ($value === null) { + return $i; + } else { + if ($this->tokens[$i]['content'] === $value) { + return $i; + } + } + } + if ($local === \true) { + if (isset($this->tokens[$i]['scope_opener']) === \true && $i === $this->tokens[$i]['scope_closer']) { + $i = $this->tokens[$i]['scope_opener']; + } else { + if (isset($this->tokens[$i]['bracket_opener']) === \true && $i === $this->tokens[$i]['bracket_closer']) { + $i = $this->tokens[$i]['bracket_opener']; + } else { + if (isset($this->tokens[$i]['parenthesis_opener']) === \true && $i === $this->tokens[$i]['parenthesis_closer']) { + $i = $this->tokens[$i]['parenthesis_opener']; + } else { + if ($this->tokens[$i]['code'] === \T_SEMICOLON) { + break; + } + } + } + } + } + } + //end for + return \false; + } + //end findPrevious() + /** + * Returns the position of the next specified token(s). + * + * If a value is specified, the next token of the specified type(s) + * containing the specified value will be returned. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. + * @param int|null $end The end position to fail if no token is found. + * if not specified or null, end will default to + * the end of the token stack. + * @param bool $exclude If true, find the next token that is NOT of + * a type specified in $types. + * @param string|null $value The value that the token(s) must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * @param bool $local If true, tokens outside the current statement + * will not be checked. i.e., checking will stop + * at the next semi-colon found. + * + * @return int|false + * @see findPrevious() + */ + public function findNext($types, $start, $end = null, $exclude = \false, $value = null, $local = \false) + { + $types = (array) $types; + if ($end === null || $end > $this->numTokens) { + $end = $this->numTokens; + } + for ($i = $start; $i < $end; $i++) { + $found = (bool) $exclude; + foreach ($types as $type) { + if ($this->tokens[$i]['code'] === $type) { + $found = !$exclude; + break; + } + } + if ($found === \true) { + if ($value === null) { + return $i; + } else { + if ($this->tokens[$i]['content'] === $value) { + return $i; + } + } + } + if ($local === \true && $this->tokens[$i]['code'] === \T_SEMICOLON) { + break; + } + } + //end for + return \false; + } + //end findNext() + /** + * Returns the position of the first non-whitespace token in a statement. + * + * @param int $start The position to start searching from in the token stack. + * @param int|string|array $ignore Token types that should not be considered stop points. + * + * @return int + */ + public function findStartOfStatement($start, $ignore = null) + { + $startTokens = Util\Tokens::$blockOpeners; + $startTokens[\T_OPEN_SHORT_ARRAY] = \true; + $startTokens[\T_OPEN_TAG] = \true; + $startTokens[\T_OPEN_TAG_WITH_ECHO] = \true; + $endTokens = [\T_CLOSE_TAG => \true, \T_COLON => \true, \T_COMMA => \true, \T_DOUBLE_ARROW => \true, \T_MATCH_ARROW => \true, \T_SEMICOLON => \true]; + if ($ignore !== null) { + $ignore = (array) $ignore; + foreach ($ignore as $code) { + if (isset($startTokens[$code]) === \true) { + unset($startTokens[$code]); + } + if (isset($endTokens[$code]) === \true) { + unset($endTokens[$code]); + } + } + } + // If the start token is inside the case part of a match expression, + // find the start of the condition. If it's in the statement part, find + // the token that comes after the match arrow. + $matchExpression = $this->getCondition($start, \T_MATCH); + if ($matchExpression !== \false) { + for ($prevMatch = $start; $prevMatch > $this->tokens[$matchExpression]['scope_opener']; $prevMatch--) { + if ($prevMatch !== $start && ($this->tokens[$prevMatch]['code'] === \T_MATCH_ARROW || $this->tokens[$prevMatch]['code'] === \T_COMMA)) { + break; + } + // Skip nested statements. + if (isset($this->tokens[$prevMatch]['bracket_opener']) === \true && $prevMatch === $this->tokens[$prevMatch]['bracket_closer']) { + $prevMatch = $this->tokens[$prevMatch]['bracket_opener']; + } else { + if (isset($this->tokens[$prevMatch]['parenthesis_opener']) === \true && $prevMatch === $this->tokens[$prevMatch]['parenthesis_closer']) { + $prevMatch = $this->tokens[$prevMatch]['parenthesis_opener']; + } + } + } + if ($prevMatch <= $this->tokens[$matchExpression]['scope_opener']) { + // We're before the arrow in the first case. + $next = $this->findNext(Util\Tokens::$emptyTokens, $this->tokens[$matchExpression]['scope_opener'] + 1, null, \true); + if ($next === \false) { + return $start; + } + return $next; + } + if ($this->tokens[$prevMatch]['code'] === \T_COMMA) { + // We're before the arrow, but not in the first case. + $prevMatchArrow = $this->findPrevious(\T_MATCH_ARROW, $prevMatch - 1, $this->tokens[$matchExpression]['scope_opener']); + if ($prevMatchArrow === \false) { + // We're before the arrow in the first case. + $next = $this->findNext(Util\Tokens::$emptyTokens, $this->tokens[$matchExpression]['scope_opener'] + 1, null, \true); + return $next; + } + $end = $this->findEndOfStatement($prevMatchArrow); + $next = $this->findNext(Util\Tokens::$emptyTokens, $end + 1, null, \true); + return $next; + } + } + //end if + $lastNotEmpty = $start; + // If we are starting at a token that ends a scope block, skip to + // the start and continue from there. + // If we are starting at a token that ends a statement, skip this + // token so we find the true start of the statement. + while (isset($endTokens[$this->tokens[$start]['code']]) === \true || isset($this->tokens[$start]['scope_condition']) === \true && $start === $this->tokens[$start]['scope_closer']) { + if (isset($this->tokens[$start]['scope_condition']) === \true) { + $start = $this->tokens[$start]['scope_condition']; + } else { + $start--; + } + } + for ($i = $start; $i >= 0; $i--) { + if (isset($startTokens[$this->tokens[$i]['code']]) === \true || isset($endTokens[$this->tokens[$i]['code']]) === \true) { + // Found the end of the previous statement. + return $lastNotEmpty; + } + if (isset($this->tokens[$i]['scope_opener']) === \true && $i === $this->tokens[$i]['scope_closer'] && $this->tokens[$i]['code'] !== \T_CLOSE_PARENTHESIS && $this->tokens[$i]['code'] !== \T_END_NOWDOC && $this->tokens[$i]['code'] !== \T_END_HEREDOC && $this->tokens[$i]['code'] !== \T_BREAK && $this->tokens[$i]['code'] !== \T_RETURN && $this->tokens[$i]['code'] !== \T_CONTINUE && $this->tokens[$i]['code'] !== \T_THROW && $this->tokens[$i]['code'] !== \T_EXIT) { + // Found the end of the previous scope block. + return $lastNotEmpty; + } + // Skip nested statements. + if (isset($this->tokens[$i]['bracket_opener']) === \true && $i === $this->tokens[$i]['bracket_closer']) { + $i = $this->tokens[$i]['bracket_opener']; + } else { + if (isset($this->tokens[$i]['parenthesis_opener']) === \true && $i === $this->tokens[$i]['parenthesis_closer']) { + $i = $this->tokens[$i]['parenthesis_opener']; + } else { + if ($this->tokens[$i]['code'] === \T_CLOSE_USE_GROUP) { + $start = $this->findPrevious(\T_OPEN_USE_GROUP, $i - 1); + if ($start !== \false) { + $i = $start; + } + } + } + } + //end if + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$i]['code']]) === \false) { + $lastNotEmpty = $i; + } + } + //end for + return 0; + } + //end findStartOfStatement() + /** + * Returns the position of the last non-whitespace token in a statement. + * + * @param int $start The position to start searching from in the token stack. + * @param int|string|array $ignore Token types that should not be considered stop points. + * + * @return int + */ + public function findEndOfStatement($start, $ignore = null) + { + $endTokens = [\T_COLON => \true, \T_COMMA => \true, \T_DOUBLE_ARROW => \true, \T_SEMICOLON => \true, \T_CLOSE_PARENTHESIS => \true, \T_CLOSE_SQUARE_BRACKET => \true, \T_CLOSE_CURLY_BRACKET => \true, \T_CLOSE_SHORT_ARRAY => \true, \T_OPEN_TAG => \true, \T_CLOSE_TAG => \true]; + if ($ignore !== null) { + $ignore = (array) $ignore; + foreach ($ignore as $code) { + unset($endTokens[$code]); + } + } + // If the start token is inside the case part of a match expression, + // advance to the match arrow and continue looking for the + // end of the statement from there so that we skip over commas. + if ($this->tokens[$start]['code'] !== \T_MATCH_ARROW) { + $matchExpression = $this->getCondition($start, \T_MATCH); + if ($matchExpression !== \false) { + $beforeArrow = \true; + $prevMatchArrow = $this->findPrevious(\T_MATCH_ARROW, $start - 1, $this->tokens[$matchExpression]['scope_opener']); + if ($prevMatchArrow !== \false) { + $prevComma = $this->findNext(\T_COMMA, $prevMatchArrow + 1, $start); + if ($prevComma === \false) { + // No comma between this token and the last match arrow, + // so this token exists after the arrow and we can continue + // checking as normal. + $beforeArrow = \false; + } + } + if ($beforeArrow === \true) { + $nextMatchArrow = $this->findNext(\T_MATCH_ARROW, $start + 1, $this->tokens[$matchExpression]['scope_closer']); + if ($nextMatchArrow !== \false) { + $start = $nextMatchArrow; + } + } + } + //end if + } + //end if + $lastNotEmpty = $start; + for ($i = $start; $i < $this->numTokens; $i++) { + if ($i !== $start && isset($endTokens[$this->tokens[$i]['code']]) === \true) { + // Found the end of the statement. + if ($this->tokens[$i]['code'] === \T_CLOSE_PARENTHESIS || $this->tokens[$i]['code'] === \T_CLOSE_SQUARE_BRACKET || $this->tokens[$i]['code'] === \T_CLOSE_CURLY_BRACKET || $this->tokens[$i]['code'] === \T_CLOSE_SHORT_ARRAY || $this->tokens[$i]['code'] === \T_OPEN_TAG || $this->tokens[$i]['code'] === \T_CLOSE_TAG) { + return $lastNotEmpty; + } + return $i; + } + // Skip nested statements. + if (isset($this->tokens[$i]['scope_closer']) === \true && ($i === $this->tokens[$i]['scope_opener'] || $i === $this->tokens[$i]['scope_condition'])) { + if ($this->tokens[$i]['code'] === \T_FN) { + $lastNotEmpty = $this->tokens[$i]['scope_closer']; + $i = $this->tokens[$i]['scope_closer'] - 1; + continue; + } + if ($i === $start && isset(Util\Tokens::$scopeOpeners[$this->tokens[$i]['code']]) === \true) { + return $this->tokens[$i]['scope_closer']; + } + $i = $this->tokens[$i]['scope_closer']; + } else { + if (isset($this->tokens[$i]['bracket_closer']) === \true && $i === $this->tokens[$i]['bracket_opener']) { + $i = $this->tokens[$i]['bracket_closer']; + } else { + if (isset($this->tokens[$i]['parenthesis_closer']) === \true && $i === $this->tokens[$i]['parenthesis_opener']) { + $i = $this->tokens[$i]['parenthesis_closer']; + } else { + if ($this->tokens[$i]['code'] === \T_OPEN_USE_GROUP) { + $end = $this->findNext(\T_CLOSE_USE_GROUP, $i + 1); + if ($end !== \false) { + $i = $end; + } + } + } + } + } + //end if + if (isset(Util\Tokens::$emptyTokens[$this->tokens[$i]['code']]) === \false) { + $lastNotEmpty = $i; + } + } + //end for + return $this->numTokens - 1; + } + //end findEndOfStatement() + /** + * Returns the position of the first token on a line, matching given type. + * + * Returns false if no token can be found. + * + * @param int|string|array $types The type(s) of tokens to search for. + * @param int $start The position to start searching from in the + * token stack. The first token matching on + * this line before this token will be returned. + * @param bool $exclude If true, find the token that is NOT of + * the types specified in $types. + * @param string $value The value that the token must be equal to. + * If value is omitted, tokens with any value will + * be returned. + * + * @return int|false + */ + public function findFirstOnLine($types, $start, $exclude = \false, $value = null) + { + if (\is_array($types) === \false) { + $types = [$types]; + } + $foundToken = \false; + for ($i = $start; $i >= 0; $i--) { + if ($this->tokens[$i]['line'] < $this->tokens[$start]['line']) { + break; + } + $found = $exclude; + foreach ($types as $type) { + if ($exclude === \false) { + if ($this->tokens[$i]['code'] === $type) { + $found = \true; + break; + } + } else { + if ($this->tokens[$i]['code'] === $type) { + $found = \false; + break; + } + } + } + if ($found === \true) { + if ($value === null) { + $foundToken = $i; + } else { + if ($this->tokens[$i]['content'] === $value) { + $foundToken = $i; + } + } + } + } + //end for + return $foundToken; + } + //end findFirstOnLine() + /** + * Determine if the passed token has a condition of one of the passed types. + * + * @param int $stackPtr The position of the token we are checking. + * @param int|string|array $types The type(s) of tokens to search for. + * + * @return boolean + */ + public function hasCondition($stackPtr, $types) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === \false) { + return \false; + } + // Make sure the token has conditions. + if (isset($this->tokens[$stackPtr]['conditions']) === \false) { + return \false; + } + $types = (array) $types; + $conditions = $this->tokens[$stackPtr]['conditions']; + foreach ($types as $type) { + if (\in_array($type, $conditions, \true) === \true) { + // We found a token with the required type. + return \true; + } + } + return \false; + } + //end hasCondition() + /** + * Return the position of the condition for the passed token. + * + * Returns FALSE if the token does not have the condition. + * + * @param int $stackPtr The position of the token we are checking. + * @param int|string $type The type of token to search for. + * @param bool $first If TRUE, will return the matched condition + * furthest away from the passed token. + * If FALSE, will return the matched condition + * closest to the passed token. + * + * @return int|false + */ + public function getCondition($stackPtr, $type, $first = \true) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === \false) { + return \false; + } + // Make sure the token has conditions. + if (isset($this->tokens[$stackPtr]['conditions']) === \false) { + return \false; + } + $conditions = $this->tokens[$stackPtr]['conditions']; + if ($first === \false) { + $conditions = \array_reverse($conditions, \true); + } + foreach ($conditions as $token => $condition) { + if ($condition === $type) { + return $token; + } + } + return \false; + } + //end getCondition() + /** + * Returns the name of the class that the specified class extends. + * (works for classes, anonymous classes and interfaces) + * + * Returns FALSE on error or if there is no extended class name. + * + * @param int $stackPtr The stack position of the class. + * + * @return string|false + */ + public function findExtendedClassName($stackPtr) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === \false) { + return \false; + } + if ($this->tokens[$stackPtr]['code'] !== \T_CLASS && $this->tokens[$stackPtr]['code'] !== \T_ANON_CLASS && $this->tokens[$stackPtr]['code'] !== \T_INTERFACE) { + return \false; + } + if (isset($this->tokens[$stackPtr]['scope_opener']) === \false) { + return \false; + } + $classOpenerIndex = $this->tokens[$stackPtr]['scope_opener']; + $extendsIndex = $this->findNext(\T_EXTENDS, $stackPtr, $classOpenerIndex); + if ($extendsIndex === \false) { + return \false; + } + $find = [\T_NS_SEPARATOR, \T_STRING, \T_WHITESPACE]; + $end = $this->findNext($find, $extendsIndex + 1, $classOpenerIndex + 1, \true); + $name = $this->getTokensAsString($extendsIndex + 1, $end - $extendsIndex - 1); + $name = \trim($name); + if ($name === '') { + return \false; + } + return $name; + } + //end findExtendedClassName() + /** + * Returns the names of the interfaces that the specified class or enum implements. + * + * Returns FALSE on error or if there are no implemented interface names. + * + * @param int $stackPtr The stack position of the class or enum token. + * + * @return array|false + */ + public function findImplementedInterfaceNames($stackPtr) + { + // Check for the existence of the token. + if (isset($this->tokens[$stackPtr]) === \false) { + return \false; + } + if ($this->tokens[$stackPtr]['code'] !== \T_CLASS && $this->tokens[$stackPtr]['code'] !== \T_ANON_CLASS && $this->tokens[$stackPtr]['code'] !== \T_ENUM) { + return \false; + } + if (isset($this->tokens[$stackPtr]['scope_closer']) === \false) { + return \false; + } + $classOpenerIndex = $this->tokens[$stackPtr]['scope_opener']; + $implementsIndex = $this->findNext(\T_IMPLEMENTS, $stackPtr, $classOpenerIndex); + if ($implementsIndex === \false) { + return \false; + } + $find = [\T_NS_SEPARATOR, \T_STRING, \T_WHITESPACE, \T_COMMA]; + $end = $this->findNext($find, $implementsIndex + 1, $classOpenerIndex + 1, \true); + $name = $this->getTokensAsString($implementsIndex + 1, $end - $implementsIndex - 1); + $name = \trim($name); + if ($name === '') { + return \false; + } else { + $names = \explode(',', $name); + $names = \array_map('trim', $names); + return $names; + } + } + //end findImplementedInterfaceNames() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/FileList.php b/vendor/squizlabs/php_codesniffer/src/Files/FileList.php new file mode 100644 index 00000000000..6ef975d0968 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/FileList.php @@ -0,0 +1,219 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Autoload; +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Exceptions\DeepExitException; +use ReturnTypeWillChange; +class FileList implements \Iterator, \Countable +{ + /** + * A list of file paths that are included in the list. + * + * @var array + */ + private $files = []; + /** + * The number of files in the list. + * + * @var integer + */ + private $numFiles = 0; + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + /** + * An array of patterns to use for skipping files. + * + * @var array + */ + protected $ignorePatterns = []; + /** + * Constructs a file list and loads in an array of file paths to process. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @return void + */ + public function __construct(Config $config, Ruleset $ruleset) + { + $this->ruleset = $ruleset; + $this->config = $config; + $paths = $config->files; + foreach ($paths as $path) { + $isPharFile = Util\Common::isPharFile($path); + if (\is_dir($path) === \true || $isPharFile === \true) { + if ($isPharFile === \true) { + $path = 'phar://' . $path; + } + $filterClass = $this->getFilterClass(); + $di = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS); + $filter = new $filterClass($di, $path, $config, $ruleset); + $iterator = new \RecursiveIteratorIterator($filter); + foreach ($iterator as $file) { + $this->files[$file->getPathname()] = null; + $this->numFiles++; + } + } else { + $this->addFile($path); + } + //end if + } + //end foreach + \reset($this->files); + } + //end __construct() + /** + * Add a file to the list. + * + * If a file object has already been created, it can be passed here. + * If it is left NULL, it will be created when accessed. + * + * @param string $path The path to the file being added. + * @param \PHP_CodeSniffer\Files\File $file The file being added. + * + * @return void + */ + public function addFile($path, $file = null) + { + // No filtering is done for STDIN when the filename + // has not been specified. + if ($path === 'STDIN') { + $this->files[$path] = $file; + $this->numFiles++; + return; + } + $filterClass = $this->getFilterClass(); + $di = new \RecursiveArrayIterator([$path]); + $filter = new $filterClass($di, $path, $this->config, $this->ruleset); + $iterator = new \RecursiveIteratorIterator($filter); + foreach ($iterator as $path) { + $this->files[$path] = $file; + $this->numFiles++; + } + } + //end addFile() + /** + * Get the class name of the filter being used for the run. + * + * @return string + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the specified filter could not be found. + */ + private function getFilterClass() + { + $filterType = $this->config->filter; + if ($filterType === null) { + $filterClass = '\\PHP_CodeSniffer\\Filters\\Filter'; + } else { + if (\strpos($filterType, '.') !== \false) { + // This is a path to a custom filter class. + $filename = \realpath($filterType); + if ($filename === \false) { + $error = "ERROR: Custom filter \"{$filterType}\" not found" . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $filterClass = Autoload::loadFile($filename); + } else { + $filterClass = '\\PHP_CodeSniffer\\Filters\\' . $filterType; + } + } + return $filterClass; + } + //end getFilterClass() + /** + * Rewind the iterator to the first file. + * + * @return void + */ + #[\ReturnTypeWillChange] + public function rewind() + { + \reset($this->files); + } + //end rewind() + /** + * Get the file that is currently being processed. + * + * @return \PHP_CodeSniffer\Files\File + */ + #[\ReturnTypeWillChange] + public function current() + { + $path = \key($this->files); + if (isset($this->files[$path]) === \false) { + $this->files[$path] = new \PHP_CodeSniffer\Files\LocalFile($path, $this->ruleset, $this->config); + } + return $this->files[$path]; + } + //end current() + /** + * Return the file path of the current file being processed. + * + * @return void + */ + #[\ReturnTypeWillChange] + public function key() + { + return \key($this->files); + } + //end key() + /** + * Move forward to the next file. + * + * @return void + */ + #[\ReturnTypeWillChange] + public function next() + { + \next($this->files); + } + //end next() + /** + * Checks if current position is valid. + * + * @return boolean + */ + #[\ReturnTypeWillChange] + public function valid() + { + if (\current($this->files) === \false) { + return \false; + } + return \true; + } + //end valid() + /** + * Return the number of files in the list. + * + * @return integer + */ + #[\ReturnTypeWillChange] + public function count() + { + return $this->numFiles; + } + //end count() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php b/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php new file mode 100644 index 00000000000..350ee49f8b1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Files/LocalFile.php @@ -0,0 +1,161 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Files; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Util\Cache; +use PHP_CodeSniffer\Util\Common; +class LocalFile extends \PHP_CodeSniffer\Files\File +{ + /** + * Creates a LocalFile object and sets the content. + * + * @param string $path The absolute path to the file. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + */ + public function __construct($path, Ruleset $ruleset, Config $config) + { + $this->path = \trim($path); + if (Common::isReadable($this->path) === \false) { + parent::__construct($this->path, $ruleset, $config); + $error = 'Error opening file; file no longer exists or you do not have access to read the file'; + $this->addMessage(\true, $error, 1, 1, 'Internal.LocalFile', [], 5, \false); + $this->ignored = \true; + return; + } + // Before we go and spend time tokenizing this file, just check + // to see if there is a tag up top to indicate that the whole + // file should be ignored. It must be on one of the first two lines. + if ($config->annotations === \true) { + $handle = \fopen($this->path, 'r'); + if ($handle !== \false) { + $firstContent = \fgets($handle); + $firstContent .= \fgets($handle); + \fclose($handle); + if (\strpos($firstContent, '@codingStandardsIgnoreFile') !== \false || \stripos($firstContent, 'phpcs:ignorefile') !== \false) { + // We are ignoring the whole file. + $this->ignored = \true; + return; + } + } + } + $this->reloadContent(); + parent::__construct($this->path, $ruleset, $config); + } + //end __construct() + /** + * Loads the latest version of the file's content from the file system. + * + * @return void + */ + public function reloadContent() + { + $this->setContent(\file_get_contents($this->path)); + } + //end reloadContent() + /** + * Processes the file. + * + * @return void + */ + public function process() + { + if ($this->ignored === \true) { + return; + } + if ($this->configCache['cache'] === \false) { + parent::process(); + return; + } + $hash = \md5_file($this->path); + $hash .= \fileperms($this->path); + $cache = Cache::get($this->path); + if ($cache !== \false && $cache['hash'] === $hash) { + // We can't filter metrics, so just load all of them. + $this->metrics = $cache['metrics']; + if ($this->configCache['recordErrors'] === \true) { + // Replay the cached errors and warnings to filter out the ones + // we don't need for this specific run. + $this->configCache['cache'] = \false; + $this->replayErrors($cache['errors'], $cache['warnings']); + $this->configCache['cache'] = \true; + } else { + $this->errorCount = $cache['errorCount']; + $this->warningCount = $cache['warningCount']; + $this->fixableCount = $cache['fixableCount']; + } + if (\PHP_CODESNIFFER_VERBOSITY > 0 || \PHP_CODESNIFFER_CBF === \true && empty($this->config->files) === \false) { + echo "[loaded from cache]... "; + } + $this->numTokens = $cache['numTokens']; + $this->fromCache = \true; + return; + } + //end if + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + parent::process(); + $cache = ['hash' => $hash, 'errors' => $this->errors, 'warnings' => $this->warnings, 'metrics' => $this->metrics, 'errorCount' => $this->errorCount, 'warningCount' => $this->warningCount, 'fixableCount' => $this->fixableCount, 'numTokens' => $this->numTokens]; + Cache::set($this->path, $cache); + // During caching, we don't filter out errors in any way, so + // we need to do that manually now by replaying them. + if ($this->configCache['recordErrors'] === \true) { + $this->configCache['cache'] = \false; + $this->replayErrors($this->errors, $this->warnings); + $this->configCache['cache'] = \true; + } + } + //end process() + /** + * Clears and replays error and warnings for the file. + * + * Replaying errors and warnings allows for filtering rules to be changed + * and then errors and warnings to be reapplied with the new rules. This is + * particularly useful while caching. + * + * @param array $errors The list of errors to replay. + * @param array $warnings The list of warnings to replay. + * + * @return void + */ + private function replayErrors($errors, $warnings) + { + $this->errors = []; + $this->warnings = []; + $this->errorCount = 0; + $this->warningCount = 0; + $this->fixableCount = 0; + $this->replayingErrors = \true; + foreach ($errors as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $this->activeListener = $error['listener']; + $this->addMessage(\true, $error['message'], $line, $column, $error['source'], [], $error['severity'], $error['fixable']); + } + } + } + foreach ($warnings as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $this->activeListener = $error['listener']; + $this->addMessage(\false, $error['message'], $line, $column, $error['source'], [], $error['severity'], $error['fixable']); + } + } + } + $this->replayingErrors = \false; + } + //end replayErrors() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php b/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php new file mode 100644 index 00000000000..a3b1779f26d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/ExactMatch.php @@ -0,0 +1,90 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; +abstract class ExactMatch extends \PHP_CodeSniffer\Filters\Filter +{ + /** + * A list of files to exclude. + * + * @var array + */ + private $blacklist = null; + /** + * A list of files to include. + * + * If the whitelist is empty, only files in the blacklist will be excluded. + * + * @var array + */ + private $whitelist = null; + /** + * Check whether the current element of the iterator is acceptable. + * + * If a file is both blacklisted and whitelisted, it will be deemed unacceptable. + * + * @return bool + */ + public function accept() + { + if (parent::accept() === \false) { + return \false; + } + if ($this->blacklist === null) { + $this->blacklist = $this->getblacklist(); + } + if ($this->whitelist === null) { + $this->whitelist = $this->getwhitelist(); + } + $filePath = Util\Common::realpath($this->current()); + // If file is both blacklisted and whitelisted, the blacklist takes precedence. + if (isset($this->blacklist[$filePath]) === \true) { + return \false; + } + if (empty($this->whitelist) === \true && empty($this->blacklist) === \false) { + // We are only checking a blacklist, so everything else should be whitelisted. + return \true; + } + return isset($this->whitelist[$filePath]); + } + //end accept() + /** + * Returns an iterator for the current entry. + * + * Ensures that the blacklist and whitelist are preserved so they don't have + * to be generated each time. + * + * @return \RecursiveIterator + */ + public function getChildren() + { + $children = parent::getChildren(); + $children->blacklist = $this->blacklist; + $children->whitelist = $this->whitelist; + return $children; + } + //end getChildren() + /** + * Get a list of blacklisted file paths. + * + * @return array + */ + protected abstract function getBlacklist(); + /** + * Get a list of whitelisted file paths. + * + * @return array + */ + protected abstract function getWhitelist(); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php b/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php new file mode 100644 index 00000000000..55494b3218c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/Filter.php @@ -0,0 +1,242 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Config; +use ReturnTypeWillChange; +class Filter extends \RecursiveFilterIterator +{ + /** + * The top-level path we are filtering. + * + * @var string + */ + protected $basedir = null; + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + protected $config = null; + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + protected $ruleset = null; + /** + * A list of ignore patterns that apply to directories only. + * + * @var array + */ + protected $ignoreDirPatterns = null; + /** + * A list of ignore patterns that apply to files only. + * + * @var array + */ + protected $ignoreFilePatterns = null; + /** + * A list of file paths we've already accepted. + * + * Used to ensure we aren't following circular symlinks. + * + * @var array + */ + protected $acceptedPaths = []; + /** + * Constructs a filter. + * + * @param \RecursiveIterator $iterator The iterator we are using to get file paths. + * @param string $basedir The top-level path we are filtering. + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @return void + */ + public function __construct($iterator, $basedir, Config $config, Ruleset $ruleset) + { + parent::__construct($iterator); + $this->basedir = $basedir; + $this->config = $config; + $this->ruleset = $ruleset; + } + //end __construct() + /** + * Check whether the current element of the iterator is acceptable. + * + * Files are checked for allowed extensions and ignore patterns. + * Directories are checked for ignore patterns only. + * + * @return bool + */ + #[\ReturnTypeWillChange] + public function accept() + { + $filePath = $this->current(); + $realPath = Util\Common::realpath($filePath); + if ($realPath !== \false) { + // It's a real path somewhere, so record it + // to check for circular symlinks. + if (isset($this->acceptedPaths[$realPath]) === \true) { + // We've been here before. + return \false; + } + } + $filePath = $this->current(); + if (\is_dir($filePath) === \true) { + if ($this->config->local === \true) { + return \false; + } + } else { + if ($this->shouldProcessFile($filePath) === \false) { + return \false; + } + } + if ($this->shouldIgnorePath($filePath) === \true) { + return \false; + } + $this->acceptedPaths[$realPath] = \true; + return \true; + } + //end accept() + /** + * Returns an iterator for the current entry. + * + * Ensures that the ignore patterns are preserved so they don't have + * to be generated each time. + * + * @return \RecursiveIterator + */ + #[\ReturnTypeWillChange] + public function getChildren() + { + $filterClass = \get_called_class(); + $children = new $filterClass(new \RecursiveDirectoryIterator($this->current(), \RecursiveDirectoryIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS), $this->basedir, $this->config, $this->ruleset); + // Set the ignore patterns so we don't have to generate them again. + $children->ignoreDirPatterns = $this->ignoreDirPatterns; + $children->ignoreFilePatterns = $this->ignoreFilePatterns; + $children->acceptedPaths = $this->acceptedPaths; + return $children; + } + //end getChildren() + /** + * Checks filtering rules to see if a file should be checked. + * + * Checks both file extension filters and path ignore filters. + * + * @param string $path The path to the file being checked. + * + * @return bool + */ + protected function shouldProcessFile($path) + { + // Check that the file's extension is one we are checking. + // We are strict about checking the extension and we don't + // let files through with no extension or that start with a dot. + $fileName = \basename($path); + $fileParts = \explode('.', $fileName); + if ($fileParts[0] === $fileName || $fileParts[0] === '') { + return \false; + } + // Checking multi-part file extensions, so need to create a + // complete extension list and make sure one is allowed. + $extensions = []; + \array_shift($fileParts); + foreach ($fileParts as $part) { + $extensions[\implode('.', $fileParts)] = 1; + \array_shift($fileParts); + } + $matches = \array_intersect_key($extensions, $this->config->extensions); + if (empty($matches) === \true) { + return \false; + } + return \true; + } + //end shouldProcessFile() + /** + * Checks filtering rules to see if a path should be ignored. + * + * @param string $path The path to the file or directory being checked. + * + * @return bool + */ + protected function shouldIgnorePath($path) + { + if ($this->ignoreFilePatterns === null) { + $this->ignoreDirPatterns = []; + $this->ignoreFilePatterns = []; + $ignorePatterns = $this->config->ignored; + $rulesetIgnorePatterns = $this->ruleset->getIgnorePatterns(); + foreach ($rulesetIgnorePatterns as $pattern => $type) { + // Ignore standard/sniff specific exclude rules. + if (\is_array($type) === \true) { + continue; + } + $ignorePatterns[$pattern] = $type; + } + foreach ($ignorePatterns as $pattern => $type) { + // If the ignore pattern ends with /* then it is ignoring an entire directory. + if (\substr($pattern, -2) === '/*') { + // Need to check this pattern for dirs as well as individual file paths. + $this->ignoreFilePatterns[$pattern] = $type; + $pattern = \substr($pattern, 0, -2) . '(?=/|$)'; + $this->ignoreDirPatterns[$pattern] = $type; + } else { + // This is a file-specific pattern, so only need to check this + // for individual file paths. + $this->ignoreFilePatterns[$pattern] = $type; + } + } + } + //end if + $relativePath = $path; + if (\strpos($path, $this->basedir) === 0) { + // The +1 cuts off the directory separator as well. + $relativePath = \substr($path, \strlen($this->basedir) + 1); + } + if (\is_dir($path) === \true) { + $ignorePatterns = $this->ignoreDirPatterns; + } else { + $ignorePatterns = $this->ignoreFilePatterns; + } + foreach ($ignorePatterns as $pattern => $type) { + // Maintains backwards compatibility in case the ignore pattern does + // not have a relative/absolute value. + if (\is_int($pattern) === \true) { + $pattern = $type; + $type = 'absolute'; + } + $replacements = ['\\,' => ',', '*' => '.*']; + // We assume a / directory separator, as do the exclude rules + // most developers write, so we need a special case for any system + // that is different. + if (\DIRECTORY_SEPARATOR === '\\') { + $replacements['/'] = '\\\\'; + } + $pattern = \strtr($pattern, $replacements); + if ($type === 'relative') { + $testPath = $relativePath; + } else { + $testPath = $path; + } + $pattern = '`' . $pattern . '`i'; + if (\preg_match($pattern, $testPath) === 1) { + return \true; + } + } + //end foreach + return \false; + } + //end shouldIgnorePath() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php b/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php new file mode 100644 index 00000000000..4e108b0776b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/GitModified.php @@ -0,0 +1,54 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; +class GitModified extends \PHP_CodeSniffer\Filters\ExactMatch +{ + /** + * Get a list of blacklisted file paths. + * + * @return array + */ + protected function getBlacklist() + { + return []; + } + //end getBlacklist() + /** + * Get a list of whitelisted file paths. + * + * @return array + */ + protected function getWhitelist() + { + $modified = []; + $cmd = 'git ls-files -o -m --exclude-standard -- ' . \escapeshellarg($this->basedir); + $output = []; + \exec($cmd, $output); + $basedir = $this->basedir; + if (\is_dir($basedir) === \false) { + $basedir = \dirname($basedir); + } + foreach ($output as $path) { + $path = Util\Common::realpath($path); + if ($path === \false) { + continue; + } + do { + $modified[$path] = \true; + $path = \dirname($path); + } while ($path !== $basedir); + } + return $modified; + } + //end getWhitelist() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php b/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php new file mode 100644 index 00000000000..1bcc4502617 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Filters/GitStaged.php @@ -0,0 +1,57 @@ + + * @copyright 2018 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Filters; + +use PHP_CodeSniffer\Util; +class GitStaged extends \PHP_CodeSniffer\Filters\ExactMatch +{ + /** + * Get a list of blacklisted file paths. + * + * @return array + */ + protected function getBlacklist() + { + return []; + } + //end getBlacklist() + /** + * Get a list of whitelisted file paths. + * + * @return array + */ + protected function getWhitelist() + { + $modified = []; + $cmd = 'git diff --cached --name-only -- ' . \escapeshellarg($this->basedir); + $output = []; + \exec($cmd, $output); + $basedir = $this->basedir; + if (\is_dir($basedir) === \false) { + $basedir = \dirname($basedir); + } + foreach ($output as $path) { + $path = Util\Common::realpath($path); + if ($path === \false) { + // Skip deleted files. + continue; + } + do { + $modified[$path] = \true; + $path = \dirname($path); + } while ($path !== $basedir); + } + return $modified; + } + //end getWhitelist() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Fixer.php b/vendor/squizlabs/php_codesniffer/src/Fixer.php new file mode 100644 index 00000000000..53ef6a093c2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Fixer.php @@ -0,0 +1,677 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Common; +class Fixer +{ + /** + * Is the fixer enabled and fixing a file? + * + * Sniffs should check this value to ensure they are not + * doing extra processing to prepare for a fix when fixing is + * not required. + * + * @var boolean + */ + public $enabled = \false; + /** + * The number of times we have looped over a file. + * + * @var integer + */ + public $loops = 0; + /** + * The file being fixed. + * + * @var \PHP_CodeSniffer\Files\File + */ + private $currentFile = null; + /** + * The list of tokens that make up the file contents. + * + * This is a simplified list which just contains the token content and nothing + * else. This is the array that is updated as fixes are made, not the file's + * token array. Imploding this array will give you the file content back. + * + * @var array + */ + private $tokens = []; + /** + * A list of tokens that have already been fixed. + * + * We don't allow the same token to be fixed more than once each time + * through a file as this can easily cause conflicts between sniffs. + * + * @var int[] + */ + private $fixedTokens = []; + /** + * The last value of each fixed token. + * + * If a token is being "fixed" back to its last value, the fix is + * probably conflicting with another. + * + * @var array + */ + private $oldTokenValues = []; + /** + * A list of tokens that have been fixed during a changeset. + * + * All changes in changeset must be able to be applied, or else + * the entire changeset is rejected. + * + * @var array + */ + private $changeset = []; + /** + * Is there an open changeset. + * + * @var boolean + */ + private $inChangeset = \false; + /** + * Is the current fixing loop in conflict? + * + * @var boolean + */ + private $inConflict = \false; + /** + * The number of fixes that have been performed. + * + * @var integer + */ + private $numFixes = 0; + /** + * Starts fixing a new file. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being fixed. + * + * @return void + */ + public function startFile(File $phpcsFile) + { + $this->currentFile = $phpcsFile; + $this->numFixes = 0; + $this->fixedTokens = []; + $tokens = $phpcsFile->getTokens(); + $this->tokens = []; + foreach ($tokens as $index => $token) { + if (isset($token['orig_content']) === \true) { + $this->tokens[$index] = $token['orig_content']; + } else { + $this->tokens[$index] = $token['content']; + } + } + } + //end startFile() + /** + * Attempt to fix the file by processing it until no fixes are made. + * + * @return boolean + */ + public function fixFile() + { + $fixable = $this->currentFile->getFixableCount(); + if ($fixable === 0) { + // Nothing to fix. + return \false; + } + $this->enabled = \true; + $this->loops = 0; + while ($this->loops < 50) { + \ob_start(); + // Only needed once file content has changed. + $contents = $this->getContents(); + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + @\ob_end_clean(); + echo '---START FILE CONTENT---' . \PHP_EOL; + $lines = \explode($this->currentFile->eolChar, $contents); + $max = \strlen(\count($lines)); + foreach ($lines as $lineNum => $line) { + $lineNum++; + echo \str_pad($lineNum, $max, ' ', \STR_PAD_LEFT) . '|' . $line . \PHP_EOL; + } + echo '--- END FILE CONTENT ---' . \PHP_EOL; + \ob_start(); + } + $this->inConflict = \false; + $this->currentFile->ruleset->populateTokenListeners(); + $this->currentFile->setContent($contents); + $this->currentFile->process(); + \ob_end_clean(); + $this->loops++; + if (\PHP_CODESNIFFER_CBF === \true && \PHP_CODESNIFFER_VERBOSITY > 0) { + echo "\r" . \str_repeat(' ', 80) . "\r"; + echo "\t=> Fixing file: {$this->numFixes}/{$fixable} violations remaining [made {$this->loops} pass"; + if ($this->loops > 1) { + echo 'es'; + } + echo ']... '; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + } + if ($this->numFixes === 0 && $this->inConflict === \false) { + // Nothing left to do. + break; + } else { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t* fixed {$this->numFixes} violations, starting loop " . ($this->loops + 1) . ' *' . \PHP_EOL; + } + } + } + //end while + $this->enabled = \false; + if ($this->numFixes > 0) { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + if (\ob_get_level() > 0) { + \ob_end_clean(); + } + echo "\t*** Reached maximum number of loops with {$this->numFixes} violations left unfixed ***" . \PHP_EOL; + \ob_start(); + } + return \false; + } + return \true; + } + //end fixFile() + /** + * Generates a text diff of the original file and the new content. + * + * @param string $filePath Optional file path to diff the file against. + * If not specified, the original version of the + * file will be used. + * @param boolean $colors Print coloured output or not. + * + * @return string + */ + public function generateDiff($filePath = null, $colors = \true) + { + if ($filePath === null) { + $filePath = $this->currentFile->getFilename(); + } + $cwd = \getcwd() . \DIRECTORY_SEPARATOR; + if (\strpos($filePath, $cwd) === 0) { + $filename = \substr($filePath, \strlen($cwd)); + } else { + $filename = $filePath; + } + $contents = $this->getContents(); + $tempName = \tempnam(\sys_get_temp_dir(), 'phpcs-fixer'); + $fixedFile = \fopen($tempName, 'w'); + \fwrite($fixedFile, $contents); + // We must use something like shell_exec() because whitespace at the end + // of lines is critical to diff files. + $filename = \escapeshellarg($filename); + $cmd = "diff -u -L{$filename} -LPHP_CodeSniffer {$filename} \"{$tempName}\""; + $diff = \shell_exec($cmd); + \fclose($fixedFile); + if (\is_file($tempName) === \true) { + \unlink($tempName); + } + if ($diff === null) { + return ''; + } + if ($colors === \false) { + return $diff; + } + $diffLines = \explode(\PHP_EOL, $diff); + if (\count($diffLines) === 1) { + // Seems to be required for cygwin. + $diffLines = \explode("\n", $diff); + } + $diff = []; + foreach ($diffLines as $line) { + if (isset($line[0]) === \true) { + switch ($line[0]) { + case '-': + $diff[] = "\x1b[31m{$line}\x1b[0m"; + break; + case '+': + $diff[] = "\x1b[32m{$line}\x1b[0m"; + break; + default: + $diff[] = $line; + } + } + } + $diff = \implode(\PHP_EOL, $diff); + return $diff; + } + //end generateDiff() + /** + * Get a count of fixes that have been performed on the file. + * + * This value is reset every time a new file is started, or an existing + * file is restarted. + * + * @return int + */ + public function getFixCount() + { + return $this->numFixes; + } + //end getFixCount() + /** + * Get the current content of the file, as a string. + * + * @return string + */ + public function getContents() + { + $contents = \implode($this->tokens); + return $contents; + } + //end getContents() + /** + * Get the current fixed content of a token. + * + * This function takes changesets into account so should be used + * instead of directly accessing the token array. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return string + */ + public function getTokenContent($stackPtr) + { + if ($this->inChangeset === \true && isset($this->changeset[$stackPtr]) === \true) { + return $this->changeset[$stackPtr]; + } else { + return $this->tokens[$stackPtr]; + } + } + //end getTokenContent() + /** + * Start recording actions for a changeset. + * + * @return void + */ + public function beginChangeset() + { + if ($this->inConflict === \true) { + return \false; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === __CLASS__) { + $sniff = 'Fixer'; + } else { + $sniff = \PHP_CodeSniffer\Util\Common::getSniffCode($bt[1]['class']); + } + $line = $bt[0]['line']; + @\ob_end_clean(); + echo "\t=> Changeset started by {$sniff}:{$line}" . \PHP_EOL; + \ob_start(); + } + $this->changeset = []; + $this->inChangeset = \true; + } + //end beginChangeset() + /** + * Stop recording actions for a changeset, and apply logged changes. + * + * @return boolean + */ + public function endChangeset() + { + if ($this->inConflict === \true) { + return \false; + } + $this->inChangeset = \false; + $success = \true; + $applied = []; + foreach ($this->changeset as $stackPtr => $content) { + $success = $this->replaceToken($stackPtr, $content); + if ($success === \false) { + break; + } else { + $applied[] = $stackPtr; + } + } + if ($success === \false) { + // Rolling back all changes. + foreach ($applied as $stackPtr) { + $this->revertToken($stackPtr); + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + @\ob_end_clean(); + echo "\t=> Changeset failed to apply" . \PHP_EOL; + \ob_start(); + } + } else { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $fixes = \count($this->changeset); + @\ob_end_clean(); + echo "\t=> Changeset ended: {$fixes} changes applied" . \PHP_EOL; + \ob_start(); + } + } + $this->changeset = []; + return \true; + } + //end endChangeset() + /** + * Stop recording actions for a changeset, and discard logged changes. + * + * @return void + */ + public function rollbackChangeset() + { + $this->inChangeset = \false; + $this->inConflict = \false; + if (empty($this->changeset) === \false) { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = \debug_backtrace(); + if ($bt[1]['class'] === 'PHP_CodeSniffer\\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + $sniff = \PHP_CodeSniffer\Util\Common::getSniffCode($sniff); + $numChanges = \count($this->changeset); + @\ob_end_clean(); + echo "\t\tR: {$sniff}:{$line} rolled back the changeset ({$numChanges} changes)" . \PHP_EOL; + echo "\t=> Changeset rolled back" . \PHP_EOL; + \ob_start(); + } + $this->changeset = []; + } + //end if + } + //end rollbackChangeset() + /** + * Replace the entire contents of a token. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The new content of the token. + * + * @return bool If the change was accepted. + */ + public function replaceToken($stackPtr, $content) + { + if ($this->inConflict === \true) { + return \false; + } + if ($this->inChangeset === \false && isset($this->fixedTokens[$stackPtr]) === \true) { + $indent = "\t"; + if (empty($this->changeset) === \false) { + $indent .= "\t"; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + @\ob_end_clean(); + echo "{$indent}* token {$stackPtr} has already been modified, skipping *" . \PHP_EOL; + \ob_start(); + } + return \false; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === 'PHP_CodeSniffer\\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + $sniff = \PHP_CodeSniffer\Util\Common::getSniffCode($sniff); + $tokens = $this->currentFile->getTokens(); + $type = $tokens[$stackPtr]['type']; + $tokenLine = $tokens[$stackPtr]['line']; + $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]); + $newContent = Common::prepareForOutput($content); + if (\trim($this->tokens[$stackPtr]) === '' && isset($this->tokens[$stackPtr + 1]) === \true) { + // Add some context for whitespace only changes. + $append = Common::prepareForOutput($this->tokens[$stackPtr + 1]); + $oldContent .= $append; + $newContent .= $append; + } + } + //end if + if ($this->inChangeset === \true) { + $this->changeset[$stackPtr] = $content; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + @\ob_end_clean(); + echo "\t\tQ: {$sniff}:{$line} replaced token {$stackPtr} ({$type} on line {$tokenLine}) \"{$oldContent}\" => \"{$newContent}\"" . \PHP_EOL; + \ob_start(); + } + return \true; + } + if (isset($this->oldTokenValues[$stackPtr]) === \false) { + $this->oldTokenValues[$stackPtr] = ['curr' => $content, 'prev' => $this->tokens[$stackPtr], 'loop' => $this->loops]; + } else { + if ($this->oldTokenValues[$stackPtr]['prev'] === $content && $this->oldTokenValues[$stackPtr]['loop'] === $this->loops - 1) { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === \false) { + $indent .= "\t"; + } + $loop = $this->oldTokenValues[$stackPtr]['loop']; + @\ob_end_clean(); + echo "{$indent}**** {$sniff}:{$line} has possible conflict with another sniff on loop {$loop}; caused by the following change ****" . \PHP_EOL; + echo "{$indent}**** replaced token {$stackPtr} ({$type} on line {$tokenLine}) \"{$oldContent}\" => \"{$newContent}\" ****" . \PHP_EOL; + } + if ($this->oldTokenValues[$stackPtr]['loop'] >= $this->loops - 1) { + $this->inConflict = \true; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo "{$indent}**** ignoring all changes until next loop ****" . \PHP_EOL; + } + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + \ob_start(); + } + return \false; + } + //end if + $this->oldTokenValues[$stackPtr]['prev'] = $this->oldTokenValues[$stackPtr]['curr']; + $this->oldTokenValues[$stackPtr]['curr'] = $content; + $this->oldTokenValues[$stackPtr]['loop'] = $this->loops; + } + //end if + $this->fixedTokens[$stackPtr] = $this->tokens[$stackPtr]; + $this->tokens[$stackPtr] = $content; + $this->numFixes++; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === \false) { + $indent .= "\tA: "; + } + if (\ob_get_level() > 0) { + \ob_end_clean(); + } + echo "{$indent}{$sniff}:{$line} replaced token {$stackPtr} ({$type} on line {$tokenLine}) \"{$oldContent}\" => \"{$newContent}\"" . \PHP_EOL; + \ob_start(); + } + return \true; + } + //end replaceToken() + /** + * Reverts the previous fix made to a token. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If a change was reverted. + */ + public function revertToken($stackPtr) + { + if (isset($this->fixedTokens[$stackPtr]) === \false) { + return \false; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $bt = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS); + if ($bt[1]['class'] === 'PHP_CodeSniffer\\Fixer') { + $sniff = $bt[2]['class']; + $line = $bt[1]['line']; + } else { + $sniff = $bt[1]['class']; + $line = $bt[0]['line']; + } + $sniff = \PHP_CodeSniffer\Util\Common::getSniffCode($sniff); + $tokens = $this->currentFile->getTokens(); + $type = $tokens[$stackPtr]['type']; + $tokenLine = $tokens[$stackPtr]['line']; + $oldContent = Common::prepareForOutput($this->tokens[$stackPtr]); + $newContent = Common::prepareForOutput($this->fixedTokens[$stackPtr]); + if (\trim($this->tokens[$stackPtr]) === '' && isset($tokens[$stackPtr + 1]) === \true) { + // Add some context for whitespace only changes. + $append = Common::prepareForOutput($this->tokens[$stackPtr + 1]); + $oldContent .= $append; + $newContent .= $append; + } + } + //end if + $this->tokens[$stackPtr] = $this->fixedTokens[$stackPtr]; + unset($this->fixedTokens[$stackPtr]); + $this->numFixes--; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $indent = "\t"; + if (empty($this->changeset) === \false) { + $indent .= "\tR: "; + } + @\ob_end_clean(); + echo "{$indent}{$sniff}:{$line} reverted token {$stackPtr} ({$type} on line {$tokenLine}) \"{$oldContent}\" => \"{$newContent}\"" . \PHP_EOL; + \ob_start(); + } + return \true; + } + //end revertToken() + /** + * Replace the content of a token with a part of its current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param int $start The first character to keep. + * @param int $length The number of characters to keep. If NULL, the content of + * the token from $start to the end of the content is kept. + * + * @return bool If the change was accepted. + */ + public function substrToken($stackPtr, $start, $length = null) + { + $current = $this->getTokenContent($stackPtr); + if ($length === null) { + $newContent = \substr($current, $start); + } else { + $newContent = \substr($current, $start, $length); + } + return $this->replaceToken($stackPtr, $newContent); + } + //end substrToken() + /** + * Adds a newline to end of a token's content. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If the change was accepted. + */ + public function addNewline($stackPtr) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $current . $this->currentFile->eolChar); + } + //end addNewline() + /** + * Adds a newline to the start of a token's content. + * + * @param int $stackPtr The position of the token in the token stack. + * + * @return bool If the change was accepted. + */ + public function addNewlineBefore($stackPtr) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $this->currentFile->eolChar . $current); + } + //end addNewlineBefore() + /** + * Adds content to the end of a token's current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The content to add. + * + * @return bool If the change was accepted. + */ + public function addContent($stackPtr, $content) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $current . $content); + } + //end addContent() + /** + * Adds content to the start of a token's current content. + * + * @param int $stackPtr The position of the token in the token stack. + * @param string $content The content to add. + * + * @return bool If the change was accepted. + */ + public function addContentBefore($stackPtr, $content) + { + $current = $this->getTokenContent($stackPtr); + return $this->replaceToken($stackPtr, $content . $current); + } + //end addContentBefore() + /** + * Adjust the indent of a code block. + * + * @param int $start The position of the token in the token stack + * to start adjusting the indent from. + * @param int $end The position of the token in the token stack + * to end adjusting the indent. + * @param int $change The number of spaces to adjust the indent by + * (positive or negative). + * + * @return void + */ + public function changeCodeBlockIndent($start, $end, $change) + { + $tokens = $this->currentFile->getTokens(); + $baseIndent = ''; + if ($change > 0) { + $baseIndent = \str_repeat(' ', $change); + } + $useChangeset = \false; + if ($this->inChangeset === \false) { + $this->beginChangeset(); + $useChangeset = \true; + } + for ($i = $start; $i <= $end; $i++) { + if ($tokens[$i]['column'] !== 1 || $tokens[$i + 1]['line'] !== $tokens[$i]['line']) { + continue; + } + $length = 0; + if ($tokens[$i]['code'] === \T_WHITESPACE || $tokens[$i]['code'] === \T_DOC_COMMENT_WHITESPACE) { + $length = $tokens[$i]['length']; + $padding = $length + $change; + if ($padding > 0) { + $padding = \str_repeat(' ', $padding); + } else { + $padding = ''; + } + $newContent = $padding . \ltrim($tokens[$i]['content']); + } else { + $newContent = $baseIndent . $tokens[$i]['content']; + } + $this->replaceToken($i, $newContent); + } + //end for + if ($useChangeset === \true) { + $this->endChangeset(); + } + } + //end changeCodeBlockIndent() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php b/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php new file mode 100644 index 00000000000..ff70f4ee381 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Generator.php @@ -0,0 +1,99 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Ruleset; +use PHP_CodeSniffer\Autoload; +abstract class Generator +{ + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + /** + * XML documentation files used to produce the final output. + * + * @var string[] + */ + public $docFiles = []; + /** + * Constructs a doc generator. + * + * @param \PHP_CodeSniffer\Ruleset $ruleset The ruleset used for the run. + * + * @see generate() + */ + public function __construct(Ruleset $ruleset) + { + $this->ruleset = $ruleset; + foreach ($ruleset->sniffs as $className => $sniffClass) { + $file = Autoload::getLoadedFileName($className); + $docFile = \str_replace(\DIRECTORY_SEPARATOR . 'Sniffs' . \DIRECTORY_SEPARATOR, \DIRECTORY_SEPARATOR . 'Docs' . \DIRECTORY_SEPARATOR, $file); + $docFile = \str_replace('Sniff.php', 'Standard.xml', $docFile); + if (\is_file($docFile) === \true) { + $this->docFiles[] = $docFile; + } + } + } + //end __construct() + /** + * Retrieves the title of the sniff from the DOMNode supplied. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return string + */ + protected function getTitle(\DOMNode $doc) + { + return $doc->getAttribute('title'); + } + //end getTitle() + /** + * Generates the documentation for a standard. + * + * It's probably wise for doc generators to override this method so they + * have control over how the docs are produced. Otherwise, the processSniff + * method should be overridden to output content for each sniff. + * + * @return void + * @see processSniff() + */ + public function generate() + { + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + } + //end generate() + /** + * Process the documentation for a single sniff. + * + * Doc generators must implement this function to produce output. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + * @see generate() + */ + protected abstract function processSniff(\DOMNode $doc); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php b/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php new file mode 100644 index 00000000000..3ee548c3497 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/HTML.php @@ -0,0 +1,243 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Config; +class HTML extends \PHP_CodeSniffer\Generators\Generator +{ + /** + * Generates the documentation for a standard. + * + * @return void + * @see processSniff() + */ + public function generate() + { + \ob_start(); + $this->printHeader(); + $this->printToc(); + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + $this->printFooter(); + $content = \ob_get_contents(); + \ob_end_clean(); + echo $content; + } + //end generate() + /** + * Print the header of the HTML page. + * + * @return void + */ + protected function printHeader() + { + $standard = $this->ruleset->name; + echo '' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo " {$standard} Coding Standards" . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo "

{$standard} Coding Standards

" . \PHP_EOL; + } + //end printHeader() + /** + * Print the table of contents for the standard. + * + * The TOC is just an unordered list of bookmarks to sniffs on the page. + * + * @return void + */ + protected function printToc() + { + echo '

Table of Contents

' . \PHP_EOL; + echo '
    ' . \PHP_EOL; + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $title = $this->getTitle($documentation); + echo '
  • {$title}
  • " . \PHP_EOL; + } + echo '
' . \PHP_EOL; + } + //end printToc() + /** + * Print the footer of the HTML page. + * + * @return void + */ + protected function printFooter() + { + // Turn off errors so we don't get timezone warnings if people + // don't have their timezone set. + $errorLevel = \error_reporting(0); + echo '
'; + echo 'Documentation generated on ' . \date('r'); + echo ' by PHP_CodeSniffer ' . Config::VERSION . ''; + echo '
' . \PHP_EOL; + \error_reporting($errorLevel); + echo ' ' . \PHP_EOL; + echo '' . \PHP_EOL; + } + //end printFooter() + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + public function processSniff(\DOMNode $doc) + { + $title = $this->getTitle($doc); + echo ' ' . \PHP_EOL; + echo "

{$title}

" . \PHP_EOL; + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else { + if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + } + } + //end processSniff() + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $content = \trim($node->nodeValue); + $content = \htmlspecialchars($content); + // Allow em tags only. + $content = \str_replace('<em>', '', $content); + $content = \str_replace('</em>', '', $content); + echo "

{$content}

" . \PHP_EOL; + } + //end printTextBlock() + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + $first = \trim($codeBlocks->item(0)->nodeValue); + $first = \str_replace('', $first); + $first = \str_replace(' ', ' ', $first); + $first = \str_replace('', '', $first); + $first = \str_replace('', '', $first); + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + $second = \trim($codeBlocks->item(1)->nodeValue); + $second = \str_replace('', $second); + $second = \str_replace(' ', ' ', $second); + $second = \str_replace('', '', $second); + $second = \str_replace('', '', $second); + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo " " . \PHP_EOL; + echo " " . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo " " . \PHP_EOL; + echo " " . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo '
{$firstTitle}{$secondTitle}
{$first}{$second}
' . \PHP_EOL; + } + //end printCodeComparisonBlock() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php b/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php new file mode 100644 index 00000000000..29bdefcf332 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Markdown.php @@ -0,0 +1,139 @@ + + * @copyright 2014 Arroba IT + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Generators; + +use PHP_CodeSniffer\Config; +class Markdown extends \PHP_CodeSniffer\Generators\Generator +{ + /** + * Generates the documentation for a standard. + * + * @return void + * @see processSniff() + */ + public function generate() + { + \ob_start(); + $this->printHeader(); + foreach ($this->docFiles as $file) { + $doc = new \DOMDocument(); + $doc->load($file); + $documentation = $doc->getElementsByTagName('documentation')->item(0); + $this->processSniff($documentation); + } + $this->printFooter(); + $content = \ob_get_contents(); + \ob_end_clean(); + echo $content; + } + //end generate() + /** + * Print the markdown header. + * + * @return void + */ + protected function printHeader() + { + $standard = $this->ruleset->name; + echo "# {$standard} Coding Standard" . \PHP_EOL; + } + //end printHeader() + /** + * Print the markdown footer. + * + * @return void + */ + protected function printFooter() + { + // Turn off errors so we don't get timezone warnings if people + // don't have their timezone set. + \error_reporting(0); + echo 'Documentation generated on ' . \date('r'); + echo ' by [PHP_CodeSniffer ' . Config::VERSION . '](https://github.com/squizlabs/PHP_CodeSniffer)' . \PHP_EOL; + } + //end printFooter() + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + protected function processSniff(\DOMNode $doc) + { + $title = $this->getTitle($doc); + echo \PHP_EOL . "## {$title}" . \PHP_EOL; + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else { + if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + } + } + //end processSniff() + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $content = \trim($node->nodeValue); + $content = \htmlspecialchars($content); + $content = \str_replace('<em>', '*', $content); + $content = \str_replace('</em>', '*', $content); + echo $content . \PHP_EOL; + } + //end printTextBlock() + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + $first = \trim($codeBlocks->item(0)->nodeValue); + $first = \str_replace("\n", "\n ", $first); + $first = \str_replace('', '', $first); + $first = \str_replace('', '', $first); + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + $second = \trim($codeBlocks->item(1)->nodeValue); + $second = \str_replace("\n", "\n ", $second); + $second = \str_replace('', '', $second); + $second = \str_replace('', '', $second); + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo " " . \PHP_EOL; + echo " " . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo '' . \PHP_EOL; + echo '' . \PHP_EOL; + echo ' ' . \PHP_EOL; + echo '
{$firstTitle}{$secondTitle}
' . \PHP_EOL . \PHP_EOL; + echo " {$first}" . \PHP_EOL . \PHP_EOL; + echo '' . \PHP_EOL . \PHP_EOL; + echo " {$second}" . \PHP_EOL . \PHP_EOL; + echo '
' . \PHP_EOL; + } + //end printCodeComparisonBlock() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Generators/Text.php b/vendor/squizlabs/php_codesniffer/src/Generators/Text.php new file mode 100644 index 00000000000..e5119a0bc31 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Generators/Text.php @@ -0,0 +1,228 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Generators; + +class Text extends \PHP_CodeSniffer\Generators\Generator +{ + /** + * Process the documentation for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + public function processSniff(\DOMNode $doc) + { + $this->printTitle($doc); + foreach ($doc->childNodes as $node) { + if ($node->nodeName === 'standard') { + $this->printTextBlock($node); + } else { + if ($node->nodeName === 'code_comparison') { + $this->printCodeComparisonBlock($node); + } + } + } + } + //end processSniff() + /** + * Prints the title area for a single sniff. + * + * @param \DOMNode $doc The DOMNode object for the sniff. + * It represents the "documentation" tag in the XML + * standard file. + * + * @return void + */ + protected function printTitle(\DOMNode $doc) + { + $title = $this->getTitle($doc); + $standard = $this->ruleset->name; + echo \PHP_EOL; + echo \str_repeat('-', \strlen("{$standard} CODING STANDARD: {$title}") + 4); + echo \strtoupper(\PHP_EOL . "| {$standard} CODING STANDARD: {$title} |" . \PHP_EOL); + echo \str_repeat('-', \strlen("{$standard} CODING STANDARD: {$title}") + 4); + echo \PHP_EOL . \PHP_EOL; + } + //end printTitle() + /** + * Print a text block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the text block. + * + * @return void + */ + protected function printTextBlock(\DOMNode $node) + { + $text = \trim($node->nodeValue); + $text = \str_replace('', '*', $text); + $text = \str_replace('', '*', $text); + $nodeLines = \explode("\n", $text); + $lines = []; + foreach ($nodeLines as $currentLine) { + $currentLine = \trim($currentLine); + if ($currentLine === '') { + // The text contained a blank line. Respect this. + $lines[] = ''; + continue; + } + $tempLine = ''; + $words = \explode(' ', $currentLine); + foreach ($words as $word) { + $currentLength = \strlen($tempLine . $word); + if ($currentLength < 99) { + $tempLine .= $word . ' '; + continue; + } + if ($currentLength === 99 || $currentLength === 100) { + // We are already at the edge, so we are done. + $lines[] = $tempLine . $word; + $tempLine = ''; + } else { + $lines[] = \rtrim($tempLine); + $tempLine = $word . ' '; + } + } + //end foreach + if ($tempLine !== '') { + $lines[] = \rtrim($tempLine); + } + } + //end foreach + echo \implode(\PHP_EOL, $lines) . \PHP_EOL . \PHP_EOL; + } + //end printTextBlock() + /** + * Print a code comparison block found in a standard. + * + * @param \DOMNode $node The DOMNode object for the code comparison block. + * + * @return void + */ + protected function printCodeComparisonBlock(\DOMNode $node) + { + $codeBlocks = $node->getElementsByTagName('code'); + $first = \trim($codeBlocks->item(0)->nodeValue); + $firstTitle = $codeBlocks->item(0)->getAttribute('title'); + $firstTitleLines = []; + $tempTitle = ''; + $words = \explode(' ', $firstTitle); + foreach ($words as $word) { + if (\strlen($tempTitle . $word) >= 45) { + if (\strlen($tempTitle . $word) === 45) { + // Adding the extra space will push us to the edge + // so we are done. + $firstTitleLines[] = $tempTitle . $word; + $tempTitle = ''; + } else { + if (\strlen($tempTitle . $word) === 46) { + // We are already at the edge, so we are done. + $firstTitleLines[] = $tempTitle . $word; + $tempTitle = ''; + } else { + $firstTitleLines[] = $tempTitle; + $tempTitle = $word . ' '; + } + } + } else { + $tempTitle .= $word . ' '; + } + } + //end foreach + if ($tempTitle !== '') { + $firstTitleLines[] = $tempTitle; + } + $first = \str_replace('', '', $first); + $first = \str_replace('', '', $first); + $firstLines = \explode("\n", $first); + $second = \trim($codeBlocks->item(1)->nodeValue); + $secondTitle = $codeBlocks->item(1)->getAttribute('title'); + $secondTitleLines = []; + $tempTitle = ''; + $words = \explode(' ', $secondTitle); + foreach ($words as $word) { + if (\strlen($tempTitle . $word) >= 45) { + if (\strlen($tempTitle . $word) === 45) { + // Adding the extra space will push us to the edge + // so we are done. + $secondTitleLines[] = $tempTitle . $word; + $tempTitle = ''; + } else { + if (\strlen($tempTitle . $word) === 46) { + // We are already at the edge, so we are done. + $secondTitleLines[] = $tempTitle . $word; + $tempTitle = ''; + } else { + $secondTitleLines[] = $tempTitle; + $tempTitle = $word . ' '; + } + } + } else { + $tempTitle .= $word . ' '; + } + } + //end foreach + if ($tempTitle !== '') { + $secondTitleLines[] = $tempTitle; + } + $second = \str_replace('', '', $second); + $second = \str_replace('', '', $second); + $secondLines = \explode("\n", $second); + $maxCodeLines = \max(\count($firstLines), \count($secondLines)); + $maxTitleLines = \max(\count($firstTitleLines), \count($secondTitleLines)); + echo \str_repeat('-', 41); + echo ' CODE COMPARISON '; + echo \str_repeat('-', 42) . \PHP_EOL; + for ($i = 0; $i < $maxTitleLines; $i++) { + if (isset($firstTitleLines[$i]) === \true) { + $firstLineText = $firstTitleLines[$i]; + } else { + $firstLineText = ''; + } + if (isset($secondTitleLines[$i]) === \true) { + $secondLineText = $secondTitleLines[$i]; + } else { + $secondLineText = ''; + } + echo '| '; + echo $firstLineText . \str_repeat(' ', 46 - \strlen($firstLineText)); + echo ' | '; + echo $secondLineText . \str_repeat(' ', 47 - \strlen($secondLineText)); + echo ' |' . \PHP_EOL; + } + //end for + echo \str_repeat('-', 100) . \PHP_EOL; + for ($i = 0; $i < $maxCodeLines; $i++) { + if (isset($firstLines[$i]) === \true) { + $firstLineText = $firstLines[$i]; + } else { + $firstLineText = ''; + } + if (isset($secondLines[$i]) === \true) { + $secondLineText = $secondLines[$i]; + } else { + $secondLineText = ''; + } + echo '| '; + echo $firstLineText . \str_repeat(' ', \max(0, 47 - \strlen($firstLineText))); + echo '| '; + echo $secondLineText . \str_repeat(' ', \max(0, 48 - \strlen($secondLineText))); + echo '|' . \PHP_EOL; + } + //end for + echo \str_repeat('-', 100) . \PHP_EOL . \PHP_EOL; + } + //end printCodeComparisonBlock() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reporter.php b/vendor/squizlabs/php_codesniffer/src/Reporter.php new file mode 100644 index 00000000000..68b92bd3166 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reporter.php @@ -0,0 +1,334 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Reports\Report; +use PHP_CodeSniffer\Util\Common; +class Reporter +{ + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + /** + * Total number of files that contain errors or warnings. + * + * @var integer + */ + public $totalFiles = 0; + /** + * Total number of errors found during the run. + * + * @var integer + */ + public $totalErrors = 0; + /** + * Total number of warnings found during the run. + * + * @var integer + */ + public $totalWarnings = 0; + /** + * Total number of errors/warnings that can be fixed. + * + * @var integer + */ + public $totalFixable = 0; + /** + * Total number of errors/warnings that were fixed. + * + * @var integer + */ + public $totalFixed = 0; + /** + * When the PHPCS run started. + * + * @var float + */ + public static $startTime = 0; + /** + * A cache of report objects. + * + * @var array + */ + private $reports = []; + /** + * A cache of opened temporary files. + * + * @var array + */ + private $tmpFiles = []; + /** + * Initialise the reporter. + * + * All reports specified in the config will be created and their + * output file (or a temp file if none is specified) initialised by + * clearing the current contents. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a custom report class could not be found. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If a report class is incorrectly set up. + */ + public function __construct(\PHP_CodeSniffer\Config $config) + { + $this->config = $config; + foreach ($config->reports as $type => $output) { + if ($output === null) { + $output = $config->reportFile; + } + $reportClassName = ''; + if (\strpos($type, '.') !== \false) { + // This is a path to a custom report class. + $filename = \realpath($type); + if ($filename === \false) { + $error = "ERROR: Custom report \"{$type}\" not found" . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $reportClassName = \PHP_CodeSniffer\Autoload::loadFile($filename); + } else { + if (\class_exists('PHP_CodeSniffer\\Reports\\' . \ucfirst($type)) === \true) { + // PHPCS native report. + $reportClassName = 'PHP_CodeSniffer\\Reports\\' . \ucfirst($type); + } else { + if (\class_exists($type) === \true) { + // FQN of a custom report. + $reportClassName = $type; + } else { + // OK, so not a FQN, try and find the report using the registered namespaces. + $registeredNamespaces = \PHP_CodeSniffer\Autoload::getSearchPaths(); + $trimmedType = \ltrim($type, '\\'); + foreach ($registeredNamespaces as $nsPrefix) { + if ($nsPrefix === '') { + continue; + } + if (\class_exists($nsPrefix . '\\' . $trimmedType) === \true) { + $reportClassName = $nsPrefix . '\\' . $trimmedType; + break; + } + } + } + } + } + //end if + if ($reportClassName === '') { + $error = "ERROR: Class file for report \"{$type}\" not found" . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $reportClass = new $reportClassName(); + if ($reportClass instanceof Report === \false) { + throw new RuntimeException('Class "' . $reportClassName . '" must implement the "PHP_CodeSniffer\\Report" interface.'); + } + $this->reports[$type] = ['output' => $output, 'class' => $reportClass]; + if ($output === null) { + // Using a temp file. + // This needs to be set in the constructor so that all + // child procs use the same report file when running in parallel. + $this->tmpFiles[$type] = \tempnam(\sys_get_temp_dir(), 'phpcs'); + \file_put_contents($this->tmpFiles[$type], ''); + } else { + \file_put_contents($output, ''); + } + } + //end foreach + } + //end __construct() + /** + * Generates and prints final versions of all reports. + * + * Returns TRUE if any of the reports output content to the screen + * or FALSE if all reports were silently printed to a file. + * + * @return bool + */ + public function printReports() + { + $toScreen = \false; + foreach ($this->reports as $type => $report) { + if ($report['output'] === null) { + $toScreen = \true; + } + $this->printReport($type); + } + return $toScreen; + } + //end printReports() + /** + * Generates and prints a single final report. + * + * @param string $report The report type to print. + * + * @return void + */ + public function printReport($report) + { + $reportClass = $this->reports[$report]['class']; + $reportFile = $this->reports[$report]['output']; + if ($reportFile !== null) { + $filename = $reportFile; + $toScreen = \false; + } else { + if (isset($this->tmpFiles[$report]) === \true) { + $filename = $this->tmpFiles[$report]; + } else { + $filename = null; + } + $toScreen = \true; + } + $reportCache = ''; + if ($filename !== null) { + $reportCache = \file_get_contents($filename); + } + \ob_start(); + $reportClass->generate($reportCache, $this->totalFiles, $this->totalErrors, $this->totalWarnings, $this->totalFixable, $this->config->showSources, $this->config->reportWidth, $this->config->interactive, $toScreen); + $generatedReport = \ob_get_contents(); + \ob_end_clean(); + if ($this->config->colors !== \true || $reportFile !== null) { + $generatedReport = \preg_replace('`\\033\\[[0-9;]+m`', '', $generatedReport); + } + if ($reportFile !== null) { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo $generatedReport; + } + \file_put_contents($reportFile, $generatedReport . \PHP_EOL); + } else { + echo $generatedReport; + if ($filename !== null && \file_exists($filename) === \true) { + \unlink($filename); + unset($this->tmpFiles[$report]); + } + } + } + //end printReport() + /** + * Caches the result of a single processed file for all reports. + * + * The report content that is generated is appended to the output file + * assigned to each report. This content may be an intermediate report format + * and not reflect the final report output. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file that has been processed. + * + * @return void + */ + public function cacheFileReport(File $phpcsFile) + { + if (isset($this->config->reports) === \false) { + // This happens during unit testing, or any time someone just wants + // the error data and not the printed report. + return; + } + $reportData = $this->prepareFileReport($phpcsFile); + $errorsShown = \false; + foreach ($this->reports as $type => $report) { + $reportClass = $report['class']; + \ob_start(); + $result = $reportClass->generateFileReport($reportData, $phpcsFile, $this->config->showSources, $this->config->reportWidth); + if ($result === \true) { + $errorsShown = \true; + } + $generatedReport = \ob_get_contents(); + \ob_end_clean(); + if ($report['output'] === null) { + // Using a temp file. + if (isset($this->tmpFiles[$type]) === \false) { + // When running in interactive mode, the reporter prints the full + // report many times, which will unlink the temp file. So we need + // to create a new one if it doesn't exist. + $this->tmpFiles[$type] = \tempnam(\sys_get_temp_dir(), 'phpcs'); + \file_put_contents($this->tmpFiles[$type], ''); + } + \file_put_contents($this->tmpFiles[$type], $generatedReport, \FILE_APPEND | \LOCK_EX); + } else { + \file_put_contents($report['output'], $generatedReport, \FILE_APPEND | \LOCK_EX); + } + //end if + } + //end foreach + if ($errorsShown === \true || \PHP_CODESNIFFER_CBF === \true) { + $this->totalFiles++; + $this->totalErrors += $reportData['errors']; + $this->totalWarnings += $reportData['warnings']; + // When PHPCBF is running, we need to use the fixable error values + // after the report has run and fixed what it can. + if (\PHP_CODESNIFFER_CBF === \true) { + $this->totalFixable += $phpcsFile->getFixableCount(); + $this->totalFixed += $phpcsFile->getFixedCount(); + } else { + $this->totalFixable += $reportData['fixable']; + } + } + } + //end cacheFileReport() + /** + * Generate summary information to be used during report generation. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file that has been processed. + * + * @return array + */ + public function prepareFileReport(File $phpcsFile) + { + $report = ['filename' => Common::stripBasepath($phpcsFile->getFilename(), $this->config->basepath), 'errors' => $phpcsFile->getErrorCount(), 'warnings' => $phpcsFile->getWarningCount(), 'fixable' => $phpcsFile->getFixableCount(), 'messages' => []]; + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Prefect score! + return $report; + } + if ($this->config->recordErrors === \false) { + $message = 'Errors are not being recorded but this report requires error messages. '; + $message .= 'This report will not show the correct information.'; + $report['messages'][1][1] = [['message' => $message, 'source' => 'Internal.RecordErrors', 'severity' => 5, 'fixable' => \false, 'type' => 'ERROR']]; + return $report; + } + $errors = []; + // Merge errors and warnings. + foreach ($phpcsFile->getErrors() as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + $newErrors = []; + foreach ($colErrors as $data) { + $newErrors[] = ['message' => $data['message'], 'source' => $data['source'], 'severity' => $data['severity'], 'fixable' => $data['fixable'], 'type' => 'ERROR']; + } + $errors[$line][$column] = $newErrors; + } + \ksort($errors[$line]); + } + //end foreach + foreach ($phpcsFile->getWarnings() as $line => $lineWarnings) { + foreach ($lineWarnings as $column => $colWarnings) { + $newWarnings = []; + foreach ($colWarnings as $data) { + $newWarnings[] = ['message' => $data['message'], 'source' => $data['source'], 'severity' => $data['severity'], 'fixable' => $data['fixable'], 'type' => 'WARNING']; + } + if (isset($errors[$line]) === \false) { + $errors[$line] = []; + } + if (isset($errors[$line][$column]) === \true) { + $errors[$line][$column] = \array_merge($newWarnings, $errors[$line][$column]); + } else { + $errors[$line][$column] = $newWarnings; + } + } + //end foreach + \ksort($errors[$line]); + } + //end foreach + \ksort($errors); + $report['messages'] = $errors; + return $report; + } + //end prepareFileReport() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php b/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php new file mode 100644 index 00000000000..a4b419005c4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Cbf.php @@ -0,0 +1,200 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; +class Cbf implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $errors = $phpcsFile->getFixableCount(); + if ($errors !== 0) { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + \ob_end_clean(); + $startTime = \microtime(\true); + echo "\t=> Fixing file: {$errors}/{$errors} violations remaining"; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + } + $fixed = $phpcsFile->fixer->fixFile(); + } + if ($phpcsFile->config->stdin === \true) { + // Replacing STDIN, so output current file to STDOUT + // even if nothing was fixed. Exit here because we + // can't process any more than 1 file in this setup. + $fixedContent = $phpcsFile->fixer->getContents(); + throw new DeepExitException($fixedContent, 1); + } + if ($errors === 0) { + return \false; + } + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + if ($fixed === \false) { + echo 'ERROR'; + } else { + echo 'DONE'; + } + $timeTaken = (\microtime(\true) - $startTime) * 1000; + if ($timeTaken < 1000) { + $timeTaken = \round($timeTaken); + echo " in {$timeTaken}ms" . \PHP_EOL; + } else { + $timeTaken = \round($timeTaken / 1000, 2); + echo " in {$timeTaken} secs" . \PHP_EOL; + } + } + if ($fixed === \true) { + // The filename in the report may be truncated due to a basepath setting + // but we are using it for writing here and not display, + // so find the correct path if basepath is in use. + $newFilename = $report['filename'] . $phpcsFile->config->suffix; + if ($phpcsFile->config->basepath !== null) { + $newFilename = $phpcsFile->config->basepath . \DIRECTORY_SEPARATOR . $newFilename; + } + $newContent = $phpcsFile->fixer->getContents(); + \file_put_contents($newFilename, $newContent); + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + if ($newFilename === $report['filename']) { + echo "\t=> File was overwritten" . \PHP_EOL; + } else { + echo "\t=> Fixed file written to " . \basename($newFilename) . \PHP_EOL; + } + } + } + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + \ob_start(); + } + $errorCount = $phpcsFile->getErrorCount(); + $warningCount = $phpcsFile->getWarningCount(); + $fixableCount = $phpcsFile->getFixableCount(); + $fixedCount = $errors - $fixableCount; + echo $report['filename'] . ">>{$errorCount}>>{$warningCount}>>{$fixableCount}>>{$fixedCount}" . \PHP_EOL; + return $fixed; + } + //end generateFileReport() + /** + * Prints a summary of fixed files. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $lines = \explode(\PHP_EOL, $cachedData); + \array_pop($lines); + if (empty($lines) === \true) { + echo \PHP_EOL . 'No fixable errors were found' . \PHP_EOL; + return; + } + $reportFiles = []; + $maxLength = 0; + $totalFixed = 0; + $failures = 0; + foreach ($lines as $line) { + $parts = \explode('>>', $line); + $fileLen = \strlen($parts[0]); + $reportFiles[$parts[0]] = ['errors' => $parts[1], 'warnings' => $parts[2], 'fixable' => $parts[3], 'fixed' => $parts[4], 'strlen' => $fileLen]; + $maxLength = \max($maxLength, $fileLen); + $totalFixed += $parts[4]; + if ($parts[3] > 0) { + $failures++; + } + } + $width = \min($width, $maxLength + 21); + $width = \max($width, 70); + echo \PHP_EOL . "\x1b[1m" . 'PHPCBF RESULT SUMMARY' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'FILE' . \str_repeat(' ', $width - 20) . 'FIXED REMAINING' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + foreach ($reportFiles as $file => $data) { + $padding = $width - 18 - $data['strlen']; + if ($padding < 0) { + $file = '...' . \substr($file, $padding * -1 + 3); + $padding = 0; + } + echo $file . \str_repeat(' ', $padding) . ' '; + if ($data['fixable'] > 0) { + echo "\x1b[31mFAILED TO FIX\x1b[0m" . \PHP_EOL; + continue; + } + $remaining = $data['errors'] + $data['warnings']; + if ($data['fixed'] !== 0) { + echo $data['fixed']; + echo \str_repeat(' ', 7 - \strlen((string) $data['fixed'])); + } else { + echo '0 '; + } + if ($remaining !== 0) { + echo $remaining; + } else { + echo '0'; + } + echo \PHP_EOL; + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mA TOTAL OF {$totalFixed} ERROR"; + if ($totalFixed !== 1) { + echo 'S'; + } + $numFiles = \count($reportFiles); + echo ' WERE FIXED IN ' . $numFiles . ' FILE'; + if ($numFiles !== 1) { + echo 'S'; + } + echo "\x1b[0m"; + if ($failures > 0) { + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mPHPCBF FAILED TO FIX {$failures} FILE"; + if ($failures !== 1) { + echo 'S'; + } + echo "\x1b[0m"; + } + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL . \PHP_EOL; + if ($toScreen === \true && $interactive === \false) { + Util\Timing::printRunTime(); + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php b/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php new file mode 100644 index 00000000000..50f64dbc5a2 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Checkstyle.php @@ -0,0 +1,89 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +class Checkstyle implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $out = new \XMLWriter(); + $out->openMemory(); + $out->setIndent(\true); + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + $out->startElement('file'); + $out->writeAttribute('name', $report['filename']); + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['type'] = \strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = \iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + $out->startElement('error'); + $out->writeAttribute('line', $line); + $out->writeAttribute('column', $column); + $out->writeAttribute('severity', $error['type']); + $out->writeAttribute('message', $error['message']); + $out->writeAttribute('source', $error['source']); + $out->endElement(); + } + } + } + //end foreach + $out->endElement(); + echo $out->flush(); + return \true; + } + //end generateFileReport() + /** + * Prints all violations for processed files, in a Checkstyle format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo '' . \PHP_EOL; + echo '' . \PHP_EOL; + echo $cachedData; + echo '' . \PHP_EOL; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Code.php b/vendor/squizlabs/php_codesniffer/src/Reports/Code.php new file mode 100644 index 00000000000..ffd52009786 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Code.php @@ -0,0 +1,297 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; +class Code implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + // How many lines to show about and below the error line. + $surroundingLines = 2; + $file = $report['filename']; + $tokens = $phpcsFile->getTokens(); + if (empty($tokens) === \true) { + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + $startTime = \microtime(\true); + echo 'CODE report is parsing ' . \basename($file) . ' '; + } else { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo "CODE report is forcing parse of {$file}" . \PHP_EOL; + } + } + try { + $phpcsFile->parse(); + } catch (\Exception $e) { + // This is a second parse, so ignore exceptions. + // They would have been added to the file's error list already. + } + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + $timeTaken = (\microtime(\true) - $startTime) * 1000; + if ($timeTaken < 1000) { + $timeTaken = \round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = \round($timeTaken / 1000, 2); + echo "DONE in {$timeTaken} secs"; + } + echo \PHP_EOL; + } + $tokens = $phpcsFile->getTokens(); + } + //end if + // Create an array that maps lines to the first token on the line. + $lineTokens = []; + $lastLine = 0; + $stackPtr = 0; + foreach ($tokens as $stackPtr => $token) { + if ($token['line'] !== $lastLine) { + if ($lastLine > 0) { + $lineTokens[$lastLine]['end'] = $stackPtr - 1; + } + $lastLine++; + $lineTokens[$lastLine] = ['start' => $stackPtr, 'end' => null]; + } + } + // Make sure the last token in the file sits on an imaginary + // last line so it is easier to generate code snippets at the + // end of the file. + $lineTokens[$lastLine]['end'] = $stackPtr; + // Determine the longest code line we will be showing. + $maxSnippetLength = 0; + $eolLen = \strlen($phpcsFile->eolChar); + foreach ($report['messages'] as $line => $lineErrors) { + $startLine = \max($line - $surroundingLines, 1); + $endLine = \min($line + $surroundingLines, $lastLine); + $maxLineNumLength = \strlen($endLine); + for ($i = $startLine; $i <= $endLine; $i++) { + if ($i === 1) { + continue; + } + $lineLength = $tokens[$lineTokens[$i]['start'] - 1]['column'] + $tokens[$lineTokens[$i]['start'] - 1]['length'] - $eolLen; + $maxSnippetLength = \max($lineLength, $maxSnippetLength); + } + } + $maxSnippetLength += $maxLineNumLength + 8; + // Determine the longest error message we will be showing. + $maxErrorLength = 0; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $length = \strlen($error['message']); + if ($showSources === \true) { + $length += \strlen($error['source']) + 3; + } + $maxErrorLength = \max($maxErrorLength, $length + 1); + } + } + } + // The padding that all lines will require that are printing an error message overflow. + if ($report['warnings'] > 0) { + $typeLength = 7; + } else { + $typeLength = 5; + } + $errorPadding = \str_repeat(' ', $maxLineNumLength + 7); + $errorPadding .= \str_repeat(' ', $typeLength); + $errorPadding .= ' '; + if ($report['fixable'] > 0) { + $errorPadding .= ' '; + } + $errorPaddingLength = \strlen($errorPadding); + // The maximum amount of space an error message can use. + $maxErrorSpace = $width - $errorPaddingLength; + if ($showSources === \true) { + // Account for the chars used to print colors. + $maxErrorSpace += 8; + } + // Figure out the max report width we need and can use. + $fileLength = \strlen($file); + $maxWidth = \max($fileLength + 6, $maxErrorLength + $errorPaddingLength); + $width = \max(\min($width, $maxWidth), $maxSnippetLength); + if ($width < 70) { + $width = 70; + } + // Print the file header. + echo \PHP_EOL . "\x1b[1mFILE: "; + if ($fileLength <= $width - 6) { + echo $file; + } else { + echo '...' . \substr($file, $fileLength - ($width - 6)); + } + echo "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'FOUND ' . $report['errors'] . ' ERROR'; + if ($report['errors'] !== 1) { + echo 'S'; + } + if ($report['warnings'] > 0) { + echo ' AND ' . $report['warnings'] . ' WARNING'; + if ($report['warnings'] !== 1) { + echo 'S'; + } + } + echo ' AFFECTING ' . \count($report['messages']) . ' LINE'; + if (\count($report['messages']) !== 1) { + echo 'S'; + } + echo "\x1b[0m" . \PHP_EOL; + foreach ($report['messages'] as $line => $lineErrors) { + $startLine = \max($line - $surroundingLines, 1); + $endLine = \min($line + $surroundingLines, $lastLine); + $snippet = ''; + if (isset($lineTokens[$startLine]) === \true) { + for ($i = $lineTokens[$startLine]['start']; $i <= $lineTokens[$endLine]['end']; $i++) { + $snippetLine = $tokens[$i]['line']; + if ($lineTokens[$snippetLine]['start'] === $i) { + // Starting a new line. + if ($snippetLine === $line) { + $snippet .= "\x1b[1m" . '>> '; + } else { + $snippet .= ' '; + } + $snippet .= \str_repeat(' ', $maxLineNumLength - \strlen($snippetLine)); + $snippet .= $snippetLine . ': '; + if ($snippetLine === $line) { + $snippet .= "\x1b[0m"; + } + } + if (isset($tokens[$i]['orig_content']) === \true) { + $tokenContent = $tokens[$i]['orig_content']; + } else { + $tokenContent = $tokens[$i]['content']; + } + if (\strpos($tokenContent, "\t") !== \false) { + $token = $tokens[$i]; + $token['content'] = $tokenContent; + if (\stripos(\PHP_OS, 'WIN') === 0) { + $tab = "\x00"; + } else { + $tab = "\x1b[30;1m»\x1b[0m"; + } + $phpcsFile->tokenizer->replaceTabsInToken($token, $tab, "\x00"); + $tokenContent = $token['content']; + } + $tokenContent = Util\Common::prepareForOutput($tokenContent, ["\r", "\n", "\t"]); + $tokenContent = \str_replace("\x00", ' ', $tokenContent); + $underline = \false; + if ($snippetLine === $line && isset($lineErrors[$tokens[$i]['column']]) === \true) { + $underline = \true; + } + // Underline invisible characters as well. + if ($underline === \true && \trim($tokenContent) === '') { + $snippet .= "\x1b[4m" . ' ' . "\x1b[0m" . $tokenContent; + } else { + if ($underline === \true) { + $snippet .= "\x1b[4m"; + } + $snippet .= $tokenContent; + if ($underline === \true) { + $snippet .= "\x1b[0m"; + } + } + } + //end for + } + //end if + echo \str_repeat('-', $width) . \PHP_EOL; + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $padding = $maxLineNumLength - \strlen($line); + echo 'LINE ' . \str_repeat(' ', $padding) . $line . ': '; + if ($error['type'] === 'ERROR') { + echo "\x1b[31mERROR\x1b[0m"; + if ($report['warnings'] > 0) { + echo ' '; + } + } else { + echo "\x1b[33mWARNING\x1b[0m"; + } + echo ' '; + if ($report['fixable'] > 0) { + echo '['; + if ($error['fixable'] === \true) { + echo 'x'; + } else { + echo ' '; + } + echo '] '; + } + $message = $error['message']; + $message = \str_replace("\n", "\n" . $errorPadding, $message); + if ($showSources === \true) { + $message = "\x1b[1m" . $message . "\x1b[0m" . ' (' . $error['source'] . ')'; + } + $errorMsg = \wordwrap($message, $maxErrorSpace, \PHP_EOL . $errorPadding); + echo $errorMsg . \PHP_EOL; + } + //end foreach + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + echo \rtrim($snippet) . \PHP_EOL; + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + if ($report['fixable'] > 0) { + echo "\x1b[1m" . 'PHPCBF CAN FIX THE ' . $report['fixable'] . ' MARKED SNIFF VIOLATIONS AUTOMATICALLY' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + } + return \true; + } + //end generateFileReport() + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + if ($cachedData === '') { + return; + } + echo $cachedData; + if ($toScreen === \true && $interactive === \false) { + Util\Timing::printRunTime(); + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php b/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php new file mode 100644 index 00000000000..ac0e0e9227b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Csv.php @@ -0,0 +1,74 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +class Csv implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $filename = \str_replace('"', '\\"', $report['filename']); + $message = \str_replace('"', '\\"', $error['message']); + $type = \strtolower($error['type']); + $source = $error['source']; + $severity = $error['severity']; + $fixable = (int) $error['fixable']; + echo "\"{$filename}\",{$line},{$column},{$type},\"{$message}\",{$source},{$severity},{$fixable}" . \PHP_EOL; + } + } + } + return \true; + } + //end generateFileReport() + /** + * Generates a csv report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo 'File,Line,Column,Type,Message,Source,Severity,Fixable' . \PHP_EOL; + echo $cachedData; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php b/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php new file mode 100644 index 00000000000..115ac3272c3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Diff.php @@ -0,0 +1,107 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +class Diff implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $errors = $phpcsFile->getFixableCount(); + if ($errors === 0) { + return \false; + } + $phpcsFile->disableCaching(); + $tokens = $phpcsFile->getTokens(); + if (empty($tokens) === \true) { + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + $startTime = \microtime(\true); + echo 'DIFF report is parsing ' . \basename($report['filename']) . ' '; + } else { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo 'DIFF report is forcing parse of ' . $report['filename'] . \PHP_EOL; + } + } + $phpcsFile->parse(); + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + $timeTaken = (\microtime(\true) - $startTime) * 1000; + if ($timeTaken < 1000) { + $timeTaken = \round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = \round($timeTaken / 1000, 2); + echo "DONE in {$timeTaken} secs"; + } + echo \PHP_EOL; + } + $phpcsFile->fixer->startFile($phpcsFile); + } + //end if + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + \ob_end_clean(); + echo "\t*** START FILE FIXING ***" . \PHP_EOL; + } + $fixed = $phpcsFile->fixer->fixFile(); + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo "\t*** END FILE FIXING ***" . \PHP_EOL; + \ob_start(); + } + if ($fixed === \false) { + return \false; + } + $diff = $phpcsFile->fixer->generateDiff(); + if ($diff === '') { + // Nothing to print. + return \false; + } + echo $diff . \PHP_EOL; + return \true; + } + //end generateFileReport() + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo $cachedData; + if ($toScreen === \true && $cachedData !== '') { + echo \PHP_EOL; + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php b/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php new file mode 100644 index 00000000000..d741995a73f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Emacs.php @@ -0,0 +1,72 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +class Emacs implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $message = $error['message']; + if ($showSources === \true) { + $message .= ' (' . $error['source'] . ')'; + } + $type = \strtolower($error['type']); + echo $report['filename'] . ':' . $line . ':' . $column . ': ' . $type . ' - ' . $message . \PHP_EOL; + } + } + } + return \true; + } + //end generateFileReport() + /** + * Generates an emacs report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo $cachedData; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Full.php b/vendor/squizlabs/php_codesniffer/src/Reports/Full.php new file mode 100644 index 00000000000..1c1a853319f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Full.php @@ -0,0 +1,188 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; +class Full implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + // The length of the word ERROR or WARNING; used for padding. + if ($report['warnings'] > 0) { + $typeLength = 7; + } else { + $typeLength = 5; + } + // Work out the max line number length for formatting. + $maxLineNumLength = \max(\array_map('strlen', \array_keys($report['messages']))); + // The padding that all lines will require that are + // printing an error message overflow. + $paddingLine2 = \str_repeat(' ', $maxLineNumLength + 1); + $paddingLine2 .= ' | '; + $paddingLine2 .= \str_repeat(' ', $typeLength); + $paddingLine2 .= ' | '; + if ($report['fixable'] > 0) { + $paddingLine2 .= ' '; + } + $paddingLength = \strlen($paddingLine2); + // Make sure the report width isn't too big. + $maxErrorLength = 0; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $length = \strlen($error['message']); + if ($showSources === \true) { + $length += \strlen($error['source']) + 3; + } + $maxErrorLength = \max($maxErrorLength, $length + 1); + } + } + } + $file = $report['filename']; + $fileLength = \strlen($file); + $maxWidth = \max($fileLength + 6, $maxErrorLength + $paddingLength); + $width = \min($width, $maxWidth); + if ($width < 70) { + $width = 70; + } + echo \PHP_EOL . "\x1b[1mFILE: "; + if ($fileLength <= $width - 6) { + echo $file; + } else { + echo '...' . \substr($file, $fileLength - ($width - 6)); + } + echo "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'FOUND ' . $report['errors'] . ' ERROR'; + if ($report['errors'] !== 1) { + echo 'S'; + } + if ($report['warnings'] > 0) { + echo ' AND ' . $report['warnings'] . ' WARNING'; + if ($report['warnings'] !== 1) { + echo 'S'; + } + } + echo ' AFFECTING ' . \count($report['messages']) . ' LINE'; + if (\count($report['messages']) !== 1) { + echo 'S'; + } + echo "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + // The maximum amount of space an error message can use. + $maxErrorSpace = $width - $paddingLength - 1; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $message = $error['message']; + $msgLines = [$message]; + if (\strpos($message, "\n") !== \false) { + $msgLines = \explode("\n", $message); + } + $errorMsg = ''; + $lastLine = \count($msgLines) - 1; + foreach ($msgLines as $k => $msgLine) { + if ($k === 0) { + if ($showSources === \true) { + $errorMsg .= "\x1b[1m"; + } + } else { + $errorMsg .= \PHP_EOL . $paddingLine2; + } + if ($k === $lastLine && $showSources === \true) { + $msgLine .= "\x1b[0m" . ' (' . $error['source'] . ')'; + } + $errorMsg .= \wordwrap($msgLine, $maxErrorSpace, \PHP_EOL . $paddingLine2); + } + // The padding that goes on the front of the line. + $padding = $maxLineNumLength - \strlen($line); + echo ' ' . \str_repeat(' ', $padding) . $line . ' | '; + if ($error['type'] === 'ERROR') { + echo "\x1b[31mERROR\x1b[0m"; + if ($report['warnings'] > 0) { + echo ' '; + } + } else { + echo "\x1b[33mWARNING\x1b[0m"; + } + echo ' | '; + if ($report['fixable'] > 0) { + echo '['; + if ($error['fixable'] === \true) { + echo 'x'; + } else { + echo ' '; + } + echo '] '; + } + echo $errorMsg . \PHP_EOL; + } + //end foreach + } + //end foreach + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + if ($report['fixable'] > 0) { + echo "\x1b[1m" . 'PHPCBF CAN FIX THE ' . $report['fixable'] . ' MARKED SNIFF VIOLATIONS AUTOMATICALLY' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + } + echo \PHP_EOL; + return \true; + } + //end generateFileReport() + /** + * Prints all errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + if ($cachedData === '') { + return; + } + echo $cachedData; + if ($toScreen === \true && $interactive === \false) { + Util\Timing::printRunTime(); + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php new file mode 100644 index 00000000000..bdd93b96927 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Gitblame.php @@ -0,0 +1,72 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +class Gitblame extends \PHP_CodeSniffer\Reports\VersionControl +{ + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'GIT'; + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + $line = \preg_replace('|\\s+|', ' ', $line); + \preg_match('|\\(.+[0-9]{4}-[0-9]{2}-[0-9]{2}\\s+[0-9]+\\)|', $line, $blameParts); + if (isset($blameParts[0]) === \false) { + return \false; + } + $parts = \explode(' ', $blameParts[0]); + if (\count($parts) < 2) { + return \false; + } + $parts = \array_slice($parts, 0, \count($parts) - 2); + $author = \preg_replace('|\\(|', '', \implode(' ', $parts)); + return $author; + } + //end getAuthor() + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $cwd = \getcwd(); + \chdir(\dirname($filename)); + $command = 'git blame --date=short "' . $filename . '" 2>&1'; + $handle = \popen($command, 'r'); + if ($handle === \false) { + $error = 'ERROR: Could not execute "' . $command . '"' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $rawContent = \stream_get_contents($handle); + \pclose($handle); + $blames = \explode("\n", $rawContent); + \chdir($cwd); + return $blames; + } + //end getBlameContent() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php new file mode 100644 index 00000000000..0f2adaa22cf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Hgblame.php @@ -0,0 +1,87 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +class Hgblame extends \PHP_CodeSniffer\Reports\VersionControl +{ + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'MERCURIAL'; + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + $line = \preg_replace('|\\s+|', ' ', $line); + \preg_match('|(.+[0-9]{2}:[0-9]{2}:[0-9]{2}\\s[0-9]{4}\\s.[0-9]{4}:)|', $line, $blameParts); + if (isset($blameParts[0]) === \false) { + return \false; + } + $parts = \explode(' ', $blameParts[0]); + if (\count($parts) < 6) { + return \false; + } + $parts = \array_slice($parts, 0, \count($parts) - 6); + return \trim(\preg_replace('|<.+>|', '', \implode(' ', $parts))); + } + //end getAuthor() + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $cwd = \getcwd(); + $fileParts = \explode(\DIRECTORY_SEPARATOR, $filename); + $found = \false; + $location = ''; + while (empty($fileParts) === \false) { + \array_pop($fileParts); + $location = \implode(\DIRECTORY_SEPARATOR, $fileParts); + if (\is_dir($location . \DIRECTORY_SEPARATOR . '.hg') === \true) { + $found = \true; + break; + } + } + if ($found === \true) { + \chdir($location); + } else { + $error = 'ERROR: Could not locate .hg directory ' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $command = 'hg blame -u -d -v "' . $filename . '" 2>&1'; + $handle = \popen($command, 'r'); + if ($handle === \false) { + $error = 'ERROR: Could not execute "' . $command . '"' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $rawContent = \stream_get_contents($handle); + \pclose($handle); + $blames = \explode("\n", $rawContent); + \chdir($cwd); + return $blames; + } + //end getBlameContent() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Info.php b/vendor/squizlabs/php_codesniffer/src/Reports/Info.php new file mode 100644 index 00000000000..46399b87ea3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Info.php @@ -0,0 +1,131 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; +class Info implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $metrics = $phpcsFile->getMetrics(); + foreach ($metrics as $metric => $data) { + foreach ($data['values'] as $value => $count) { + echo "{$metric}>>{$value}>>{$count}" . \PHP_EOL; + } + } + return \true; + } + //end generateFileReport() + /** + * Prints the source of all errors and warnings. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $lines = \explode(\PHP_EOL, $cachedData); + \array_pop($lines); + if (empty($lines) === \true) { + return; + } + $metrics = []; + foreach ($lines as $line) { + $parts = \explode('>>', $line); + $metric = $parts[0]; + $value = $parts[1]; + $count = $parts[2]; + if (isset($metrics[$metric]) === \false) { + $metrics[$metric] = []; + } + if (isset($metrics[$metric][$value]) === \false) { + $metrics[$metric][$value] = $count; + } else { + $metrics[$metric][$value] += $count; + } + } + \ksort($metrics); + echo \PHP_EOL . "\x1b[1m" . 'PHP CODE SNIFFER INFORMATION REPORT' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', 70) . \PHP_EOL; + foreach ($metrics as $metric => $values) { + if (\count($values) === 1) { + $count = \reset($values); + $value = \key($values); + echo "{$metric}: \x1b[4m{$value}\x1b[0m [{$count}/{$count}, 100%]" . \PHP_EOL; + } else { + $totalCount = 0; + $valueWidth = 0; + foreach ($values as $value => $count) { + $totalCount += $count; + $valueWidth = \max($valueWidth, \strlen($value)); + } + // Length of the total string, plus however many + // thousands separators there are. + $countWidth = \strlen($totalCount); + $thousandSeparatorCount = \floor($countWidth / 3); + $countWidth += $thousandSeparatorCount; + // Account for 'total' line. + $valueWidth = \max(5, $valueWidth); + echo "{$metric}:" . \PHP_EOL; + \ksort($values, \SORT_NATURAL); + \arsort($values); + $percentPrefixWidth = 0; + $percentWidth = 6; + foreach ($values as $value => $count) { + $percent = \round($count / $totalCount * 100, 2); + $percentPrefix = ''; + if ($percent === 0.0) { + $percent = 0.01; + $percentPrefix = '<'; + $percentPrefixWidth = 2; + $percentWidth = 4; + } + \printf("\t%-{$valueWidth}s => %{$countWidth}s (%{$percentPrefixWidth}s%{$percentWidth}.2f%%)" . \PHP_EOL, $value, \number_format($count), $percentPrefix, $percent); + } + echo "\t" . \str_repeat('-', $valueWidth + $countWidth + 15) . \PHP_EOL; + \printf("\t%-{$valueWidth}s => %{$countWidth}s (100.00%%)" . \PHP_EOL, 'total', \number_format($totalCount)); + } + //end if + echo \PHP_EOL; + } + //end foreach + echo \str_repeat('-', 70) . \PHP_EOL; + if ($toScreen === \true && $interactive === \false) { + Timing::printRunTime(); + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Json.php b/vendor/squizlabs/php_codesniffer/src/Reports/Json.php new file mode 100644 index 00000000000..b0d5d83684c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Json.php @@ -0,0 +1,86 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +class Json implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $filename = \str_replace('\\', '\\\\', $report['filename']); + $filename = \str_replace('"', '\\"', $filename); + $filename = \str_replace('/', '\\/', $filename); + echo '"' . $filename . '":{'; + echo '"errors":' . $report['errors'] . ',"warnings":' . $report['warnings'] . ',"messages":['; + $messages = ''; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['message'] = \str_replace("\n", '\\n', $error['message']); + $error['message'] = \str_replace("\r", '\\r', $error['message']); + $error['message'] = \str_replace("\t", '\\t', $error['message']); + $fixable = \false; + if ($error['fixable'] === \true) { + $fixable = \true; + } + $messagesObject = (object) $error; + $messagesObject->line = $line; + $messagesObject->column = $column; + $messagesObject->fixable = $fixable; + $messages .= \json_encode($messagesObject) . ","; + } + } + } + //end foreach + echo \rtrim($messages, ','); + echo ']},'; + return \true; + } + //end generateFileReport() + /** + * Generates a JSON report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo '{"totals":{"errors":' . $totalErrors . ',"warnings":' . $totalWarnings . ',"fixable":' . $totalFixable . '},"files":{'; + echo \rtrim($cachedData, ','); + echo "}}" . \PHP_EOL; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php b/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php new file mode 100644 index 00000000000..69b98916750 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Junit.php @@ -0,0 +1,108 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +class Junit implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $out = new \XMLWriter(); + $out->openMemory(); + $out->setIndent(\true); + $out->startElement('testsuite'); + $out->writeAttribute('name', $report['filename']); + $out->writeAttribute('errors', 0); + if (\count($report['messages']) === 0) { + $out->writeAttribute('tests', 1); + $out->writeAttribute('failures', 0); + $out->startElement('testcase'); + $out->writeAttribute('name', $report['filename']); + $out->endElement(); + } else { + $failures = $report['errors'] + $report['warnings']; + $out->writeAttribute('tests', $failures); + $out->writeAttribute('failures', $failures); + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $out->startElement('testcase'); + $out->writeAttribute('name', $error['source'] . ' at ' . $report['filename'] . " ({$line}:{$column})"); + $error['type'] = \strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = \iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + $out->startElement('failure'); + $out->writeAttribute('type', $error['type']); + $out->writeAttribute('message', $error['message']); + $out->endElement(); + $out->endElement(); + } + } + } + } + //end if + $out->endElement(); + echo $out->flush(); + return \true; + } + //end generateFileReport() + /** + * Prints all violations for processed files, in a proprietary XML format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + // Figure out the total number of tests. + $tests = 0; + $matches = []; + \preg_match_all('/tests="([0-9]+)"/', $cachedData, $matches); + if (isset($matches[1]) === \true) { + foreach ($matches[1] as $match) { + $tests += $match; + } + } + $failures = $totalErrors + $totalWarnings; + echo '' . \PHP_EOL; + echo '' . \PHP_EOL; + echo $cachedData; + echo '' . \PHP_EOL; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php b/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php new file mode 100644 index 00000000000..c2259680c25 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Notifysend.php @@ -0,0 +1,198 @@ + + * @author Greg Sherwood + * @copyright 2012-2014 Christian Weiske + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Common; +class Notifysend implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Notification timeout in milliseconds. + * + * @var integer + */ + protected $timeout = 3000; + /** + * Path to notify-send command. + * + * @var string + */ + protected $path = 'notify-send'; + /** + * Show "ok, all fine" messages. + * + * @var boolean + */ + protected $showOk = \true; + /** + * Version of installed notify-send executable. + * + * @var string + */ + protected $version = null; + /** + * Load configuration data. + */ + public function __construct() + { + $path = Config::getExecutablePath('notifysend'); + if ($path !== null) { + $this->path = Common::escapeshellcmd($path); + } + $timeout = Config::getConfigData('notifysend_timeout'); + if ($timeout !== null) { + $this->timeout = (int) $timeout; + } + $showOk = Config::getConfigData('notifysend_showok'); + if ($showOk !== null) { + $this->showOk = (bool) $showOk; + } + $this->version = \str_replace('notify-send ', '', \exec($this->path . ' --version')); + } + //end __construct() + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + echo $report['filename'] . \PHP_EOL; + // We want this file counted in the total number + // of checked files even if it has no errors. + return \true; + } + //end generateFileReport() + /** + * Generates a summary of errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $checkedFiles = \explode(\PHP_EOL, \trim($cachedData)); + $msg = $this->generateMessage($checkedFiles, $totalErrors, $totalWarnings); + if ($msg === null) { + if ($this->showOk === \true) { + $this->notifyAllFine(); + } + } else { + $this->notifyErrors($msg); + } + } + //end generate() + /** + * Generate the error message to show to the user. + * + * @param string[] $checkedFiles The files checked during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * + * @return string Error message or NULL if no error/warning found. + */ + protected function generateMessage($checkedFiles, $totalErrors, $totalWarnings) + { + if ($totalErrors === 0 && $totalWarnings === 0) { + // Nothing to print. + return null; + } + $totalFiles = \count($checkedFiles); + $msg = ''; + if ($totalFiles > 1) { + $msg .= 'Checked ' . $totalFiles . ' files' . \PHP_EOL; + } else { + $msg .= $checkedFiles[0] . \PHP_EOL; + } + if ($totalWarnings > 0) { + $msg .= $totalWarnings . ' warnings' . \PHP_EOL; + } + if ($totalErrors > 0) { + $msg .= $totalErrors . ' errors' . \PHP_EOL; + } + return $msg; + } + //end generateMessage() + /** + * Tell the user that all is fine and no error/warning has been found. + * + * @return void + */ + protected function notifyAllFine() + { + $cmd = $this->getBasicCommand(); + $cmd .= ' -i info'; + $cmd .= ' "PHP CodeSniffer: Ok"'; + $cmd .= ' "All fine"'; + \exec($cmd); + } + //end notifyAllFine() + /** + * Tell the user that errors/warnings have been found. + * + * @param string $msg Message to display. + * + * @return void + */ + protected function notifyErrors($msg) + { + $cmd = $this->getBasicCommand(); + $cmd .= ' -i error'; + $cmd .= ' "PHP CodeSniffer: Error"'; + $cmd .= ' ' . \escapeshellarg(\trim($msg)); + \exec($cmd); + } + //end notifyErrors() + /** + * Generate and return the basic notify-send command string to execute. + * + * @return string Shell command with common parameters. + */ + protected function getBasicCommand() + { + $cmd = $this->path; + $cmd .= ' --category dev.validate'; + $cmd .= ' -h int:transient:1'; + $cmd .= ' -t ' . (int) $this->timeout; + if (\version_compare($this->version, '0.7.3', '>=') === \true) { + $cmd .= ' -a phpcs'; + } + return $cmd; + } + //end getBasicCommand() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Report.php b/vendor/squizlabs/php_codesniffer/src/Reports/Report.php new file mode 100644 index 00000000000..fcb00260912 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Report.php @@ -0,0 +1,48 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +interface Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80); + /** + * Generate the actual report. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true); +} +//end interface diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Source.php b/vendor/squizlabs/php_codesniffer/src/Reports/Source.php new file mode 100644 index 00000000000..085a6753871 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Source.php @@ -0,0 +1,272 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; +class Source implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + $sources = []; + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $src = $error['source']; + if (isset($sources[$src]) === \false) { + $sources[$src] = ['fixable' => (int) $error['fixable'], 'count' => 1]; + } else { + $sources[$src]['count']++; + } + } + } + } + foreach ($sources as $source => $data) { + echo $source . '>>' . $data['fixable'] . '>>' . $data['count'] . \PHP_EOL; + } + return \true; + } + //end generateFileReport() + /** + * Prints the source of all errors and warnings. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $lines = \explode(\PHP_EOL, $cachedData); + \array_pop($lines); + if (empty($lines) === \true) { + return; + } + $sources = []; + $maxLength = 0; + foreach ($lines as $line) { + $parts = \explode('>>', $line); + $source = $parts[0]; + $fixable = (bool) $parts[1]; + $count = $parts[2]; + if (isset($sources[$source]) === \false) { + if ($showSources === \true) { + $parts = null; + $sniff = $source; + } else { + $parts = \explode('.', $source); + if ($parts[0] === 'Internal') { + $parts[2] = $parts[1]; + $parts[1] = ''; + } + $parts[1] = $this->makeFriendlyName($parts[1]); + $sniff = $this->makeFriendlyName($parts[2]); + if (isset($parts[3]) === \true) { + $name = $this->makeFriendlyName($parts[3]); + $name[0] = \strtolower($name[0]); + $sniff .= ' ' . $name; + unset($parts[3]); + } + $parts[2] = $sniff; + } + //end if + $maxLength = \max($maxLength, \strlen($sniff)); + $sources[$source] = ['count' => $count, 'fixable' => $fixable, 'parts' => $parts]; + } else { + $sources[$source]['count'] += $count; + } + //end if + } + //end foreach + if ($showSources === \true) { + $width = \min($width, $maxLength + 11); + } else { + $width = \min($width, $maxLength + 41); + } + $width = \max($width, 70); + // Sort the data based on counts and source code. + $sourceCodes = \array_keys($sources); + $counts = []; + foreach ($sources as $source => $data) { + $counts[$source] = $data['count']; + } + \array_multisort($counts, \SORT_DESC, $sourceCodes, \SORT_ASC, \SORT_NATURAL, $sources); + echo \PHP_EOL . "\x1b[1mPHP CODE SNIFFER VIOLATION SOURCE SUMMARY\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL . "\x1b[1m"; + if ($showSources === \true) { + if ($totalFixable > 0) { + echo ' SOURCE' . \str_repeat(' ', $width - 15) . 'COUNT' . \PHP_EOL; + } else { + echo 'SOURCE' . \str_repeat(' ', $width - 11) . 'COUNT' . \PHP_EOL; + } + } else { + if ($totalFixable > 0) { + echo ' STANDARD CATEGORY SNIFF' . \str_repeat(' ', $width - 44) . 'COUNT' . \PHP_EOL; + } else { + echo 'STANDARD CATEGORY SNIFF' . \str_repeat(' ', $width - 40) . 'COUNT' . \PHP_EOL; + } + } + echo "\x1b[0m" . \str_repeat('-', $width) . \PHP_EOL; + $fixableSources = 0; + if ($showSources === \true) { + $maxSniffWidth = $width - 7; + } else { + $maxSniffWidth = $width - 37; + } + if ($totalFixable > 0) { + $maxSniffWidth -= 4; + } + foreach ($sources as $source => $sourceData) { + if ($totalFixable > 0) { + echo '['; + if ($sourceData['fixable'] === \true) { + echo 'x'; + $fixableSources++; + } else { + echo ' '; + } + echo '] '; + } + if ($showSources === \true) { + if (\strlen($source) > $maxSniffWidth) { + $source = \substr($source, 0, $maxSniffWidth); + } + echo $source; + if ($totalFixable > 0) { + echo \str_repeat(' ', $width - 9 - \strlen($source)); + } else { + echo \str_repeat(' ', $width - 5 - \strlen($source)); + } + } else { + $parts = $sourceData['parts']; + if (\strlen($parts[0]) > 8) { + $parts[0] = \substr($parts[0], 0, (\strlen($parts[0]) - 8) * -1); + } + echo $parts[0] . \str_repeat(' ', 10 - \strlen($parts[0])); + $category = $parts[1]; + if (\strlen($category) > 18) { + $category = \substr($category, 0, (\strlen($category) - 18) * -1); + } + echo $category . \str_repeat(' ', 20 - \strlen($category)); + $sniff = $parts[2]; + if (\strlen($sniff) > $maxSniffWidth) { + $sniff = \substr($sniff, 0, $maxSniffWidth); + } + if ($totalFixable > 0) { + echo $sniff . \str_repeat(' ', $width - 39 - \strlen($sniff)); + } else { + echo $sniff . \str_repeat(' ', $width - 35 - \strlen($sniff)); + } + } + //end if + echo $sourceData['count'] . \PHP_EOL; + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'A TOTAL OF ' . ($totalErrors + $totalWarnings) . ' SNIFF VIOLATION'; + if ($totalErrors + $totalWarnings > 1) { + echo 'S'; + } + echo ' WERE FOUND IN ' . \count($sources) . ' SOURCE'; + if (\count($sources) !== 1) { + echo 'S'; + } + echo "\x1b[0m"; + if ($totalFixable > 0) { + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mPHPCBF CAN FIX THE {$fixableSources} MARKED SOURCES AUTOMATICALLY ({$totalFixable} VIOLATIONS IN TOTAL)\x1b[0m"; + } + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL . \PHP_EOL; + if ($toScreen === \true && $interactive === \false) { + Timing::printRunTime(); + } + } + //end generate() + /** + * Converts a camel caps name into a readable string. + * + * @param string $name The camel caps name to convert. + * + * @return string + */ + public function makeFriendlyName($name) + { + if (\trim($name) === '') { + return ''; + } + $friendlyName = ''; + $length = \strlen($name); + $lastWasUpper = \false; + $lastWasNumeric = \false; + for ($i = 0; $i < $length; $i++) { + if (\is_numeric($name[$i]) === \true) { + if ($lastWasNumeric === \false) { + $friendlyName .= ' '; + } + $lastWasUpper = \false; + $lastWasNumeric = \true; + } else { + $lastWasNumeric = \false; + $char = \strtolower($name[$i]); + if ($char === $name[$i]) { + // Lowercase. + $lastWasUpper = \false; + } else { + // Uppercase. + if ($lastWasUpper === \false) { + $friendlyName .= ' '; + if ($i < $length - 1) { + $next = $name[$i + 1]; + if (\strtolower($next) === $next) { + // Next char is lowercase so it is a word boundary. + $name[$i] = \strtolower($name[$i]); + } + } + } + $lastWasUpper = \true; + } + } + //end if + $friendlyName .= $name[$i]; + } + //end for + $friendlyName = \trim($friendlyName); + $friendlyName[0] = \strtoupper($friendlyName[0]); + return $friendlyName; + } + //end makeFriendlyName() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php b/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php new file mode 100644 index 00000000000..9398863b186 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Summary.php @@ -0,0 +1,140 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util; +class Summary implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + if (\PHP_CODESNIFFER_VERBOSITY === 0 && $report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + echo $report['filename'] . '>>' . $report['errors'] . '>>' . $report['warnings'] . \PHP_EOL; + return \true; + } + //end generateFileReport() + /** + * Generates a summary of errors and warnings for each file processed. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $lines = \explode(\PHP_EOL, $cachedData); + \array_pop($lines); + if (empty($lines) === \true) { + return; + } + $reportFiles = []; + $maxLength = 0; + foreach ($lines as $line) { + $parts = \explode('>>', $line); + $fileLen = \strlen($parts[0]); + $reportFiles[$parts[0]] = ['errors' => $parts[1], 'warnings' => $parts[2], 'strlen' => $fileLen]; + $maxLength = \max($maxLength, $fileLen); + } + \uksort($reportFiles, function ($keyA, $keyB) { + $pathPartsA = \explode(\DIRECTORY_SEPARATOR, $keyA); + $pathPartsB = \explode(\DIRECTORY_SEPARATOR, $keyB); + do { + $partA = \array_shift($pathPartsA); + $partB = \array_shift($pathPartsB); + } while ($partA === $partB && empty($pathPartsA) === \false && empty($pathPartsB) === \false); + if (empty($pathPartsA) === \false && empty($pathPartsB) === \true) { + return 1; + } else { + if (empty($pathPartsA) === \true && empty($pathPartsB) === \false) { + return -1; + } else { + return \strcasecmp($partA, $partB); + } + } + }); + $width = \min($width, $maxLength + 21); + $width = \max($width, 70); + echo \PHP_EOL . "\x1b[1m" . 'PHP CODE SNIFFER REPORT SUMMARY' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'FILE' . \str_repeat(' ', $width - 20) . 'ERRORS WARNINGS' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + foreach ($reportFiles as $file => $data) { + $padding = $width - 18 - $data['strlen']; + if ($padding < 0) { + $file = '...' . \substr($file, $padding * -1 + 3); + $padding = 0; + } + echo $file . \str_repeat(' ', $padding) . ' '; + if ($data['errors'] !== 0) { + echo "\x1b[31m" . $data['errors'] . "\x1b[0m"; + echo \str_repeat(' ', 8 - \strlen((string) $data['errors'])); + } else { + echo '0 '; + } + if ($data['warnings'] !== 0) { + echo "\x1b[33m" . $data['warnings'] . "\x1b[0m"; + } else { + echo '0'; + } + echo \PHP_EOL; + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mA TOTAL OF {$totalErrors} ERROR"; + if ($totalErrors !== 1) { + echo 'S'; + } + echo ' AND ' . $totalWarnings . ' WARNING'; + if ($totalWarnings !== 1) { + echo 'S'; + } + echo ' WERE FOUND IN ' . $totalFiles . ' FILE'; + if ($totalFiles !== 1) { + echo 'S'; + } + echo "\x1b[0m"; + if ($totalFixable > 0) { + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mPHPCBF CAN FIX {$totalFixable} OF THESE SNIFF VIOLATIONS AUTOMATICALLY\x1b[0m"; + } + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL . \PHP_EOL; + if ($toScreen === \true && $interactive === \false) { + Util\Timing::printRunTime(); + } + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php b/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php new file mode 100644 index 00000000000..7dfcde1db06 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Svnblame.php @@ -0,0 +1,61 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +class Svnblame extends \PHP_CodeSniffer\Reports\VersionControl +{ + /** + * The name of the report we want in the output + * + * @var string + */ + protected $reportName = 'SVN'; + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected function getAuthor($line) + { + $blameParts = []; + \preg_match('|\\s*([^\\s]+)\\s+([^\\s]+)|', $line, $blameParts); + if (isset($blameParts[2]) === \false) { + return \false; + } + return $blameParts[2]; + } + //end getAuthor() + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + protected function getBlameContent($filename) + { + $command = 'svn blame "' . $filename . '" 2>&1'; + $handle = \popen($command, 'r'); + if ($handle === \false) { + $error = 'ERROR: Could not execute "' . $command . '"' . \PHP_EOL . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $rawContent = \stream_get_contents($handle); + \pclose($handle); + $blames = \explode("\n", $rawContent); + return $blames; + } + //end getBlameContent() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php b/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php new file mode 100644 index 00000000000..d97147fca3a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/VersionControl.php @@ -0,0 +1,301 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Timing; +abstract class VersionControl implements \PHP_CodeSniffer\Reports\Report +{ + /** + * The name of the report we want in the output. + * + * @var string + */ + protected $reportName = 'VERSION CONTROL'; + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $blames = $this->getBlameContent($report['filename']); + $authorCache = []; + $praiseCache = []; + $sourceCache = []; + foreach ($report['messages'] as $line => $lineErrors) { + $author = 'Unknown'; + if (isset($blames[$line - 1]) === \true) { + $blameAuthor = $this->getAuthor($blames[$line - 1]); + if ($blameAuthor !== \false) { + $author = $blameAuthor; + } + } + if (isset($authorCache[$author]) === \false) { + $authorCache[$author] = 0; + $praiseCache[$author] = ['good' => 0, 'bad' => 0]; + } + $praiseCache[$author]['bad']++; + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $authorCache[$author]++; + if ($showSources === \true) { + $source = $error['source']; + if (isset($sourceCache[$author][$source]) === \false) { + $sourceCache[$author][$source] = ['count' => 1, 'fixable' => $error['fixable']]; + } else { + $sourceCache[$author][$source]['count']++; + } + } + } + } + unset($blames[$line - 1]); + } + //end foreach + // Now go through and give the authors some credit for + // all the lines that do not have errors. + foreach ($blames as $line) { + $author = $this->getAuthor($line); + if ($author === \false) { + $author = 'Unknown'; + } + if (isset($authorCache[$author]) === \false) { + // This author doesn't have any errors. + if (\PHP_CODESNIFFER_VERBOSITY === 0) { + continue; + } + $authorCache[$author] = 0; + $praiseCache[$author] = ['good' => 0, 'bad' => 0]; + } + $praiseCache[$author]['good']++; + } + //end foreach + foreach ($authorCache as $author => $errors) { + echo "AUTHOR>>{$author}>>{$errors}" . \PHP_EOL; + } + foreach ($praiseCache as $author => $praise) { + echo "PRAISE>>{$author}>>" . $praise['good'] . '>>' . $praise['bad'] . \PHP_EOL; + } + foreach ($sourceCache as $author => $sources) { + foreach ($sources as $source => $sourceData) { + $count = $sourceData['count']; + $fixable = (int) $sourceData['fixable']; + echo "SOURCE>>{$author}>>{$source}>>{$count}>>{$fixable}" . \PHP_EOL; + } + } + return \true; + } + //end generateFileReport() + /** + * Prints the author of all errors and warnings, as given by "version control blame". + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + $errorsShown = $totalErrors + $totalWarnings; + if ($errorsShown === 0) { + // Nothing to show. + return; + } + $lines = \explode(\PHP_EOL, $cachedData); + \array_pop($lines); + if (empty($lines) === \true) { + return; + } + $authorCache = []; + $praiseCache = []; + $sourceCache = []; + foreach ($lines as $line) { + $parts = \explode('>>', $line); + switch ($parts[0]) { + case 'AUTHOR': + if (isset($authorCache[$parts[1]]) === \false) { + $authorCache[$parts[1]] = $parts[2]; + } else { + $authorCache[$parts[1]] += $parts[2]; + } + break; + case 'PRAISE': + if (isset($praiseCache[$parts[1]]) === \false) { + $praiseCache[$parts[1]] = ['good' => $parts[2], 'bad' => $parts[3]]; + } else { + $praiseCache[$parts[1]]['good'] += $parts[2]; + $praiseCache[$parts[1]]['bad'] += $parts[3]; + } + break; + case 'SOURCE': + if (isset($praiseCache[$parts[1]]) === \false) { + $praiseCache[$parts[1]] = []; + } + if (isset($sourceCache[$parts[1]][$parts[2]]) === \false) { + $sourceCache[$parts[1]][$parts[2]] = ['count' => $parts[3], 'fixable' => (bool) $parts[4]]; + } else { + $sourceCache[$parts[1]][$parts[2]]['count'] += $parts[3]; + } + break; + default: + break; + } + //end switch + } + //end foreach + // Make sure the report width isn't too big. + $maxLength = 0; + foreach ($authorCache as $author => $count) { + $maxLength = \max($maxLength, \strlen($author)); + if ($showSources === \true && isset($sourceCache[$author]) === \true) { + foreach ($sourceCache[$author] as $source => $sourceData) { + if ($source === 'count') { + continue; + } + $maxLength = \max($maxLength, \strlen($source) + 9); + } + } + } + $width = \min($width, $maxLength + 30); + $width = \max($width, 70); + \arsort($authorCache); + echo \PHP_EOL . "\x1b[1m" . 'PHP CODE SNIFFER ' . $this->reportName . ' BLAME SUMMARY' . "\x1b[0m" . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL . "\x1b[1m"; + if ($showSources === \true) { + echo 'AUTHOR SOURCE' . \str_repeat(' ', $width - 43) . '(Author %) (Overall %) COUNT' . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + } else { + echo 'AUTHOR' . \str_repeat(' ', $width - 34) . '(Author %) (Overall %) COUNT' . \PHP_EOL; + echo \str_repeat('-', $width) . \PHP_EOL; + } + echo "\x1b[0m"; + if ($showSources === \true) { + $maxSniffWidth = $width - 15; + if ($totalFixable > 0) { + $maxSniffWidth -= 4; + } + } + $fixableSources = 0; + foreach ($authorCache as $author => $count) { + if ($praiseCache[$author]['good'] === 0) { + $percent = 0; + } else { + $total = $praiseCache[$author]['bad'] + $praiseCache[$author]['good']; + $percent = \round($praiseCache[$author]['bad'] / $total * 100, 2); + } + $overallPercent = '(' . \round($count / $errorsShown * 100, 2) . ')'; + $authorPercent = '(' . $percent . ')'; + $line = \str_repeat(' ', 6 - \strlen($count)) . $count; + $line = \str_repeat(' ', 12 - \strlen($overallPercent)) . $overallPercent . $line; + $line = \str_repeat(' ', 11 - \strlen($authorPercent)) . $authorPercent . $line; + $line = $author . \str_repeat(' ', $width - \strlen($author) - \strlen($line)) . $line; + if ($showSources === \true) { + $line = "\x1b[1m{$line}\x1b[0m"; + } + echo $line . \PHP_EOL; + if ($showSources === \true && isset($sourceCache[$author]) === \true) { + $errors = $sourceCache[$author]; + \asort($errors); + $errors = \array_reverse($errors); + foreach ($errors as $source => $sourceData) { + if ($source === 'count') { + continue; + } + $count = $sourceData['count']; + $srcLength = \strlen($source); + if ($srcLength > $maxSniffWidth) { + $source = \substr($source, 0, $maxSniffWidth); + } + $line = \str_repeat(' ', 5 - \strlen($count)) . $count; + echo ' '; + if ($totalFixable > 0) { + echo '['; + if ($sourceData['fixable'] === \true) { + echo 'x'; + $fixableSources++; + } else { + echo ' '; + } + echo '] '; + } + echo $source; + if ($totalFixable > 0) { + echo \str_repeat(' ', $width - 18 - \strlen($source)); + } else { + echo \str_repeat(' ', $width - 14 - \strlen($source)); + } + echo $line . \PHP_EOL; + } + //end foreach + } + //end if + } + //end foreach + echo \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1m" . 'A TOTAL OF ' . $errorsShown . ' SNIFF VIOLATION'; + if ($errorsShown !== 1) { + echo 'S'; + } + echo ' WERE COMMITTED BY ' . \count($authorCache) . ' AUTHOR'; + if (\count($authorCache) !== 1) { + echo 'S'; + } + echo "\x1b[0m"; + if ($totalFixable > 0) { + if ($showSources === \true) { + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mPHPCBF CAN FIX THE {$fixableSources} MARKED SOURCES AUTOMATICALLY ({$totalFixable} VIOLATIONS IN TOTAL)\x1b[0m"; + } else { + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL; + echo "\x1b[1mPHPCBF CAN FIX {$totalFixable} OF THESE SNIFF VIOLATIONS AUTOMATICALLY\x1b[0m"; + } + } + echo \PHP_EOL . \str_repeat('-', $width) . \PHP_EOL . \PHP_EOL; + if ($toScreen === \true && $interactive === \false) { + Timing::printRunTime(); + } + } + //end generate() + /** + * Extract the author from a blame line. + * + * @param string $line Line to parse. + * + * @return mixed string or false if impossible to recover. + */ + protected abstract function getAuthor($line); + /** + * Gets the blame output. + * + * @param string $filename File to blame. + * + * @return array + */ + protected abstract function getBlameContent($filename); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php b/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php new file mode 100644 index 00000000000..6c240903bdc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Reports/Xml.php @@ -0,0 +1,106 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Reports; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +class Xml implements \PHP_CodeSniffer\Reports\Report +{ + /** + * Generate a partial report for a single processed file. + * + * Function should return TRUE if it printed or stored data about the file + * and FALSE if it ignored the file. Returning TRUE indicates that the file and + * its data should be counted in the grand totals. + * + * @param array $report Prepared report data. + * @param \PHP_CodeSniffer\File $phpcsFile The file being reported on. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * + * @return bool + */ + public function generateFileReport($report, File $phpcsFile, $showSources = \false, $width = 80) + { + $out = new \XMLWriter(); + $out->openMemory(); + $out->setIndent(\true); + $out->setIndentString(' '); + $out->startDocument('1.0', 'UTF-8'); + if ($report['errors'] === 0 && $report['warnings'] === 0) { + // Nothing to print. + return \false; + } + $out->startElement('file'); + $out->writeAttribute('name', $report['filename']); + $out->writeAttribute('errors', $report['errors']); + $out->writeAttribute('warnings', $report['warnings']); + $out->writeAttribute('fixable', $report['fixable']); + foreach ($report['messages'] as $line => $lineErrors) { + foreach ($lineErrors as $column => $colErrors) { + foreach ($colErrors as $error) { + $error['type'] = \strtolower($error['type']); + if ($phpcsFile->config->encoding !== 'utf-8') { + $error['message'] = \iconv($phpcsFile->config->encoding, 'utf-8', $error['message']); + } + $out->startElement($error['type']); + $out->writeAttribute('line', $line); + $out->writeAttribute('column', $column); + $out->writeAttribute('source', $error['source']); + $out->writeAttribute('severity', $error['severity']); + $out->writeAttribute('fixable', (int) $error['fixable']); + $out->text($error['message']); + $out->endElement(); + } + } + } + //end foreach + $out->endElement(); + // Remove the start of the document because we will + // add that manually later. We only have it in here to + // properly set the encoding. + $content = $out->flush(); + if (\strpos($content, \PHP_EOL) !== \false) { + $content = \substr($content, \strpos($content, \PHP_EOL) + \strlen(\PHP_EOL)); + } else { + if (\strpos($content, "\n") !== \false) { + $content = \substr($content, \strpos($content, "\n") + 1); + } + } + echo $content; + return \true; + } + //end generateFileReport() + /** + * Prints all violations for processed files, in a proprietary XML format. + * + * @param string $cachedData Any partial report data that was returned from + * generateFileReport during the run. + * @param int $totalFiles Total number of files processed during the run. + * @param int $totalErrors Total number of errors found during the run. + * @param int $totalWarnings Total number of warnings found during the run. + * @param int $totalFixable Total number of problems that can be fixed. + * @param bool $showSources Show sources? + * @param int $width Maximum allowed line width. + * @param bool $interactive Are we running in interactive mode? + * @param bool $toScreen Is the report being printed to screen? + * + * @return void + */ + public function generate($cachedData, $totalFiles, $totalErrors, $totalWarnings, $totalFixable, $showSources = \false, $width = 80, $interactive = \false, $toScreen = \true) + { + echo '' . \PHP_EOL; + echo '' . \PHP_EOL; + echo $cachedData; + echo '' . \PHP_EOL; + } + //end generate() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Ruleset.php b/vendor/squizlabs/php_codesniffer/src/Ruleset.php new file mode 100644 index 00000000000..a78f4ddbd61 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Ruleset.php @@ -0,0 +1,1170 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Util; +class Ruleset +{ + /** + * The name of the coding standard being used. + * + * If a top-level standard includes other standards, or sniffs + * from other standards, only the name of the top-level standard + * will be stored in here. + * + * If multiple top-level standards are being loaded into + * a single ruleset object, this will store a comma separated list + * of the top-level standard names. + * + * @var string + */ + public $name = ''; + /** + * A list of file paths for the ruleset files being used. + * + * @var string[] + */ + public $paths = []; + /** + * A list of regular expressions used to ignore specific sniffs for files and folders. + * + * Is also used to set global exclude patterns. + * The key is the regular expression and the value is the type + * of ignore pattern (absolute or relative). + * + * @var array + */ + public $ignorePatterns = []; + /** + * A list of regular expressions used to include specific sniffs for files and folders. + * + * The key is the sniff code and the value is an array with + * the key being a regular expression and the value is the type + * of ignore pattern (absolute or relative). + * + * @var array> + */ + public $includePatterns = []; + /** + * An array of sniff objects that are being used to check files. + * + * The key is the fully qualified name of the sniff class + * and the value is the sniff object. + * + * @var array + */ + public $sniffs = []; + /** + * A mapping of sniff codes to fully qualified class names. + * + * The key is the sniff code and the value + * is the fully qualified name of the sniff class. + * + * @var array + */ + public $sniffCodes = []; + /** + * An array of token types and the sniffs that are listening for them. + * + * The key is the token name being listened for and the value + * is the sniff object. + * + * @var array + */ + public $tokenListeners = []; + /** + * An array of rules from the ruleset.xml file. + * + * It may be empty, indicating that the ruleset does not override + * any of the default sniff settings. + * + * @var array + */ + public $ruleset = []; + /** + * The directories that the processed rulesets are in. + * + * @var string[] + */ + protected $rulesetDirs = []; + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + private $config = null; + /** + * Initialise the ruleset that the run will use. + * + * @param \PHP_CodeSniffer\Config $config The config data for the run. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If no sniffs were registered. + */ + public function __construct(\PHP_CodeSniffer\Config $config) + { + $this->config = $config; + $restrictions = $config->sniffs; + $exclusions = $config->exclude; + $sniffs = []; + $standardPaths = []; + foreach ($config->standards as $standard) { + $installed = Util\Standards::getInstalledStandardPath($standard); + if ($installed === null) { + $standard = Util\Common::realpath($standard); + if (\is_dir($standard) === \true && \is_file(Util\Common::realpath($standard . \DIRECTORY_SEPARATOR . 'ruleset.xml')) === \true) { + $standard = Util\Common::realpath($standard . \DIRECTORY_SEPARATOR . 'ruleset.xml'); + } + } else { + $standard = $installed; + } + $standardPaths[] = $standard; + } + foreach ($standardPaths as $standard) { + $ruleset = @\simplexml_load_string(\file_get_contents($standard)); + if ($ruleset !== \false) { + $standardName = (string) $ruleset['name']; + if ($this->name !== '') { + $this->name .= ', '; + } + $this->name .= $standardName; + // Allow autoloading of custom files inside this standard. + if (isset($ruleset['namespace']) === \true) { + $namespace = (string) $ruleset['namespace']; + } else { + $namespace = \basename(\dirname($standard)); + } + \PHP_CodeSniffer\Autoload::addSearchPath(\dirname($standard), $namespace); + } + if (\defined('ECSPrefix202307\\PHP_CODESNIFFER_IN_TESTS') === \true && empty($restrictions) === \false) { + // In unit tests, only register the sniffs that the test wants and not the entire standard. + try { + foreach ($restrictions as $restriction) { + $sniffs = \array_merge($sniffs, $this->expandRulesetReference($restriction, \dirname($standard))); + } + } catch (RuntimeException $e) { + // Sniff reference could not be expanded, which probably means this + // is an installed standard. Let the unit test system take care of + // setting the correct sniff for testing. + return; + } + break; + } + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + echo "Registering sniffs in the {$standardName} standard... "; + if (\count($config->standards) > 1 || \PHP_CODESNIFFER_VERBOSITY > 2) { + echo \PHP_EOL; + } + } + $sniffs = \array_merge($sniffs, $this->processRuleset($standard)); + } + //end foreach + // Ignore sniff restrictions if caching is on. + if ($config->cache === \true) { + $restrictions = []; + $exclusions = []; + } + $sniffRestrictions = []; + foreach ($restrictions as $sniffCode) { + $parts = \explode('.', \strtolower($sniffCode)); + $sniffName = $parts[0] . '\\sniffs\\' . $parts[1] . '\\' . $parts[2] . 'sniff'; + $sniffRestrictions[$sniffName] = \true; + } + $sniffExclusions = []; + foreach ($exclusions as $sniffCode) { + $parts = \explode('.', \strtolower($sniffCode)); + $sniffName = $parts[0] . '\\sniffs\\' . $parts[1] . '\\' . $parts[2] . 'sniff'; + $sniffExclusions[$sniffName] = \true; + } + $this->registerSniffs($sniffs, $sniffRestrictions, $sniffExclusions); + $this->populateTokenListeners(); + $numSniffs = \count($this->sniffs); + if (\PHP_CODESNIFFER_VERBOSITY === 1) { + echo "DONE ({$numSniffs} sniffs registered)" . \PHP_EOL; + } + if ($numSniffs === 0) { + throw new RuntimeException('No sniffs were registered'); + } + } + //end __construct() + /** + * Prints a report showing the sniffs contained in a standard. + * + * @return void + */ + public function explain() + { + $sniffs = \array_keys($this->sniffCodes); + \sort($sniffs); + \ob_start(); + $lastStandard = null; + $lastCount = ''; + $sniffCount = \count($sniffs); + // Add a dummy entry to the end so we loop + // one last time and clear the output buffer. + $sniffs[] = ''; + $summaryLine = \PHP_EOL . "The {$this->name} standard contains 1 sniff" . \PHP_EOL; + if ($sniffCount !== 1) { + $summaryLine = \str_replace('1 sniff', "{$sniffCount} sniffs", $summaryLine); + } + echo $summaryLine; + \ob_start(); + foreach ($sniffs as $i => $sniff) { + if ($i === $sniffCount) { + $currentStandard = null; + } else { + $currentStandard = \substr($sniff, 0, \strpos($sniff, '.')); + if ($lastStandard === null) { + $lastStandard = $currentStandard; + } + } + if ($currentStandard !== $lastStandard) { + $sniffList = \ob_get_contents(); + \ob_end_clean(); + echo \PHP_EOL . $lastStandard . ' (' . $lastCount . ' sniff'; + if ($lastCount > 1) { + echo 's'; + } + echo ')' . \PHP_EOL; + echo \str_repeat('-', \strlen($lastStandard . $lastCount) + 10); + echo \PHP_EOL; + echo $sniffList; + $lastStandard = $currentStandard; + $lastCount = 0; + if ($currentStandard === null) { + break; + } + \ob_start(); + } + //end if + echo ' ' . $sniff . \PHP_EOL; + $lastCount++; + } + //end foreach + } + //end explain() + /** + * Processes a single ruleset and returns a list of the sniffs it represents. + * + * Rules founds within the ruleset are processed immediately, but sniff classes + * are not registered by this method. + * + * @param string $rulesetPath The path to a ruleset XML file. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return string[] + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException - If the ruleset path is invalid. + * - If a specified autoload file could not be found. + */ + public function processRuleset($rulesetPath, $depth = 0) + { + $rulesetPath = Util\Common::realpath($rulesetPath); + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo 'Processing ruleset ' . Util\Common::stripBasepath($rulesetPath, $this->config->basepath) . \PHP_EOL; + } + \libxml_use_internal_errors(\true); + $ruleset = \simplexml_load_string(\file_get_contents($rulesetPath)); + if ($ruleset === \false) { + $errorMsg = "Ruleset {$rulesetPath} is not valid" . \PHP_EOL; + $errors = \libxml_get_errors(); + foreach ($errors as $error) { + $errorMsg .= '- On line ' . $error->line . ', column ' . $error->column . ': ' . $error->message; + } + \libxml_clear_errors(); + throw new RuntimeException($errorMsg); + } + \libxml_use_internal_errors(\false); + $ownSniffs = []; + $includedSniffs = []; + $excludedSniffs = []; + $this->paths[] = $rulesetPath; + $rulesetDir = \dirname($rulesetPath); + $this->rulesetDirs[] = $rulesetDir; + $sniffDir = $rulesetDir . \DIRECTORY_SEPARATOR . 'Sniffs'; + if (\is_dir($sniffDir) === \true) { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\tAdding sniff files from " . Util\Common::stripBasepath($sniffDir, $this->config->basepath) . ' directory' . \PHP_EOL; + } + $ownSniffs = $this->expandSniffDirectory($sniffDir, $depth); + } + // Include custom autoloaders. + foreach ($ruleset->{'autoload'} as $autoload) { + if ($this->shouldProcessElement($autoload) === \false) { + continue; + } + $autoloadPath = (string) $autoload; + // Try relative autoload paths first. + $relativePath = Util\Common::realPath(\dirname($rulesetPath) . \DIRECTORY_SEPARATOR . $autoloadPath); + if ($relativePath !== \false && \is_file($relativePath) === \true) { + $autoloadPath = $relativePath; + } else { + if (\is_file($autoloadPath) === \false) { + throw new RuntimeException('The specified autoload file "' . $autoload . '" does not exist'); + } + } + include_once $autoloadPath; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> included autoloader {$autoloadPath}" . \PHP_EOL; + } + } + //end foreach + // Process custom sniff config settings. + foreach ($ruleset->{'config'} as $config) { + if ($this->shouldProcessElement($config) === \false) { + continue; + } + \PHP_CodeSniffer\Config::setConfigData((string) $config['name'], (string) $config['value'], \true); + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> set config value " . (string) $config['name'] . ': ' . (string) $config['value'] . \PHP_EOL; + } + } + foreach ($ruleset->rule as $rule) { + if (isset($rule['ref']) === \false || $this->shouldProcessElement($rule) === \false) { + continue; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\tProcessing rule \"" . $rule['ref'] . '"' . \PHP_EOL; + } + $expandedSniffs = $this->expandRulesetReference((string) $rule['ref'], $rulesetDir, $depth); + $newSniffs = \array_diff($expandedSniffs, $includedSniffs); + $includedSniffs = \array_merge($includedSniffs, $expandedSniffs); + $parts = \explode('.', $rule['ref']); + if (\count($parts) === 4 && $parts[0] !== '' && $parts[1] !== '' && $parts[2] !== '') { + $sniffCode = $parts[0] . '.' . $parts[1] . '.' . $parts[2]; + if (isset($this->ruleset[$sniffCode]['severity']) === \true && $this->ruleset[$sniffCode]['severity'] === 0) { + // This sniff code has already been turned off, but now + // it is being explicitly included again, so turn it back on. + $this->ruleset[(string) $rule['ref']]['severity'] = 5; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* disabling sniff exclusion for specific message code *" . \PHP_EOL; + echo \str_repeat("\t", $depth); + echo "\t\t=> severity set to 5" . \PHP_EOL; + } + } else { + if (empty($newSniffs) === \false) { + $newSniff = $newSniffs[0]; + if (\in_array($newSniff, $ownSniffs, \true) === \false) { + // Including a sniff that hasn't been included higher up, but + // only including a single message from it. So turn off all messages in + // the sniff, except this one. + $this->ruleset[$sniffCode]['severity'] = 0; + $this->ruleset[(string) $rule['ref']]['severity'] = 5; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\tExcluding sniff \"" . $sniffCode . '" except for "' . $parts[3] . '"' . \PHP_EOL; + } + } + } + } + //end if + } + //end if + if (isset($rule->exclude) === \true) { + foreach ($rule->exclude as $exclude) { + if (isset($exclude['name']) === \false) { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* ignoring empty exclude rule *" . \PHP_EOL; + echo "\t\t\t=> " . $exclude->asXML() . \PHP_EOL; + } + continue; + } + if ($this->shouldProcessElement($exclude) === \false) { + continue; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\tExcluding rule \"" . $exclude['name'] . '"' . \PHP_EOL; + } + // Check if a single code is being excluded, which is a shortcut + // for setting the severity of the message to 0. + $parts = \explode('.', $exclude['name']); + if (\count($parts) === 4) { + $this->ruleset[(string) $exclude['name']]['severity'] = 0; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> severity set to 0" . \PHP_EOL; + } + } else { + $excludedSniffs = \array_merge($excludedSniffs, $this->expandRulesetReference((string) $exclude['name'], $rulesetDir, $depth + 1)); + } + } + //end foreach + } + //end if + $this->processRule($rule, $newSniffs, $depth); + } + //end foreach + // Process custom command line arguments. + $cliArgs = []; + foreach ($ruleset->{'arg'} as $arg) { + if ($this->shouldProcessElement($arg) === \false) { + continue; + } + if (isset($arg['name']) === \true) { + $argString = '--' . (string) $arg['name']; + if (isset($arg['value']) === \true) { + $argString .= '=' . (string) $arg['value']; + } + } else { + $argString = '-' . (string) $arg['value']; + } + $cliArgs[] = $argString; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> set command line value {$argString}" . \PHP_EOL; + } + } + //end foreach + // Set custom php ini values as CLI args. + foreach ($ruleset->{'ini'} as $arg) { + if ($this->shouldProcessElement($arg) === \false) { + continue; + } + if (isset($arg['name']) === \false) { + continue; + } + $name = (string) $arg['name']; + $argString = $name; + if (isset($arg['value']) === \true) { + $value = (string) $arg['value']; + $argString .= "={$value}"; + } else { + $value = 'true'; + } + $cliArgs[] = '-d'; + $cliArgs[] = $argString; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> set PHP ini value {$name} to {$value}" . \PHP_EOL; + } + } + //end foreach + if (empty($this->config->files) === \true) { + // Process hard-coded file paths. + foreach ($ruleset->{'file'} as $file) { + $file = (string) $file; + $cliArgs[] = $file; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> added \"{$file}\" to the file list" . \PHP_EOL; + } + } + } + if (empty($cliArgs) === \false) { + // Change the directory so all relative paths are worked + // out based on the location of the ruleset instead of + // the location of the user. + $inPhar = Util\Common::isPharFile($rulesetDir); + if ($inPhar === \false) { + $currentDir = \getcwd(); + \chdir($rulesetDir); + } + $this->config->setCommandLineValues($cliArgs); + if ($inPhar === \false) { + \chdir($currentDir); + } + } + // Process custom ignore pattern rules. + foreach ($ruleset->{'exclude-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === \false) { + continue; + } + if (isset($pattern['type']) === \false) { + $pattern['type'] = 'absolute'; + } + $this->ignorePatterns[(string) $pattern] = (string) $pattern['type']; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t=> added global " . (string) $pattern['type'] . ' ignore pattern: ' . (string) $pattern . \PHP_EOL; + } + } + $includedSniffs = \array_unique(\array_merge($ownSniffs, $includedSniffs)); + $excludedSniffs = \array_unique($excludedSniffs); + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $included = \count($includedSniffs); + $excluded = \count($excludedSniffs); + echo \str_repeat("\t", $depth); + echo "=> Ruleset processing complete; included {$included} sniffs and excluded {$excluded}" . \PHP_EOL; + } + // Merge our own sniff list with our externally included + // sniff list, but filter out any excluded sniffs. + $files = []; + foreach ($includedSniffs as $sniff) { + if (\in_array($sniff, $excludedSniffs, \true) === \true) { + continue; + } else { + $files[] = Util\Common::realpath($sniff); + } + } + return $files; + } + //end processRuleset() + /** + * Expands a directory into a list of sniff files within. + * + * @param string $directory The path to a directory. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return array + */ + private function expandSniffDirectory($directory, $depth = 0) + { + $sniffs = []; + $rdi = new \RecursiveDirectoryIterator($directory, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS); + $di = new \RecursiveIteratorIterator($rdi, 0, \RecursiveIteratorIterator::CATCH_GET_CHILD); + $dirLen = \strlen($directory); + foreach ($di as $file) { + $filename = $file->getFilename(); + // Skip hidden files. + if (\substr($filename, 0, 1) === '.') { + continue; + } + // We are only interested in PHP and sniff files. + $fileParts = \explode('.', $filename); + if (\array_pop($fileParts) !== 'php') { + continue; + } + $basename = \basename($filename, '.php'); + if (\substr($basename, -5) !== 'Sniff') { + continue; + } + $path = $file->getPathname(); + // Skip files in hidden directories within the Sniffs directory of this + // standard. We use the offset with strpos() to allow hidden directories + // before, valid example: + // /home/foo/.composer/vendor/squiz/custom_tool/MyStandard/Sniffs/... + if (\strpos($path, \DIRECTORY_SEPARATOR . '.', $dirLen) !== \false) { + continue; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> " . Util\Common::stripBasepath($path, $this->config->basepath) . \PHP_EOL; + } + $sniffs[] = $path; + } + //end foreach + return $sniffs; + } + //end expandSniffDirectory() + /** + * Expands a ruleset reference into a list of sniff files. + * + * @param string $ref The reference from the ruleset XML file. + * @param string $rulesetDir The directory of the ruleset XML file, used to + * evaluate relative paths. + * @param int $depth How many nested processing steps we are in. This + * is only used for debug output. + * + * @return array + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the reference is invalid. + */ + private function expandRulesetReference($ref, $rulesetDir, $depth = 0) + { + // Ignore internal sniffs codes as they are used to only + // hide and change internal messages. + if (\substr($ref, 0, 9) === 'Internal.') { + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* ignoring internal sniff code *" . \PHP_EOL; + } + return []; + } + // As sniffs can't begin with a full stop, assume references in + // this format are relative paths and attempt to convert them + // to absolute paths. If this fails, let the reference run through + // the normal checks and have it fail as normal. + if (\substr($ref, 0, 1) === '.') { + $realpath = Util\Common::realpath($rulesetDir . '/' . $ref); + if ($realpath !== \false) { + $ref = $realpath; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> " . Util\Common::stripBasepath($ref, $this->config->basepath) . \PHP_EOL; + } + } + } + // As sniffs can't begin with a tilde, assume references in + // this format are relative to the user's home directory. + if (\substr($ref, 0, 2) === '~/') { + $realpath = Util\Common::realpath($ref); + if ($realpath !== \false) { + $ref = $realpath; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> " . Util\Common::stripBasepath($ref, $this->config->basepath) . \PHP_EOL; + } + } + } + if (\is_file($ref) === \true) { + if (\substr($ref, -9) === 'Sniff.php') { + // A single external sniff. + $this->rulesetDirs[] = \dirname(\dirname(\dirname($ref))); + return [$ref]; + } + } else { + // See if this is a whole standard being referenced. + $path = Util\Standards::getInstalledStandardPath($ref); + if ($path !== null && Util\Common::isPharFile($path) === \true && \strpos($path, 'ruleset.xml') === \false) { + // If the ruleset exists inside the phar file, use it. + if (\file_exists($path . \DIRECTORY_SEPARATOR . 'ruleset.xml') === \true) { + $path .= \DIRECTORY_SEPARATOR . 'ruleset.xml'; + } else { + $path = null; + } + } + if ($path !== null) { + $ref = $path; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> " . Util\Common::stripBasepath($ref, $this->config->basepath) . \PHP_EOL; + } + } else { + if (\is_dir($ref) === \false) { + // Work out the sniff path. + $sepPos = \strpos($ref, \DIRECTORY_SEPARATOR); + if ($sepPos !== \false) { + $stdName = \substr($ref, 0, $sepPos); + $path = \substr($ref, $sepPos); + } else { + $parts = \explode('.', $ref); + $stdName = $parts[0]; + if (\count($parts) === 1) { + // A whole standard? + $path = ''; + } else { + if (\count($parts) === 2) { + // A directory of sniffs? + $path = \DIRECTORY_SEPARATOR . 'Sniffs' . \DIRECTORY_SEPARATOR . $parts[1]; + } else { + // A single sniff? + $path = \DIRECTORY_SEPARATOR . 'Sniffs' . \DIRECTORY_SEPARATOR . $parts[1] . \DIRECTORY_SEPARATOR . $parts[2] . 'Sniff.php'; + } + } + } + $newRef = \false; + $stdPath = Util\Standards::getInstalledStandardPath($stdName); + if ($stdPath !== null && $path !== '') { + if (Util\Common::isPharFile($stdPath) === \true && \strpos($stdPath, 'ruleset.xml') === \false) { + // Phar files can only return the directory, + // since ruleset can be omitted if building one standard. + $newRef = Util\Common::realpath($stdPath . $path); + } else { + $newRef = Util\Common::realpath(\dirname($stdPath) . $path); + } + } + if ($newRef === \false) { + // The sniff is not locally installed, so check if it is being + // referenced as a remote sniff outside the install. We do this + // by looking through all directories where we have found ruleset + // files before, looking for ones for this particular standard, + // and seeing if it is in there. + foreach ($this->rulesetDirs as $dir) { + if (\strtolower(\basename($dir)) !== \strtolower($stdName)) { + continue; + } + $newRef = Util\Common::realpath($dir . $path); + if ($newRef !== \false) { + $ref = $newRef; + } + } + } else { + $ref = $newRef; + } + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> " . Util\Common::stripBasepath($ref, $this->config->basepath) . \PHP_EOL; + } + } + } + //end if + } + //end if + if (\is_dir($ref) === \true) { + if (\is_file($ref . \DIRECTORY_SEPARATOR . 'ruleset.xml') === \true) { + // We are referencing an external coding standard. + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* rule is referencing a standard using directory name; processing *" . \PHP_EOL; + } + return $this->processRuleset($ref . \DIRECTORY_SEPARATOR . 'ruleset.xml', $depth + 2); + } else { + // We are referencing a whole directory of sniffs. + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* rule is referencing a directory of sniffs *" . \PHP_EOL; + echo \str_repeat("\t", $depth); + echo "\t\tAdding sniff files from directory" . \PHP_EOL; + } + return $this->expandSniffDirectory($ref, $depth + 1); + } + } else { + if (\is_file($ref) === \false) { + $error = "Referenced sniff \"{$ref}\" does not exist"; + throw new RuntimeException($error); + } + if (\substr($ref, -9) === 'Sniff.php') { + // A single sniff. + return [$ref]; + } else { + // Assume an external ruleset.xml file. + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t* rule is referencing a standard using ruleset path; processing *" . \PHP_EOL; + } + return $this->processRuleset($ref, $depth + 2); + } + } + //end if + } + //end expandRulesetReference() + /** + * Processes a rule from a ruleset XML file, overriding built-in defaults. + * + * @param \SimpleXMLElement $rule The rule object from a ruleset XML file. + * @param string[] $newSniffs An array of sniffs that got included by this rule. + * @param int $depth How many nested processing steps we are in. + * This is only used for debug output. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If rule settings are invalid. + */ + private function processRule($rule, $newSniffs, $depth = 0) + { + $ref = (string) $rule['ref']; + $todo = [$ref]; + $parts = \explode('.', $ref); + $partsCount = \count($parts); + if ($partsCount <= 2 || $partsCount > \count(\array_filter($parts)) || \in_array($ref, $newSniffs) === \true) { + // We are processing a standard, a category of sniffs or a relative path inclusion. + foreach ($newSniffs as $sniffFile) { + $parts = \explode(\DIRECTORY_SEPARATOR, $sniffFile); + if (\count($parts) === 1 && \DIRECTORY_SEPARATOR === '\\') { + // Path using forward slashes while running on Windows. + $parts = \explode('/', $sniffFile); + } + $sniffName = \array_pop($parts); + $sniffCategory = \array_pop($parts); + \array_pop($parts); + $sniffStandard = \array_pop($parts); + $todo[] = $sniffStandard . '.' . $sniffCategory . '.' . \substr($sniffName, 0, -9); + } + } + foreach ($todo as $code) { + // Custom severity. + if (isset($rule->severity) === \true && $this->shouldProcessElement($rule->severity) === \true) { + if (isset($this->ruleset[$code]) === \false) { + $this->ruleset[$code] = []; + } + $this->ruleset[$code]['severity'] = (int) $rule->severity; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> severity set to " . (int) $rule->severity; + if ($code !== $ref) { + echo " for {$code}"; + } + echo \PHP_EOL; + } + } + // Custom message type. + if (isset($rule->type) === \true && $this->shouldProcessElement($rule->type) === \true) { + if (isset($this->ruleset[$code]) === \false) { + $this->ruleset[$code] = []; + } + $type = \strtolower((string) $rule->type); + if ($type !== 'error' && $type !== 'warning') { + throw new RuntimeException("Message type \"{$type}\" is invalid; must be \"error\" or \"warning\""); + } + $this->ruleset[$code]['type'] = $type; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> message type set to " . (string) $rule->type; + if ($code !== $ref) { + echo " for {$code}"; + } + echo \PHP_EOL; + } + } + //end if + // Custom message. + if (isset($rule->message) === \true && $this->shouldProcessElement($rule->message) === \true) { + if (isset($this->ruleset[$code]) === \false) { + $this->ruleset[$code] = []; + } + $this->ruleset[$code]['message'] = (string) $rule->message; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> message set to " . (string) $rule->message; + if ($code !== $ref) { + echo " for {$code}"; + } + echo \PHP_EOL; + } + } + // Custom properties. + if (isset($rule->properties) === \true && $this->shouldProcessElement($rule->properties) === \true) { + foreach ($rule->properties->property as $prop) { + if ($this->shouldProcessElement($prop) === \false) { + continue; + } + if (isset($this->ruleset[$code]) === \false) { + $this->ruleset[$code] = ['properties' => []]; + } else { + if (isset($this->ruleset[$code]['properties']) === \false) { + $this->ruleset[$code]['properties'] = []; + } + } + $name = (string) $prop['name']; + if (isset($prop['type']) === \true && (string) $prop['type'] === 'array') { + $values = []; + if (isset($prop['extend']) === \true && (string) $prop['extend'] === 'true' && isset($this->ruleset[$code]['properties'][$name]) === \true) { + $values = $this->ruleset[$code]['properties'][$name]; + } + if (isset($prop->element) === \true) { + $printValue = ''; + foreach ($prop->element as $element) { + if ($this->shouldProcessElement($element) === \false) { + continue; + } + $value = (string) $element['value']; + if (isset($element['key']) === \true) { + $key = (string) $element['key']; + $values[$key] = $value; + $printValue .= $key . '=>' . $value . ','; + } else { + $values[] = $value; + $printValue .= $value . ','; + } + } + $printValue = \rtrim($printValue, ','); + } else { + $value = (string) $prop['value']; + $printValue = $value; + foreach (\explode(',', $value) as $val) { + list($k, $v) = \explode('=>', $val . '=>'); + if ($v !== '') { + $values[\trim($k)] = \trim($v); + } else { + $values[] = \trim($k); + } + } + } + //end if + $this->ruleset[$code]['properties'][$name] = $values; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> array property \"{$name}\" set to \"{$printValue}\""; + if ($code !== $ref) { + echo " for {$code}"; + } + echo \PHP_EOL; + } + } else { + $this->ruleset[$code]['properties'][$name] = (string) $prop['value']; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> property \"{$name}\" set to \"" . (string) $prop['value'] . '"'; + if ($code !== $ref) { + echo " for {$code}"; + } + echo \PHP_EOL; + } + } + //end if + } + //end foreach + } + //end if + // Ignore patterns. + foreach ($rule->{'exclude-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === \false) { + continue; + } + if (isset($this->ignorePatterns[$code]) === \false) { + $this->ignorePatterns[$code] = []; + } + if (isset($pattern['type']) === \false) { + $pattern['type'] = 'absolute'; + } + $this->ignorePatterns[$code][(string) $pattern] = (string) $pattern['type']; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> added rule-specific " . (string) $pattern['type'] . ' ignore pattern'; + if ($code !== $ref) { + echo " for {$code}"; + } + echo ': ' . (string) $pattern . \PHP_EOL; + } + } + //end foreach + // Include patterns. + foreach ($rule->{'include-pattern'} as $pattern) { + if ($this->shouldProcessElement($pattern) === \false) { + continue; + } + if (isset($this->includePatterns[$code]) === \false) { + $this->includePatterns[$code] = []; + } + if (isset($pattern['type']) === \false) { + $pattern['type'] = 'absolute'; + } + $this->includePatterns[$code][(string) $pattern] = (string) $pattern['type']; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \str_repeat("\t", $depth); + echo "\t\t=> added rule-specific " . (string) $pattern['type'] . ' include pattern'; + if ($code !== $ref) { + echo " for {$code}"; + } + echo ': ' . (string) $pattern . \PHP_EOL; + } + } + //end foreach + } + //end foreach + } + //end processRule() + /** + * Determine if an element should be processed or ignored. + * + * @param \SimpleXMLElement $element An object from a ruleset XML file. + * + * @return bool + */ + private function shouldProcessElement($element) + { + if (isset($element['phpcbf-only']) === \false && isset($element['phpcs-only']) === \false) { + // No exceptions are being made. + return \true; + } + if (\PHP_CODESNIFFER_CBF === \true && isset($element['phpcbf-only']) === \true && (string) $element['phpcbf-only'] === 'true') { + return \true; + } + if (\PHP_CODESNIFFER_CBF === \false && isset($element['phpcs-only']) === \true && (string) $element['phpcs-only'] === 'true') { + return \true; + } + return \false; + } + //end shouldProcessElement() + /** + * Loads and stores sniffs objects used for sniffing files. + * + * @param array $files Paths to the sniff files to register. + * @param array $restrictions The sniff class names to restrict the allowed + * listeners to. + * @param array $exclusions The sniff class names to exclude from the + * listeners list. + * + * @return void + */ + public function registerSniffs($files, $restrictions, $exclusions) + { + $listeners = []; + foreach ($files as $file) { + // Work out where the position of /StandardName/Sniffs/... is + // so we can determine what the class will be called. + $sniffPos = \strrpos($file, \DIRECTORY_SEPARATOR . 'Sniffs' . \DIRECTORY_SEPARATOR); + if ($sniffPos === \false) { + continue; + } + $slashPos = \strrpos(\substr($file, 0, $sniffPos), \DIRECTORY_SEPARATOR); + if ($slashPos === \false) { + continue; + } + $className = \PHP_CodeSniffer\Autoload::loadFile($file); + $compareName = Util\Common::cleanSniffClass($className); + // If they have specified a list of sniffs to restrict to, check + // to see if this sniff is allowed. + if (empty($restrictions) === \false && isset($restrictions[$compareName]) === \false) { + continue; + } + // If they have specified a list of sniffs to exclude, check + // to see if this sniff is allowed. + if (empty($exclusions) === \false && isset($exclusions[$compareName]) === \true) { + continue; + } + // Skip abstract classes. + $reflection = new \ReflectionClass($className); + if ($reflection->isAbstract() === \true) { + continue; + } + $listeners[$className] = $className; + if (\PHP_CODESNIFFER_VERBOSITY > 2) { + echo "Registered {$className}" . \PHP_EOL; + } + } + //end foreach + $this->sniffs = $listeners; + } + //end registerSniffs() + /** + * Populates the array of PHP_CodeSniffer_Sniff objects for this file. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If sniff registration fails. + */ + public function populateTokenListeners() + { + // Construct a list of listeners indexed by token being listened for. + $this->tokenListeners = []; + foreach ($this->sniffs as $sniffClass => $sniffObject) { + $this->sniffs[$sniffClass] = null; + $this->sniffs[$sniffClass] = new $sniffClass(); + $sniffCode = Util\Common::getSniffCode($sniffClass); + $this->sniffCodes[$sniffCode] = $sniffClass; + // Set custom properties. + if (isset($this->ruleset[$sniffCode]['properties']) === \true) { + foreach ($this->ruleset[$sniffCode]['properties'] as $name => $value) { + $this->setSniffProperty($sniffClass, $name, $value); + } + } + $tokenizers = []; + $vars = \get_class_vars($sniffClass); + if (isset($vars['supportedTokenizers']) === \true) { + foreach ($vars['supportedTokenizers'] as $tokenizer) { + $tokenizers[$tokenizer] = $tokenizer; + } + } else { + $tokenizers = ['PHP' => 'PHP']; + } + $tokens = $this->sniffs[$sniffClass]->register(); + if (\is_array($tokens) === \false) { + $msg = "Sniff {$sniffClass} register() method must return an array"; + throw new RuntimeException($msg); + } + $ignorePatterns = []; + $patterns = $this->getIgnorePatterns($sniffCode); + foreach ($patterns as $pattern => $type) { + $replacements = ['\\,' => ',', '*' => '.*']; + $ignorePatterns[] = \strtr($pattern, $replacements); + } + $includePatterns = []; + $patterns = $this->getIncludePatterns($sniffCode); + foreach ($patterns as $pattern => $type) { + $replacements = ['\\,' => ',', '*' => '.*']; + $includePatterns[] = \strtr($pattern, $replacements); + } + foreach ($tokens as $token) { + if (isset($this->tokenListeners[$token]) === \false) { + $this->tokenListeners[$token] = []; + } + if (isset($this->tokenListeners[$token][$sniffClass]) === \false) { + $this->tokenListeners[$token][$sniffClass] = ['class' => $sniffClass, 'source' => $sniffCode, 'tokenizers' => $tokenizers, 'ignore' => $ignorePatterns, 'include' => $includePatterns]; + } + } + } + //end foreach + } + //end populateTokenListeners() + /** + * Set a single property for a sniff. + * + * @param string $sniffClass The class name of the sniff. + * @param string $name The name of the property to change. + * @param string $value The new value of the property. + * + * @return void + */ + public function setSniffProperty($sniffClass, $name, $value) + { + // Setting a property for a sniff we are not using. + if (isset($this->sniffs[$sniffClass]) === \false) { + return; + } + $name = \trim($name); + if (\is_string($value) === \true) { + $value = \trim($value); + } + if ($value === '') { + $value = null; + } + // Special case for booleans. + if ($value === 'true') { + $value = \true; + } else { + if ($value === 'false') { + $value = \false; + } else { + if (\substr($name, -2) === '[]') { + $name = \substr($name, 0, -2); + $values = []; + if ($value !== null) { + foreach (\explode(',', $value) as $val) { + list($k, $v) = \explode('=>', $val . '=>'); + if ($v !== '') { + $values[\trim($k)] = \trim($v); + } else { + $values[] = \trim($k); + } + } + } + $value = $values; + } + } + } + $this->sniffs[$sniffClass]->{$name} = $value; + } + //end setSniffProperty() + /** + * Gets the array of ignore patterns. + * + * Optionally takes a listener to get ignore patterns specified + * for that sniff only. + * + * @param string $listener The listener to get patterns for. If NULL, all + * patterns are returned. + * + * @return array + */ + public function getIgnorePatterns($listener = null) + { + if ($listener === null) { + return $this->ignorePatterns; + } + if (isset($this->ignorePatterns[$listener]) === \true) { + return $this->ignorePatterns[$listener]; + } + return []; + } + //end getIgnorePatterns() + /** + * Gets the array of include patterns. + * + * Optionally takes a listener to get include patterns specified + * for that sniff only. + * + * @param string $listener The listener to get patterns for. If NULL, all + * patterns are returned. + * + * @return array + */ + public function getIncludePatterns($listener = null) + { + if ($listener === null) { + return $this->includePatterns; + } + if (isset($this->includePatterns[$listener]) === \true) { + return $this->includePatterns[$listener]; + } + return []; + } + //end getIncludePatterns() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Runner.php b/vendor/squizlabs/php_codesniffer/src/Runner.php new file mode 100644 index 00000000000..bc26ec517ea --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Runner.php @@ -0,0 +1,782 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer; + +use PHP_CodeSniffer\Exceptions\DeepExitException; +use PHP_CodeSniffer\Exceptions\RuntimeException; +use PHP_CodeSniffer\Files\DummyFile; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Files\FileList; +use PHP_CodeSniffer\Util\Cache; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Standards; +class Runner +{ + /** + * The config data for the run. + * + * @var \PHP_CodeSniffer\Config + */ + public $config = null; + /** + * The ruleset used for the run. + * + * @var \PHP_CodeSniffer\Ruleset + */ + public $ruleset = null; + /** + * The reporter used for generating reports after the run. + * + * @var \PHP_CodeSniffer\Reporter + */ + public $reporter = null; + /** + * Run the PHPCS script. + * + * @return array + */ + public function runPHPCS() + { + $this->registerOutOfMemoryShutdownMessage('phpcs'); + try { + \PHP_CodeSniffer\Util\Timing::startTiming(); + \PHP_CodeSniffer\Runner::checkRequirements(); + if (\defined('PHP_CODESNIFFER_CBF') === \false) { + \define('PHP_CODESNIFFER_CBF', \false); + } + // Creating the Config object populates it with all required settings + // based on the CLI arguments provided to the script and any config + // values the user has set. + $this->config = new \PHP_CodeSniffer\Config(); + // Init the run and load the rulesets to set additional config vars. + $this->init(); + // Print a list of sniffs in each of the supplied standards. + // We fudge the config here so that each standard is explained in isolation. + if ($this->config->explain === \true) { + $standards = $this->config->standards; + foreach ($standards as $standard) { + $this->config->standards = [$standard]; + $ruleset = new \PHP_CodeSniffer\Ruleset($this->config); + $ruleset->explain(); + } + return 0; + } + // Generate documentation for each of the supplied standards. + if ($this->config->generator !== null) { + $standards = $this->config->standards; + foreach ($standards as $standard) { + $this->config->standards = [$standard]; + $ruleset = new \PHP_CodeSniffer\Ruleset($this->config); + $class = 'PHP_CodeSniffer\\Generators\\' . $this->config->generator; + $generator = new $class($ruleset); + $generator->generate(); + } + return 0; + } + // Other report formats don't really make sense in interactive mode + // so we hard-code the full report here and when outputting. + // We also ensure parallel processing is off because we need to do one file at a time. + if ($this->config->interactive === \true) { + $this->config->reports = ['full' => null]; + $this->config->parallel = 1; + $this->config->showProgress = \false; + } + // Disable caching if we are processing STDIN as we can't be 100% + // sure where the file came from or if it will change in the future. + if ($this->config->stdin === \true) { + $this->config->cache = \false; + } + $numErrors = $this->run(); + // Print all the reports for this run. + $toScreen = $this->reporter->printReports(); + // Only print timer output if no reports were + // printed to the screen so we don't put additional output + // in something like an XML report. If we are printing to screen, + // the report types would have already worked out who should + // print the timer info. + if ($this->config->interactive === \false && ($toScreen === \false || $this->reporter->totalErrors + $this->reporter->totalWarnings === 0 && $this->config->showProgress === \true)) { + \PHP_CodeSniffer\Util\Timing::printRunTime(); + } + } catch (DeepExitException $e) { + echo $e->getMessage(); + return $e->getCode(); + } + //end try + if ($numErrors === 0) { + // No errors found. + return 0; + } else { + if ($this->reporter->totalFixable === 0) { + // Errors found, but none of them can be fixed by PHPCBF. + return 1; + } else { + // Errors found, and some can be fixed by PHPCBF. + return 2; + } + } + } + //end runPHPCS() + /** + * Run the PHPCBF script. + * + * @return array + */ + public function runPHPCBF() + { + $this->registerOutOfMemoryShutdownMessage('phpcbf'); + if (\defined('PHP_CODESNIFFER_CBF') === \false) { + \define('PHP_CODESNIFFER_CBF', \true); + } + try { + \PHP_CodeSniffer\Util\Timing::startTiming(); + \PHP_CodeSniffer\Runner::checkRequirements(); + // Creating the Config object populates it with all required settings + // based on the CLI arguments provided to the script and any config + // values the user has set. + $this->config = new \PHP_CodeSniffer\Config(); + // When processing STDIN, we can't output anything to the screen + // or it will end up mixed in with the file output. + if ($this->config->stdin === \true) { + $this->config->verbosity = 0; + } + // Init the run and load the rulesets to set additional config vars. + $this->init(); + // When processing STDIN, we only process one file at a time and + // we don't process all the way through, so we can't use the parallel + // running system. + if ($this->config->stdin === \true) { + $this->config->parallel = 1; + } + // Override some of the command line settings that might break the fixes. + $this->config->generator = null; + $this->config->explain = \false; + $this->config->interactive = \false; + $this->config->cache = \false; + $this->config->showSources = \false; + $this->config->recordErrors = \false; + $this->config->reportFile = null; + $this->config->reports = ['cbf' => null]; + // If a standard tries to set command line arguments itself, some + // may be blocked because PHPCBF is running, so stop the script + // dying if any are found. + $this->config->dieOnUnknownArg = \false; + $this->run(); + $this->reporter->printReports(); + echo \PHP_EOL; + \PHP_CodeSniffer\Util\Timing::printRunTime(); + } catch (DeepExitException $e) { + echo $e->getMessage(); + return $e->getCode(); + } + //end try + if ($this->reporter->totalFixed === 0) { + // Nothing was fixed by PHPCBF. + if ($this->reporter->totalFixable === 0) { + // Nothing found that could be fixed. + return 0; + } else { + // Something failed to fix. + return 2; + } + } + if ($this->reporter->totalFixable === 0) { + // PHPCBF fixed all fixable errors. + return 1; + } + // PHPCBF fixed some fixable errors, but others failed to fix. + return 2; + } + //end runPHPCBF() + /** + * Exits if the minimum requirements of PHP_CodeSniffer are not met. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If the requirements are not met. + */ + public function checkRequirements() + { + // Check the PHP version. + if (\PHP_VERSION_ID < 50400) { + $error = 'ERROR: PHP_CodeSniffer requires PHP version 5.4.0 or greater.' . \PHP_EOL; + throw new DeepExitException($error, 3); + } + $requiredExtensions = ['tokenizer', 'xmlwriter', 'SimpleXML']; + $missingExtensions = []; + foreach ($requiredExtensions as $extension) { + if (\extension_loaded($extension) === \false) { + $missingExtensions[] = $extension; + } + } + if (empty($missingExtensions) === \false) { + $last = \array_pop($requiredExtensions); + $required = \implode(', ', $requiredExtensions); + $required .= ' and ' . $last; + if (\count($missingExtensions) === 1) { + $missing = $missingExtensions[0]; + } else { + $last = \array_pop($missingExtensions); + $missing = \implode(', ', $missingExtensions); + $missing .= ' and ' . $last; + } + $error = 'ERROR: PHP_CodeSniffer requires the %s extensions to be enabled. Please enable %s.' . \PHP_EOL; + $error = \sprintf($error, $required, $missing); + throw new DeepExitException($error, 3); + } + } + //end checkRequirements() + /** + * Init the rulesets and other high-level settings. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException If a referenced standard is not installed. + */ + public function init() + { + if (\defined('PHP_CODESNIFFER_CBF') === \false) { + \define('PHP_CODESNIFFER_CBF', \false); + } + // Ensure this option is enabled or else line endings will not always + // be detected properly for files created on a Mac with the /r line ending. + @\ini_set('auto_detect_line_endings', \true); + // Disable the PCRE JIT as this caused issues with parallel running. + \ini_set('pcre.jit', \false); + // Check that the standards are valid. + foreach ($this->config->standards as $standard) { + if (\PHP_CodeSniffer\Util\Standards::isInstalledStandard($standard) === \false) { + // They didn't select a valid coding standard, so help them + // out by letting them know which standards are installed. + $error = 'ERROR: the "' . $standard . '" coding standard is not installed. '; + \ob_start(); + \PHP_CodeSniffer\Util\Standards::printInstalledStandards(); + $error .= \ob_get_contents(); + \ob_end_clean(); + throw new DeepExitException($error, 3); + } + } + // Saves passing the Config object into other objects that only need + // the verbosity flag for debug output. + if (\defined('PHP_CODESNIFFER_VERBOSITY') === \false) { + \define('PHP_CODESNIFFER_VERBOSITY', $this->config->verbosity); + } + // Create this class so it is autoloaded and sets up a bunch + // of PHP_CodeSniffer-specific token type constants. + $tokens = new \PHP_CodeSniffer\Util\Tokens(); + // Allow autoloading of custom files inside installed standards. + $installedStandards = Standards::getInstalledStandardDetails(); + foreach ($installedStandards as $name => $details) { + \PHP_CodeSniffer\Autoload::addSearchPath($details['path'], $details['namespace']); + } + // The ruleset contains all the information about how the files + // should be checked and/or fixed. + try { + $this->ruleset = new \PHP_CodeSniffer\Ruleset($this->config); + } catch (RuntimeException $e) { + $error = 'ERROR: ' . $e->getMessage() . \PHP_EOL . \PHP_EOL; + $error .= $this->config->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + } + //end init() + /** + * Performs the run. + * + * @return int The number of errors and warnings found. + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException + */ + private function run() + { + // The class that manages all reporters for the run. + $this->reporter = new \PHP_CodeSniffer\Reporter($this->config); + // Include bootstrap files. + foreach ($this->config->bootstrap as $bootstrap) { + include $bootstrap; + } + if ($this->config->stdin === \true) { + $fileContents = $this->config->stdinContent; + if ($fileContents === null) { + $handle = \fopen('php://stdin', 'r'); + \stream_set_blocking($handle, \true); + $fileContents = \stream_get_contents($handle); + \fclose($handle); + } + $todo = new FileList($this->config, $this->ruleset); + $dummy = new DummyFile($fileContents, $this->ruleset, $this->config); + $todo->addFile($dummy->path, $dummy); + } else { + if (empty($this->config->files) === \true) { + $error = 'ERROR: You must supply at least one file or directory to process.' . \PHP_EOL . \PHP_EOL; + $error .= $this->config->printShortUsage(\true); + throw new DeepExitException($error, 3); + } + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Creating file list... '; + } + $todo = new FileList($this->config, $this->ruleset); + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + $numFiles = \count($todo); + echo "DONE ({$numFiles} files in queue)" . \PHP_EOL; + } + if ($this->config->cache === \true) { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Loading cache... '; + } + Cache::load($this->ruleset, $this->config); + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + $size = Cache::getSize(); + echo "DONE ({$size} files in cache)" . \PHP_EOL; + } + } + } + //end if + // Turn all sniff errors into exceptions. + \set_error_handler([$this, 'handleErrors']); + // If verbosity is too high, turn off parallelism so the + // debug output is clean. + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + $this->config->parallel = 1; + } + // If the PCNTL extension isn't installed, we can't fork. + if (\function_exists('pcntl_fork') === \false) { + $this->config->parallel = 1; + } + $lastDir = ''; + $numFiles = \count($todo); + if ($this->config->parallel === 1) { + // Running normally. + $numProcessed = 0; + foreach ($todo as $path => $file) { + if ($file->ignored === \false) { + $currDir = \dirname($path); + if ($lastDir !== $currDir) { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Changing into directory ' . Common::stripBasepath($currDir, $this->config->basepath) . \PHP_EOL; + } + $lastDir = $currDir; + } + $this->processFile($file); + } else { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Skipping ' . \basename($file->path) . \PHP_EOL; + } + } + $numProcessed++; + $this->printProgress($file, $numFiles, $numProcessed); + } + } else { + // Batching and forking. + $childProcs = []; + $numPerBatch = \ceil($numFiles / $this->config->parallel); + for ($batch = 0; $batch < $this->config->parallel; $batch++) { + $startAt = $batch * $numPerBatch; + if ($startAt >= $numFiles) { + break; + } + $endAt = $startAt + $numPerBatch; + if ($endAt > $numFiles) { + $endAt = $numFiles; + } + $childOutFilename = \tempnam(\sys_get_temp_dir(), 'phpcs-child'); + $pid = \pcntl_fork(); + if ($pid === -1) { + throw new RuntimeException('Failed to create child process'); + } else { + if ($pid !== 0) { + $childProcs[$pid] = $childOutFilename; + } else { + // Move forward to the start of the batch. + $todo->rewind(); + for ($i = 0; $i < $startAt; $i++) { + $todo->next(); + } + // Reset the reporter to make sure only figures from this + // file batch are recorded. + $this->reporter->totalFiles = 0; + $this->reporter->totalErrors = 0; + $this->reporter->totalWarnings = 0; + $this->reporter->totalFixable = 0; + $this->reporter->totalFixed = 0; + // Process the files. + $pathsProcessed = []; + \ob_start(); + for ($i = $startAt; $i < $endAt; $i++) { + $path = $todo->key(); + $file = $todo->current(); + if ($file->ignored === \true) { + $todo->next(); + continue; + } + $currDir = \dirname($path); + if ($lastDir !== $currDir) { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + echo 'Changing into directory ' . Common::stripBasepath($currDir, $this->config->basepath) . \PHP_EOL; + } + $lastDir = $currDir; + } + $this->processFile($file); + $pathsProcessed[] = $path; + $todo->next(); + } + //end for + $debugOutput = \ob_get_contents(); + \ob_end_clean(); + // Write information about the run to the filesystem + // so it can be picked up by the main process. + $childOutput = ['totalFiles' => $this->reporter->totalFiles, 'totalErrors' => $this->reporter->totalErrors, 'totalWarnings' => $this->reporter->totalWarnings, 'totalFixable' => $this->reporter->totalFixable, 'totalFixed' => $this->reporter->totalFixed]; + $output = '<' . '?php' . "\n" . ' $childOutput = '; + $output .= \var_export($childOutput, \true); + $output .= ";\n\$debugOutput = "; + $output .= \var_export($debugOutput, \true); + if ($this->config->cache === \true) { + $childCache = []; + foreach ($pathsProcessed as $path) { + $childCache[$path] = Cache::get($path); + } + $output .= ";\n\$childCache = "; + $output .= \var_export($childCache, \true); + } + $output .= ";\n?" . '>'; + \file_put_contents($childOutFilename, $output); + exit; + } + } + //end if + } + //end for + $success = $this->processChildProcs($childProcs); + if ($success === \false) { + throw new RuntimeException('One or more child processes failed to run'); + } + } + //end if + \restore_error_handler(); + if (\PHP_CODESNIFFER_VERBOSITY === 0 && $this->config->interactive === \false && $this->config->showProgress === \true) { + echo \PHP_EOL . \PHP_EOL; + } + if ($this->config->cache === \true) { + Cache::save(); + } + $ignoreWarnings = \PHP_CodeSniffer\Config::getConfigData('ignore_warnings_on_exit'); + $ignoreErrors = \PHP_CodeSniffer\Config::getConfigData('ignore_errors_on_exit'); + $return = $this->reporter->totalErrors + $this->reporter->totalWarnings; + if ($ignoreErrors !== null) { + $ignoreErrors = (bool) $ignoreErrors; + if ($ignoreErrors === \true) { + $return -= $this->reporter->totalErrors; + } + } + if ($ignoreWarnings !== null) { + $ignoreWarnings = (bool) $ignoreWarnings; + if ($ignoreWarnings === \true) { + $return -= $this->reporter->totalWarnings; + } + } + return $return; + } + //end run() + /** + * Converts all PHP errors into exceptions. + * + * This method forces a sniff to stop processing if it is not + * able to handle a specific piece of code, instead of continuing + * and potentially getting into a loop. + * + * @param int $code The level of error raised. + * @param string $message The error message. + * @param string $file The path of the file that raised the error. + * @param int $line The line number the error was raised at. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException + */ + public function handleErrors($code, $message, $file, $line) + { + if ((\error_reporting() & $code) === 0) { + // This type of error is being muted. + return \true; + } + throw new RuntimeException("{$message} in {$file} on line {$line}"); + } + //end handleErrors() + /** + * Processes a single file, including checking and fixing. + * + * @param \PHP_CodeSniffer\Files\File $file The file to be processed. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\DeepExitException + */ + public function processFile($file) + { + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + $startTime = \microtime(\true); + echo 'Processing ' . \basename($file->path) . ' '; + if (\PHP_CODESNIFFER_VERBOSITY > 1) { + echo \PHP_EOL; + } + } + try { + $file->process(); + if (\PHP_CODESNIFFER_VERBOSITY > 0) { + $timeTaken = (\microtime(\true) - $startTime) * 1000; + if ($timeTaken < 1000) { + $timeTaken = \round($timeTaken); + echo "DONE in {$timeTaken}ms"; + } else { + $timeTaken = \round($timeTaken / 1000, 2); + echo "DONE in {$timeTaken} secs"; + } + if (\PHP_CODESNIFFER_CBF === \true) { + $errors = $file->getFixableCount(); + echo " ({$errors} fixable violations)" . \PHP_EOL; + } else { + $errors = $file->getErrorCount(); + $warnings = $file->getWarningCount(); + echo " ({$errors} errors, {$warnings} warnings)" . \PHP_EOL; + } + } + } catch (\Exception $e) { + $error = 'An error occurred during processing; checking has been aborted. The error message was: ' . $e->getMessage(); + $file->addErrorOnLine($error, 1, 'Internal.Exception'); + } + //end try + $this->reporter->cacheFileReport($file, $this->config); + if ($this->config->interactive === \true) { + /* + Running interactively. + Print the error report for the current file and then wait for user input. + */ + // Get current violations and then clear the list to make sure + // we only print violations for a single file each time. + $numErrors = null; + while ($numErrors !== 0) { + $numErrors = $file->getErrorCount() + $file->getWarningCount(); + if ($numErrors === 0) { + continue; + } + $this->reporter->printReport('full'); + echo ' to recheck, [s] to skip or [q] to quit : '; + $input = \fgets(\STDIN); + $input = \trim($input); + switch ($input) { + case 's': + break 2; + case 'q': + throw new DeepExitException('', 0); + default: + // Repopulate the sniffs because some of them save their state + // and only clear it when the file changes, but we are rechecking + // the same file. + $file->ruleset->populateTokenListeners(); + $file->reloadContent(); + $file->process(); + $this->reporter->cacheFileReport($file, $this->config); + break; + } + } + //end while + } + //end if + // Clean up the file to save (a lot of) memory. + $file->cleanUp(); + } + //end processFile() + /** + * Waits for child processes to complete and cleans up after them. + * + * The reporting information returned by each child process is merged + * into the main reporter class. + * + * @param array $childProcs An array of child processes to wait for. + * + * @return bool + */ + private function processChildProcs($childProcs) + { + $numProcessed = 0; + $totalBatches = \count($childProcs); + $success = \true; + while (\count($childProcs) > 0) { + $pid = \pcntl_waitpid(0, $status); + if ($pid <= 0) { + continue; + } + $childProcessStatus = \pcntl_wexitstatus($status); + if ($childProcessStatus !== 0) { + $success = \false; + } + $out = $childProcs[$pid]; + unset($childProcs[$pid]); + if (\file_exists($out) === \false) { + continue; + } + include $out; + \unlink($out); + $numProcessed++; + if (isset($childOutput) === \false) { + // The child process died, so the run has failed. + $file = new DummyFile('', $this->ruleset, $this->config); + $file->setErrorCounts(1, 0, 0, 0); + $this->printProgress($file, $totalBatches, $numProcessed); + $success = \false; + continue; + } + $this->reporter->totalFiles += $childOutput['totalFiles']; + $this->reporter->totalErrors += $childOutput['totalErrors']; + $this->reporter->totalWarnings += $childOutput['totalWarnings']; + $this->reporter->totalFixable += $childOutput['totalFixable']; + $this->reporter->totalFixed += $childOutput['totalFixed']; + if (isset($debugOutput) === \true) { + echo $debugOutput; + } + if (isset($childCache) === \true) { + foreach ($childCache as $path => $cache) { + Cache::set($path, $cache); + } + } + // Fake a processed file so we can print progress output for the batch. + $file = new DummyFile('', $this->ruleset, $this->config); + $file->setErrorCounts($childOutput['totalErrors'], $childOutput['totalWarnings'], $childOutput['totalFixable'], $childOutput['totalFixed']); + $this->printProgress($file, $totalBatches, $numProcessed); + } + //end while + return $success; + } + //end processChildProcs() + /** + * Print progress information for a single processed file. + * + * @param \PHP_CodeSniffer\Files\File $file The file that was processed. + * @param int $numFiles The total number of files to process. + * @param int $numProcessed The number of files that have been processed, + * including this one. + * + * @return void + */ + public function printProgress(File $file, $numFiles, $numProcessed) + { + if (\PHP_CODESNIFFER_VERBOSITY > 0 || $this->config->showProgress === \false) { + return; + } + // Show progress information. + if ($file->ignored === \true) { + echo 'S'; + } else { + $errors = $file->getErrorCount(); + $warnings = $file->getWarningCount(); + $fixable = $file->getFixableCount(); + $fixed = $file->getFixedCount(); + if (\PHP_CODESNIFFER_CBF === \true) { + // Files with fixed errors or warnings are F (green). + // Files with unfixable errors or warnings are E (red). + // Files with no errors or warnings are . (black). + if ($fixable > 0) { + if ($this->config->colors === \true) { + echo "\x1b[31m"; + } + echo 'E'; + if ($this->config->colors === \true) { + echo "\x1b[0m"; + } + } else { + if ($fixed > 0) { + if ($this->config->colors === \true) { + echo "\x1b[32m"; + } + echo 'F'; + if ($this->config->colors === \true) { + echo "\x1b[0m"; + } + } else { + echo '.'; + } + } + //end if + } else { + // Files with errors are E (red). + // Files with fixable errors are E (green). + // Files with warnings are W (yellow). + // Files with fixable warnings are W (green). + // Files with no errors or warnings are . (black). + if ($errors > 0) { + if ($this->config->colors === \true) { + if ($fixable > 0) { + echo "\x1b[32m"; + } else { + echo "\x1b[31m"; + } + } + echo 'E'; + if ($this->config->colors === \true) { + echo "\x1b[0m"; + } + } else { + if ($warnings > 0) { + if ($this->config->colors === \true) { + if ($fixable > 0) { + echo "\x1b[32m"; + } else { + echo "\x1b[33m"; + } + } + echo 'W'; + if ($this->config->colors === \true) { + echo "\x1b[0m"; + } + } else { + echo '.'; + } + } + //end if + } + //end if + } + //end if + $numPerLine = 60; + if ($numProcessed !== $numFiles && $numProcessed % $numPerLine !== 0) { + return; + } + $percent = \round($numProcessed / $numFiles * 100); + $padding = \strlen($numFiles) - \strlen($numProcessed); + if ($numProcessed === $numFiles && $numFiles > $numPerLine && $numProcessed % $numPerLine !== 0) { + $padding += $numPerLine - ($numFiles - \floor($numFiles / $numPerLine) * $numPerLine); + } + echo \str_repeat(' ', $padding) . " {$numProcessed} / {$numFiles} ({$percent}%)" . \PHP_EOL; + } + //end printProgress() + /** + * Registers a PHP shutdown function to provide a more informative out of memory error. + * + * @param string $command The command which was used to initiate the PHPCS run. + * + * @return void + */ + private function registerOutOfMemoryShutdownMessage($command) + { + // Allocate all needed memory beforehand as much as possible. + $errorMsg = \PHP_EOL . 'The PHP_CodeSniffer "%1$s" command ran out of memory.' . \PHP_EOL; + $errorMsg .= 'Either raise the "memory_limit" of PHP in the php.ini file or raise the memory limit at runtime' . \PHP_EOL; + $errorMsg .= 'using `%1$s -d memory_limit=512M` (replace 512M with the desired memory limit).' . \PHP_EOL; + $errorMsg = \sprintf($errorMsg, $command); + $memoryError = 'Allowed memory size of'; + $errorArray = ['type' => 42, 'message' => 'Some random dummy string to take up memory and take up some more memory and some more', 'file' => 'Another random string, which would be a filename this time. Should be relatively long to allow for deeply nested files', 'line' => 31427]; + \register_shutdown_function(static function () use($errorMsg, $memoryError, $errorArray) { + $errorArray = \error_get_last(); + if (\is_array($errorArray) === \true && \strpos($errorArray['message'], $memoryError) !== \false) { + echo $errorMsg; + } + }); + } + //end registerOutOfMemoryShutdownMessage() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php new file mode 100644 index 00000000000..a9238993c7e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractArraySniff.php @@ -0,0 +1,140 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; +abstract class AbstractArraySniff implements \PHP_CodeSniffer\Sniffs\Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public final function register() + { + return [\T_ARRAY, \T_OPEN_SHORT_ARRAY]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr]['code'] === \T_ARRAY) { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no'); + $arrayStart = $tokens[$stackPtr]['parenthesis_opener']; + if (isset($tokens[$arrayStart]['parenthesis_closer']) === \false) { + // Incomplete array. + return; + } + $arrayEnd = $tokens[$arrayStart]['parenthesis_closer']; + } else { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); + $arrayStart = $stackPtr; + $arrayEnd = $tokens[$stackPtr]['bracket_closer']; + } + $lastContent = $phpcsFile->findPrevious(Tokens::$emptyTokens, $arrayEnd - 1, null, \true); + if ($tokens[$lastContent]['code'] === \T_COMMA) { + // Last array item ends with a comma. + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'yes'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Array end comma', 'no'); + } + $indices = []; + $current = $arrayStart; + while (($next = $phpcsFile->findNext(Tokens::$emptyTokens, $current + 1, $arrayEnd, \true)) !== \false) { + $end = $this->getNext($phpcsFile, $next, $arrayEnd); + if ($tokens[$end]['code'] === \T_DOUBLE_ARROW) { + $indexEnd = $phpcsFile->findPrevious(\T_WHITESPACE, $end - 1, null, \true); + $valueStart = $phpcsFile->findNext(Tokens::$emptyTokens, $end + 1, null, \true); + $indices[] = ['index_start' => $next, 'index_end' => $indexEnd, 'arrow' => $end, 'value_start' => $valueStart]; + } else { + $valueStart = $next; + $indices[] = ['value_start' => $valueStart]; + } + $current = $this->getNext($phpcsFile, $valueStart, $arrayEnd); + } + if ($tokens[$arrayStart]['line'] === $tokens[$arrayEnd]['line']) { + $this->processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + } else { + $this->processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + } + } + //end process() + /** + * Find next separator in array - either: comma or double arrow. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $ptr The position of current token. + * @param int $arrayEnd The token that ends the array definition. + * + * @return int + */ + private function getNext(File $phpcsFile, $ptr, $arrayEnd) + { + $tokens = $phpcsFile->getTokens(); + while ($ptr < $arrayEnd) { + if (isset($tokens[$ptr]['scope_closer']) === \true) { + $ptr = $tokens[$ptr]['scope_closer']; + } else { + if (isset($tokens[$ptr]['parenthesis_closer']) === \true) { + $ptr = $tokens[$ptr]['parenthesis_closer']; + } else { + if (isset($tokens[$ptr]['bracket_closer']) === \true) { + $ptr = $tokens[$ptr]['bracket_closer']; + } + } + } + if ($tokens[$ptr]['code'] === \T_COMMA || $tokens[$ptr]['code'] === \T_DOUBLE_ARROW) { + return $ptr; + } + ++$ptr; + } + return $ptr; + } + //end getNext() + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + protected abstract function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + protected abstract function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php new file mode 100644 index 00000000000..313fd39fc07 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractPatternSniff.php @@ -0,0 +1,766 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; +use PHP_CodeSniffer\Tokenizers\PHP; +use PHP_CodeSniffer\Exceptions\RuntimeException; +abstract class AbstractPatternSniff implements \PHP_CodeSniffer\Sniffs\Sniff +{ + /** + * If true, comments will be ignored if they are found in the code. + * + * @var boolean + */ + public $ignoreComments = \false; + /** + * The current file being checked. + * + * @var string + */ + protected $currFile = ''; + /** + * The parsed patterns array. + * + * @var array + */ + private $parsedPatterns = []; + /** + * Tokens that this sniff wishes to process outside of the patterns. + * + * @var int[] + * @see registerSupplementary() + * @see processSupplementary() + */ + private $supplementaryTokens = []; + /** + * Positions in the stack where errors have occurred. + * + * @var array + */ + private $errorPos = []; + /** + * Constructs a AbstractPatternSniff. + * + * @param boolean $ignoreComments If true, comments will be ignored. + */ + public function __construct($ignoreComments = null) + { + // This is here for backwards compatibility. + if ($ignoreComments !== null) { + $this->ignoreComments = $ignoreComments; + } + $this->supplementaryTokens = $this->registerSupplementary(); + } + //end __construct() + /** + * Registers the tokens to listen to. + * + * Classes extending AbstractPatternTest should implement the + * getPatterns() method to register the patterns they wish to test. + * + * @return int[] + * @see process() + */ + public final function register() + { + $listenTypes = []; + $patterns = $this->getPatterns(); + foreach ($patterns as $pattern) { + $parsedPattern = $this->parse($pattern); + // Find a token position in the pattern that we can use + // for a listener token. + $pos = $this->getListenerTokenPos($parsedPattern); + $tokenType = $parsedPattern[$pos]['token']; + $listenTypes[] = $tokenType; + $patternArray = ['listen_pos' => $pos, 'pattern' => $parsedPattern, 'pattern_code' => $pattern]; + if (isset($this->parsedPatterns[$tokenType]) === \false) { + $this->parsedPatterns[$tokenType] = []; + } + $this->parsedPatterns[$tokenType][] = $patternArray; + } + //end foreach + return \array_unique(\array_merge($listenTypes, $this->supplementaryTokens)); + } + //end register() + /** + * Returns the token types that the specified pattern is checking for. + * + * Returned array is in the format: + * + * array( + * T_WHITESPACE => 0, // 0 is the position where the T_WHITESPACE token + * // should occur in the pattern. + * ); + * + * + * @param array $pattern The parsed pattern to find the acquire the token + * types from. + * + * @return array + */ + private function getPatternTokenTypes($pattern) + { + $tokenTypes = []; + foreach ($pattern as $pos => $patternInfo) { + if ($patternInfo['type'] === 'token') { + if (isset($tokenTypes[$patternInfo['token']]) === \false) { + $tokenTypes[$patternInfo['token']] = $pos; + } + } + } + return $tokenTypes; + } + //end getPatternTokenTypes() + /** + * Returns the position in the pattern that this test should register as + * a listener for the pattern. + * + * @param array $pattern The pattern to acquire the listener for. + * + * @return int The position in the pattern that this test should register + * as the listener. + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If we could not determine a token to listen for. + */ + private function getListenerTokenPos($pattern) + { + $tokenTypes = $this->getPatternTokenTypes($pattern); + $tokenCodes = \array_keys($tokenTypes); + $token = Tokens::getHighestWeightedToken($tokenCodes); + // If we could not get a token. + if ($token === \false) { + $error = 'Could not determine a token to listen for'; + throw new RuntimeException($error); + } + return $tokenTypes[$token]; + } + //end getListenerTokenPos() + /** + * Processes the test. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack + * where the listening token type + * was found. + * + * @return void + * @see register() + */ + public final function process(File $phpcsFile, $stackPtr) + { + $file = $phpcsFile->getFilename(); + if ($this->currFile !== $file) { + // We have changed files, so clean up. + $this->errorPos = []; + $this->currFile = $file; + } + $tokens = $phpcsFile->getTokens(); + if (\in_array($tokens[$stackPtr]['code'], $this->supplementaryTokens, \true) === \true) { + $this->processSupplementary($phpcsFile, $stackPtr); + } + $type = $tokens[$stackPtr]['code']; + // If the type is not set, then it must have been a token registered + // with registerSupplementary(). + if (isset($this->parsedPatterns[$type]) === \false) { + return; + } + $allErrors = []; + // Loop over each pattern that is listening to the current token type + // that we are processing. + foreach ($this->parsedPatterns[$type] as $patternInfo) { + // If processPattern returns false, then the pattern that we are + // checking the code with must not be designed to check that code. + $errors = $this->processPattern($patternInfo, $phpcsFile, $stackPtr); + if ($errors === \false) { + // The pattern didn't match. + continue; + } else { + if (empty($errors) === \true) { + // The pattern matched, but there were no errors. + break; + } + } + foreach ($errors as $stackPtr => $error) { + if (isset($this->errorPos[$stackPtr]) === \false) { + $this->errorPos[$stackPtr] = \true; + $allErrors[$stackPtr] = $error; + } + } + } + foreach ($allErrors as $stackPtr => $error) { + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + } + //end process() + /** + * Processes the pattern and verifies the code at $stackPtr. + * + * @param array $patternInfo Information about the pattern used + * for checking, which includes are + * parsed token representation of the + * pattern. + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token occurred. + * @param int $stackPtr The position in the tokens stack where + * the listening token type was found. + * + * @return array + */ + protected function processPattern($patternInfo, File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $pattern = $patternInfo['pattern']; + $patternCode = $patternInfo['pattern_code']; + $errors = []; + $found = ''; + $ignoreTokens = [\T_WHITESPACE => \T_WHITESPACE]; + if ($this->ignoreComments === \true) { + $ignoreTokens += Tokens::$commentTokens; + } + $origStackPtr = $stackPtr; + $hasError = \false; + if ($patternInfo['listen_pos'] > 0) { + $stackPtr--; + for ($i = $patternInfo['listen_pos'] - 1; $i >= 0; $i--) { + if ($pattern[$i]['type'] === 'token') { + if ($pattern[$i]['token'] === \T_WHITESPACE) { + if ($tokens[$stackPtr]['code'] === \T_WHITESPACE) { + $found = $tokens[$stackPtr]['content'] . $found; + } + // Only check the size of the whitespace if this is not + // the first token. We don't care about the size of + // leading whitespace, just that there is some. + if ($i !== 0) { + if ($tokens[$stackPtr]['content'] !== $pattern[$i]['value']) { + $hasError = \true; + } + } + } else { + // Check to see if this important token is the same as the + // previous important token in the pattern. If it is not, + // then the pattern cannot be for this piece of code. + $prev = $phpcsFile->findPrevious($ignoreTokens, $stackPtr, null, \true); + if ($prev === \false || $tokens[$prev]['code'] !== $pattern[$i]['token']) { + return \false; + } + // If we skipped past some whitespace tokens, then add them + // to the found string. + $tokenContent = $phpcsFile->getTokensAsString($prev + 1, $stackPtr - $prev - 1); + $found = $tokens[$prev]['content'] . $tokenContent . $found; + if (isset($pattern[$i - 1]) === \true && $pattern[$i - 1]['type'] === 'skip') { + $stackPtr = $prev; + } else { + $stackPtr = $prev - 1; + } + } + //end if + } else { + if ($pattern[$i]['type'] === 'skip') { + // Skip to next piece of relevant code. + if ($pattern[$i]['to'] === 'parenthesis_closer') { + $to = 'parenthesis_opener'; + } else { + $to = 'scope_opener'; + } + // Find the previous opener. + $next = $phpcsFile->findPrevious($ignoreTokens, $stackPtr, null, \true); + if ($next === \false || isset($tokens[$next][$to]) === \false) { + // If there was not opener, then we must be + // using the wrong pattern. + return \false; + } + if ($to === 'parenthesis_opener') { + $found = '{' . $found; + } else { + $found = '(' . $found; + } + $found = '...' . $found; + // Skip to the opening token. + $stackPtr = $tokens[$next][$to] - 1; + } else { + if ($pattern[$i]['type'] === 'string') { + $found = 'abc'; + } else { + if ($pattern[$i]['type'] === 'newline') { + if ($this->ignoreComments === \true && isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === \true) { + $startComment = $phpcsFile->findPrevious(Tokens::$commentTokens, $stackPtr - 1, null, \true); + if ($tokens[$startComment]['line'] !== $tokens[$startComment + 1]['line']) { + $startComment++; + } + $tokenContent = $phpcsFile->getTokensAsString($startComment, $stackPtr - $startComment + 1); + $found = $tokenContent . $found; + $stackPtr = $startComment - 1; + } + if ($tokens[$stackPtr]['code'] === \T_WHITESPACE) { + if ($tokens[$stackPtr]['content'] !== $phpcsFile->eolChar) { + $found = $tokens[$stackPtr]['content'] . $found; + // This may just be an indent that comes after a newline + // so check the token before to make sure. If it is a newline, we + // can ignore the error here. + if ($tokens[$stackPtr - 1]['content'] !== $phpcsFile->eolChar && ($this->ignoreComments === \true && isset(Tokens::$commentTokens[$tokens[$stackPtr - 1]['code']]) === \false)) { + $hasError = \true; + } else { + $stackPtr--; + } + } else { + $found = 'EOL' . $found; + } + } else { + $found = $tokens[$stackPtr]['content'] . $found; + $hasError = \true; + } + //end if + if ($hasError === \false && $pattern[$i - 1]['type'] !== 'newline') { + // Make sure they only have 1 newline. + $prev = $phpcsFile->findPrevious($ignoreTokens, $stackPtr - 1, null, \true); + if ($prev !== \false && $tokens[$prev]['line'] !== $tokens[$stackPtr]['line']) { + $hasError = \true; + } + } + } + } + } + } + //end if + } + //end for + } + //end if + $stackPtr = $origStackPtr; + $lastAddedStackPtr = null; + $patternLen = \count($pattern); + for ($i = $patternInfo['listen_pos']; $i < $patternLen; $i++) { + if (isset($tokens[$stackPtr]) === \false) { + break; + } + if ($pattern[$i]['type'] === 'token') { + if ($pattern[$i]['token'] === \T_WHITESPACE) { + if ($this->ignoreComments === \true) { + // If we are ignoring comments, check to see if this current + // token is a comment. If so skip it. + if (isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === \true) { + continue; + } + // If the next token is a comment, the we need to skip the + // current token as we should allow a space before a + // comment for readability. + if (isset($tokens[$stackPtr + 1]) === \true && isset(Tokens::$commentTokens[$tokens[$stackPtr + 1]['code']]) === \true) { + continue; + } + } + $tokenContent = ''; + if ($tokens[$stackPtr]['code'] === \T_WHITESPACE) { + if (isset($pattern[$i + 1]) === \false) { + // This is the last token in the pattern, so just compare + // the next token of content. + $tokenContent = $tokens[$stackPtr]['content']; + } else { + // Get all the whitespace to the next token. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr, null, \true); + $tokenContent = $phpcsFile->getTokensAsString($stackPtr, $next - $stackPtr); + $lastAddedStackPtr = $stackPtr; + $stackPtr = $next; + } + //end if + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $tokenContent; + } + } else { + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $tokens[$stackPtr]['content']; + $lastAddedStackPtr = $stackPtr; + } + } + //end if + if (isset($pattern[$i + 1]) === \true && $pattern[$i + 1]['type'] === 'skip') { + // The next token is a skip token, so we just need to make + // sure the whitespace we found has *at least* the + // whitespace required. + if (\strpos($tokenContent, $pattern[$i]['value']) !== 0) { + $hasError = \true; + } + } else { + if ($tokenContent !== $pattern[$i]['value']) { + $hasError = \true; + } + } + } else { + // Check to see if this important token is the same as the + // next important token in the pattern. If it is not, then + // the pattern cannot be for this piece of code. + $next = $phpcsFile->findNext($ignoreTokens, $stackPtr, null, \true); + if ($next === \false || $tokens[$next]['code'] !== $pattern[$i]['token']) { + // The next important token did not match the pattern. + return \false; + } + if ($lastAddedStackPtr !== null) { + if (($tokens[$next]['code'] === \T_OPEN_CURLY_BRACKET || $tokens[$next]['code'] === \T_CLOSE_CURLY_BRACKET) && isset($tokens[$next]['scope_condition']) === \true && $tokens[$next]['scope_condition'] > $lastAddedStackPtr) { + // This is a brace, but the owner of it is after the current + // token, which means it does not belong to any token in + // our pattern. This means the pattern is not for us. + return \false; + } + if (($tokens[$next]['code'] === \T_OPEN_PARENTHESIS || $tokens[$next]['code'] === \T_CLOSE_PARENTHESIS) && isset($tokens[$next]['parenthesis_owner']) === \true && $tokens[$next]['parenthesis_owner'] > $lastAddedStackPtr) { + // This is a bracket, but the owner of it is after the current + // token, which means it does not belong to any token in + // our pattern. This means the pattern is not for us. + return \false; + } + } + //end if + // If we skipped past some whitespace tokens, then add them + // to the found string. + if ($next - $stackPtr > 0) { + $hasComment = \false; + for ($j = $stackPtr; $j < $next; $j++) { + $found .= $tokens[$j]['content']; + if (isset(Tokens::$commentTokens[$tokens[$j]['code']]) === \true) { + $hasComment = \true; + } + } + // If we are not ignoring comments, this additional + // whitespace or comment is not allowed. If we are + // ignoring comments, there needs to be at least one + // comment for this to be allowed. + if ($this->ignoreComments === \false || $this->ignoreComments === \true && $hasComment === \false) { + $hasError = \true; + } + // Even when ignoring comments, we are not allowed to include + // newlines without the pattern specifying them, so + // everything should be on the same line. + if ($tokens[$next]['line'] !== $tokens[$stackPtr]['line']) { + $hasError = \true; + } + } + //end if + if ($next !== $lastAddedStackPtr) { + $found .= $tokens[$next]['content']; + $lastAddedStackPtr = $next; + } + if (isset($pattern[$i + 1]) === \true && $pattern[$i + 1]['type'] === 'skip') { + $stackPtr = $next; + } else { + $stackPtr = $next + 1; + } + } + //end if + } else { + if ($pattern[$i]['type'] === 'skip') { + if ($pattern[$i]['to'] === 'unknown') { + $next = $phpcsFile->findNext($pattern[$i + 1]['token'], $stackPtr); + if ($next === \false) { + // Couldn't find the next token, so we must + // be using the wrong pattern. + return \false; + } + $found .= '...'; + $stackPtr = $next; + } else { + // Find the previous opener. + $next = $phpcsFile->findPrevious(Tokens::$blockOpeners, $stackPtr); + if ($next === \false || isset($tokens[$next][$pattern[$i]['to']]) === \false) { + // If there was not opener, then we must + // be using the wrong pattern. + return \false; + } + $found .= '...'; + if ($pattern[$i]['to'] === 'parenthesis_closer') { + $found .= ')'; + } else { + $found .= '}'; + } + // Skip to the closing token. + $stackPtr = $tokens[$next][$pattern[$i]['to']] + 1; + } + //end if + } else { + if ($pattern[$i]['type'] === 'string') { + if ($tokens[$stackPtr]['code'] !== \T_STRING) { + $hasError = \true; + } + if ($stackPtr !== $lastAddedStackPtr) { + $found .= 'abc'; + $lastAddedStackPtr = $stackPtr; + } + $stackPtr++; + } else { + if ($pattern[$i]['type'] === 'newline') { + // Find the next token that contains a newline character. + $newline = 0; + for ($j = $stackPtr; $j < $phpcsFile->numTokens; $j++) { + if (\strpos($tokens[$j]['content'], $phpcsFile->eolChar) !== \false) { + $newline = $j; + break; + } + } + if ($newline === 0) { + // We didn't find a newline character in the rest of the file. + $next = $phpcsFile->numTokens - 1; + $hasError = \true; + } else { + if ($this->ignoreComments === \false) { + // The newline character cannot be part of a comment. + if (isset(Tokens::$commentTokens[$tokens[$newline]['code']]) === \true) { + $hasError = \true; + } + } + if ($newline === $stackPtr) { + $next = $stackPtr + 1; + } else { + // Check that there were no significant tokens that we + // skipped over to find our newline character. + $next = $phpcsFile->findNext($ignoreTokens, $stackPtr, null, \true); + if ($next < $newline) { + // We skipped a non-ignored token. + $hasError = \true; + } else { + $next = $newline + 1; + } + } + } + //end if + if ($stackPtr !== $lastAddedStackPtr) { + $found .= $phpcsFile->getTokensAsString($stackPtr, $next - $stackPtr); + $lastAddedStackPtr = $next - 1; + } + $stackPtr = $next; + } + } + } + } + //end if + } + //end for + if ($hasError === \true) { + $error = $this->prepareError($found, $patternCode); + $errors[$origStackPtr] = $error; + } + return $errors; + } + //end processPattern() + /** + * Prepares an error for the specified patternCode. + * + * @param string $found The actual found string in the code. + * @param string $patternCode The expected pattern code. + * + * @return string The error message. + */ + protected function prepareError($found, $patternCode) + { + $found = \str_replace("\r\n", '\\n', $found); + $found = \str_replace("\n", '\\n', $found); + $found = \str_replace("\r", '\\n', $found); + $found = \str_replace("\t", '\\t', $found); + $found = \str_replace('EOL', '\\n', $found); + $expected = \str_replace('EOL', '\\n', $patternCode); + $error = "Expected \"{$expected}\"; found \"{$found}\""; + return $error; + } + //end prepareError() + /** + * Returns the patterns that should be checked. + * + * @return string[] + */ + protected abstract function getPatterns(); + /** + * Registers any supplementary tokens that this test might wish to process. + * + * A sniff may wish to register supplementary tests when it wishes to group + * an arbitrary validation that cannot be performed using a pattern, with + * other pattern tests. + * + * @return int[] + * @see processSupplementary() + */ + protected function registerSupplementary() + { + return []; + } + //end registerSupplementary() + /** + * Processes any tokens registered with registerSupplementary(). + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where to + * process the skip. + * @param int $stackPtr The position in the tokens stack to + * process. + * + * @return void + * @see registerSupplementary() + */ + protected function processSupplementary(File $phpcsFile, $stackPtr) + { + } + //end processSupplementary() + /** + * Parses a pattern string into an array of pattern steps. + * + * @param string $pattern The pattern to parse. + * + * @return array The parsed pattern array. + * @see createSkipPattern() + * @see createTokenPattern() + */ + private function parse($pattern) + { + $patterns = []; + $length = \strlen($pattern); + $lastToken = 0; + $firstToken = 0; + for ($i = 0; $i < $length; $i++) { + $specialPattern = \false; + $isLastChar = $i === $length - 1; + $oldFirstToken = $firstToken; + if (\substr($pattern, $i, 3) === '...') { + // It's a skip pattern. The skip pattern requires the + // content of the token in the "from" position and the token + // to skip to. + $specialPattern = $this->createSkipPattern($pattern, $i - 1); + $lastToken = $i - $firstToken; + $firstToken = $i + 3; + $i += 2; + if ($specialPattern['to'] !== 'unknown') { + $firstToken++; + } + } else { + if (\substr($pattern, $i, 3) === 'abc') { + $specialPattern = ['type' => 'string']; + $lastToken = $i - $firstToken; + $firstToken = $i + 3; + $i += 2; + } else { + if (\substr($pattern, $i, 3) === 'EOL') { + $specialPattern = ['type' => 'newline']; + $lastToken = $i - $firstToken; + $firstToken = $i + 3; + $i += 2; + } + } + } + //end if + if ($specialPattern !== \false || $isLastChar === \true) { + // If we are at the end of the string, don't worry about a limit. + if ($isLastChar === \true) { + // Get the string from the end of the last skip pattern, if any, + // to the end of the pattern string. + $str = \substr($pattern, $oldFirstToken); + } else { + // Get the string from the end of the last special pattern, + // if any, to the start of this special pattern. + if ($lastToken === 0) { + // Note that if the last special token was zero characters ago, + // there will be nothing to process so we can skip this bit. + // This happens if you have something like: EOL... in your pattern. + $str = ''; + } else { + $str = \substr($pattern, $oldFirstToken, $lastToken); + } + } + if ($str !== '') { + $tokenPatterns = $this->createTokenPattern($str); + foreach ($tokenPatterns as $tokenPattern) { + $patterns[] = $tokenPattern; + } + } + // Make sure we don't skip the last token. + if ($isLastChar === \false && $i === $length - 1) { + $i--; + } + } + //end if + // Add the skip pattern *after* we have processed + // all the tokens from the end of the last skip pattern + // to the start of this skip pattern. + if ($specialPattern !== \false) { + $patterns[] = $specialPattern; + } + } + //end for + return $patterns; + } + //end parse() + /** + * Creates a skip pattern. + * + * @param string $pattern The pattern being parsed. + * @param string $from The token content that the skip pattern starts from. + * + * @return array The pattern step. + * @see createTokenPattern() + * @see parse() + */ + private function createSkipPattern($pattern, $from) + { + $skip = ['type' => 'skip']; + $nestedParenthesis = 0; + $nestedBraces = 0; + for ($start = $from; $start >= 0; $start--) { + switch ($pattern[$start]) { + case '(': + if ($nestedParenthesis === 0) { + $skip['to'] = 'parenthesis_closer'; + } + $nestedParenthesis--; + break; + case '{': + if ($nestedBraces === 0) { + $skip['to'] = 'scope_closer'; + } + $nestedBraces--; + break; + case '}': + $nestedBraces++; + break; + case ')': + $nestedParenthesis++; + break; + } + //end switch + if (isset($skip['to']) === \true) { + break; + } + } + //end for + if (isset($skip['to']) === \false) { + $skip['to'] = 'unknown'; + } + return $skip; + } + //end createSkipPattern() + /** + * Creates a token pattern. + * + * @param string $str The tokens string that the pattern should match. + * + * @return array The pattern step. + * @see createSkipPattern() + * @see parse() + */ + private function createTokenPattern($str) + { + // Don't add a space after the closing php tag as it will add a new + // whitespace token. + $tokenizer = new PHP('', null); + // Remove the getTokens(); + $tokens = \array_slice($tokens, 1, \count($tokens) - 2); + $patterns = []; + foreach ($tokens as $patternInfo) { + $patterns[] = ['type' => 'token', 'token' => $patternInfo['code'], 'value' => $patternInfo['content']]; + } + return $patterns; + } + //end createTokenPattern() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php new file mode 100644 index 00000000000..adde0a9ec26 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractScopeSniff.php @@ -0,0 +1,166 @@ + + * class ClassScopeTest extends PHP_CodeSniffer_Standards_AbstractScopeSniff + * { + * public function __construct() + * { + * parent::__construct(array(T_CLASS), array(T_FUNCTION)); + * } + * + * protected function processTokenWithinScope(\PHP_CodeSniffer\Files\File $phpcsFile, $stackPtr, $currScope) + * { + * $className = $phpcsFile->getDeclarationName($currScope); + * echo 'encountered a method within class '.$className; + * } + * } + * + * + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Exceptions\RuntimeException; +abstract class AbstractScopeSniff implements \PHP_CodeSniffer\Sniffs\Sniff +{ + /** + * The token types that this test wishes to listen to within the scope. + * + * @var array + */ + private $tokens = []; + /** + * The type of scope opener tokens that this test wishes to listen to. + * + * @var string + */ + private $scopeTokens = []; + /** + * True if this test should fire on tokens outside of the scope. + * + * @var boolean + */ + private $listenOutside = \false; + /** + * Constructs a new AbstractScopeTest. + * + * @param array $scopeTokens The type of scope the test wishes to listen to. + * @param array $tokens The tokens that the test wishes to listen to + * within the scope. + * @param boolean $listenOutside If true this test will also alert the + * extending class when a token is found outside + * the scope, by calling the + * processTokenOutsideScope method. + * + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If the specified tokens arrays are empty + * or invalid. + */ + public function __construct(array $scopeTokens, array $tokens, $listenOutside = \false) + { + if (empty($scopeTokens) === \true) { + $error = 'The scope tokens list cannot be empty'; + throw new RuntimeException($error); + } + if (empty($tokens) === \true) { + $error = 'The tokens list cannot be empty'; + throw new RuntimeException($error); + } + $invalidScopeTokens = \array_intersect($scopeTokens, $tokens); + if (empty($invalidScopeTokens) === \false) { + $invalid = \implode(', ', $invalidScopeTokens); + $error = "Scope tokens [{$invalid}] can't be in the tokens array"; + throw new RuntimeException($error); + } + $this->listenOutside = $listenOutside; + $this->scopeTokens = \array_flip($scopeTokens); + $this->tokens = $tokens; + } + //end __construct() + /** + * The method that is called to register the tokens this test wishes to + * listen to. + * + * DO NOT OVERRIDE THIS METHOD. Use the constructor of this class to register + * for the desired tokens and scope. + * + * @return int[] + * @see __constructor() + */ + public final function register() + { + return $this->tokens; + } + //end register() + /** + * Processes the tokens that this test is listening for. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + * @see processTokenWithinScope() + */ + public final function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $foundScope = \false; + $skipTokens = []; + foreach ($tokens[$stackPtr]['conditions'] as $scope => $code) { + if (isset($this->scopeTokens[$code]) === \true) { + $skipTokens[] = $this->processTokenWithinScope($phpcsFile, $stackPtr, $scope); + $foundScope = \true; + } + } + if ($this->listenOutside === \true && $foundScope === \false) { + $skipTokens[] = $this->processTokenOutsideScope($phpcsFile, $stackPtr); + } + if (empty($skipTokens) === \false) { + return \min($skipTokens); + } + return; + } + //end process() + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * @param int $currScope The position in the tokens array that + * opened the scope that this test is + * listening for. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected abstract function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope); + /** + * Processes a token that is found outside the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return (count($tokens) + 1) to skip + * the rest of the file. + */ + protected abstract function processTokenOutsideScope(File $phpcsFile, $stackPtr); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php new file mode 100644 index 00000000000..da5e3546120 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/AbstractVariableSniff.php @@ -0,0 +1,184 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Util\Tokens; +abstract class AbstractVariableSniff extends \PHP_CodeSniffer\Sniffs\AbstractScopeSniff +{ + /** + * List of PHP Reserved variables. + * + * Used by various naming convention sniffs. + * + * @var array + */ + protected $phpReservedVars = ['_SERVER' => \true, '_GET' => \true, '_POST' => \true, '_REQUEST' => \true, '_SESSION' => \true, '_ENV' => \true, '_COOKIE' => \true, '_FILES' => \true, 'GLOBALS' => \true, 'http_response_header' => \true, 'HTTP_RAW_POST_DATA' => \true, 'php_errormsg' => \true]; + /** + * Constructs an AbstractVariableTest. + */ + public function __construct() + { + $scopes = Tokens::$ooScopeTokens; + $listen = [\T_VARIABLE, \T_DOUBLE_QUOTED_STRING, \T_HEREDOC]; + parent::__construct($scopes, $listen, \true); + } + //end __construct() + /** + * Processes the token in the specified PHP_CodeSniffer\Files\File. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * @param int $currScope The current scope opener token. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected final function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr]['code'] === \T_DOUBLE_QUOTED_STRING || $tokens[$stackPtr]['code'] === \T_HEREDOC) { + // Check to see if this string has a variable in it. + $pattern = '|(?processVariableInString($phpcsFile, $stackPtr); + } + return; + } + // If this token is nested inside a function at a deeper + // level than the current OO scope that was found, it's a normal + // variable and not a member var. + $conditions = \array_reverse($tokens[$stackPtr]['conditions'], \true); + $inFunction = \false; + foreach ($conditions as $scope => $code) { + if (isset(Tokens::$ooScopeTokens[$code]) === \true) { + break; + } + if ($code === \T_FUNCTION || $code === \T_CLOSURE) { + $inFunction = \true; + } + } + if ($scope !== $currScope) { + // We found a closer scope to this token, so ignore + // this particular time through the sniff. We will process + // this token when this closer scope is found to avoid + // duplicate checks. + return; + } + // Just make sure this isn't a variable in a function declaration. + if ($inFunction === \false && isset($tokens[$stackPtr]['nested_parenthesis']) === \true) { + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $opener => $closer) { + if (isset($tokens[$opener]['parenthesis_owner']) === \false) { + // Check if this is a USE statement for a closure. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $opener - 1, null, \true); + if ($tokens[$prev]['code'] === \T_USE) { + $inFunction = \true; + break; + } + continue; + } + $owner = $tokens[$opener]['parenthesis_owner']; + if ($tokens[$owner]['code'] === \T_FUNCTION || $tokens[$owner]['code'] === \T_CLOSURE) { + $inFunction = \true; + break; + } + } + } + //end if + if ($inFunction === \true) { + return $this->processVariable($phpcsFile, $stackPtr); + } else { + return $this->processMemberVar($phpcsFile, $stackPtr); + } + } + //end processTokenWithinScope() + /** + * Processes the token outside the scope in the file. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected final function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + // These variables are not member vars. + if ($tokens[$stackPtr]['code'] === \T_VARIABLE) { + return $this->processVariable($phpcsFile, $stackPtr); + } else { + if ($tokens[$stackPtr]['code'] === \T_DOUBLE_QUOTED_STRING || $tokens[$stackPtr]['code'] === \T_HEREDOC) { + // Check to see if this string has a variable in it. + $pattern = '|(?processVariableInString($phpcsFile, $stackPtr); + } + } + } + } + //end processTokenOutsideScope() + /** + * Called to process class member vars. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected abstract function processMemberVar(File $phpcsFile, $stackPtr); + /** + * Called to process normal member vars. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the token was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected abstract function processVariable(File $phpcsFile, $stackPtr); + /** + * Called to process variables found in double quoted strings or heredocs. + * + * Note that there may be more than one variable in the string, which will + * result only in one call for the string or one call per line for heredocs. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where this + * token was found. + * @param int $stackPtr The position where the double quoted + * string was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return ($phpcsFile->numTokens + 1) to skip + * the rest of the file. + */ + protected abstract function processVariableInString(File $phpcsFile, $stackPtr); +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php b/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php new file mode 100644 index 00000000000..857280deb09 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Sniffs/Sniff.php @@ -0,0 +1,74 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Sniffs; + +use PHP_CodeSniffer\Files\File; +interface Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * An example return value for a sniff that wants to listen for whitespace + * and any comments would be: + * + * + * return array( + * T_WHITESPACE, + * T_DOC_COMMENT, + * T_COMMENT, + * ); + * + * + * @return mixed[] + * @see Tokens.php + */ + public function register(); + /** + * Called when one of the token types that this sniff is listening for + * is found. + * + * The stackPtr variable indicates where in the stack the token was found. + * A sniff can acquire information about this token, along with all the other + * tokens within the stack by first acquiring the token stack: + * + * + * $tokens = $phpcsFile->getTokens(); + * echo 'Encountered a '.$tokens[$stackPtr]['type'].' token'; + * echo 'token information: '; + * print_r($tokens[$stackPtr]); + * + * + * If the sniff discovers an anomaly in the code, they can raise an error + * by calling addError() on the \PHP_CodeSniffer\Files\File object, specifying an error + * message and the position of the offending token: + * + * + * $phpcsFile->addError('Encountered an error', $stackPtr); + * + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The PHP_CodeSniffer file where the + * token was found. + * @param int $stackPtr The position in the PHP_CodeSniffer + * file's token stack where the token + * was found. + * + * @return void|int Optionally returns a stack pointer. The sniff will not be + * called again on the current file until the returned stack + * pointer is reached. Return (count($tokens) + 1) to skip + * the rest of the file. + */ + public function process(File $phpcsFile, $stackPtr); +} +//end interface diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml new file mode 100644 index 00000000000..21b0d27d27d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowLongArraySyntaxStandard.xml @@ -0,0 +1,23 @@ + + + + + + + [ + 'foo' => 'bar', +]; + ]]> + + + array( + 'foo' => 'bar', +); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml new file mode 100644 index 00000000000..f24767ca508 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Arrays/DisallowShortArraySyntaxStandard.xml @@ -0,0 +1,23 @@ + + + + + + + array( + 'foo' => 'bar', +); + ]]> + + + [ + 'foo' => 'bar', +]; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml new file mode 100644 index 00000000000..4b0ec96d431 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/DuplicateClassNameStandard.xml @@ -0,0 +1,27 @@ + + + + + + + Foo +{ +} + ]]> + + + Foo +{ +} + +class Foo +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml new file mode 100644 index 00000000000..6fa08be7a45 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Classes/OpeningBraceSameLineStandard.xml @@ -0,0 +1,36 @@ + + + + + + + { +} + ]]> + + + { +} + ]]> + + + + + { +} + ]]> + + + // Start of class. +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml new file mode 100644 index 00000000000..9961ea054d9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/AssignmentInConditionStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $test === 'abc') { + // Code. +} + ]]> + + + $test = 'abc') { + // Code. +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml new file mode 100644 index 00000000000..c400d75e2fe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/EmptyStatementStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + // do nothing +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml new file mode 100644 index 00000000000..06f0b7a5b20 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopShouldBeWhileLoopStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $i = 0; $i < 10; $i++) { + echo "{$i}\n"; +} + ]]> + + + ;$test;) { + $test = doSomething(); +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml new file mode 100644 index 00000000000..f40d94bb128 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/ForLoopWithTestFunctionCallStandard.xml @@ -0,0 +1,24 @@ + + + + + + + $end = count($foo); +for ($i = 0; $i < $end; $i++) { + echo $foo[$i]."\n"; +} + ]]> + + + count($foo); $i++) { + echo $foo[$i]."\n"; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml new file mode 100644 index 00000000000..50f0782883b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/JumbledIncrementerStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $i++) { + for ($j = 0; $j < 10; $j++) { + } +} + ]]> + + + $i++) { + for ($j = 0; $j < 10; $i++) { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml new file mode 100644 index 00000000000..b2eaabe7924 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnconditionalIfStatementStandard.xml @@ -0,0 +1,39 @@ + + + + + + + $test) { + $var = 1; +} + ]]> + + + true) { + $var = 1; +} + ]]> + + + + + $test) { + $var = 1; +} + ]]> + + + false) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml new file mode 100644 index 00000000000..8936740776a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnnecessaryFinalModifierStandard.xml @@ -0,0 +1,29 @@ + + + + + + + + + + final function bar() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml new file mode 100644 index 00000000000..181dff4ee3c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UnusedFunctionParameterStandard.xml @@ -0,0 +1,25 @@ + + + + + + + $a + $b + $c; +} + ]]> + + + $a + $b; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml new file mode 100644 index 00000000000..ba8bd7e427e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/CodeAnalysis/UselessOverridingMethodStandard.xml @@ -0,0 +1,32 @@ + + + + + + + $this->doSomethingElse(); + } +} + ]]> + + + parent::bar(); + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml new file mode 100644 index 00000000000..174c6b0a83f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/FixmeStandard.xml @@ -0,0 +1,25 @@ + + + + + + + Handle strange case +if ($test) { + $var = 1; +} + ]]> + + + FIXME: This needs to be fixed! +if ($test) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml new file mode 100644 index 00000000000..c9c4fc06133 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Commenting/TodoStandard.xml @@ -0,0 +1,25 @@ + + + + + + + Handle strange case +if ($test) { + $var = 1; +} + ]]> + + + TODO: This needs to be fixed! +if ($test) { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml new file mode 100644 index 00000000000..570e4192b38 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/DisallowYodaConditionsStandard.xml @@ -0,0 +1,23 @@ + + + + + + + { + $var = 1; +} + ]]> + + + { + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml new file mode 100644 index 00000000000..06ae14b76c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/ControlStructures/InlineControlStructureStandard.xml @@ -0,0 +1,22 @@ + + + + + + + { + $var = 1; +} + ]]> + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml new file mode 100644 index 00000000000..b57a970685f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/CSSLintStandard.xml @@ -0,0 +1,19 @@ + + + + + + + %; } + ]]> + + + %; } + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml new file mode 100644 index 00000000000..9df9aec4894 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/ClosureLinterStandard.xml @@ -0,0 +1,19 @@ + + + + + + + ]; + ]]> + + + ,]; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml new file mode 100644 index 00000000000..7525e9e6bfe --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Debug/JSHintStandard.xml @@ -0,0 +1,19 @@ + + + + + + + var foo = 5; + ]]> + + + foo = 5; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml new file mode 100644 index 00000000000..88591f92519 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ByteOrderMarkStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml new file mode 100644 index 00000000000..aa757edc65d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNewlineStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml new file mode 100644 index 00000000000..227d5621a00 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/EndFileNoNewlineStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml new file mode 100644 index 00000000000..6114f24c584 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/ExecutableFileStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml new file mode 100644 index 00000000000..3fbf5024dbc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/InlineHTMLStandard.xml @@ -0,0 +1,24 @@ + + + + + + + + + + some string here + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml new file mode 100644 index 00000000000..eb4508fda94 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineEndingsStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml new file mode 100644 index 00000000000..31342e3c92d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LineLengthStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml new file mode 100644 index 00000000000..a1be34cb028 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/LowercasedFilenameStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml new file mode 100644 index 00000000000..7b5857633d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneClassPerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + class Foo +{ +} + ]]> + + + class Foo +{ +} + +class Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml new file mode 100644 index 00000000000..de975319a8d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneInterfacePerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + interface Foo +{ +} + ]]> + + + interface Foo +{ +} + +interface Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml new file mode 100644 index 00000000000..4d957e7017f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneObjectStructurePerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + trait Foo +{ +} + ]]> + + + trait Foo +{ +} + +class Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml new file mode 100644 index 00000000000..58a6482f18d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Files/OneTraitPerFileStandard.xml @@ -0,0 +1,29 @@ + + + + + + + trait Foo +{ +} + ]]> + + + trait Foo +{ +} + +trait Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml new file mode 100644 index 00000000000..f0d4490c339 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/DisallowMultipleStatementsStandard.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml new file mode 100644 index 00000000000..4c33d763d91 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/MultipleStatementAlignmentStandard.xml @@ -0,0 +1,56 @@ + + + + + + + = (1 + 2); +$veryLongVarName = 'string'; +$var = foo($bar, $baz); + ]]> + + + = (1 + 2); +$veryLongVarName = 'string'; +$var = foo($bar, $baz); + ]]> + + + + + + + + += 1; +$veryLongVarName = 1; + ]]> + + + += 1; +$veryLongVarName = 1; + ]]> + + + + + = 1; +$veryLongVarName -= 1; + ]]> + + + = 1; +$veryLongVarName -= 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml new file mode 100644 index 00000000000..042e4f8033f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/NoSpaceAfterCastStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml new file mode 100644 index 00000000000..75eba77cbfc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterCastStandard.xml @@ -0,0 +1,19 @@ + + + + + + + 1; + ]]> + + + 1; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml new file mode 100644 index 00000000000..aea863695e9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Formatting/SpaceAfterNotStandard.xml @@ -0,0 +1,22 @@ + + + + + + + $someVar || ! $x instanceOf stdClass) {}; + ]]> + + + $someVar || !$x instanceOf stdClass) {}; + +if (! $someVar || ! + $x instanceOf stdClass) {}; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml new file mode 100644 index 00000000000..738998d4326 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/CallTimePassByReferenceStandard.xml @@ -0,0 +1,31 @@ + + + + + + + &$bar) +{ + $bar++; +} + +$baz = 1; +foo($baz); + ]]> + + + &$baz); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml new file mode 100644 index 00000000000..9809844d8d7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/FunctionCallArgumentSpacingStandard.xml @@ -0,0 +1,39 @@ + + + + + + + $baz) +{ +} + ]]> + + + $baz) +{ +} + ]]> + + + + + = true) +{ +} + ]]> + + + =true) +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml new file mode 100644 index 00000000000..414dc289ef4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceBsdAllmanStandard.xml @@ -0,0 +1,24 @@ + + + + + + + { + ... +} + ]]> + + + { + ... +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml new file mode 100644 index 00000000000..84c2bdd869a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Functions/OpeningFunctionBraceKernighanRitchieStandard.xml @@ -0,0 +1,24 @@ + + + + + + + { + ... +} + ]]> + + + { + ... +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml new file mode 100644 index 00000000000..a928e7db1e9 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/CyclomaticComplexityStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml new file mode 100644 index 00000000000..f66cd92c96c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Metrics/NestingLevelStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml new file mode 100644 index 00000000000..c30d26e9d5e --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/AbstractClassNamePrefixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + AbstractBar +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml new file mode 100644 index 00000000000..f5345b7122f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/CamelCapsFunctionNameStandard.xml @@ -0,0 +1,23 @@ + + + + + + + doSomething() +{ +} + ]]> + + + do_something() +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml new file mode 100644 index 00000000000..9dfc175ff43 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/ConstructorNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + __construct() + { + } +} + ]]> + + + Foo() + { + } +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml new file mode 100644 index 00000000000..0aa0c76e4df --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/InterfaceNameSuffixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + BarInterface +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml new file mode 100644 index 00000000000..711867e4513 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/TraitNameSuffixStandard.xml @@ -0,0 +1,23 @@ + + + + + + + BarTrait +{ +} + ]]> + + + Bar +{ +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml new file mode 100644 index 00000000000..6ef61b93c97 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/NamingConventions/UpperCaseConstantNameStandard.xml @@ -0,0 +1,29 @@ + + + + + + + FOO_CONSTANT', 'foo'); + +class FooClass +{ + const FOO_CONSTANT = 'foo'; +} + ]]> + + + Foo_Constant', 'foo'); + +class FooClass +{ + const foo_constant = 'foo'; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml new file mode 100644 index 00000000000..4ebd6770490 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/BacktickOperatorStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml new file mode 100644 index 00000000000..df5a0eba4c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/CharacterBeforePHPOpeningTagStandard.xml @@ -0,0 +1,22 @@ + + + + + + + + + + Beginning content + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml new file mode 100644 index 00000000000..09afb2d75a7 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ClosingPHPTagStandard.xml @@ -0,0 +1,22 @@ + + + + + + + +echo 'Foo'; +?> + ]]> + + + +echo 'Foo'; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml new file mode 100644 index 00000000000..33b803a75b5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DeprecatedFunctionsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + explode('a', $bar); + ]]> + + + split('a', $bar); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml new file mode 100644 index 00000000000..bdfd5dc16aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowAlternativePHPTagsStandard.xml @@ -0,0 +1,7 @@ + + + to delimit PHP code, do not use the ASP <% %> style tags nor the tags. This is the most portable way to include PHP code on differing operating systems and setups. + ]]> + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml new file mode 100644 index 00000000000..f94769427c8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowRequestSuperglobalStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml new file mode 100644 index 00000000000..8086ea271aa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DisallowShortOpenTagStandard.xml @@ -0,0 +1,7 @@ + + + to delimit PHP code, not the shorthand. This is the most portable way to include PHP code on differing operating systems and setups. + ]]> + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml new file mode 100644 index 00000000000..83bceef40d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/DiscourageGotoStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml new file mode 100644 index 00000000000..c0f18b55770 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/ForbiddenFunctionsStandard.xml @@ -0,0 +1,19 @@ + + + + + + + count($bar); + ]]> + + + sizeof($bar); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml new file mode 100644 index 00000000000..7dc30c10d55 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseConstantStandard.xml @@ -0,0 +1,23 @@ + + + true, false and null constants must always be lowercase. + ]]> + + + + false || $var === null) { + $var = true; +} + ]]> + + + FALSE || $var === NULL) { + $var = TRUE; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml new file mode 100644 index 00000000000..965742d945c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseKeywordStandard.xml @@ -0,0 +1,19 @@ + + + + + + + array(); + ]]> + + + Array(); + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml new file mode 100644 index 00000000000..f38df3af56c --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/LowerCaseTypeStandard.xml @@ -0,0 +1,38 @@ + + + + + + + + + + Int $foo) : STRING { +} + ]]> + + + + + + + + + + + (BOOL) $isValid; + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml new file mode 100644 index 00000000000..31770707c35 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/NoSilencedErrorsStandard.xml @@ -0,0 +1,23 @@ + + + + + + + isset($foo) && $foo) { + echo "ECSPrefix202307\Hello\n"; +} + ]]> + + + @$foo) { + echo "ECSPrefix202307\Hello\n"; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml new file mode 100644 index 00000000000..e74005ad12d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/SAPIUsageStandard.xml @@ -0,0 +1,23 @@ + + + + + + + PHP_SAPI === 'cli') { + echo "Hello, CLI user."; +} + ]]> + + + php_sapi_name() === 'cli') { + echo "Hello, CLI user."; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml new file mode 100644 index 00000000000..1f337f77ed5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/PHP/UpperCaseConstantStandard.xml @@ -0,0 +1,23 @@ + + + true, false and null constants must always be uppercase. + ]]> + + + + FALSE || $var === NULL) { + $var = TRUE; +} + ]]> + + + false || $var === null) { + $var = true; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml new file mode 100644 index 00000000000..a4c9887b283 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/Strings/UnnecessaryStringConcatStandard.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml new file mode 100644 index 00000000000..f4f3e19cb5f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/VersionControl/SubversionPropertiesStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml new file mode 100644 index 00000000000..338c8389336 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ArbitraryParenthesesSpacingStandard.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml new file mode 100644 index 00000000000..2e399b34b4d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowSpaceIndentStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml new file mode 100644 index 00000000000..7013ffd90ee --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/DisallowTabIndentStandard.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml new file mode 100644 index 00000000000..bdd36d498ef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/ScopeIndentStandard.xml @@ -0,0 +1,23 @@ + + + + + + + $var = 1; +} + ]]> + + + $var = 1; +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml new file mode 100644 index 00000000000..d33b6051d4f --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Docs/WhiteSpace/SpreadOperatorSpacingAfterStandard.xml @@ -0,0 +1,34 @@ + + + + + + + &...$spread) { + bar(...$spread); + + bar( + [...$foo], + ...array_values($keyedArray) + ); +} + ]]> + + + ... $spread) { + bar(... + $spread + ); + + bar( + [... $foo ],.../*comment*/array_values($keyedArray) + ); +} + ]]> + + + diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php new file mode 100644 index 00000000000..e6b1d39fe12 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/ArrayIndentSniff.php @@ -0,0 +1,147 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Sniffs\AbstractArraySniff; +use PHP_CodeSniffer\Util\Tokens; +class ArrayIndentSniff extends AbstractArraySniff +{ + /** + * The number of spaces each array key should be indented. + * + * @var integer + */ + public $indent = 4; + /** + * Processes a single-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processSingleLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + } + //end processSingleLineArray() + /** + * Processes a multi-line array definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being checked. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $arrayStart The token that starts the array definition. + * @param int $arrayEnd The token that ends the array definition. + * @param array $indices An array of token positions for the array keys, + * double arrows, and values. + * + * @return void + */ + public function processMultiLineArray($phpcsFile, $stackPtr, $arrayStart, $arrayEnd, $indices) + { + $tokens = $phpcsFile->getTokens(); + // Determine how far indented the entire array declaration should be. + $ignore = Tokens::$emptyTokens; + $ignore[] = \T_DOUBLE_ARROW; + $ignore[] = \T_COMMA; + $prev = $phpcsFile->findPrevious($ignore, $stackPtr - 1, null, \true); + $start = $phpcsFile->findStartOfStatement($prev); + $first = $phpcsFile->findFirstOnLine(\T_WHITESPACE, $start, \true); + $baseIndent = $tokens[$first]['column'] - 1; + $first = $phpcsFile->findFirstOnLine(\T_WHITESPACE, $stackPtr, \true); + $startIndent = $tokens[$first]['column'] - 1; + // If the open brace is not indented to at least to the level of the start + // of the statement, the sniff will conflict with other sniffs trying to + // check indent levels because it's not valid. But we don't enforce exactly + // how far indented it should be. + if ($startIndent < $baseIndent) { + $error = 'Array open brace not indented correctly; expected at least %s spaces but found %s'; + $data = [$baseIndent, $startIndent]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'OpenBraceIncorrect', $data); + if ($fix === \true) { + $padding = \str_repeat(' ', $baseIndent); + if ($startIndent === 0) { + $phpcsFile->fixer->addContentBefore($first, $padding); + } else { + $phpcsFile->fixer->replaceToken($first - 1, $padding); + } + } + return; + } + //end if + $expectedIndent = $startIndent + $this->indent; + foreach ($indices as $index) { + if (isset($index['index_start']) === \true) { + $start = $index['index_start']; + } else { + $start = $index['value_start']; + } + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $start - 1, null, \true); + if ($tokens[$prev]['line'] === $tokens[$start]['line']) { + // This index isn't the only content on the line + // so we can't check indent rules. + continue; + } + $first = $phpcsFile->findFirstOnLine(\T_WHITESPACE, $start, \true); + $foundIndent = $tokens[$first]['column'] - 1; + if ($foundIndent === $expectedIndent) { + continue; + } + $error = 'Array key not indented correctly; expected %s spaces but found %s'; + $data = [$expectedIndent, $foundIndent]; + $fix = $phpcsFile->addFixableError($error, $first, 'KeyIncorrect', $data); + if ($fix === \false) { + continue; + } + $padding = \str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($first, $padding); + } else { + $phpcsFile->fixer->replaceToken($first - 1, $padding); + } + } + //end foreach + $prev = $phpcsFile->findPrevious(\T_WHITESPACE, $arrayEnd - 1, null, \true); + if ($tokens[$prev]['line'] === $tokens[$arrayEnd]['line']) { + $error = 'Closing brace of array declaration must be on a new line'; + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceNotNewLine'); + if ($fix === \true) { + $padding = $phpcsFile->eolChar . \str_repeat(' ', $expectedIndent); + $phpcsFile->fixer->addContentBefore($arrayEnd, $padding); + } + return; + } + // The close brace must be indented one stop less. + $expectedIndent -= $this->indent; + $foundIndent = $tokens[$arrayEnd]['column'] - 1; + if ($foundIndent === $expectedIndent) { + return; + } + $error = 'Array close brace not indented correctly; expected %s spaces but found %s'; + $data = [$expectedIndent, $foundIndent]; + $fix = $phpcsFile->addFixableError($error, $arrayEnd, 'CloseBraceIncorrect', $data); + if ($fix === \false) { + return; + } + $padding = \str_repeat(' ', $expectedIndent); + if ($foundIndent === 0) { + $phpcsFile->fixer->addContentBefore($arrayEnd, $padding); + } else { + $phpcsFile->fixer->replaceToken($arrayEnd - 1, $padding); + } + } + //end processMultiLineArray() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php new file mode 100644 index 00000000000..add14a8f727 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowLongArraySyntaxSniff.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DisallowLongArraySyntaxSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_ARRAY]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'no'); + $error = 'Short array syntax must be used to define arrays'; + if (isset($tokens[$stackPtr]['parenthesis_opener']) === \false || isset($tokens[$stackPtr]['parenthesis_closer']) === \false) { + // Live coding/parse error, just show the error, don't try and fix it. + $phpcsFile->addError($error, $stackPtr, 'Found'); + return; + } + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + if ($fix === \true) { + $opener = $tokens[$stackPtr]['parenthesis_opener']; + $closer = $tokens[$stackPtr]['parenthesis_closer']; + $phpcsFile->fixer->beginChangeset(); + if ($opener === null) { + $phpcsFile->fixer->replaceToken($stackPtr, '[]'); + } else { + $phpcsFile->fixer->replaceToken($stackPtr, ''); + $phpcsFile->fixer->replaceToken($opener, '['); + $phpcsFile->fixer->replaceToken($closer, ']'); + } + $phpcsFile->fixer->endChangeset(); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php new file mode 100644 index 00000000000..dae2fc4c170 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Arrays/DisallowShortArraySyntaxSniff.php @@ -0,0 +1,52 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Arrays; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DisallowShortArraySyntaxSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_SHORT_ARRAY]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $phpcsFile->recordMetric($stackPtr, 'Short array syntax used', 'yes'); + $error = 'Short array syntax is not allowed'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + if ($fix === \true) { + $tokens = $phpcsFile->getTokens(); + $opener = $tokens[$stackPtr]['bracket_opener']; + $closer = $tokens[$stackPtr]['bracket_closer']; + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->replaceToken($opener, 'array('); + $phpcsFile->fixer->replaceToken($closer, ')'); + $phpcsFile->fixer->endChangeset(); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php new file mode 100644 index 00000000000..8603f3102f6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/DuplicateClassNameSniff.php @@ -0,0 +1,83 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DuplicateClassNameSniff implements Sniff +{ + /** + * List of classes that have been found during checking. + * + * @var array + */ + protected $foundClasses = []; + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $namespace = ''; + $findTokens = [\T_CLASS, \T_INTERFACE, \T_TRAIT, \T_ENUM, \T_NAMESPACE, \T_CLOSE_TAG]; + $stackPtr = $phpcsFile->findNext($findTokens, $stackPtr + 1); + while ($stackPtr !== \false) { + if ($tokens[$stackPtr]['code'] === \T_CLOSE_TAG) { + // We can stop here. The sniff will continue from the next open + // tag when PHPCS reaches that token, if there is one. + return; + } + // Keep track of what namespace we are in. + if ($tokens[$stackPtr]['code'] === \T_NAMESPACE) { + $nsEnd = $phpcsFile->findNext([\T_NS_SEPARATOR, \T_STRING, \T_WHITESPACE], $stackPtr + 1, null, \true); + $namespace = \trim($phpcsFile->getTokensAsString($stackPtr + 1, $nsEnd - $stackPtr - 1)); + $stackPtr = $nsEnd; + } else { + $nameToken = $phpcsFile->findNext(\T_STRING, $stackPtr); + $name = $tokens[$nameToken]['content']; + if ($namespace !== '') { + $name = $namespace . '\\' . $name; + } + $compareName = \strtolower($name); + if (isset($this->foundClasses[$compareName]) === \true) { + $type = \strtolower($tokens[$stackPtr]['content']); + $file = $this->foundClasses[$compareName]['file']; + $line = $this->foundClasses[$compareName]['line']; + $error = 'Duplicate %s name "%s" found; first defined in %s on line %s'; + $data = [$type, $name, $file, $line]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } else { + $this->foundClasses[$compareName] = ['file' => $phpcsFile->getFilename(), 'line' => $tokens[$stackPtr]['line']]; + } + } + //end if + $stackPtr = $phpcsFile->findNext($findTokens, $stackPtr + 1); + } + //end while + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php new file mode 100644 index 00000000000..27a83a37dac --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Classes/OpeningBraceSameLineSniff.php @@ -0,0 +1,106 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Classes; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class OpeningBraceSameLineSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_CLASS, \T_INTERFACE, \T_TRAIT, \T_ENUM]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $scopeIdentifier = $phpcsFile->findNext(\T_STRING, $stackPtr + 1); + $errorData = [\strtolower($tokens[$stackPtr]['content']) . ' ' . $tokens[$scopeIdentifier]['content']]; + if (isset($tokens[$stackPtr]['scope_opener']) === \false) { + $error = 'Possible parse error: %s missing opening or closing brace'; + $phpcsFile->addWarning($error, $stackPtr, 'MissingBrace', $errorData); + return; + } + $openingBrace = $tokens[$stackPtr]['scope_opener']; + // Is the brace on the same line as the class/interface/trait declaration ? + $lastClassLineToken = $phpcsFile->findPrevious(\T_WHITESPACE, $openingBrace - 1, $stackPtr, \true); + $lastClassLine = $tokens[$lastClassLineToken]['line']; + $braceLine = $tokens[$openingBrace]['line']; + $lineDifference = $braceLine - $lastClassLine; + if ($lineDifference > 0) { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'new line'); + $error = 'Opening brace should be on the same line as the declaration for %s'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnNewLine', $errorData); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($lastClassLineToken, ' {'); + $phpcsFile->fixer->replaceToken($openingBrace, ''); + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Class opening brace placement', 'same line'); + } + // Is the opening brace the last thing on the line ? + $next = $phpcsFile->findNext(\T_WHITESPACE, $openingBrace + 1, null, \true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + if ($next === $tokens[$stackPtr]['scope_closer']) { + // Ignore empty classes. + return; + } + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === \true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + // Only continue checking if the opening brace looks good. + if ($lineDifference > 0) { + return; + } + // Is there precisely one space before the opening brace ? + if ($tokens[$openingBrace - 1]['code'] !== \T_WHITESPACE) { + $length = 0; + } else { + if ($tokens[$openingBrace - 1]['content'] === "\t") { + $length = '\\t'; + } else { + $length = $tokens[$openingBrace - 1]['length']; + } + } + if ($length !== 1) { + $error = 'Expected 1 space before opening brace; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'SpaceBeforeBrace', $data); + if ($fix === \true) { + if ($length === 0 || $length === '\\t') { + $phpcsFile->fixer->addContentBefore($openingBrace, ' '); + } else { + $phpcsFile->fixer->replaceToken($openingBrace - 1, ' '); + } + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php new file mode 100644 index 00000000000..541d1ee6452 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/AssignmentInConditionSniff.php @@ -0,0 +1,135 @@ + + * @copyright 2017 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class AssignmentInConditionSniff implements Sniff +{ + /** + * Assignment tokens to trigger on. + * + * Set in the register() method. + * + * @var array + */ + protected $assignmentTokens = []; + /** + * The tokens that indicate the start of a condition. + * + * @var array + */ + protected $conditionStartTokens = []; + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + $this->assignmentTokens = Tokens::$assignmentTokens; + unset($this->assignmentTokens[\T_DOUBLE_ARROW]); + $starters = Tokens::$booleanOperators; + $starters[\T_SEMICOLON] = \T_SEMICOLON; + $starters[\T_OPEN_PARENTHESIS] = \T_OPEN_PARENTHESIS; + $this->conditionStartTokens = $starters; + return [\T_IF, \T_ELSEIF, \T_FOR, \T_SWITCH, \T_CASE, \T_WHILE, \T_MATCH]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Find the condition opener/closer. + if ($token['code'] === \T_FOR) { + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === \false) { + return; + } + $semicolon = $phpcsFile->findNext(\T_SEMICOLON, $token['parenthesis_opener'] + 1, $token['parenthesis_closer']); + if ($semicolon === \false) { + return; + } + $opener = $semicolon; + $semicolon = $phpcsFile->findNext(\T_SEMICOLON, $opener + 1, $token['parenthesis_closer']); + if ($semicolon === \false) { + return; + } + $closer = $semicolon; + unset($semicolon); + } else { + if ($token['code'] === \T_CASE) { + if (isset($token['scope_opener']) === \false) { + return; + } + $opener = $stackPtr; + $closer = $token['scope_opener']; + } else { + if (isset($token['parenthesis_opener'], $token['parenthesis_closer']) === \false) { + return; + } + $opener = $token['parenthesis_opener']; + $closer = $token['parenthesis_closer']; + } + } + //end if + $startPos = $opener; + do { + $hasAssignment = $phpcsFile->findNext($this->assignmentTokens, $startPos + 1, $closer); + if ($hasAssignment === \false) { + return; + } + // Examine whether the left side is a variable. + $hasVariable = \false; + $conditionStart = $startPos; + $altConditionStart = $phpcsFile->findPrevious($this->conditionStartTokens, $hasAssignment - 1, $startPos); + if ($altConditionStart !== \false) { + $conditionStart = $altConditionStart; + } + for ($i = $hasAssignment; $i > $conditionStart; $i--) { + if (isset(Tokens::$emptyTokens[$tokens[$i]['code']]) === \true) { + continue; + } + // If this is a variable or array, we've seen all we need to see. + if ($tokens[$i]['code'] === \T_VARIABLE || $tokens[$i]['code'] === \T_CLOSE_SQUARE_BRACKET) { + $hasVariable = \true; + break; + } + // If this is a function call or something, we are OK. + if ($tokens[$i]['code'] === \T_CLOSE_PARENTHESIS) { + break; + } + } + if ($hasVariable === \true) { + $errorCode = 'Found'; + if ($token['code'] === \T_WHILE) { + $errorCode = 'FoundInWhileCondition'; + } + $phpcsFile->addWarning('Variable assignment found within a condition. Did you mean to do a comparison ?', $hasAssignment, $errorCode); + } + $startPos = $hasAssignment; + } while ($startPos < $closer); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php new file mode 100644 index 00000000000..be27b4317db --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php @@ -0,0 +1,115 @@ + + * @copyright 2017 Juliette Reinders Folmer. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class EmptyPHPStatementSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_SEMICOLON, \T_CLOSE_TAG]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + switch ($tokens[$stackPtr]['type']) { + // Detect `something();;`. + case 'T_SEMICOLON': + $prevNonEmpty = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, \true); + if ($prevNonEmpty === \false) { + return; + } + if ($tokens[$prevNonEmpty]['code'] !== \T_SEMICOLON && $tokens[$prevNonEmpty]['code'] !== \T_OPEN_TAG && $tokens[$prevNonEmpty]['code'] !== \T_OPEN_TAG_WITH_ECHO) { + if (isset($tokens[$prevNonEmpty]['scope_condition']) === \false) { + return; + } + if ($tokens[$prevNonEmpty]['scope_opener'] !== $prevNonEmpty && $tokens[$prevNonEmpty]['code'] !== \T_CLOSE_CURLY_BRACKET) { + return; + } + $scopeOwner = $tokens[$tokens[$prevNonEmpty]['scope_condition']]['code']; + if ($scopeOwner === \T_CLOSURE || $scopeOwner === \T_ANON_CLASS || $scopeOwner === \T_MATCH) { + return; + } + // Else, it's something like `if (foo) {};` and the semi-colon is not needed. + } + if (isset($tokens[$stackPtr]['nested_parenthesis']) === \true) { + $nested = $tokens[$stackPtr]['nested_parenthesis']; + $lastCloser = \array_pop($nested); + if (isset($tokens[$lastCloser]['parenthesis_owner']) === \true && $tokens[$tokens[$lastCloser]['parenthesis_owner']]['code'] === \T_FOR) { + // Empty for() condition. + return; + } + } + $fix = $phpcsFile->addFixableWarning('Empty PHP statement detected: superfluous semi-colon.', $stackPtr, 'SemicolonWithoutCodeDetected'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + if ($tokens[$prevNonEmpty]['code'] === \T_OPEN_TAG || $tokens[$prevNonEmpty]['code'] === \T_OPEN_TAG_WITH_ECHO) { + // Check for superfluous whitespace after the semi-colon which will be + // removed as the `fixer->replaceToken($stackPtr + 1, $replacement); + } + } + for ($i = $stackPtr; $i > $prevNonEmpty; $i--) { + if ($tokens[$i]['code'] !== \T_SEMICOLON && $tokens[$i]['code'] !== \T_WHITESPACE) { + break; + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + //end if + break; + // Detect ``. + case 'T_CLOSE_TAG': + $prevNonEmpty = $phpcsFile->findPrevious(\T_WHITESPACE, $stackPtr - 1, null, \true); + if ($prevNonEmpty === \false || $tokens[$prevNonEmpty]['code'] !== \T_OPEN_TAG && $tokens[$prevNonEmpty]['code'] !== \T_OPEN_TAG_WITH_ECHO) { + return; + } + $fix = $phpcsFile->addFixableWarning('Empty PHP open/close tag combination detected.', $prevNonEmpty, 'EmptyPHPOpenCloseTagsDetected'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $prevNonEmpty; $i <= $stackPtr; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + break; + default: + // Deliberately left empty. + break; + } + //end switch + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php new file mode 100644 index 00000000000..f87eb64e9f3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyStatementSniff.php @@ -0,0 +1,69 @@ + + * stmt { + * // foo + * } + * stmt (conditions) { + * // foo + * } + * + * + * @author Manuel Pichler + * @author Greg Sherwood + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class EmptyStatementSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_TRY, \T_CATCH, \T_FINALLY, \T_DO, \T_ELSE, \T_ELSEIF, \T_FOR, \T_FOREACH, \T_IF, \T_SWITCH, \T_WHILE, \T_MATCH]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip statements without a body. + if (isset($token['scope_opener']) === \false) { + return; + } + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $token['scope_opener'] + 1, $token['scope_closer'] - 1, \true); + if ($next !== \false) { + return; + } + // Get token identifier. + $name = \strtoupper($token['content']); + $error = 'Empty %s statement detected'; + $phpcsFile->addError($error, $stackPtr, 'Detected' . \ucfirst(\strtolower($name)), [$name]); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php new file mode 100644 index 00000000000..10fdb898ea8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopShouldBeWhileLoopSniff.php @@ -0,0 +1,78 @@ + + * class Foo + * { + * public function bar($x) + * { + * for (;true;) true; // No Init or Update part, may as well be: while (true) + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class ForLoopShouldBeWhileLoopSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_FOR]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip invalid statement. + if (isset($token['parenthesis_opener']) === \false) { + return; + } + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + $parts = [0, 0, 0]; + $index = 0; + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === \T_SEMICOLON) { + ++$index; + } else { + if (isset(Tokens::$emptyTokens[$code]) === \false) { + ++$parts[$index]; + } + } + } + if ($parts[0] === 0 && $parts[2] === 0 && $parts[1] > 0) { + $error = 'This FOR loop can be simplified to a WHILE loop'; + $phpcsFile->addWarning($error, $stackPtr, 'CanSimplify'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php new file mode 100644 index 00000000000..2b5ba528ecd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/ForLoopWithTestFunctionCallSniff.php @@ -0,0 +1,93 @@ + + * class Foo + * { + * public function bar($x) + * { + * $a = array(1, 2, 3, 4); + * for ($i = 0; $i < count($a); $i++) { + * $a[$i] *= $i; + * } + * } + * } + * + * + * @author Greg Sherwood + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class ForLoopWithTestFunctionCallSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_FOR]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip invalid statement. + if (isset($token['parenthesis_opener']) === \false) { + return; + } + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + $position = 0; + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === \T_SEMICOLON) { + ++$position; + } + if ($position < 1) { + continue; + } else { + if ($position > 1) { + break; + } else { + if ($code !== \T_VARIABLE && $code !== \T_STRING) { + continue; + } + } + } + // Find next non empty token, if it is a open curly brace we have a + // function call. + $index = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + if ($tokens[$index]['code'] === \T_OPEN_PARENTHESIS) { + $error = 'Avoid function calls in a FOR loop test part'; + $phpcsFile->addWarning($error, $stackPtr, 'NotAllowed'); + break; + } + } + //end for + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php new file mode 100644 index 00000000000..8aae66f3d17 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/JumbledIncrementerSniff.php @@ -0,0 +1,118 @@ + + * class Foo + * { + * public function bar($x) + * { + * for ($i = 0; $i < 10; $i++) + * { + * for ($k = 0; $k < 20; $i++) + * { + * echo 'Hello'; + * } + * } + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class JumbledIncrementerSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_FOR]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip for-loop without body. + if (isset($token['scope_opener']) === \false) { + return; + } + // Find incrementors for outer loop. + $outer = $this->findIncrementers($tokens, $token); + // Skip if empty. + if (\count($outer) === 0) { + return; + } + // Find nested for loops. + $start = ++$token['scope_opener']; + $end = --$token['scope_closer']; + for (; $start <= $end; ++$start) { + if ($tokens[$start]['code'] !== \T_FOR) { + continue; + } + $inner = $this->findIncrementers($tokens, $tokens[$start]); + $diff = \array_intersect($outer, $inner); + if (\count($diff) !== 0) { + $error = 'Loop incrementor (%s) jumbling with inner loop'; + $data = [\join(', ', $diff)]; + $phpcsFile->addWarning($error, $stackPtr, 'Found', $data); + } + } + } + //end process() + /** + * Get all used variables in the incrementer part of a for statement. + * + * @param array(integer=>array) $tokens Array with all code sniffer tokens. + * @param array(string=>mixed) $token Current for loop token + * + * @return string[] List of all found incrementer variables. + */ + protected function findIncrementers(array $tokens, array $token) + { + // Skip invalid statement. + if (isset($token['parenthesis_opener']) === \false) { + return []; + } + $start = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + $incrementers = []; + $semicolons = 0; + for ($next = $start; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if ($code === \T_SEMICOLON) { + ++$semicolons; + } else { + if ($semicolons === 2 && $code === \T_VARIABLE) { + $incrementers[] = $tokens[$next]['content']; + } + } + } + return $incrementers; + } + //end findIncrementers() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php new file mode 100644 index 00000000000..efbad19cca4 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnconditionalIfStatementSniff.php @@ -0,0 +1,81 @@ +true or false + * + * + * class Foo + * { + * public function close() + * { + * if (true) + * { + * // ... + * } + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class UnconditionalIfStatementSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_IF, \T_ELSEIF]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip if statement without body. + if (isset($token['parenthesis_opener']) === \false) { + return; + } + $next = ++$token['parenthesis_opener']; + $end = --$token['parenthesis_closer']; + $goodCondition = \false; + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if (isset(Tokens::$emptyTokens[$code]) === \true) { + continue; + } else { + if ($code !== \T_TRUE && $code !== \T_FALSE) { + $goodCondition = \true; + } + } + } + if ($goodCondition === \false) { + $error = 'Avoid IF statements that are always true or false'; + $phpcsFile->addWarning($error, $stackPtr, 'Found'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php new file mode 100644 index 00000000000..f02594d4aac --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnnecessaryFinalModifierSniff.php @@ -0,0 +1,74 @@ + + * final class Foo + * { + * public final function bar() + * { + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class UnnecessaryFinalModifierSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_CLASS]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip for-statements without body. + if (isset($token['scope_opener']) === \false) { + return; + } + // Fetch previous token. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, \true); + // Skip for non final class. + if ($prev === \false || $tokens[$prev]['code'] !== \T_FINAL) { + return; + } + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + for (; $next <= $end; ++$next) { + if ($tokens[$next]['code'] === \T_FINAL) { + $error = 'Unnecessary FINAL modifier in FINAL class'; + $phpcsFile->addWarning($error, $next, 'Found'); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php new file mode 100644 index 00000000000..674b90dd830 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UnusedFunctionParameterSniff.php @@ -0,0 +1,224 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class UnusedFunctionParameterSniff implements Sniff +{ + /** + * The list of class type hints which will be ignored. + * + * @var array + */ + public $ignoreTypeHints = []; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_FUNCTION, \T_CLOSURE, \T_FN]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip broken function declarations. + if (isset($token['scope_opener']) === \false || isset($token['parenthesis_opener']) === \false) { + return; + } + $errorCode = 'Found'; + $implements = \false; + $extends = \false; + $classPtr = $phpcsFile->getCondition($stackPtr, \T_CLASS); + if ($classPtr !== \false) { + $implements = $phpcsFile->findImplementedInterfaceNames($classPtr); + $extends = $phpcsFile->findExtendedClassName($classPtr); + if ($extends !== \false) { + $errorCode .= 'InExtendedClass'; + } else { + if ($implements !== \false) { + $errorCode .= 'InImplementedInterface'; + } + } + } + $params = []; + $methodParams = $phpcsFile->getMethodParameters($stackPtr); + // Skip when no parameters found. + $methodParamsCount = \count($methodParams); + if ($methodParamsCount === 0) { + return; + } + foreach ($methodParams as $param) { + if (isset($param['property_visibility']) === \true) { + // Ignore constructor property promotion. + continue; + } + $params[$param['name']] = $stackPtr; + } + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + // Check the end token for arrow functions as + // they can end at a content token due to not having + // a clearly defined closing token. + if ($token['code'] === \T_FN) { + ++$end; + } + $foundContent = \false; + $validTokens = [\T_HEREDOC => \T_HEREDOC, \T_NOWDOC => \T_NOWDOC, \T_END_HEREDOC => \T_END_HEREDOC, \T_END_NOWDOC => \T_END_NOWDOC, \T_DOUBLE_QUOTED_STRING => \T_DOUBLE_QUOTED_STRING]; + $validTokens += Tokens::$emptyTokens; + for (; $next <= $end; ++$next) { + $token = $tokens[$next]; + $code = $token['code']; + // Ignorable tokens. + if (isset(Tokens::$emptyTokens[$code]) === \true) { + continue; + } + if ($foundContent === \false) { + // A throw statement as the first content indicates an interface method. + if ($code === \T_THROW && $implements !== \false) { + return; + } + // A return statement as the first content indicates an interface method. + if ($code === \T_RETURN) { + $tmp = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + if ($tmp === \false && $implements !== \false) { + return; + } + // There is a return. + if ($tokens[$tmp]['code'] === \T_SEMICOLON && $implements !== \false) { + return; + } + $tmp = $phpcsFile->findNext(Tokens::$emptyTokens, $tmp + 1, null, \true); + if ($tmp !== \false && $tokens[$tmp]['code'] === \T_SEMICOLON && $implements !== \false) { + // There is a return . + return; + } + } + //end if + } + //end if + $foundContent = \true; + if ($code === \T_VARIABLE && isset($params[$token['content']]) === \true) { + unset($params[$token['content']]); + } else { + if ($code === \T_DOLLAR) { + $nextToken = $phpcsFile->findNext(\T_WHITESPACE, $next + 1, null, \true); + if ($tokens[$nextToken]['code'] === \T_OPEN_CURLY_BRACKET) { + $nextToken = $phpcsFile->findNext(\T_WHITESPACE, $nextToken + 1, null, \true); + if ($tokens[$nextToken]['code'] === \T_STRING) { + $varContent = '$' . $tokens[$nextToken]['content']; + if (isset($params[$varContent]) === \true) { + unset($params[$varContent]); + } + } + } + } else { + if ($code === \T_DOUBLE_QUOTED_STRING || $code === \T_START_HEREDOC || $code === \T_START_NOWDOC) { + // Tokenize strings that can contain variables. + // Make sure the string is re-joined if it occurs over multiple lines. + $content = $token['content']; + for ($i = $next + 1; $i <= $end; $i++) { + if (isset($validTokens[$tokens[$i]['code']]) === \true) { + $content .= $tokens[$i]['content']; + $next++; + } else { + break; + } + } + $stringTokens = \token_get_all(\sprintf('', $content)); + foreach ($stringTokens as $stringPtr => $stringToken) { + if (\is_array($stringToken) === \false) { + continue; + } + $varContent = ''; + if ($stringToken[0] === \T_DOLLAR_OPEN_CURLY_BRACES) { + $varContent = '$' . $stringTokens[$stringPtr + 1][1]; + } else { + if ($stringToken[0] === \T_VARIABLE) { + $varContent = $stringToken[1]; + } + } + if ($varContent !== '' && isset($params[$varContent]) === \true) { + unset($params[$varContent]); + } + } + } + } + } + //end if + } + //end for + if ($foundContent === \true && \count($params) > 0) { + $error = 'The method parameter %s is never used'; + // If there is only one parameter and it is unused, no need for additional errorcode toggling logic. + if ($methodParamsCount === 1) { + foreach ($params as $paramName => $position) { + if (\in_array($methodParams[0]['type_hint'], $this->ignoreTypeHints, \true) === \true) { + continue; + } + $data = [$paramName]; + $phpcsFile->addWarning($error, $position, $errorCode, $data); + } + return; + } + $foundLastUsed = \false; + $lastIndex = $methodParamsCount - 1; + $errorInfo = []; + for ($i = $lastIndex; $i >= 0; --$i) { + if ($foundLastUsed !== \false) { + if (isset($params[$methodParams[$i]['name']]) === \true) { + $errorInfo[$methodParams[$i]['name']] = ['position' => $params[$methodParams[$i]['name']], 'errorcode' => $errorCode . 'BeforeLastUsed', 'typehint' => $methodParams[$i]['type_hint']]; + } + } else { + if (isset($params[$methodParams[$i]['name']]) === \false) { + $foundLastUsed = \true; + } else { + $errorInfo[$methodParams[$i]['name']] = ['position' => $params[$methodParams[$i]['name']], 'errorcode' => $errorCode . 'AfterLastUsed', 'typehint' => $methodParams[$i]['type_hint']]; + } + } + } + //end for + if (\count($errorInfo) > 0) { + $errorInfo = \array_reverse($errorInfo); + foreach ($errorInfo as $paramName => $info) { + if (\in_array($info['typehint'], $this->ignoreTypeHints, \true) === \true) { + continue; + } + $data = [$paramName]; + $phpcsFile->addWarning($error, $info['position'], $info['errorcode'], $data); + } + } + } + //end if + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php new file mode 100644 index 00000000000..187451fdd30 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/CodeAnalysis/UselessOverridingMethodSniff.php @@ -0,0 +1,143 @@ + + * class FooBar { + * public function __construct($a, $b) { + * parent::__construct($a, $b); + * } + * } + * + * + * @author Manuel Pichler + * @copyright 2007-2014 Manuel Pichler. All rights reserved. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\CodeAnalysis; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class UselessOverridingMethodSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_FUNCTION]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[$stackPtr]; + // Skip function without body. + if (isset($token['scope_opener']) === \false) { + return; + } + // Get function name. + $methodName = $phpcsFile->getDeclarationName($stackPtr); + // Get all parameters from method signature. + $signature = []; + foreach ($phpcsFile->getMethodParameters($stackPtr) as $param) { + $signature[] = $param['name']; + } + $next = ++$token['scope_opener']; + $end = --$token['scope_closer']; + for (; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + if (isset(Tokens::$emptyTokens[$code]) === \true) { + continue; + } else { + if ($code === \T_RETURN) { + continue; + } + } + break; + } + // Any token except 'parent' indicates correct code. + if ($tokens[$next]['code'] !== \T_PARENT) { + return; + } + // Find next non empty token index, should be double colon. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + // Skip for invalid code. + if ($next === \false || $tokens[$next]['code'] !== \T_DOUBLE_COLON) { + return; + } + // Find next non empty token index, should be the function name. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + // Skip for invalid code or other method. + if ($next === \false || $tokens[$next]['content'] !== $methodName) { + return; + } + // Find next non empty token index, should be the open parenthesis. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + // Skip for invalid code. + if ($next === \false || $tokens[$next]['code'] !== \T_OPEN_PARENTHESIS) { + return; + } + $parameters = ['']; + $parenthesisCount = 1; + $count = \count($tokens); + for (++$next; $next < $count; ++$next) { + $code = $tokens[$next]['code']; + if ($code === \T_OPEN_PARENTHESIS) { + ++$parenthesisCount; + } else { + if ($code === \T_CLOSE_PARENTHESIS) { + --$parenthesisCount; + } else { + if ($parenthesisCount === 1 && $code === \T_COMMA) { + $parameters[] = ''; + } else { + if (isset(Tokens::$emptyTokens[$code]) === \false) { + $parameters[\count($parameters) - 1] .= $tokens[$next]['content']; + } + } + } + } + if ($parenthesisCount === 0) { + break; + } + } + //end for + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, \true); + if ($next === \false || $tokens[$next]['code'] !== \T_SEMICOLON) { + return; + } + // Check rest of the scope. + for (++$next; $next <= $end; ++$next) { + $code = $tokens[$next]['code']; + // Skip for any other content. + if (isset(Tokens::$emptyTokens[$code]) === \false) { + return; + } + } + $parameters = \array_map('trim', $parameters); + $parameters = \array_filter($parameters); + if (\count($parameters) === \count($signature) && $parameters === $signature) { + $phpcsFile->addWarning('Possible useless method overriding detected', $stackPtr, 'Found'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php new file mode 100644 index 00000000000..8472cb7570d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/DocCommentSniff.php @@ -0,0 +1,292 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DocCommentSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_DOC_COMMENT_OPEN_TAG]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['comment_closer']) === \false || $tokens[$tokens[$stackPtr]['comment_closer']]['content'] === '' && $tokens[$stackPtr]['comment_closer'] === $phpcsFile->numTokens - 1) { + // Don't process an unfinished comment during live coding. + return; + } + $commentStart = $stackPtr; + $commentEnd = $tokens[$stackPtr]['comment_closer']; + $empty = [\T_DOC_COMMENT_WHITESPACE, \T_DOC_COMMENT_STAR]; + $short = $phpcsFile->findNext($empty, $stackPtr + 1, $commentEnd, \true); + if ($short === \false) { + // No content at all. + $error = 'Doc comment is empty'; + $phpcsFile->addError($error, $stackPtr, 'Empty'); + return; + } + // The first line of the comment should just be the /** code. + if ($tokens[$short]['line'] === $tokens[$stackPtr]['line']) { + $error = 'The open comment tag must be the only content on the line'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentAfterOpen'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($stackPtr); + $phpcsFile->fixer->addContentBefore($short, '* '); + $phpcsFile->fixer->endChangeset(); + } + } + // The last line of the comment should just be the */ code. + $prev = $phpcsFile->findPrevious($empty, $commentEnd - 1, $stackPtr, \true); + if ($tokens[$prev]['line'] === $tokens[$commentEnd]['line']) { + $error = 'The close comment tag must be the only content on the line'; + $fix = $phpcsFile->addFixableError($error, $commentEnd, 'ContentBeforeClose'); + if ($fix === \true) { + $phpcsFile->fixer->addNewlineBefore($commentEnd); + } + } + // Check for additional blank lines at the end of the comment. + if ($tokens[$prev]['line'] < $tokens[$commentEnd]['line'] - 1) { + $error = 'Additional blank lines found at end of doc comment'; + $fix = $phpcsFile->addFixableError($error, $commentEnd, 'SpacingAfter'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $prev + 1; $i < $commentEnd; $i++) { + if ($tokens[$i + 1]['line'] === $tokens[$commentEnd]['line']) { + break; + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + // Check for a comment description. + if ($tokens[$short]['code'] !== \T_DOC_COMMENT_STRING) { + $error = 'Missing short description in doc comment'; + $phpcsFile->addError($error, $stackPtr, 'MissingShort'); + } else { + // No extra newline before short description. + if ($tokens[$short]['line'] !== $tokens[$stackPtr]['line'] + 1) { + $error = 'Doc comment short description must be on the first line'; + $fix = $phpcsFile->addFixableError($error, $short, 'SpacingBeforeShort'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $stackPtr; $i < $short; $i++) { + if ($tokens[$i]['line'] === $tokens[$stackPtr]['line']) { + continue; + } else { + if ($tokens[$i]['line'] === $tokens[$short]['line']) { + break; + } + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + // Account for the fact that a short description might cover + // multiple lines. + $shortContent = $tokens[$short]['content']; + $shortEnd = $short; + for ($i = $short + 1; $i < $commentEnd; $i++) { + if ($tokens[$i]['code'] === \T_DOC_COMMENT_STRING) { + if ($tokens[$i]['line'] === $tokens[$shortEnd]['line'] + 1) { + $shortContent .= $tokens[$i]['content']; + $shortEnd = $i; + } else { + break; + } + } + } + if (\preg_match('/^\\p{Ll}/u', $shortContent) === 1) { + $error = 'Doc comment short description must start with a capital letter'; + $phpcsFile->addError($error, $short, 'ShortNotCapital'); + } + $long = $phpcsFile->findNext($empty, $shortEnd + 1, $commentEnd - 1, \true); + if ($long !== \false && $tokens[$long]['code'] === \T_DOC_COMMENT_STRING) { + if ($tokens[$long]['line'] !== $tokens[$shortEnd]['line'] + 2) { + $error = 'There must be exactly one blank line between descriptions in a doc comment'; + $fix = $phpcsFile->addFixableError($error, $long, 'SpacingBetween'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $shortEnd + 1; $i < $long; $i++) { + if ($tokens[$i]['line'] === $tokens[$shortEnd]['line']) { + continue; + } else { + if ($tokens[$i]['line'] === $tokens[$long]['line'] - 1) { + break; + } + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + if (\preg_match('/^\\p{Ll}/u', $tokens[$long]['content']) === 1) { + $error = 'Doc comment long description must start with a capital letter'; + $phpcsFile->addError($error, $long, 'LongNotCapital'); + } + } + //end if + } + //end if + if (empty($tokens[$commentStart]['comment_tags']) === \true) { + // No tags in the comment. + return; + } + $firstTag = $tokens[$commentStart]['comment_tags'][0]; + $prev = $phpcsFile->findPrevious($empty, $firstTag - 1, $stackPtr, \true); + if ($tokens[$firstTag]['line'] !== $tokens[$prev]['line'] + 2 && $tokens[$prev]['code'] !== \T_DOC_COMMENT_OPEN_TAG) { + $error = 'There must be exactly one blank line before the tags in a doc comment'; + $fix = $phpcsFile->addFixableError($error, $firstTag, 'SpacingBeforeTags'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $prev + 1; $i < $firstTag; $i++) { + if ($tokens[$i]['line'] === $tokens[$firstTag]['line']) { + break; + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $indent = \str_repeat(' ', $tokens[$stackPtr]['column']); + $phpcsFile->fixer->addContent($prev, $phpcsFile->eolChar . $indent . '*' . $phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } + // Break out the tags into groups and check alignment within each. + // A tag group is one where there are no blank lines between tags. + // The param tag group is special as it requires all @param tags to be inside. + $tagGroups = []; + $groupid = 0; + $paramGroupid = null; + foreach ($tokens[$commentStart]['comment_tags'] as $pos => $tag) { + if ($pos > 0) { + $prev = $phpcsFile->findPrevious(\T_DOC_COMMENT_STRING, $tag - 1, $tokens[$commentStart]['comment_tags'][$pos - 1]); + if ($prev === \false) { + $prev = $tokens[$commentStart]['comment_tags'][$pos - 1]; + } + if ($tokens[$prev]['line'] !== $tokens[$tag]['line'] - 1) { + $groupid++; + } + } + if ($tokens[$tag]['content'] === '@param') { + if ($paramGroupid !== null && $paramGroupid !== $groupid) { + $error = 'Parameter tags must be grouped together in a doc comment'; + $phpcsFile->addError($error, $tag, 'ParamGroup'); + } + if ($paramGroupid === null) { + $paramGroupid = $groupid; + } + } + //end if + $tagGroups[$groupid][] = $tag; + } + //end foreach + foreach ($tagGroups as $groupid => $group) { + $maxLength = 0; + $paddings = []; + foreach ($group as $pos => $tag) { + if ($paramGroupid === $groupid && $tokens[$tag]['content'] !== '@param') { + $error = 'Tag %s cannot be grouped with parameter tags in a doc comment'; + $data = [$tokens[$tag]['content']]; + $phpcsFile->addError($error, $tag, 'NonParamGroup', $data); + } + $tagLength = $tokens[$tag]['length']; + if ($tagLength > $maxLength) { + $maxLength = $tagLength; + } + // Check for a value. No value means no padding needed. + $string = $phpcsFile->findNext(\T_DOC_COMMENT_STRING, $tag, $commentEnd); + if ($string !== \false && $tokens[$string]['line'] === $tokens[$tag]['line']) { + $paddings[$tag] = $tokens[$tag + 1]['length']; + } + } + // Check that there was single blank line after the tag block + // but account for a multi-line tag comments. + $lastTag = $group[$pos]; + $next = $phpcsFile->findNext(\T_DOC_COMMENT_TAG, $lastTag + 3, $commentEnd); + if ($next !== \false) { + $prev = $phpcsFile->findPrevious([\T_DOC_COMMENT_TAG, \T_DOC_COMMENT_STRING], $next - 1, $commentStart); + if ($tokens[$next]['line'] !== $tokens[$prev]['line'] + 2) { + $error = 'There must be a single blank line after a tag group'; + $fix = $phpcsFile->addFixableError($error, $lastTag, 'SpacingAfterTagGroup'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $prev + 1; $i < $next; $i++) { + if ($tokens[$i]['line'] === $tokens[$next]['line']) { + break; + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $indent = \str_repeat(' ', $tokens[$stackPtr]['column']); + $phpcsFile->fixer->addContent($prev, $phpcsFile->eolChar . $indent . '*' . $phpcsFile->eolChar); + $phpcsFile->fixer->endChangeset(); + } + } + } + //end if + // Now check paddings. + foreach ($paddings as $tag => $padding) { + $required = $maxLength - $tokens[$tag]['length'] + 1; + if ($padding !== $required) { + $error = 'Tag value for %s tag indented incorrectly; expected %s spaces but found %s'; + $data = [$tokens[$tag]['content'], $required, $padding]; + $fix = $phpcsFile->addFixableError($error, $tag + 1, 'TagValueIndent', $data); + if ($fix === \true) { + $phpcsFile->fixer->replaceToken($tag + 1, \str_repeat(' ', $required)); + } + } + } + } + //end foreach + // If there is a param group, it needs to be first. + if ($paramGroupid !== null && $paramGroupid !== 0) { + $error = 'Parameter tags must be defined first in a doc comment'; + $phpcsFile->addError($error, $tagGroups[$paramGroupid][0], 'ParamNotFirst'); + } + $foundTags = []; + foreach ($tokens[$stackPtr]['comment_tags'] as $pos => $tag) { + $tagName = $tokens[$tag]['content']; + if (isset($foundTags[$tagName]) === \true) { + $lastTag = $tokens[$stackPtr]['comment_tags'][$pos - 1]; + if ($tokens[$lastTag]['content'] !== $tagName) { + $error = 'Tags must be grouped together in a doc comment'; + $phpcsFile->addError($error, $tag, 'TagsNotGrouped'); + } + continue; + } + $foundTags[$tagName] = \true; + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php new file mode 100644 index 00000000000..844730c0a2d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/FixmeSniff.php @@ -0,0 +1,66 @@ + + * @author Sam Graham + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class FixmeSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return \array_diff(Tokens::$commentTokens, Tokens::$phpcsCommentTokens); + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $content = $tokens[$stackPtr]['content']; + $matches = []; + \preg_match('/(?:\\A|[^\\p{L}]+)fixme([^\\p{L}]+(.*)|\\Z)/ui', $content, $matches); + if (empty($matches) === \false) { + // Clear whitespace and some common characters not required at + // the end of a fixme message to make the error more informative. + $type = 'CommentFound'; + $fixmeMessage = \trim($matches[1]); + $fixmeMessage = \trim($fixmeMessage, '-:[](). '); + $error = 'Comment refers to a FIXME task'; + $data = [$fixmeMessage]; + if ($fixmeMessage !== '') { + $type = 'TaskFound'; + $error .= ' "%s"'; + } + $phpcsFile->addError($error, $stackPtr, $type, $data); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php new file mode 100644 index 00000000000..1c9591e22d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Commenting/TodoSniff.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Commenting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class TodoSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return \array_diff(Tokens::$commentTokens, Tokens::$phpcsCommentTokens); + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $content = $tokens[$stackPtr]['content']; + $matches = []; + \preg_match('/(?:\\A|[^\\p{L}]+)todo([^\\p{L}]+(.*)|\\Z)/ui', $content, $matches); + if (empty($matches) === \false) { + // Clear whitespace and some common characters not required at + // the end of a to-do message to make the warning more informative. + $type = 'CommentFound'; + $todoMessage = \trim($matches[1]); + $todoMessage = \trim($todoMessage, '-:[](). '); + $error = 'Comment refers to a TODO task'; + $data = [$todoMessage]; + if ($todoMessage !== '') { + $type = 'TaskFound'; + $error .= ' "%s"'; + } + $phpcsFile->addWarning($error, $stackPtr, $type, $data); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php new file mode 100644 index 00000000000..c1630d3fa24 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/DisallowYodaConditionsSniff.php @@ -0,0 +1,139 @@ + + * @author Mark Scherer + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class DisallowYodaConditionsSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$comparisonTokens; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $previousIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, \true); + $relevantTokens = [\T_CLOSE_SHORT_ARRAY, \T_CLOSE_PARENTHESIS, \T_TRUE, \T_FALSE, \T_NULL, \T_LNUMBER, \T_DNUMBER, \T_CONSTANT_ENCAPSED_STRING]; + if ($previousIndex === \false || \in_array($tokens[$previousIndex]['code'], $relevantTokens, \true) === \false) { + return; + } + if ($tokens[$previousIndex]['code'] === \T_CLOSE_SHORT_ARRAY) { + $previousIndex = $tokens[$previousIndex]['bracket_opener']; + if ($this->isArrayStatic($phpcsFile, $previousIndex) === \false) { + return; + } + } + $prevIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, $previousIndex - 1, null, \true); + if ($prevIndex === \false) { + return; + } + if (\in_array($tokens[$prevIndex]['code'], Tokens::$arithmeticTokens, \true) === \true) { + return; + } + if ($tokens[$prevIndex]['code'] === \T_STRING_CONCAT) { + return; + } + // Is it a parenthesis. + if ($tokens[$previousIndex]['code'] === \T_CLOSE_PARENTHESIS) { + // Check what exists inside the parenthesis. + $closeParenthesisIndex = $phpcsFile->findPrevious(Tokens::$emptyTokens, $tokens[$previousIndex]['parenthesis_opener'] - 1, null, \true); + if ($closeParenthesisIndex === \false || $tokens[$closeParenthesisIndex]['code'] !== \T_ARRAY) { + if ($tokens[$closeParenthesisIndex]['code'] === \T_STRING) { + return; + } + // If it is not an array check what is inside. + $found = $phpcsFile->findPrevious(\T_VARIABLE, $previousIndex - 1, $tokens[$previousIndex]['parenthesis_opener']); + // If a variable exists, it is not Yoda. + if ($found !== \false) { + return; + } + // If there is nothing inside the parenthesis, it it not a Yoda. + $opener = $tokens[$previousIndex]['parenthesis_opener']; + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $previousIndex - 1, $opener + 1, \true); + if ($prev === \false) { + return; + } + } else { + if ($tokens[$closeParenthesisIndex]['code'] === \T_ARRAY && $this->isArrayStatic($phpcsFile, $closeParenthesisIndex) === \false) { + return; + } + } + //end if + } + //end if + $phpcsFile->addError('Usage of Yoda conditions is not allowed; switch the expression order', $stackPtr, 'Found'); + } + //end process() + /** + * Determines if an array is a static definition. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $arrayToken The position of the array token. + * + * @return bool + */ + public function isArrayStatic(File $phpcsFile, $arrayToken) + { + $tokens = $phpcsFile->getTokens(); + $arrayEnd = null; + if ($tokens[$arrayToken]['code'] === \T_OPEN_SHORT_ARRAY) { + $start = $arrayToken; + $end = $tokens[$arrayToken]['bracket_closer']; + } else { + if ($tokens[$arrayToken]['code'] === \T_ARRAY) { + $start = $tokens[$arrayToken]['parenthesis_opener']; + $end = $tokens[$arrayToken]['parenthesis_closer']; + } else { + return \true; + } + } + $staticTokens = Tokens::$emptyTokens; + $staticTokens += Tokens::$textStringTokens; + $staticTokens += Tokens::$assignmentTokens; + $staticTokens += Tokens::$equalityTokens; + $staticTokens += Tokens::$comparisonTokens; + $staticTokens += Tokens::$arithmeticTokens; + $staticTokens += Tokens::$operators; + $staticTokens += Tokens::$booleanOperators; + $staticTokens += Tokens::$castTokens; + $staticTokens += Tokens::$bracketTokens; + $staticTokens += [\T_DOUBLE_ARROW => \T_DOUBLE_ARROW, \T_COMMA => \T_COMMA, \T_TRUE => \T_TRUE, \T_FALSE => \T_FALSE]; + for ($i = $start + 1; $i < $end; $i++) { + if (isset($tokens[$i]['scope_closer']) === \true) { + $i = $tokens[$i]['scope_closer']; + continue; + } + if (isset($staticTokens[$tokens[$i]['code']]) === \false) { + return \false; + } + } + return \true; + } + //end isArrayStatic() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php new file mode 100644 index 00000000000..8f1f09e00dc --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/ControlStructures/InlineControlStructureSniff.php @@ -0,0 +1,288 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\ControlStructures; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class InlineControlStructureSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = \true; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_IF, \T_ELSE, \T_ELSEIF, \T_FOREACH, \T_WHILE, \T_DO, \T_SWITCH, \T_FOR]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === \true) { + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no'); + return; + } + // Ignore the ELSE in ELSE IF. We'll process the IF part later. + if ($tokens[$stackPtr]['code'] === \T_ELSE) { + $next = $phpcsFile->findNext(\T_WHITESPACE, $stackPtr + 1, null, \true); + if ($tokens[$next]['code'] === \T_IF) { + return; + } + } + if ($tokens[$stackPtr]['code'] === \T_WHILE || $tokens[$stackPtr]['code'] === \T_FOR) { + // This could be from a DO WHILE, which doesn't have an opening brace or a while/for without body. + if (isset($tokens[$stackPtr]['parenthesis_closer']) === \true) { + $afterParensCloser = $phpcsFile->findNext(Tokens::$emptyTokens, $tokens[$stackPtr]['parenthesis_closer'] + 1, null, \true); + if ($afterParensCloser === \false) { + // Live coding. + return; + } + if ($tokens[$afterParensCloser]['code'] === \T_SEMICOLON) { + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'no'); + return; + } + } + // In Javascript DO WHILE loops without curly braces are legal. This + // is only valid if a single statement is present between the DO and + // the WHILE. We can detect this by checking only a single semicolon + // is present between them. + if ($tokens[$stackPtr]['code'] === \T_WHILE && $phpcsFile->tokenizerType === 'JS') { + $lastDo = $phpcsFile->findPrevious(\T_DO, $stackPtr - 1); + $lastSemicolon = $phpcsFile->findPrevious(\T_SEMICOLON, $stackPtr - 1); + if ($lastDo !== \false && $lastSemicolon !== \false && $lastDo < $lastSemicolon) { + $precedingSemicolon = $phpcsFile->findPrevious(\T_SEMICOLON, $lastSemicolon - 1); + if ($precedingSemicolon === \false || $precedingSemicolon < $lastDo) { + return; + } + } + } + } + //end if + if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === \false && $tokens[$stackPtr]['code'] !== \T_ELSE) { + if ($tokens[$stackPtr]['code'] !== \T_DO) { + // Live coding or parse error. + return; + } + $nextWhile = $phpcsFile->findNext(\T_WHILE, $stackPtr + 1); + if ($nextWhile !== \false && isset($tokens[$nextWhile]['parenthesis_opener'], $tokens[$nextWhile]['parenthesis_closer']) === \false) { + // Live coding or parse error. + return; + } + unset($nextWhile); + } + $start = $stackPtr; + if (isset($tokens[$stackPtr]['parenthesis_closer']) === \true) { + $start = $tokens[$stackPtr]['parenthesis_closer']; + } + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, $start + 1, null, \true); + if ($nextNonEmpty === \false) { + // Live coding or parse error. + return; + } + if ($tokens[$nextNonEmpty]['code'] === \T_OPEN_CURLY_BRACKET || $tokens[$nextNonEmpty]['code'] === \T_COLON) { + // T_CLOSE_CURLY_BRACKET missing, or alternative control structure with + // T_END... missing. Either live coding, parse error or end + // tag in short open tags and scan run with short_open_tag=Off. + // Bow out completely as any further detection will be unreliable + // and create incorrect fixes or cause fixer conflicts. + return $phpcsFile->numTokens + 1; + } + unset($nextNonEmpty, $start); + // This is a control structure without an opening brace, + // so it is an inline statement. + if ($this->error === \true) { + $fix = $phpcsFile->addFixableError('Inline control structures are not allowed', $stackPtr, 'NotAllowed'); + } else { + $fix = $phpcsFile->addFixableWarning('Inline control structures are discouraged', $stackPtr, 'Discouraged'); + } + $phpcsFile->recordMetric($stackPtr, 'Control structure defined inline', 'yes'); + // Stop here if we are not fixing the error. + if ($fix !== \true) { + return; + } + $phpcsFile->fixer->beginChangeset(); + if (isset($tokens[$stackPtr]['parenthesis_closer']) === \true) { + $closer = $tokens[$stackPtr]['parenthesis_closer']; + } else { + $closer = $stackPtr; + } + if ($tokens[$closer + 1]['code'] === \T_WHITESPACE || $tokens[$closer + 1]['code'] === \T_SEMICOLON) { + $phpcsFile->fixer->addContent($closer, ' {'); + } else { + $phpcsFile->fixer->addContent($closer, ' { '); + } + $fixableScopeOpeners = $this->register(); + $lastNonEmpty = $closer; + for ($end = $closer + 1; $end < $phpcsFile->numTokens; $end++) { + if ($tokens[$end]['code'] === \T_SEMICOLON) { + break; + } + if ($tokens[$end]['code'] === \T_CLOSE_TAG) { + $end = $lastNonEmpty; + break; + } + if (\in_array($tokens[$end]['code'], $fixableScopeOpeners, \true) === \true && isset($tokens[$end]['scope_opener']) === \false) { + // The best way to fix nested inline scopes is middle-out. + // So skip this one. It will be detected and fixed on a future loop. + $phpcsFile->fixer->rollbackChangeset(); + return; + } + if (isset($tokens[$end]['scope_opener']) === \true) { + $type = $tokens[$end]['code']; + $end = $tokens[$end]['scope_closer']; + if ($type === \T_DO || $type === \T_IF || $type === \T_ELSEIF || $type === \T_TRY || $type === \T_CATCH || $type === \T_FINALLY) { + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $end + 1, null, \true); + if ($next === \false) { + break; + } + $nextType = $tokens[$next]['code']; + // Let additional conditions loop and find their ending. + if (($type === \T_IF || $type === \T_ELSEIF) && ($nextType === \T_ELSEIF || $nextType === \T_ELSE)) { + continue; + } + // Account for TRY... CATCH/FINALLY statements. + if (($type === \T_TRY || $type === \T_CATCH || $type === \T_FINALLY) && ($nextType === \T_CATCH || $nextType === \T_FINALLY)) { + continue; + } + // Account for DO... WHILE conditions. + if ($type === \T_DO && $nextType === \T_WHILE) { + $end = $phpcsFile->findNext(\T_SEMICOLON, $next + 1); + } + } else { + if ($type === \T_CLOSURE) { + // There should be a semicolon after the closing brace. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $end + 1, null, \true); + if ($next !== \false && $tokens[$next]['code'] === \T_SEMICOLON) { + $end = $next; + } + } + } + //end if + if ($tokens[$end]['code'] !== \T_END_HEREDOC && $tokens[$end]['code'] !== \T_END_NOWDOC) { + break; + } + } + //end if + if (isset($tokens[$end]['parenthesis_closer']) === \true) { + $end = $tokens[$end]['parenthesis_closer']; + $lastNonEmpty = $end; + continue; + } + if ($tokens[$end]['code'] !== \T_WHITESPACE) { + $lastNonEmpty = $end; + } + } + //end for + if ($end === $phpcsFile->numTokens) { + $end = $lastNonEmpty; + } + $nextContent = $phpcsFile->findNext(Tokens::$emptyTokens, $end + 1, null, \true); + if ($nextContent === \false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Looks for completely empty statements. + $next = $phpcsFile->findNext(\T_WHITESPACE, $closer + 1, $end + 1, \true); + } else { + $next = $end + 1; + $endLine = $end; + } + if ($next !== $end) { + if ($nextContent === \false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Account for a comment on the end of the line. + for ($endLine = $end; $endLine < $phpcsFile->numTokens; $endLine++) { + if (isset($tokens[$endLine + 1]) === \false || $tokens[$endLine]['line'] !== $tokens[$endLine + 1]['line']) { + break; + } + } + if (isset(Tokens::$commentTokens[$tokens[$endLine]['code']]) === \false && ($tokens[$endLine]['code'] !== \T_WHITESPACE || isset(Tokens::$commentTokens[$tokens[$endLine - 1]['code']]) === \false)) { + $endLine = $end; + } + } + if ($endLine !== $end) { + $endToken = $endLine; + $addedContent = ''; + } else { + $endToken = $end; + $addedContent = $phpcsFile->eolChar; + if ($tokens[$end]['code'] !== \T_SEMICOLON && $tokens[$end]['code'] !== \T_CLOSE_CURLY_BRACKET) { + $phpcsFile->fixer->addContent($end, '; '); + } + } + $next = $phpcsFile->findNext(\T_WHITESPACE, $endToken + 1, null, \true); + if ($next !== \false && ($tokens[$next]['code'] === \T_ELSE || $tokens[$next]['code'] === \T_ELSEIF)) { + $phpcsFile->fixer->addContentBefore($next, '} '); + } else { + $indent = ''; + for ($first = $stackPtr; $first > 0; $first--) { + if ($tokens[$first]['column'] === 1) { + break; + } + } + if ($tokens[$first]['code'] === \T_WHITESPACE) { + $indent = $tokens[$first]['content']; + } else { + if ($tokens[$first]['code'] === \T_INLINE_HTML || $tokens[$first]['code'] === \T_OPEN_TAG) { + $addedContent = ''; + } + } + $addedContent .= $indent . '}'; + if ($next !== \false && $tokens[$endToken]['code'] === \T_COMMENT) { + $addedContent .= $phpcsFile->eolChar; + } + $phpcsFile->fixer->addContent($endToken, $addedContent); + } + //end if + } else { + if ($nextContent === \false || $tokens[$nextContent]['line'] !== $tokens[$end]['line']) { + // Account for a comment on the end of the line. + for ($endLine = $end; $endLine < $phpcsFile->numTokens; $endLine++) { + if (isset($tokens[$endLine + 1]) === \false || $tokens[$endLine]['line'] !== $tokens[$endLine + 1]['line']) { + break; + } + } + if ($tokens[$endLine]['code'] !== \T_COMMENT && ($tokens[$endLine]['code'] !== \T_WHITESPACE || $tokens[$endLine - 1]['code'] !== \T_COMMENT)) { + $endLine = $end; + } + } + if ($endLine !== $end) { + $phpcsFile->fixer->replaceToken($end, ''); + $phpcsFile->fixer->addNewlineBefore($endLine); + $phpcsFile->fixer->addContent($endLine, '}'); + } else { + $phpcsFile->fixer->replaceToken($end, '}'); + } + } + //end if + $phpcsFile->fixer->endChangeset(); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php new file mode 100644 index 00000000000..2ae3b73d6a5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/CSSLintSniff.php @@ -0,0 +1,77 @@ + + * @copyright 2013-2014 Roman Levishchenko + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; +class CSSLintSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['CSS']; + /** + * Returns the token types that this sniff is interested in. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $csslintPath = Config::getExecutablePath('csslint'); + if ($csslintPath === null) { + return; + } + $fileName = $phpcsFile->getFilename(); + $cmd = Common::escapeshellcmd($csslintPath) . ' ' . \escapeshellarg($fileName) . ' 2>&1'; + \exec($cmd, $output, $retval); + if (\is_array($output) === \false) { + return; + } + $count = \count($output); + for ($i = 0; $i < $count; $i++) { + $matches = []; + $numMatches = \preg_match('/(error|warning) at line (\\d+)/', $output[$i], $matches); + if ($numMatches === 0) { + continue; + } + $line = (int) $matches[2]; + $message = 'csslint says: ' . $output[$i + 1]; + // First line is message with error line and error code. + // Second is error message. + // Third is wrong line in file. + // Fourth is empty line. + $i += 4; + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool'); + } + //end for + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php new file mode 100644 index 00000000000..88e0df26fc8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ClosureLinterSniff.php @@ -0,0 +1,98 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; +class ClosureLinterSniff implements Sniff +{ + /** + * A list of error codes that should show errors. + * + * All other error codes will show warnings. + * + * @var integer + */ + public $errorCodes = []; + /** + * A list of error codes to ignore. + * + * @var integer + */ + public $ignoreCodes = []; + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + /** + * Returns the token types that this sniff is interested in. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jslint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $lintPath = Config::getExecutablePath('gjslint'); + if ($lintPath === null) { + return; + } + $fileName = $phpcsFile->getFilename(); + $lintPath = Common::escapeshellcmd($lintPath); + $cmd = $lintPath . ' --nosummary --notime --unix_mode ' . \escapeshellarg($fileName); + \exec($cmd, $output, $retval); + if (\is_array($output) === \false) { + return; + } + foreach ($output as $finding) { + $matches = []; + $numMatches = \preg_match('/^(.*):([0-9]+):\\(.*?([0-9]+)\\)(.*)$/', $finding, $matches); + if ($numMatches === 0) { + continue; + } + // Skip error codes we are ignoring. + $code = $matches[3]; + if (\in_array($code, $this->ignoreCodes) === \true) { + continue; + } + $line = (int) $matches[2]; + $error = \trim($matches[4]); + $message = 'gjslint says: (%s) %s'; + $data = [$code, $error]; + if (\in_array($code, $this->errorCodes) === \true) { + $phpcsFile->addErrorOnLine($message, $line, 'ExternalToolError', $data); + } else { + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool', $data); + } + } + //end foreach + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php new file mode 100644 index 00000000000..727c4603ffa --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/ESLintSniff.php @@ -0,0 +1,96 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; +class ESLintSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + /** + * ESLint configuration file path. + * + * @var string|null Path to eslintrc. Null to autodetect. + */ + public $configFile = null; + /** + * Returns the token types that this sniff is interested in. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jshint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $eslintPath = Config::getExecutablePath('eslint'); + if ($eslintPath === null) { + return; + } + $filename = $phpcsFile->getFilename(); + $configFile = $this->configFile; + if (empty($configFile) === \true) { + // Attempt to autodetect. + $candidates = \glob('.eslintrc{.js,.yaml,.yml,.json}', \GLOB_BRACE); + if (empty($candidates) === \false) { + $configFile = $candidates[0]; + } + } + $eslintOptions = ['--format json']; + if (empty($configFile) === \false) { + $eslintOptions[] = '--config ' . \escapeshellarg($configFile); + } + $cmd = Common::escapeshellcmd(\escapeshellarg($eslintPath) . ' ' . \implode(' ', $eslintOptions) . ' ' . \escapeshellarg($filename)); + // Execute! + \exec($cmd, $stdout, $code); + if ($code <= 0) { + // No errors, continue. + return $phpcsFile->numTokens + 1; + } + $data = \json_decode(\implode("\n", $stdout)); + if (\json_last_error() !== \JSON_ERROR_NONE) { + // Ignore any errors. + return $phpcsFile->numTokens + 1; + } + // Data is a list of files, but we only pass a single one. + $messages = $data[0]->messages; + foreach ($messages as $error) { + $message = 'eslint says: ' . $error->message; + if (empty($error->fatal) === \false || $error->severity === 2) { + $phpcsFile->addErrorOnLine($message, $error->line, 'ExternalTool'); + } else { + $phpcsFile->addWarningOnLine($message, $error->line, 'ExternalTool'); + } + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php new file mode 100644 index 00000000000..7ef0e0efa2b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Debug/JSHintSniff.php @@ -0,0 +1,81 @@ + + * @author Alexander Wei§ + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Debug; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Common; +class JSHintSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['JS']; + /** + * Returns the token types that this sniff is interested in. + * + * @return int[] + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes the tokens that this sniff is interested in. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where the token was found. + * @param int $stackPtr The position in the stack where + * the token was found. + * + * @return void + * @throws \PHP_CodeSniffer\Exceptions\RuntimeException If jshint.js could not be run + */ + public function process(File $phpcsFile, $stackPtr) + { + $rhinoPath = Config::getExecutablePath('rhino'); + $jshintPath = Config::getExecutablePath('jshint'); + if ($rhinoPath === null && $jshintPath === null) { + return; + } + $fileName = $phpcsFile->getFilename(); + $jshintPath = Common::escapeshellcmd($jshintPath); + if ($rhinoPath !== null) { + $rhinoPath = Common::escapeshellcmd($rhinoPath); + $cmd = "{$rhinoPath} \"{$jshintPath}\" " . \escapeshellarg($fileName); + \exec($cmd, $output, $retval); + $regex = '`^(?P.+)\\(.+:(?P[0-9]+).*:[0-9]+\\)$`'; + } else { + $cmd = "{$jshintPath} " . \escapeshellarg($fileName); + \exec($cmd, $output, $retval); + $regex = '`^(.+?): line (?P[0-9]+), col [0-9]+, (?P.+)$`'; + } + if (\is_array($output) === \true) { + foreach ($output as $finding) { + $matches = []; + $numMatches = \preg_match($regex, $finding, $matches); + if ($numMatches === 0) { + continue; + } + $line = (int) $matches['line']; + $message = 'jshint says: ' . \trim($matches['error']); + $phpcsFile->addWarningOnLine($message, $line, 'ExternalTool'); + } + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php new file mode 100644 index 00000000000..8c1619dbd87 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ByteOrderMarkSniff.php @@ -0,0 +1,66 @@ + + * @author Greg Sherwood + * @copyright 2010-2014 mediaSELF Sp. z o.o. + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class ByteOrderMarkSniff implements Sniff +{ + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = ['UTF-8' => 'efbbbf', 'UTF-16 (BE)' => 'feff', 'UTF-16 (LE)' => 'fffe']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_INLINE_HTML]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + // The BOM will be the very first token in the file. + if ($stackPtr !== 0) { + return; + } + $tokens = $phpcsFile->getTokens(); + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = \strlen($expectedBomHex) / 2; + $htmlBomHex = \bin2hex(\substr($tokens[$stackPtr]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex) { + $errorData = [$bomName]; + $error = 'File contains %s byte order mark, which may corrupt your application'; + $phpcsFile->addError($error, $stackPtr, 'Found', $errorData); + $phpcsFile->recordMetric($stackPtr, 'Using byte order mark', 'yes'); + return; + } + } + $phpcsFile->recordMetric($stackPtr, 'Using byte order mark', 'no'); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php new file mode 100644 index 00000000000..00a4ec1ab98 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNewlineSniff.php @@ -0,0 +1,66 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class EndFileNewlineSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS', 'CSS']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + // Skip to the end of the file. + $tokens = $phpcsFile->getTokens(); + $stackPtr = $phpcsFile->numTokens - 1; + if ($tokens[$stackPtr]['content'] === '') { + $stackPtr--; + } + $eolCharLen = \strlen($phpcsFile->eolChar); + $lastChars = \substr($tokens[$stackPtr]['content'], $eolCharLen * -1); + if ($lastChars !== $phpcsFile->eolChar) { + $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'no'); + $error = 'File must end with a newline character'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NotFound'); + if ($fix === \true) { + $phpcsFile->fixer->addNewline($stackPtr); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'yes'); + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php new file mode 100644 index 00000000000..23f7d685b32 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/EndFileNoNewlineSniff.php @@ -0,0 +1,71 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class EndFileNoNewlineSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS', 'CSS']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + // Skip to the end of the file. + $tokens = $phpcsFile->getTokens(); + $stackPtr = $phpcsFile->numTokens - 1; + if ($tokens[$stackPtr]['content'] === '') { + --$stackPtr; + } + $eolCharLen = \strlen($phpcsFile->eolChar); + $lastChars = \substr($tokens[$stackPtr]['content'], $eolCharLen * -1); + if ($lastChars === $phpcsFile->eolChar) { + $error = 'File must not end with a newline character'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Found'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $stackPtr; $i > 0; $i--) { + $newContent = \rtrim($tokens[$i]['content'], $phpcsFile->eolChar); + $phpcsFile->fixer->replaceToken($i, $newContent); + if ($newContent !== '') { + break; + } + } + $phpcsFile->fixer->endChangeset(); + } + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php new file mode 100644 index 00000000000..dac99681875 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/ExecutableFileSniff.php @@ -0,0 +1,51 @@ + + * @copyright 2019 Matthew Peveler + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class ExecutableFileSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $filename = $phpcsFile->getFilename(); + if ($filename !== 'STDIN') { + $perms = \fileperms($phpcsFile->getFilename()); + if (($perms & 0x40) !== 0 || ($perms & 0x8) !== 0 || ($perms & 0x1) !== 0) { + $error = 'A PHP file should not be executable; found file permissions set to %s'; + $data = [\substr(\sprintf('%o', $perms), -4)]; + $phpcsFile->addError($error, 0, 'Executable', $data); + } + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php new file mode 100644 index 00000000000..c08e46e30fd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/InlineHTMLSniff.php @@ -0,0 +1,65 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class InlineHTMLSniff implements Sniff +{ + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = ['UTF-8' => 'efbbbf', 'UTF-16 (BE)' => 'feff', 'UTF-16 (LE)' => 'fffe']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_INLINE_HTML]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int|null + */ + public function process(File $phpcsFile, $stackPtr) + { + // Allow a byte-order mark. + $tokens = $phpcsFile->getTokens(); + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = \strlen($expectedBomHex) / 2; + $htmlBomHex = \bin2hex(\substr($tokens[0]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex && \strlen($tokens[0]['content']) === $bomByteLength) { + return; + } + } + // Ignore shebang lines. + $tokens = $phpcsFile->getTokens(); + if (\substr($tokens[$stackPtr]['content'], 0, 2) === '#!') { + return; + } + $error = 'PHP files must only contain PHP code'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + return $phpcsFile->numTokens; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php new file mode 100644 index 00000000000..44fed0a133a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineEndingsSniff.php @@ -0,0 +1,117 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class LineEndingsSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS', 'CSS']; + /** + * The valid EOL character. + * + * @var string + */ + public $eolChar = '\\n'; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $found = $phpcsFile->eolChar; + $found = \str_replace("\n", '\\n', $found); + $found = \str_replace("\r", '\\r', $found); + $phpcsFile->recordMetric($stackPtr, 'EOL char', $found); + if ($found === $this->eolChar) { + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + // Check for single line files without an EOL. This is a very special + // case and the EOL char is set to \n when this happens. + if ($found === '\\n') { + $tokens = $phpcsFile->getTokens(); + $lastToken = $phpcsFile->numTokens - 1; + if ($tokens[$lastToken]['line'] === 1 && $tokens[$lastToken]['content'] !== "\n") { + return; + } + } + $error = 'End of line character is invalid; expected "%s" but found "%s"'; + $expected = $this->eolChar; + $expected = \str_replace("\n", '\\n', $expected); + $expected = \str_replace("\r", '\\r', $expected); + $data = [$expected, $found]; + // Errors are always reported on line 1, no matter where the first PHP tag is. + $fix = $phpcsFile->addFixableError($error, 0, 'InvalidEOLChar', $data); + if ($fix === \true) { + $tokens = $phpcsFile->getTokens(); + switch ($this->eolChar) { + case '\\n': + $eolChar = "\n"; + break; + case '\\r': + $eolChar = "\r"; + break; + case '\\r\\n': + $eolChar = "\r\n"; + break; + default: + $eolChar = $this->eolChar; + break; + } + for ($i = 0; $i < $phpcsFile->numTokens; $i++) { + if (isset($tokens[$i + 1]) === \true && $tokens[$i + 1]['line'] <= $tokens[$i]['line']) { + continue; + } + // Token is the last on a line. + if (isset($tokens[$i]['orig_content']) === \true) { + $tokenContent = $tokens[$i]['orig_content']; + } else { + $tokenContent = $tokens[$i]['content']; + } + if ($tokenContent === '') { + // Special case for JS/CSS close tag. + continue; + } + $newContent = \rtrim($tokenContent, "\r\n"); + $newContent .= $eolChar; + if ($tokenContent !== $newContent) { + $phpcsFile->fixer->replaceToken($i, $newContent); + } + } + //end for + } + //end if + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php new file mode 100644 index 00000000000..73f64fbfe4b --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LineLengthSniff.php @@ -0,0 +1,164 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class LineLengthSniff implements Sniff +{ + /** + * The limit that the length of a line should not exceed. + * + * @var integer + */ + public $lineLimit = 80; + /** + * The limit that the length of a line must not exceed. + * + * Set to zero (0) to disable. + * + * @var integer + */ + public $absoluteLineLimit = 100; + /** + * Whether or not to ignore trailing comments. + * + * This has the effect of also ignoring all lines + * that only contain comments. + * + * @var boolean + */ + public $ignoreComments = \false; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + for ($i = 1; $i < $phpcsFile->numTokens; $i++) { + if ($tokens[$i]['column'] === 1) { + $this->checkLineLength($phpcsFile, $tokens, $i); + } + } + $this->checkLineLength($phpcsFile, $tokens, $i); + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() + /** + * Checks if a line is too long. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param array $tokens The token stack. + * @param int $stackPtr The first token on the next line. + * + * @return void + */ + protected function checkLineLength($phpcsFile, $tokens, $stackPtr) + { + // The passed token is the first on the line. + $stackPtr--; + if ($tokens[$stackPtr]['column'] === 1 && $tokens[$stackPtr]['length'] === 0) { + // Blank line. + return; + } + if ($tokens[$stackPtr]['column'] !== 1 && $tokens[$stackPtr]['content'] === $phpcsFile->eolChar) { + $stackPtr--; + } + $onlyComment = \false; + if (isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === \true) { + $prevNonWhiteSpace = $phpcsFile->findPrevious(Tokens::$emptyTokens, $stackPtr - 1, null, \true); + if ($tokens[$stackPtr]['line'] !== $tokens[$prevNonWhiteSpace]['line']) { + $onlyComment = \true; + } + } + if ($onlyComment === \true && isset(Tokens::$phpcsCommentTokens[$tokens[$stackPtr]['code']]) === \true) { + // Ignore PHPCS annotation comments that are on a line by themselves. + return; + } + $lineLength = $tokens[$stackPtr]['column'] + $tokens[$stackPtr]['length'] - 1; + if ($this->ignoreComments === \true && isset(Tokens::$commentTokens[$tokens[$stackPtr]['code']]) === \true) { + // Trailing comments are being ignored in line length calculations. + if ($onlyComment === \true) { + // The comment is the only thing on the line, so no need to check length. + return; + } + $lineLength -= $tokens[$stackPtr]['length']; + } + // Record metrics for common line length groupings. + if ($lineLength <= 80) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '80 or less'); + } else { + if ($lineLength <= 120) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '81-120'); + } else { + if ($lineLength <= 150) { + $phpcsFile->recordMetric($stackPtr, 'Line length', '121-150'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Line length', '151 or more'); + } + } + } + if ($onlyComment === \true) { + // If this is a long comment, check if it can be broken up onto multiple lines. + // Some comments contain unbreakable strings like URLs and so it makes sense + // to ignore the line length in these cases if the URL would be longer than the max + // line length once you indent it to the correct level. + if ($lineLength > $this->lineLimit) { + $oldLength = \strlen($tokens[$stackPtr]['content']); + $newLength = \strlen(\ltrim($tokens[$stackPtr]['content'], "/#\t ")); + $indent = $tokens[$stackPtr]['column'] - 1 + ($oldLength - $newLength); + $nonBreakingLength = $tokens[$stackPtr]['length']; + $space = \strrpos($tokens[$stackPtr]['content'], ' '); + if ($space !== \false) { + $nonBreakingLength -= $space + 1; + } + if ($nonBreakingLength + $indent > $this->lineLimit) { + return; + } + } + } + //end if + if ($this->absoluteLineLimit > 0 && $lineLength > $this->absoluteLineLimit) { + $data = [$this->absoluteLineLimit, $lineLength]; + $error = 'Line exceeds maximum limit of %s characters; contains %s characters'; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else { + if ($lineLength > $this->lineLimit) { + $data = [$this->lineLimit, $lineLength]; + $warning = 'Line exceeds %s characters; contains %s characters'; + $phpcsFile->addWarning($warning, $stackPtr, 'TooLong', $data); + } + } + } + //end checkLineLength() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php new file mode 100644 index 00000000000..b9c23545002 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/LowercasedFilenameSniff.php @@ -0,0 +1,56 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class LowercasedFilenameSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $filename = $phpcsFile->getFilename(); + if ($filename === 'STDIN') { + return; + } + $filename = \basename($filename); + $lowercaseFilename = \strtolower($filename); + if ($filename !== $lowercaseFilename) { + $data = [$filename, $lowercaseFilename]; + $error = 'Filename "%s" doesn\'t match the expected filename "%s"'; + $phpcsFile->addError($error, $stackPtr, 'NotFound', $data); + $phpcsFile->recordMetric($stackPtr, 'Lowercase filename', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Lowercase filename', 'yes'); + } + // Ignore the rest of the file. + return $phpcsFile->numTokens + 1; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php new file mode 100644 index 00000000000..3a2f6e2f35a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneClassPerFileSniff.php @@ -0,0 +1,50 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class OneClassPerFileSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_CLASS]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = $stackPtr + 1; + if (isset($tokens[$stackPtr]['scope_closer']) === \true) { + $start = $tokens[$stackPtr]['scope_closer'] + 1; + } + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== \false) { + $error = 'Only one class is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php new file mode 100644 index 00000000000..0890b6affef --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneInterfacePerFileSniff.php @@ -0,0 +1,50 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class OneInterfacePerFileSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_INTERFACE]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = $stackPtr + 1; + if (isset($tokens[$stackPtr]['scope_closer']) === \true) { + $start = $tokens[$stackPtr]['scope_closer'] + 1; + } + $nextInterface = $phpcsFile->findNext($this->register(), $start); + if ($nextInterface !== \false) { + $error = 'Only one interface is allowed in a file'; + $phpcsFile->addError($error, $nextInterface, 'MultipleFound'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php new file mode 100644 index 00000000000..49abdf0a96a --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneObjectStructurePerFileSniff.php @@ -0,0 +1,50 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class OneObjectStructurePerFileSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_CLASS, \T_INTERFACE, \T_TRAIT, \T_ENUM]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = $stackPtr + 1; + if (isset($tokens[$stackPtr]['scope_closer']) === \true) { + $start = $tokens[$stackPtr]['scope_closer'] + 1; + } + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== \false) { + $error = 'Only one object structure is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php new file mode 100644 index 00000000000..c9d0f01f237 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Files/OneTraitPerFileSniff.php @@ -0,0 +1,50 @@ + + * @copyright 2010-2014 Alexander Obuhovich + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Files; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class OneTraitPerFileSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_TRAIT]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $start = $stackPtr + 1; + if (isset($tokens[$stackPtr]['scope_closer']) === \true) { + $start = $tokens[$stackPtr]['scope_closer'] + 1; + } + $nextClass = $phpcsFile->findNext($this->register(), $start); + if ($nextClass !== \false) { + $error = 'Only one trait is allowed in a file'; + $phpcsFile->addError($error, $nextClass, 'MultipleFound'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php new file mode 100644 index 00000000000..c2def6348f1 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/DisallowMultipleStatementsSniff.php @@ -0,0 +1,89 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DisallowMultipleStatementsSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_SEMICOLON]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $fixable = \true; + $prev = $stackPtr; + do { + $prev = $phpcsFile->findPrevious([\T_SEMICOLON, \T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO, \T_PHPCS_IGNORE], $prev - 1); + if ($prev === \false || $tokens[$prev]['code'] === \T_OPEN_TAG || $tokens[$prev]['code'] === \T_OPEN_TAG_WITH_ECHO) { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'no'); + return; + } + if ($tokens[$prev]['code'] === \T_PHPCS_IGNORE) { + $fixable = \false; + } + } while ($tokens[$prev]['code'] === \T_PHPCS_IGNORE); + // Ignore multiple statements in a FOR condition. + foreach ([$stackPtr, $prev] as $checkToken) { + if (isset($tokens[$checkToken]['nested_parenthesis']) === \true) { + foreach ($tokens[$checkToken]['nested_parenthesis'] as $bracket) { + if (isset($tokens[$bracket]['parenthesis_owner']) === \false) { + // Probably a closure sitting inside a function call. + continue; + } + $owner = $tokens[$bracket]['parenthesis_owner']; + if ($tokens[$owner]['code'] === \T_FOR) { + return; + } + } + } + } + if ($tokens[$prev]['line'] === $tokens[$stackPtr]['line']) { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'yes'); + $error = 'Each PHP statement must be on a line by itself'; + $code = 'SameLine'; + if ($fixable === \false) { + $phpcsFile->addError($error, $stackPtr, $code); + return; + } + $fix = $phpcsFile->addFixableError($error, $stackPtr, $code); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addNewline($prev); + if ($tokens[$prev + 1]['code'] === \T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($prev + 1, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } else { + $phpcsFile->recordMetric($stackPtr, 'Multiple statements on same line', 'no'); + } + //end if + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php new file mode 100644 index 00000000000..01c0697f54d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/MultipleStatementAlignmentSniff.php @@ -0,0 +1,359 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class MultipleStatementAlignmentSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * If true, an error will be thrown; otherwise a warning. + * + * @var boolean + */ + public $error = \false; + /** + * The maximum amount of padding before the alignment is ignored. + * + * If the amount of padding required to align this assignment with the + * surrounding assignments exceeds this number, the assignment will be + * ignored and no errors or warnings will be thrown. + * + * @var integer + */ + public $maxPadding = 1000; + /** + * Controls which side of the assignment token is used for alignment. + * + * @var boolean + */ + public $alignAtEnd = \true; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + $tokens = Tokens::$assignmentTokens; + unset($tokens[\T_DOUBLE_ARROW]); + return $tokens; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $lastAssign = $this->checkAlignment($phpcsFile, $stackPtr); + return $lastAssign + 1; + } + //end process() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $end The token where checking should end. + * If NULL, the entire file will be checked. + * + * @return int + */ + public function checkAlignment($phpcsFile, $stackPtr, $end = null) + { + $tokens = $phpcsFile->getTokens(); + // Ignore assignments used in a condition, like an IF or FOR or closure param defaults. + if (isset($tokens[$stackPtr]['nested_parenthesis']) === \true) { + // If the parenthesis is on the same line as the assignment, + // then it should be ignored as it is specifically being grouped. + $parens = $tokens[$stackPtr]['nested_parenthesis']; + $lastParen = \array_pop($parens); + if ($tokens[$lastParen]['line'] === $tokens[$stackPtr]['line']) { + return $stackPtr; + } + foreach ($tokens[$stackPtr]['nested_parenthesis'] as $start => $end) { + if (isset($tokens[$start]['parenthesis_owner']) === \true) { + return $stackPtr; + } + } + } + $assignments = []; + $prevAssign = null; + $lastLine = $tokens[$stackPtr]['line']; + $maxPadding = null; + $stopped = null; + $lastCode = $stackPtr; + $lastSemi = null; + $arrayEnd = null; + if ($end === null) { + $end = $phpcsFile->numTokens; + } + $find = Tokens::$assignmentTokens; + unset($find[\T_DOUBLE_ARROW]); + $scopes = Tokens::$scopeOpeners; + unset($scopes[\T_CLOSURE]); + unset($scopes[\T_ANON_CLASS]); + unset($scopes[\T_OBJECT]); + for ($assign = $stackPtr; $assign < $end; $assign++) { + if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // Statement is in a different context, so the block is over. + break; + } + if (isset($tokens[$assign]['scope_opener']) === \true && $tokens[$assign]['level'] === $tokens[$stackPtr]['level']) { + if (isset($scopes[$tokens[$assign]['code']]) === \true) { + // This type of scope indicates that the assignment block is over. + break; + } + // Skip over the scope block because it is seen as part of the assignment block, + // but also process any assignment blocks that are inside as well. + $nextAssign = $phpcsFile->findNext($find, $assign + 1, $tokens[$assign]['scope_closer'] - 1); + if ($nextAssign !== \false) { + $assign = $this->checkAlignment($phpcsFile, $nextAssign); + } else { + $assign = $tokens[$assign]['scope_closer']; + } + $lastCode = $assign; + continue; + } + if ($assign === $arrayEnd) { + $arrayEnd = null; + } + if (isset($find[$tokens[$assign]['code']]) === \false) { + // A blank line indicates that the assignment block has ended. + if (isset(Tokens::$emptyTokens[$tokens[$assign]['code']]) === \false && $tokens[$assign]['line'] - $tokens[$lastCode]['line'] > 1 && $tokens[$assign]['level'] === $tokens[$stackPtr]['level'] && $arrayEnd === null) { + break; + } + if ($tokens[$assign]['code'] === \T_CLOSE_TAG) { + // Breaking out of PHP ends the assignment block. + break; + } + if ($tokens[$assign]['code'] === \T_OPEN_SHORT_ARRAY && isset($tokens[$assign]['bracket_closer']) === \true) { + $arrayEnd = $tokens[$assign]['bracket_closer']; + } + if ($tokens[$assign]['code'] === \T_ARRAY && isset($tokens[$assign]['parenthesis_opener']) === \true && isset($tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer']) === \true) { + $arrayEnd = $tokens[$tokens[$assign]['parenthesis_opener']]['parenthesis_closer']; + } + if (isset(Tokens::$emptyTokens[$tokens[$assign]['code']]) === \false) { + $lastCode = $assign; + if ($tokens[$assign]['code'] === \T_SEMICOLON) { + if ($tokens[$assign]['conditions'] === $tokens[$stackPtr]['conditions']) { + if ($lastSemi !== null && $prevAssign !== null && $lastSemi > $prevAssign) { + // This statement did not have an assignment operator in it. + break; + } else { + $lastSemi = $assign; + } + } else { + if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // Statement is in a different context, so the block is over. + break; + } + } + } + } + //end if + continue; + } else { + if ($assign !== $stackPtr && $tokens[$assign]['line'] === $lastLine) { + // Skip multiple assignments on the same line. We only need to + // try and align the first assignment. + continue; + } + } + //end if + if ($assign !== $stackPtr) { + if ($tokens[$assign]['level'] > $tokens[$stackPtr]['level']) { + // Has to be nested inside the same conditions as the first assignment. + // We've gone one level down, so process this new block. + $assign = $this->checkAlignment($phpcsFile, $assign); + $lastCode = $assign; + continue; + } else { + if ($tokens[$assign]['level'] < $tokens[$stackPtr]['level']) { + // We've gone one level up, so the block we are processing is done. + break; + } else { + if ($arrayEnd !== null) { + // Assignments inside arrays are not part of + // the original block, so process this new block. + $assign = $this->checkAlignment($phpcsFile, $assign, $arrayEnd) - 1; + $arrayEnd = null; + $lastCode = $assign; + continue; + } + } + } + // Make sure it is not assigned inside a condition (eg. IF, FOR). + if (isset($tokens[$assign]['nested_parenthesis']) === \true) { + // If the parenthesis is on the same line as the assignment, + // then it should be ignored as it is specifically being grouped. + $parens = $tokens[$assign]['nested_parenthesis']; + $lastParen = \array_pop($parens); + if ($tokens[$lastParen]['line'] === $tokens[$assign]['line']) { + break; + } + foreach ($tokens[$assign]['nested_parenthesis'] as $start => $end) { + if (isset($tokens[$start]['parenthesis_owner']) === \true) { + break 2; + } + } + } + } + //end if + $var = $phpcsFile->findPrevious(Tokens::$emptyTokens, $assign - 1, null, \true); + // Make sure we wouldn't break our max padding length if we + // aligned with this statement, or they wouldn't break the max + // padding length if they aligned with us. + $varEnd = $tokens[$var + 1]['column']; + $assignLen = $tokens[$assign]['length']; + if ($this->alignAtEnd !== \true) { + $assignLen = 1; + } + if ($assign !== $stackPtr) { + if ($prevAssign === null) { + // Processing an inner block but no assignments found. + break; + } + if ($varEnd + 1 > $assignments[$prevAssign]['assign_col']) { + $padding = 1; + $assignColumn = $varEnd + 1; + } else { + $padding = $assignments[$prevAssign]['assign_col'] - $varEnd + $assignments[$prevAssign]['assign_len'] - $assignLen; + if ($padding <= 0) { + $padding = 1; + } + if ($padding > $this->maxPadding) { + $stopped = $assign; + break; + } + $assignColumn = $varEnd + $padding; + } + //end if + if ($assignColumn + $assignLen > $assignments[$maxPadding]['assign_col'] + $assignments[$maxPadding]['assign_len']) { + $newPadding = $varEnd - $assignments[$maxPadding]['var_end'] + $assignLen - $assignments[$maxPadding]['assign_len'] + 1; + if ($newPadding > $this->maxPadding) { + $stopped = $assign; + break; + } else { + // New alignment settings for previous assignments. + foreach ($assignments as $i => $data) { + if ($i === $assign) { + break; + } + $newPadding = $varEnd - $data['var_end'] + $assignLen - $data['assign_len'] + 1; + $assignments[$i]['expected'] = $newPadding; + $assignments[$i]['assign_col'] = $data['var_end'] + $newPadding; + } + $padding = 1; + $assignColumn = $varEnd + 1; + } + } else { + if ($padding > $assignments[$maxPadding]['expected']) { + $maxPadding = $assign; + } + } + //end if + } else { + $padding = 1; + $assignColumn = $varEnd + 1; + $maxPadding = $assign; + } + //end if + $found = 0; + if ($tokens[$var + 1]['code'] === \T_WHITESPACE) { + $found = $tokens[$var + 1]['length']; + if ($found === 0) { + // This means a newline was found. + $found = 1; + } + } + $assignments[$assign] = ['var_end' => $varEnd, 'assign_len' => $assignLen, 'assign_col' => $assignColumn, 'expected' => $padding, 'found' => $found]; + $lastLine = $tokens[$assign]['line']; + $prevAssign = $assign; + } + //end for + if (empty($assignments) === \true) { + return $stackPtr; + } + $numAssignments = \count($assignments); + $errorGenerated = \false; + foreach ($assignments as $assignment => $data) { + if ($data['found'] === $data['expected']) { + continue; + } + $expectedText = $data['expected'] . ' space'; + if ($data['expected'] !== 1) { + $expectedText .= 's'; + } + if ($data['found'] === null) { + $foundText = 'a new line'; + } else { + $foundText = $data['found'] . ' space'; + if ($data['found'] !== 1) { + $foundText .= 's'; + } + } + if ($numAssignments === 1) { + $type = 'Incorrect'; + $error = 'Equals sign not aligned correctly; expected %s but found %s'; + } else { + $type = 'NotSame'; + $error = 'Equals sign not aligned with surrounding assignments; expected %s but found %s'; + } + $errorData = [$expectedText, $foundText]; + if ($this->error === \true) { + $fix = $phpcsFile->addFixableError($error, $assignment, $type, $errorData); + } else { + $fix = $phpcsFile->addFixableWarning($error, $assignment, $type . 'Warning', $errorData); + } + $errorGenerated = \true; + if ($fix === \true && $data['found'] !== null) { + $newContent = \str_repeat(' ', $data['expected']); + if ($data['found'] === 0) { + $phpcsFile->fixer->addContentBefore($assignment, $newContent); + } else { + $phpcsFile->fixer->replaceToken($assignment - 1, $newContent); + } + } + } + //end foreach + if ($numAssignments > 1) { + if ($errorGenerated === \true) { + $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Adjacent assignments aligned', 'yes'); + } + } + if ($stopped !== null) { + return $this->checkAlignment($phpcsFile, $stopped); + } else { + return $assign; + } + } + //end checkAlignment() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php new file mode 100644 index 00000000000..4f6b3e37667 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/NoSpaceAfterCastSniff.php @@ -0,0 +1,53 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + * + * @deprecated 3.4.0 Use the Generic.Formatting.SpaceAfterCast sniff with + * the $spacing property set to 0 instead. + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class NoSpaceAfterCastSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr + 1]['code'] !== \T_WHITESPACE) { + return; + } + $error = 'A cast statement must not be followed by a space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'SpaceFound'); + if ($fix === \true) { + $phpcsFile->fixer->replaceToken($stackPtr + 1, ''); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php new file mode 100644 index 00000000000..9fcd8b526dd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterCastSniff.php @@ -0,0 +1,125 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class SpaceAfterCastSniff implements Sniff +{ + /** + * The number of spaces desired after a cast token. + * + * @var integer + */ + public $spacing = 1; + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = \false; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $this->spacing = (int) $this->spacing; + if ($tokens[$stackPtr]['code'] === \T_BINARY_CAST && $tokens[$stackPtr]['content'] === 'b') { + // You can't replace a space after this type of binary casting. + return; + } + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, \true); + if ($nextNonEmpty === \false) { + return; + } + if ($this->ignoreNewlines === \true && $tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 'newline'); + return; + } + if ($this->spacing === 0 && $nextNonEmpty === $stackPtr + 1) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 0); + return; + } + $nextNonWhitespace = $phpcsFile->findNext(\T_WHITESPACE, $stackPtr + 1, null, \true); + if ($nextNonEmpty !== $nextNonWhitespace) { + $error = 'Expected %s space(s) after cast statement; comment found'; + $data = [$this->spacing]; + $phpcsFile->addError($error, $stackPtr, 'CommentFound', $data); + if ($tokens[$stackPtr + 1]['code'] === \T_WHITESPACE) { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', $tokens[$stackPtr + 1]['length']); + } else { + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', 0); + } + return; + } + $found = 0; + if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $found = 'newline'; + } else { + if ($tokens[$stackPtr + 1]['code'] === \T_WHITESPACE) { + $found = $tokens[$stackPtr + 1]['length']; + } + } + $phpcsFile->recordMetric($stackPtr, 'Spacing after cast statement', $found); + if ($found === $this->spacing) { + return; + } + $error = 'Expected %s space(s) after cast statement; %s found'; + $data = [$this->spacing, $found]; + $errorCode = 'TooMuchSpace'; + if ($this->spacing !== 0) { + if ($found === 0) { + $errorCode = 'NoSpace'; + } else { + if ($found !== 'newline' && $found < $this->spacing) { + $errorCode = 'TooLittleSpace'; + } + } + } + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data); + if ($fix === \true) { + $padding = \str_repeat(' ', $this->spacing); + if ($found === 0) { + $phpcsFile->fixer->addContent($stackPtr, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $start = $stackPtr + 1; + if ($this->spacing > 0) { + $phpcsFile->fixer->replaceToken($start, $padding); + ++$start; + } + for ($i = $start; $i < $nextNonWhitespace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php new file mode 100644 index 00000000000..834bd9918d3 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceAfterNotSniff.php @@ -0,0 +1,109 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class SpaceAfterNotSniff implements Sniff +{ + /** + * A list of tokenizers this sniff supports. + * + * @var array + */ + public $supportedTokenizers = ['PHP', 'JS']; + /** + * The number of spaces desired after the NOT operator. + * + * @var integer + */ + public $spacing = 1; + /** + * Allow newlines instead of spaces. + * + * @var boolean + */ + public $ignoreNewlines = \false; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_BOOLEAN_NOT]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $this->spacing = (int) $this->spacing; + $nextNonEmpty = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, \true); + if ($nextNonEmpty === \false) { + return; + } + if ($this->ignoreNewlines === \true && $tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + return; + } + if ($this->spacing === 0 && $nextNonEmpty === $stackPtr + 1) { + return; + } + $nextNonWhitespace = $phpcsFile->findNext(\T_WHITESPACE, $stackPtr + 1, null, \true); + if ($nextNonEmpty !== $nextNonWhitespace) { + $error = 'Expected %s space(s) after NOT operator; comment found'; + $data = [$this->spacing]; + $phpcsFile->addError($error, $stackPtr, 'CommentFound', $data); + return; + } + $found = 0; + if ($tokens[$stackPtr]['line'] !== $tokens[$nextNonEmpty]['line']) { + $found = 'newline'; + } else { + if ($tokens[$stackPtr + 1]['code'] === \T_WHITESPACE) { + $found = $tokens[$stackPtr + 1]['length']; + } + } + if ($found === $this->spacing) { + return; + } + $error = 'Expected %s space(s) after NOT operator; %s found'; + $data = [$this->spacing, $found]; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'Incorrect', $data); + if ($fix === \true) { + $padding = \str_repeat(' ', $this->spacing); + if ($found === 0) { + $phpcsFile->fixer->addContent($stackPtr, $padding); + } else { + $phpcsFile->fixer->beginChangeset(); + $start = $stackPtr + 1; + if ($this->spacing > 0) { + $phpcsFile->fixer->replaceToken($start, $padding); + ++$start; + } + for ($i = $start; $i < $nextNonWhitespace; $i++) { + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php new file mode 100644 index 00000000000..9c293243a33 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Formatting/SpaceBeforeCastSniff.php @@ -0,0 +1,62 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Formatting; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class SpaceBeforeCastSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return Tokens::$castTokens; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr]['column'] === 1) { + return; + } + if ($tokens[$stackPtr - 1]['code'] !== \T_WHITESPACE) { + $error = 'A cast statement must be preceded by a single space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'NoSpace'); + if ($fix === \true) { + $phpcsFile->fixer->addContentBefore($stackPtr, ' '); + } + $phpcsFile->recordMetric($stackPtr, 'Spacing before cast statement', 0); + return; + } + $phpcsFile->recordMetric($stackPtr, 'Spacing before cast statement', $tokens[$stackPtr - 1]['length']); + if ($tokens[$stackPtr - 1]['column'] !== 1 && $tokens[$stackPtr - 1]['length'] !== 1) { + $error = 'A cast statement must be preceded by a single space'; + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'TooMuchSpace'); + if ($fix === \true) { + $phpcsFile->fixer->replaceToken($stackPtr - 1, ' '); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php new file mode 100644 index 00000000000..f5c4bbec553 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/CallTimePassByReferenceSniff.php @@ -0,0 +1,100 @@ + + * @copyright 2009-2014 Florian Grandel + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class CallTimePassByReferenceSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_STRING, \T_VARIABLE]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $findTokens = Tokens::$emptyTokens; + $findTokens[] = \T_BITWISE_AND; + $prev = $phpcsFile->findPrevious($findTokens, $stackPtr - 1, null, \true); + // Skip tokens that are the names of functions or classes + // within their definitions. For example: function myFunction... + // "myFunction" is T_STRING but we should skip because it is not a + // function or method *call*. + $prevCode = $tokens[$prev]['code']; + if ($prevCode === \T_FUNCTION || $prevCode === \T_CLASS) { + return; + } + // If the next non-whitespace token after the function or method call + // is not an opening parenthesis then it cant really be a *call*. + $functionName = $stackPtr; + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, $functionName + 1, null, \true); + if ($tokens[$openBracket]['code'] !== \T_OPEN_PARENTHESIS) { + return; + } + if (isset($tokens[$openBracket]['parenthesis_closer']) === \false) { + return; + } + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + $nextSeparator = $openBracket; + $find = [\T_VARIABLE, \T_OPEN_SHORT_ARRAY]; + while (($nextSeparator = $phpcsFile->findNext($find, $nextSeparator + 1, $closeBracket)) !== \false) { + if (isset($tokens[$nextSeparator]['nested_parenthesis']) === \false) { + continue; + } + if ($tokens[$nextSeparator]['code'] === \T_OPEN_SHORT_ARRAY) { + $nextSeparator = $tokens[$nextSeparator]['bracket_closer']; + continue; + } + // Make sure the variable belongs directly to this function call + // and is not inside a nested function call or array. + $brackets = $tokens[$nextSeparator]['nested_parenthesis']; + $lastBracket = \array_pop($brackets); + if ($lastBracket !== $closeBracket) { + continue; + } + $tokenBefore = $phpcsFile->findPrevious(Tokens::$emptyTokens, $nextSeparator - 1, null, \true); + if ($tokens[$tokenBefore]['code'] === \T_BITWISE_AND) { + if ($phpcsFile->isReference($tokenBefore) === \false) { + continue; + } + // We also want to ignore references used in assignment + // operations passed as function arguments, but isReference() + // sees them as valid references (which they are). + $tokenBefore = $phpcsFile->findPrevious(Tokens::$emptyTokens, $tokenBefore - 1, null, \true); + if (isset(Tokens::$assignmentTokens[$tokens[$tokenBefore]['code']]) === \true) { + continue; + } + // T_BITWISE_AND represents a pass-by-reference. + $error = 'Call-time pass-by-reference calls are prohibited'; + $phpcsFile->addError($error, $tokenBefore, 'NotAllowed'); + } + //end if + } + //end while + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php new file mode 100644 index 00000000000..18eea4fa171 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/FunctionCallArgumentSpacingSniff.php @@ -0,0 +1,153 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class FunctionCallArgumentSpacingSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_STRING, \T_ISSET, \T_UNSET, \T_SELF, \T_STATIC, \T_PARENT, \T_VARIABLE, \T_CLOSE_CURLY_BRACKET, \T_CLOSE_PARENTHESIS]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + // Skip tokens that are the names of functions or classes + // within their definitions. For example: + // function myFunction... + // "myFunction" is T_STRING but we should skip because it is not a + // function or method *call*. + $functionName = $stackPtr; + $ignoreTokens = Tokens::$emptyTokens; + $ignoreTokens[] = \T_BITWISE_AND; + $functionKeyword = $phpcsFile->findPrevious($ignoreTokens, $stackPtr - 1, null, \true); + if ($tokens[$functionKeyword]['code'] === \T_FUNCTION || $tokens[$functionKeyword]['code'] === \T_CLASS) { + return; + } + if ($tokens[$stackPtr]['code'] === \T_CLOSE_CURLY_BRACKET && isset($tokens[$stackPtr]['scope_condition']) === \true) { + // Not a function call. + return; + } + // If the next non-whitespace token after the function or method call + // is not an opening parenthesis then it can't really be a *call*. + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, $functionName + 1, null, \true); + if ($tokens[$openBracket]['code'] !== \T_OPEN_PARENTHESIS) { + return; + } + if (isset($tokens[$openBracket]['parenthesis_closer']) === \false) { + return; + } + $this->checkSpacing($phpcsFile, $stackPtr, $openBracket); + } + //end process() + /** + * Checks the spacing around commas. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * @param int $openBracket The position of the opening bracket + * in the stack passed in $tokens. + * + * @return void + */ + public function checkSpacing(File $phpcsFile, $stackPtr, $openBracket) + { + $tokens = $phpcsFile->getTokens(); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + $nextSeparator = $openBracket; + $find = [\T_COMMA, \T_CLOSURE, \T_ANON_CLASS, \T_OPEN_SHORT_ARRAY]; + while (($nextSeparator = $phpcsFile->findNext($find, $nextSeparator + 1, $closeBracket)) !== \false) { + if ($tokens[$nextSeparator]['code'] === \T_CLOSURE || $tokens[$nextSeparator]['code'] === \T_ANON_CLASS) { + // Skip closures. + $nextSeparator = $tokens[$nextSeparator]['scope_closer']; + continue; + } else { + if ($tokens[$nextSeparator]['code'] === \T_OPEN_SHORT_ARRAY) { + // Skips arrays using short notation. + $nextSeparator = $tokens[$nextSeparator]['bracket_closer']; + continue; + } + } + // Make sure the comma or variable belongs directly to this function call, + // and is not inside a nested function call or array. + $brackets = $tokens[$nextSeparator]['nested_parenthesis']; + $lastBracket = \array_pop($brackets); + if ($lastBracket !== $closeBracket) { + continue; + } + if ($tokens[$nextSeparator]['code'] === \T_COMMA) { + if ($tokens[$nextSeparator - 1]['code'] === \T_WHITESPACE) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $nextSeparator - 2, null, \true); + if (isset(Tokens::$heredocTokens[$tokens[$prev]['code']]) === \false) { + $error = 'Space found before comma in argument list'; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'SpaceBeforeComma'); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + if ($tokens[$prev]['line'] !== $tokens[$nextSeparator]['line']) { + $phpcsFile->fixer->addContent($prev, ','); + $phpcsFile->fixer->replaceToken($nextSeparator, ''); + } else { + $phpcsFile->fixer->replaceToken($nextSeparator - 1, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + //end if + } + //end if + if ($tokens[$nextSeparator + 1]['code'] !== \T_WHITESPACE) { + $error = 'No space found after comma in argument list'; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'NoSpaceAfterComma'); + if ($fix === \true) { + $phpcsFile->fixer->addContent($nextSeparator, ' '); + } + } else { + // If there is a newline in the space, then they must be formatting + // each argument on a newline, which is valid, so ignore it. + $next = $phpcsFile->findNext(Tokens::$emptyTokens, $nextSeparator + 1, null, \true); + if ($tokens[$next]['line'] === $tokens[$nextSeparator]['line']) { + $space = $tokens[$nextSeparator + 1]['length']; + if ($space > 1) { + $error = 'Expected 1 space after comma in argument list; %s found'; + $data = [$space]; + $fix = $phpcsFile->addFixableError($error, $nextSeparator, 'TooMuchSpaceAfterComma', $data); + if ($fix === \true) { + $phpcsFile->fixer->replaceToken($nextSeparator + 1, ' '); + } + } + } + } + //end if + } + //end if + } + //end while + } + //end checkSpacing() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php new file mode 100644 index 00000000000..05959243149 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceBsdAllmanSniff.php @@ -0,0 +1,186 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class OpeningFunctionBraceBsdAllmanSniff implements Sniff +{ + /** + * Should this sniff check function braces? + * + * @var boolean + */ + public $checkFunctions = \true; + /** + * Should this sniff check closure braces? + * + * @var boolean + */ + public $checkClosures = \false; + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_FUNCTION, \T_CLOSURE]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === \false) { + return; + } + if ($tokens[$stackPtr]['code'] === \T_FUNCTION && (bool) $this->checkFunctions === \false || $tokens[$stackPtr]['code'] === \T_CLOSURE && (bool) $this->checkClosures === \false) { + return; + } + $openingBrace = $tokens[$stackPtr]['scope_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[$stackPtr]['code'] === \T_CLOSURE) { + $use = $phpcsFile->findNext(\T_USE, $closeBracket + 1, $tokens[$stackPtr]['scope_opener']); + if ($use !== \false) { + $openBracket = $phpcsFile->findNext(\T_OPEN_PARENTHESIS, $use + 1); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + } + } + // Find the end of the function declaration. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $openingBrace - 1, $closeBracket, \true); + $functionLine = $tokens[$prev]['line']; + $braceLine = $tokens[$openingBrace]['line']; + $lineDifference = $braceLine - $functionLine; + $metricType = 'Function'; + if ($tokens[$stackPtr]['code'] === \T_CLOSURE) { + $metricType = 'Closure'; + } + if ($lineDifference === 0) { + $error = 'Opening brace should be on a new line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnSameLine'); + if ($fix === \true) { + $hasTrailingAnnotation = \false; + for ($nextLine = $openingBrace + 1; $nextLine < $phpcsFile->numTokens; $nextLine++) { + if ($tokens[$openingBrace]['line'] !== $tokens[$nextLine]['line']) { + break; + } + if (isset(Tokens::$phpcsCommentTokens[$tokens[$nextLine]['code']]) === \true) { + $hasTrailingAnnotation = \true; + } + } + $phpcsFile->fixer->beginChangeset(); + $indent = $phpcsFile->findFirstOnLine([], $openingBrace); + if ($hasTrailingAnnotation === \false || $nextLine === \false) { + if ($tokens[$indent]['code'] === \T_WHITESPACE) { + $phpcsFile->fixer->addContentBefore($openingBrace, $tokens[$indent]['content']); + } + if ($tokens[$openingBrace - 1]['code'] === \T_WHITESPACE) { + $phpcsFile->fixer->replaceToken($openingBrace - 1, ''); + } + $phpcsFile->fixer->addNewlineBefore($openingBrace); + } else { + $phpcsFile->fixer->replaceToken($openingBrace, ''); + $phpcsFile->fixer->addNewlineBefore($nextLine); + $phpcsFile->fixer->addContentBefore($nextLine, '{'); + if ($tokens[$indent]['code'] === \T_WHITESPACE) { + $phpcsFile->fixer->addContentBefore($nextLine, $tokens[$indent]['content']); + } + } + $phpcsFile->fixer->endChangeset(); + } + //end if + $phpcsFile->recordMetric($stackPtr, "{$metricType} opening brace placement", 'same line'); + } else { + if ($lineDifference > 1) { + $error = 'Opening brace should be on the line after the declaration; found %s blank line(s)'; + $data = [$lineDifference - 1]; + $prevNonWs = $phpcsFile->findPrevious(\T_WHITESPACE, $openingBrace - 1, $closeBracket, \true); + if ($prevNonWs !== $prev) { + // There must be a comment between the end of the function declaration and the open brace. + // Report, but don't fix. + $phpcsFile->addError($error, $openingBrace, 'BraceSpacing', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceSpacing', $data); + if ($fix === \true) { + $phpcsFile->fixer->beginChangeset(); + for ($i = $openingBrace; $i > $prev; $i--) { + if ($tokens[$i]['line'] === $tokens[$openingBrace]['line']) { + if ($tokens[$i]['column'] === 1) { + $phpcsFile->fixer->addNewLineBefore($i); + } + continue; + } + $phpcsFile->fixer->replaceToken($i, ''); + } + $phpcsFile->fixer->endChangeset(); + } + } + //end if + } + } + //end if + $ignore = Tokens::$phpcsCommentTokens; + $ignore[] = \T_WHITESPACE; + $next = $phpcsFile->findNext($ignore, $openingBrace + 1, null, \true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + if ($next === $tokens[$stackPtr]['scope_closer']) { + // Ignore empty functions. + return; + } + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === \true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + // Only continue checking if the opening brace looks good. + if ($lineDifference !== 1) { + return; + } + // We need to actually find the first piece of content on this line, + // as if this is a method with tokens before it (public, static etc) + // or an if with an else before it, then we need to start the scope + // checking from there, rather than the current token. + $lineStart = $phpcsFile->findFirstOnLine(\T_WHITESPACE, $stackPtr, \true); + // The opening brace is on the correct line, now it needs to be + // checked to be correctly indented. + $startColumn = $tokens[$lineStart]['column']; + $braceIndent = $tokens[$openingBrace]['column']; + if ($braceIndent !== $startColumn) { + $expected = $startColumn - 1; + $found = $braceIndent - 1; + $error = 'Opening brace indented incorrectly; expected %s spaces, found %s'; + $data = [$expected, $found]; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceIndent', $data); + if ($fix === \true) { + $indent = \str_repeat(' ', $expected); + if ($found === 0) { + $phpcsFile->fixer->addContentBefore($openingBrace, $indent); + } else { + $phpcsFile->fixer->replaceToken($openingBrace - 1, $indent); + } + } + } + //end if + $phpcsFile->recordMetric($stackPtr, "{$metricType} opening brace placement", 'new line'); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php new file mode 100644 index 00000000000..bf2ce8276c6 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Functions/OpeningFunctionBraceKernighanRitchieSniff.php @@ -0,0 +1,150 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Functions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class OpeningFunctionBraceKernighanRitchieSniff implements Sniff +{ + /** + * Should this sniff check function braces? + * + * @var boolean + */ + public $checkFunctions = \true; + /** + * Should this sniff check closure braces? + * + * @var boolean + */ + public $checkClosures = \false; + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return void + */ + public function register() + { + return [\T_FUNCTION, \T_CLOSURE]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if (isset($tokens[$stackPtr]['scope_opener']) === \false) { + return; + } + if ($tokens[$stackPtr]['code'] === \T_FUNCTION && (bool) $this->checkFunctions === \false || $tokens[$stackPtr]['code'] === \T_CLOSURE && (bool) $this->checkClosures === \false) { + return; + } + $openingBrace = $tokens[$stackPtr]['scope_opener']; + $closeBracket = $tokens[$stackPtr]['parenthesis_closer']; + if ($tokens[$stackPtr]['code'] === \T_CLOSURE) { + $use = $phpcsFile->findNext(\T_USE, $closeBracket + 1, $tokens[$stackPtr]['scope_opener']); + if ($use !== \false) { + $openBracket = $phpcsFile->findNext(\T_OPEN_PARENTHESIS, $use + 1); + $closeBracket = $tokens[$openBracket]['parenthesis_closer']; + } + } + // Find the end of the function declaration. + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $openingBrace - 1, $closeBracket, \true); + $functionLine = $tokens[$prev]['line']; + $braceLine = $tokens[$openingBrace]['line']; + $lineDifference = $braceLine - $functionLine; + $metricType = 'Function'; + if ($tokens[$stackPtr]['code'] === \T_CLOSURE) { + $metricType = 'Closure'; + } + if ($lineDifference > 0) { + $phpcsFile->recordMetric($stackPtr, "{$metricType} opening brace placement", 'new line'); + $error = 'Opening brace should be on the same line as the declaration'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'BraceOnNewLine'); + if ($fix === \true) { + $prev = $phpcsFile->findPrevious(Tokens::$emptyTokens, $openingBrace - 1, $closeBracket, \true); + $phpcsFile->fixer->beginChangeset(); + $phpcsFile->fixer->addContent($prev, ' {'); + $phpcsFile->fixer->replaceToken($openingBrace, ''); + if ($tokens[$openingBrace + 1]['code'] === \T_WHITESPACE && $tokens[$openingBrace + 2]['line'] > $tokens[$openingBrace]['line']) { + // Brace is followed by a new line, so remove it to ensure we don't + // leave behind a blank line at the top of the block. + $phpcsFile->fixer->replaceToken($openingBrace + 1, ''); + if ($tokens[$openingBrace - 1]['code'] === \T_WHITESPACE && $tokens[$openingBrace - 1]['line'] === $tokens[$openingBrace]['line'] && $tokens[$openingBrace - 2]['line'] < $tokens[$openingBrace]['line']) { + // Brace is preceded by indent, so remove it to ensure we don't + // leave behind more indent than is required for the first line. + $phpcsFile->fixer->replaceToken($openingBrace - 1, ''); + } + } + $phpcsFile->fixer->endChangeset(); + } + //end if + } else { + $phpcsFile->recordMetric($stackPtr, "{$metricType} opening brace placement", 'same line'); + } + //end if + $ignore = Tokens::$phpcsCommentTokens; + $ignore[] = \T_WHITESPACE; + $next = $phpcsFile->findNext($ignore, $openingBrace + 1, null, \true); + if ($tokens[$next]['line'] === $tokens[$openingBrace]['line']) { + if ($next === $tokens[$stackPtr]['scope_closer'] || $tokens[$next]['code'] === \T_CLOSE_TAG) { + // Ignore empty functions. + return; + } + $error = 'Opening brace must be the last content on the line'; + $fix = $phpcsFile->addFixableError($error, $openingBrace, 'ContentAfterBrace'); + if ($fix === \true) { + $phpcsFile->fixer->addNewline($openingBrace); + } + } + // Only continue checking if the opening brace looks good. + if ($lineDifference > 0) { + return; + } + // We are looking for tabs, even if they have been replaced, because + // we enforce a space here. + if (isset($tokens[$openingBrace - 1]['orig_content']) === \true) { + $spacing = $tokens[$openingBrace - 1]['orig_content']; + } else { + $spacing = $tokens[$openingBrace - 1]['content']; + } + if ($tokens[$openingBrace - 1]['code'] !== \T_WHITESPACE) { + $length = 0; + } else { + if ($spacing === "\t") { + $length = '\\t'; + } else { + $length = \strlen($spacing); + } + } + if ($length !== 1) { + $error = 'Expected 1 space before opening brace; found %s'; + $data = [$length]; + $fix = $phpcsFile->addFixableError($error, $closeBracket, 'SpaceBeforeBrace', $data); + if ($fix === \true) { + if ($length === 0 || $length === '\\t') { + $phpcsFile->fixer->addContentBefore($openingBrace, ' '); + } else { + $phpcsFile->fixer->replaceToken($openingBrace - 1, ' '); + } + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php new file mode 100644 index 00000000000..29a7190c502 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/CyclomaticComplexitySniff.php @@ -0,0 +1,85 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Mayflower GmbH + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class CyclomaticComplexitySniff implements Sniff +{ + /** + * A complexity higher than this value will throw a warning. + * + * @var integer + */ + public $complexity = 10; + /** + * A complexity higher than this value will throw an error. + * + * @var integer + */ + public $absoluteComplexity = 20; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_FUNCTION]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + // Ignore abstract methods. + if (isset($tokens[$stackPtr]['scope_opener']) === \false) { + return; + } + // Detect start and end of this function definition. + $start = $tokens[$stackPtr]['scope_opener']; + $end = $tokens[$stackPtr]['scope_closer']; + // Predicate nodes for PHP. + $find = [\T_CASE => \true, \T_DEFAULT => \true, \T_CATCH => \true, \T_IF => \true, \T_FOR => \true, \T_FOREACH => \true, \T_WHILE => \true, \T_ELSEIF => \true, \T_INLINE_THEN => \true, \T_COALESCE => \true, \T_COALESCE_EQUAL => \true, \T_MATCH_ARROW => \true, \T_NULLSAFE_OBJECT_OPERATOR => \true]; + $complexity = 1; + // Iterate from start to end and count predicate nodes. + for ($i = $start + 1; $i < $end; $i++) { + if (isset($find[$tokens[$i]['code']]) === \true) { + $complexity++; + } + } + if ($complexity > $this->absoluteComplexity) { + $error = 'Function\'s cyclomatic complexity (%s) exceeds allowed maximum of %s'; + $data = [$complexity, $this->absoluteComplexity]; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else { + if ($complexity > $this->complexity) { + $warning = 'Function\'s cyclomatic complexity (%s) exceeds %s; consider refactoring the function'; + $data = [$complexity, $this->complexity]; + $phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php new file mode 100644 index 00000000000..452ebd9d5d8 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/Metrics/NestingLevelSniff.php @@ -0,0 +1,82 @@ + + * @author Greg Sherwood + * @copyright 2007-2014 Mayflower GmbH + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\Metrics; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class NestingLevelSniff implements Sniff +{ + /** + * A nesting level higher than this value will throw a warning. + * + * @var integer + */ + public $nestingLevel = 5; + /** + * A nesting level higher than this value will throw an error. + * + * @var integer + */ + public $absoluteNestingLevel = 10; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_FUNCTION]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + // Ignore abstract methods. + if (isset($tokens[$stackPtr]['scope_opener']) === \false) { + return; + } + // Detect start and end of this function definition. + $start = $tokens[$stackPtr]['scope_opener']; + $end = $tokens[$stackPtr]['scope_closer']; + $nestingLevel = 0; + // Find the maximum nesting level of any token in the function. + for ($i = $start + 1; $i < $end; $i++) { + $level = $tokens[$i]['level']; + if ($nestingLevel < $level) { + $nestingLevel = $level; + } + } + // We subtract the nesting level of the function itself. + $nestingLevel = $nestingLevel - $tokens[$stackPtr]['level'] - 1; + if ($nestingLevel > $this->absoluteNestingLevel) { + $error = 'Function\'s nesting level (%s) exceeds allowed maximum of %s'; + $data = [$nestingLevel, $this->absoluteNestingLevel]; + $phpcsFile->addError($error, $stackPtr, 'MaxExceeded', $data); + } else { + if ($nestingLevel > $this->nestingLevel) { + $warning = 'Function\'s nesting level (%s) exceeds %s; consider refactoring the function'; + $data = [$nestingLevel, $this->nestingLevel]; + $phpcsFile->addWarning($warning, $stackPtr, 'TooHigh', $data); + } + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php new file mode 100644 index 00000000000..ec010d32139 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/AbstractClassNamePrefixSniff.php @@ -0,0 +1,52 @@ + + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class AbstractClassNamePrefixSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_CLASS]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + if ($phpcsFile->getClassProperties($stackPtr)['is_abstract'] === \false) { + // This class is not abstract so we don't need to check it. + return; + } + $className = $phpcsFile->getDeclarationName($stackPtr); + if ($className === null) { + // We are not interested in anonymous classes. + return; + } + $prefix = \substr($className, 0, 8); + if (\strtolower($prefix) !== 'abstract') { + $phpcsFile->addError('Abstract class names must be prefixed with "Abstract"; found "%s"', $stackPtr, 'Missing', [$className]); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php new file mode 100644 index 00000000000..49c5a55090d --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/CamelCapsFunctionNameSniff.php @@ -0,0 +1,158 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +use PHP_CodeSniffer\Util\Common; +use PHP_CodeSniffer\Util\Tokens; +class CamelCapsFunctionNameSniff extends AbstractScopeSniff +{ + /** + * A list of all PHP magic methods. + * + * @var array + */ + protected $magicMethods = ['construct' => \true, 'destruct' => \true, 'call' => \true, 'callstatic' => \true, 'get' => \true, 'set' => \true, 'isset' => \true, 'unset' => \true, 'sleep' => \true, 'wakeup' => \true, 'serialize' => \true, 'unserialize' => \true, 'tostring' => \true, 'invoke' => \true, 'set_state' => \true, 'clone' => \true, 'debuginfo' => \true]; + /** + * A list of all PHP non-magic methods starting with a double underscore. + * + * These come from PHP modules such as SOAPClient. + * + * @var array + */ + protected $methodsDoubleUnderscore = ['dorequest' => \true, 'getcookies' => \true, 'getfunctions' => \true, 'getlastrequest' => \true, 'getlastrequestheaders' => \true, 'getlastresponse' => \true, 'getlastresponseheaders' => \true, 'gettypes' => \true, 'setcookie' => \true, 'setlocation' => \true, 'setsoapheaders' => \true, 'soapcall' => \true]; + /** + * A list of all PHP magic functions. + * + * @var array + */ + protected $magicFunctions = ['autoload' => \true]; + /** + * If TRUE, the string must not have two capital letters next to each other. + * + * @var boolean + */ + public $strict = \true; + /** + * Constructs a Generic_Sniffs_NamingConventions_CamelCapsFunctionNameSniff. + */ + public function __construct() + { + parent::__construct(Tokens::$ooScopeTokens, [\T_FUNCTION], \true); + } + //end __construct() + /** + * Processes the tokens within the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * @param int $currScope The position of the current scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + \end($conditions); + $deepestScope = \key($conditions); + if ($deepestScope !== $currScope) { + return; + } + $methodName = $phpcsFile->getDeclarationName($stackPtr); + if ($methodName === null) { + // Ignore closures. + return; + } + $className = $phpcsFile->getDeclarationName($currScope); + if (isset($className) === \false) { + $className = '[Anonymous Class]'; + } + $errorData = [$className . '::' . $methodName]; + $methodNameLc = \strtolower($methodName); + $classNameLc = \strtolower($className); + // Is this a magic method. i.e., is prefixed with "__" ? + if (\preg_match('|^__[^_]|', $methodName) !== 0) { + $magicPart = \substr($methodNameLc, 2); + if (isset($this->magicMethods[$magicPart]) === \true || isset($this->methodsDoubleUnderscore[$magicPart]) === \true) { + return; + } + $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'MethodDoubleUnderscore', $errorData); + } + // PHP4 constructors are allowed to break our rules. + if ($methodNameLc === $classNameLc) { + return; + } + // PHP4 destructors are allowed to break our rules. + if ($methodNameLc === '_' . $classNameLc) { + return; + } + // Ignore first underscore in methods prefixed with "_". + $methodName = \ltrim($methodName, '_'); + $methodProps = $phpcsFile->getMethodProperties($stackPtr); + if (Common::isCamelCaps($methodName, \false, \true, $this->strict) === \false) { + if ($methodProps['scope_specified'] === \true) { + $error = '%s method name "%s" is not in camel caps format'; + $data = [\ucfirst($methodProps['scope']), $errorData[0]]; + $phpcsFile->addError($error, $stackPtr, 'ScopeNotCamelCaps', $data); + } else { + $error = 'Method name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + } + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'no'); + return; + } else { + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'yes'); + } + } + //end processTokenWithinScope() + /** + * Processes the tokens outside the scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being processed. + * @param int $stackPtr The position where this token was + * found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + $functionName = $phpcsFile->getDeclarationName($stackPtr); + if ($functionName === null) { + // Ignore closures. + return; + } + $errorData = [$functionName]; + // Is this a magic function. i.e., it is prefixed with "__". + if (\preg_match('|^__[^_]|', $functionName) !== 0) { + $magicPart = \strtolower(\substr($functionName, 2)); + if (isset($this->magicFunctions[$magicPart]) === \true) { + return; + } + $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; + $phpcsFile->addError($error, $stackPtr, 'FunctionDoubleUnderscore', $errorData); + } + // Ignore first underscore in functions prefixed with "_". + $functionName = \ltrim($functionName, '_'); + if (Common::isCamelCaps($functionName, \false, \true, $this->strict) === \false) { + $error = 'Function name "%s" is not in camel caps format'; + $phpcsFile->addError($error, $stackPtr, 'NotCamelCaps', $errorData); + $phpcsFile->recordMetric($stackPtr, 'CamelCase function name', 'no'); + } else { + $phpcsFile->recordMetric($stackPtr, 'CamelCase method name', 'yes'); + } + } + //end processTokenOutsideScope() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php new file mode 100644 index 00000000000..fd545867962 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/ConstructorNameSniff.php @@ -0,0 +1,139 @@ + + * @author Leif Wickland + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\AbstractScopeSniff; +class ConstructorNameSniff extends AbstractScopeSniff +{ + /** + * The name of the class we are currently checking. + * + * @var string + */ + private $currentClass = ''; + /** + * A list of functions in the current class. + * + * @var string[] + */ + private $functionList = []; + /** + * Constructs the test with the tokens it wishes to listen for. + */ + public function __construct() + { + parent::__construct([\T_CLASS, \T_ANON_CLASS], [\T_FUNCTION], \true); + } + //end __construct() + /** + * Processes this test when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * @param int $currScope A pointer to the start of the scope. + * + * @return void + */ + protected function processTokenWithinScope(File $phpcsFile, $stackPtr, $currScope) + { + $tokens = $phpcsFile->getTokens(); + // Determine if this is a function which needs to be examined. + $conditions = $tokens[$stackPtr]['conditions']; + \end($conditions); + $deepestScope = \key($conditions); + if ($deepestScope !== $currScope) { + return; + } + $className = $phpcsFile->getDeclarationName($currScope); + if (empty($className) === \false) { + // Not an anonymous class. + $className = \strtolower($className); + } + if ($className !== $this->currentClass) { + $this->loadFunctionNamesInScope($phpcsFile, $currScope); + $this->currentClass = $className; + } + $methodName = \strtolower($phpcsFile->getDeclarationName($stackPtr)); + if ($methodName === $className) { + if (\in_array('__construct', $this->functionList, \true) === \false) { + $error = 'PHP4 style constructors are not allowed; use "__construct()" instead'; + $phpcsFile->addError($error, $stackPtr, 'OldStyle'); + } + } else { + if ($methodName !== '__construct') { + // Not a constructor. + return; + } + } + // Stop if the constructor doesn't have a body, like when it is abstract. + if (isset($tokens[$stackPtr]['scope_closer']) === \false) { + return; + } + $parentClassName = \strtolower($phpcsFile->findExtendedClassName($currScope)); + if ($parentClassName === \false) { + return; + } + $endFunctionIndex = $tokens[$stackPtr]['scope_closer']; + $startIndex = $stackPtr; + while (($doubleColonIndex = $phpcsFile->findNext(\T_DOUBLE_COLON, $startIndex, $endFunctionIndex)) !== \false) { + if ($tokens[$doubleColonIndex + 1]['code'] === \T_STRING && \strtolower($tokens[$doubleColonIndex + 1]['content']) === $parentClassName) { + $error = 'PHP4 style calls to parent constructors are not allowed; use "parent::__construct()" instead'; + $phpcsFile->addError($error, $doubleColonIndex + 1, 'OldStyleCall'); + } + $startIndex = $doubleColonIndex + 1; + } + } + //end processTokenWithinScope() + /** + * Processes a token that is found within the scope that this test is + * listening to. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. + * @param int $stackPtr The position in the stack where this + * token was found. + * + * @return void + */ + protected function processTokenOutsideScope(File $phpcsFile, $stackPtr) + { + } + //end processTokenOutsideScope() + /** + * Extracts all the function names found in the given scope. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The current file being scanned. + * @param int $currScope A pointer to the start of the scope. + * + * @return void + */ + protected function loadFunctionNamesInScope(File $phpcsFile, $currScope) + { + $this->functionList = []; + $tokens = $phpcsFile->getTokens(); + for ($i = $tokens[$currScope]['scope_opener'] + 1; $i < $tokens[$currScope]['scope_closer']; $i++) { + if ($tokens[$i]['code'] !== \T_FUNCTION) { + continue; + } + $this->functionList[] = \trim(\strtolower($phpcsFile->getDeclarationName($i))); + if (isset($tokens[$i]['scope_closer']) !== \false) { + // Skip past nested functions and such. + $i = $tokens[$i]['scope_closer']; + } + } + } + //end loadFunctionNamesInScope() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php new file mode 100644 index 00000000000..7112106c9fd --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/InterfaceNameSuffixSniff.php @@ -0,0 +1,47 @@ + + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class InterfaceNameSuffixSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_INTERFACE]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $interfaceName = $phpcsFile->getDeclarationName($stackPtr); + if ($interfaceName === null) { + return; + } + $suffix = \substr($interfaceName, -9); + if (\strtolower($suffix) !== 'interface') { + $phpcsFile->addError('Interface names must be suffixed with "Interface"; found "%s"', $stackPtr, 'Missing', [$interfaceName]); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php new file mode 100644 index 00000000000..c9a648861d0 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/TraitNameSuffixSniff.php @@ -0,0 +1,47 @@ + + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class TraitNameSuffixSniff implements Sniff +{ + /** + * Registers the tokens that this sniff wants to listen for. + * + * @return int[] + */ + public function register() + { + return [\T_TRAIT]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $traitName = $phpcsFile->getDeclarationName($stackPtr); + if ($traitName === null) { + return; + } + $suffix = \substr($traitName, -5); + if (\strtolower($suffix) !== 'trait') { + $phpcsFile->addError('Trait names must be suffixed with "Trait"; found "%s"', $stackPtr, 'Missing', [$traitName]); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php new file mode 100644 index 00000000000..91a865436cf --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/NamingConventions/UpperCaseConstantNameSniff.php @@ -0,0 +1,110 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\NamingConventions; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +use PHP_CodeSniffer\Util\Tokens; +class UpperCaseConstantNameSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_STRING, \T_CONST]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in the + * stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + if ($tokens[$stackPtr]['code'] === \T_CONST) { + // This is a class constant. + $constant = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, \true); + if ($constant === \false) { + return; + } + $constName = $tokens[$constant]['content']; + if (\strtoupper($constName) !== $constName) { + if (\strtolower($constName) === $constName) { + $phpcsFile->recordMetric($constant, 'Constant name case', 'lower'); + } else { + $phpcsFile->recordMetric($constant, 'Constant name case', 'mixed'); + } + $error = 'Class constants must be uppercase; expected %s but found %s'; + $data = [\strtoupper($constName), $constName]; + $phpcsFile->addError($error, $constant, 'ClassConstantNotUpperCase', $data); + } else { + $phpcsFile->recordMetric($constant, 'Constant name case', 'upper'); + } + return; + } + //end if + // Only interested in define statements now. + if (\strtolower($tokens[$stackPtr]['content']) !== 'define') { + return; + } + // Make sure this is not a method call. + $prev = $phpcsFile->findPrevious(\T_WHITESPACE, $stackPtr - 1, null, \true); + if ($tokens[$prev]['code'] === \T_OBJECT_OPERATOR || $tokens[$prev]['code'] === \T_DOUBLE_COLON || $tokens[$prev]['code'] === \T_NULLSAFE_OBJECT_OPERATOR) { + return; + } + // If the next non-whitespace token after this token + // is not an opening parenthesis then it is not a function call. + $openBracket = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, \true); + if ($openBracket === \false) { + return; + } + // The next non-whitespace token must be the constant name. + $constPtr = $phpcsFile->findNext(\T_WHITESPACE, $openBracket + 1, null, \true); + if ($tokens[$constPtr]['code'] !== \T_CONSTANT_ENCAPSED_STRING) { + return; + } + $constName = $tokens[$constPtr]['content']; + // Check for constants like self::CONSTANT. + $prefix = ''; + $splitPos = \strpos($constName, '::'); + if ($splitPos !== \false) { + $prefix = \substr($constName, 0, $splitPos + 2); + $constName = \substr($constName, $splitPos + 2); + } + // Strip namespace from constant like /foo/bar/CONSTANT. + $splitPos = \strrpos($constName, '\\'); + if ($splitPos !== \false) { + $prefix = \substr($constName, 0, $splitPos + 1); + $constName = \substr($constName, $splitPos + 1); + } + if (\strtoupper($constName) !== $constName) { + if (\strtolower($constName) === $constName) { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'lower'); + } else { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'mixed'); + } + $error = 'Constants must be uppercase; expected %s but found %s'; + $data = [$prefix . \strtoupper($constName), $prefix . $constName]; + $phpcsFile->addError($error, $stackPtr, 'ConstantNotUpperCase', $data); + } else { + $phpcsFile->recordMetric($stackPtr, 'Constant name case', 'upper'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php new file mode 100644 index 00000000000..79fb0911411 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/BacktickOperatorSniff.php @@ -0,0 +1,42 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class BacktickOperatorSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_BACKTICK]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $error = 'Use of the backtick operator is forbidden'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php new file mode 100644 index 00000000000..2cd045eeaac --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/CharacterBeforePHPOpeningTagSniff.php @@ -0,0 +1,72 @@ + + * @copyright 2010-2014 Andy Grunwald + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class CharacterBeforePHPOpeningTagSniff implements Sniff +{ + /** + * List of supported BOM definitions. + * + * Use encoding names as keys and hex BOM representations as values. + * + * @var array + */ + protected $bomDefinitions = ['UTF-8' => 'efbbbf', 'UTF-16 (BE)' => 'feff', 'UTF-16 (LE)' => 'fffe']; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return int + */ + public function process(File $phpcsFile, $stackPtr) + { + $expected = 0; + if ($stackPtr > 0) { + // Allow a byte-order mark. + $tokens = $phpcsFile->getTokens(); + foreach ($this->bomDefinitions as $bomName => $expectedBomHex) { + $bomByteLength = \strlen($expectedBomHex) / 2; + $htmlBomHex = \bin2hex(\substr($tokens[0]['content'], 0, $bomByteLength)); + if ($htmlBomHex === $expectedBomHex) { + $expected++; + break; + } + } + // Allow a shebang line. + if (\substr($tokens[0]['content'], 0, 2) === '#!') { + $expected++; + } + } + if ($stackPtr !== $expected) { + $error = 'The opening PHP tag must be the first content in the file'; + $phpcsFile->addError($error, $stackPtr, 'Found'); + } + // Skip the rest of the file so we don't pick up additional + // open tags, typically embedded in HTML. + return $phpcsFile->numTokens; + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php new file mode 100644 index 00000000000..ff298aaba30 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/ClosingPHPTagSniff.php @@ -0,0 +1,45 @@ + + * @copyright 2010-2014 Stefano Kowalke + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class ClosingPHPTagSniff implements Sniff +{ + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO]; + } + //end register() + /** + * Processes this sniff, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token in + * the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $closeTag = $phpcsFile->findNext(\T_CLOSE_TAG, $stackPtr); + if ($closeTag === \false) { + $error = 'The PHP open tag does not have a corresponding PHP close tag'; + $phpcsFile->addError($error, $stackPtr, 'NotFound'); + } + } + //end process() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php new file mode 100644 index 00000000000..13595a97fc5 --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DeprecatedFunctionsSniff.php @@ -0,0 +1,64 @@ + + * @author Greg Sherwood + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +class DeprecatedFunctionsSniff extends \PHP_CodeSniffer\Standards\Generic\Sniffs\PHP\ForbiddenFunctionsSniff +{ + /** + * A list of forbidden functions with their alternatives. + * + * The value is NULL if no alternative exists. IE, the + * function should just not be used. + * + * @var array + */ + public $forbiddenFunctions = []; + /** + * Constructor. + * + * Uses the Reflection API to get a list of deprecated functions. + */ + public function __construct() + { + $functions = \get_defined_functions(); + foreach ($functions['internal'] as $functionName) { + $function = new \ReflectionFunction($functionName); + if ($function->isDeprecated() === \true) { + $this->forbiddenFunctions[$functionName] = null; + } + } + } + //end __construct() + /** + * Generates the error or warning for this sniff. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the forbidden function + * in the token array. + * @param string $function The name of the forbidden function. + * @param string $pattern The pattern used for the match. + * + * @return void + */ + protected function addError($phpcsFile, $stackPtr, $function, $pattern = null) + { + $data = [$function]; + $error = 'Function %s() has been deprecated'; + $type = 'Deprecated'; + if ($this->error === \true) { + $phpcsFile->addError($error, $stackPtr, $type, $data); + } else { + $phpcsFile->addWarning($error, $stackPtr, $type, $data); + } + } + //end addError() +} +//end class diff --git a/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php new file mode 100644 index 00000000000..4aaa1bfb2eb --- /dev/null +++ b/vendor/squizlabs/php_codesniffer/src/Standards/Generic/Sniffs/PHP/DisallowAlternativePHPTagsSniff.php @@ -0,0 +1,211 @@ + + * @copyright 2006-2015 Squiz Pty Ltd (ABN 77 084 670 600) + * @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence + */ +namespace PHP_CodeSniffer\Standards\Generic\Sniffs\PHP; + +use PHP_CodeSniffer\Config; +use PHP_CodeSniffer\Files\File; +use PHP_CodeSniffer\Sniffs\Sniff; +class DisallowAlternativePHPTagsSniff implements Sniff +{ + /** + * Whether ASP tags are enabled or not. + * + * @var boolean + */ + private $aspTags = \false; + /** + * The current PHP version. + * + * @var integer + */ + private $phpVersion = null; + /** + * Returns an array of tokens this test wants to listen for. + * + * @return array + */ + public function register() + { + if ($this->phpVersion === null) { + $this->phpVersion = Config::getConfigData('php_version'); + if ($this->phpVersion === null) { + $this->phpVersion = \PHP_VERSION_ID; + } + } + if ($this->phpVersion < 70000) { + $this->aspTags = (bool) \ini_get('asp_tags'); + } + return [\T_OPEN_TAG, \T_OPEN_TAG_WITH_ECHO, \T_INLINE_HTML]; + } + //end register() + /** + * Processes this test, when one of its tokens is encountered. + * + * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process(File $phpcsFile, $stackPtr) + { + $tokens = $phpcsFile->getTokens(); + $openTag = $tokens[$stackPtr]; + $content = $openTag['content']; + if (\trim($content) === '') { + return; + } + if ($openTag['code'] === \T_OPEN_TAG) { + if ($content === '<%') { + $error = 'ASP style opening tag used; expected "findClosingTag($phpcsFile, $tokens, $stackPtr, '%>'); + $errorCode = 'ASPOpenTagFound'; + } else { + if (\strpos($content, ''); + $errorCode = 'ScriptOpenTagFound'; + } + } + if (isset($error, $closer, $errorCode) === \true) { + $data = [$content]; + if ($closer === \false) { + $phpcsFile->addError($error, $stackPtr, $errorCode, $data); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, $errorCode, $data); + if ($fix === \true) { + $this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer); + } + } + } + return; + } + //end if + if ($openTag['code'] === \T_OPEN_TAG_WITH_ECHO && $content === '<%=') { + $error = 'ASP style opening tag used with echo; expected "findNext(\T_WHITESPACE, $stackPtr + 1, null, \true); + $snippet = $this->getSnippet($tokens[$nextVar]['content']); + $data = [$snippet, $content, $snippet]; + $closer = $this->findClosingTag($phpcsFile, $tokens, $stackPtr, '%>'); + if ($closer === \false) { + $phpcsFile->addError($error, $stackPtr, 'ASPShortOpenTagFound', $data); + } else { + $fix = $phpcsFile->addFixableError($error, $stackPtr, 'ASPShortOpenTagFound', $data); + if ($fix === \true) { + $this->addChangeset($phpcsFile, $tokens, $stackPtr, $closer, \true); + } + } + return; + } + //end if + // Account for incorrect script open tags. + if ($openTag['code'] === \T_INLINE_HTML && \preg_match('`(