diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index e2c4301661b0..8e567fe0c369 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -16,8 +16,8 @@ ->in(__DIR__.'/tests') ->name('*.php') ->notPath('Fixtures') - ->notPath(__DIR__.'/src/Composer/Autoload/ClassLoader.php') - ->notPath(__DIR__.'/src/Composer/InstalledVersions.php') + ->notPath('Composer/Autoload/ClassLoader.php') + ->notPath('Composer/InstalledVersions.php') ; $config = new PhpCsFixer\Config(); @@ -70,7 +70,11 @@ 'combine_nested_dirname' => true, 'random_api_migration' => true, 'ternary_to_null_coalescing' => true, + 'phpdoc_to_param_type' => true, //'declare_strict_types' => true, + + // TODO php 7.4 migration (one day..) + // 'phpdoc_to_property_type' => true, ]) ->setUsingCache(true) ->setRiskyAllowed(true) diff --git a/bin/compile b/bin/compile index f9156245f4b2..59e420f3ab81 100755 --- a/bin/compile +++ b/bin/compile @@ -2,6 +2,7 @@ , array\\|string\\|null given\\.$#" count: 1 @@ -485,11 +460,6 @@ parameters: count: 1 path: ../src/Composer/Command/ConfigCommand.php - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/CreateProjectCommand.php - - message: "#^Only booleans are allowed in &&, Composer\\\\Package\\\\PackageInterface\\|false given on the right side\\.$#" count: 1 @@ -515,21 +485,6 @@ parameters: count: 2 path: ../src/Composer/Command/CreateProjectCommand.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Command/CreateProjectCommand.php - - - - message: "#^Parameter \\#1 \\$dirs of method Symfony\\\\Component\\\\Finder\\\\Finder\\:\\:in\\(\\) expects array\\\\|string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Command/CreateProjectCommand.php - - - - message: "#^Parameter \\#1 \\$from of method Composer\\\\Util\\\\Filesystem\\:\\:findShortestPath\\(\\) expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Command/CreateProjectCommand.php - - message: "#^Parameter \\#3 \\$existingRepos of static method Composer\\\\Repository\\\\RepositoryFactory\\:\\:generateRepositoryName\\(\\) expects array\\, array\\ given\\.$#" count: 1 @@ -600,11 +555,6 @@ parameters: count: 1 path: ../src/Composer/Command/DiagnoseCommand.php - - - message: "#^Only booleans are allowed in an if condition, array\\\\|null given\\.$#" - count: 1 - path: ../src/Composer/Command/DiagnoseCommand.php - - message: "#^Only booleans are allowed in an if condition, array\\\\|string\\|false given\\.$#" count: 1 @@ -795,11 +745,6 @@ parameters: count: 8 path: ../src/Composer/Command/InitCommand.php - - - message: "#^Only booleans are allowed in a negated boolean, Composer\\\\Package\\\\Locker\\|null given\\.$#" - count: 1 - path: ../src/Composer/Command/InstallCommand.php - - message: "#^Only booleans are allowed in \\|\\|, mixed given on the right side\\.$#" count: 3 @@ -830,16 +775,6 @@ parameters: count: 3 path: ../src/Composer/Command/ReinstallCommand.php - - - message: "#^Cannot call method getLockedRepository\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/RemoveCommand.php - - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/RemoveCommand.php - - message: "#^Foreach overwrites \\$type with its key variable\\.$#" count: 1 @@ -875,11 +810,6 @@ parameters: count: 4 path: ../src/Composer/Command/RequireCommand.php - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/RequireCommand.php - - message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#" count: 3 @@ -940,11 +870,6 @@ parameters: count: 1 path: ../src/Composer/Command/RunScriptCommand.php - - - message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#" - count: 1 - path: ../src/Composer/Command/ScriptAliasCommand.php - - message: "#^Only booleans are allowed in a negated boolean, mixed given\\.$#" count: 1 @@ -1130,11 +1055,6 @@ parameters: count: 2 path: ../src/Composer/Command/ShowCommand.php - - - message: "#^Cannot call method getLockedRepository\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/ShowCommand.php - - message: "#^Cannot call method getPrettyVersion\\(\\) on Composer\\\\Package\\\\BasePackage\\|int\\.$#" count: 1 @@ -1145,11 +1065,6 @@ parameters: count: 1 path: ../src/Composer/Command/ShowCommand.php - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/ShowCommand.php - - message: "#^Foreach overwrites \\$packages with its value variable\\.$#" count: 1 @@ -1180,11 +1095,6 @@ parameters: count: 1 path: ../src/Composer/Command/ShowCommand.php - - - message: "#^Only booleans are allowed in &&, Composer\\\\Package\\\\PackageInterface\\|false\\|null given on the right side\\.$#" - count: 1 - path: ../src/Composer/Command/ShowCommand.php - - message: "#^Only booleans are allowed in &&, Composer\\\\Package\\\\PackageInterface\\|null given on the left side\\.$#" count: 1 @@ -1455,21 +1365,6 @@ parameters: count: 1 path: ../src/Composer/Command/SuggestsCommand.php - - - message: "#^Cannot call method getLockedRepository\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/SuggestsCommand.php - - - - message: "#^Cannot call method getPlatformOverrides\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/SuggestsCommand.php - - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/SuggestsCommand.php - - message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#" count: 2 @@ -1505,21 +1400,6 @@ parameters: count: 3 path: ../src/Composer/Command/UpdateCommand.php - - - message: "#^Cannot call method getLockedRepository\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/ValidateCommand.php - - - - message: "#^Cannot call method isFresh\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 1 - path: ../src/Composer/Command/ValidateCommand.php - - - - message: "#^Cannot call method isLocked\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/ValidateCommand.php - - message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" count: 1 @@ -1710,11 +1590,6 @@ parameters: count: 1 path: ../src/Composer/Console/Application.php - - - message: "#^Only booleans are allowed in an if condition, array\\\\|null given\\.$#" - count: 1 - path: ../src/Composer/Console/Application.php - - message: "#^Only booleans are allowed in an if condition, int given\\.$#" count: 1 @@ -1745,21 +1620,11 @@ parameters: count: 1 path: ../src/Composer/Console/Application.php - - - message: "#^Parameter \\#1 \\$path of function dirname expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Console/Application.php - - message: "#^Parameter \\#2 \\$file of method Composer\\\\Console\\\\GithubActionError\\:\\:emit\\(\\) expects string\\|null, string\\|false given\\.$#" count: 1 path: ../src/Composer/Console/Application.php - - - message: "#^Property Composer\\\\Console\\\\Application\\:\\:\\$initialWorkingDirectory \\(string\\) does not accept string\\|false\\.$#" - count: 1 - path: ../src/Composer/Console/Application.php - - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" count: 2 @@ -1820,21 +1685,11 @@ parameters: count: 1 path: ../src/Composer/DependencyResolver/DefaultPolicy.php - - - message: "#^Parameter \\#3 \\$requiredPackage \\(string\\) of method Composer\\\\DependencyResolver\\\\DefaultPolicy\\:\\:selectPreferredPackages\\(\\) should be contravariant with parameter \\$requiredPackage \\(string\\|null\\) of method Composer\\\\DependencyResolver\\\\PolicyInterface\\:\\:selectPreferredPackages\\(\\)$#" - count: 1 - path: ../src/Composer/DependencyResolver/DefaultPolicy.php - - message: "#^Cannot access offset 'hash' on array\\|false\\.$#" count: 1 path: ../src/Composer/DependencyResolver/GenericRule.php - - - message: "#^Only booleans are allowed in &&, DateTime\\|null given on the left side\\.$#" - count: 1 - path: ../src/Composer/DependencyResolver/LockTransaction.php - - message: "#^Only booleans are allowed in &&, string\\|null given on the left side\\.$#" count: 1 @@ -2340,11 +2195,6 @@ parameters: count: 4 path: ../src/Composer/Downloader/DownloadManager.php - - - message: "#^Only booleans are allowed in an if condition, React\\\\Promise\\\\PromiseInterface\\|null given\\.$#" - count: 1 - path: ../src/Composer/Downloader/DownloadManager.php - - message: "#^Only booleans are allowed in an if condition, string\\|null given\\.$#" count: 2 @@ -2725,11 +2575,6 @@ parameters: count: 2 path: ../src/Composer/Downloader/VcsDownloader.php - - - message: "#^Only booleans are allowed in a negated boolean, string given\\.$#" - count: 1 - path: ../src/Composer/Downloader/VcsDownloader.php - - message: "#^Only booleans are allowed in a negated boolean, string\\|null given\\.$#" count: 3 @@ -2745,11 +2590,6 @@ parameters: count: 1 path: ../src/Composer/Downloader/VcsDownloader.php - - - message: "#^Only booleans are allowed in an if condition, string given\\.$#" - count: 1 - path: ../src/Composer/Downloader/VcsDownloader.php - - message: "#^Parameter \\#1 \\$fromReference of method Composer\\\\Downloader\\\\VcsDownloader\\:\\:getCommitLogs\\(\\) expects string, string\\|null given\\.$#" count: 1 @@ -2990,11 +2830,6 @@ parameters: count: 1 path: ../src/Composer/Factory.php - - - message: "#^Parameter \\#1 \\$str of function trim expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Factory.php - - message: "#^Parameter \\#4 \\$composerFileContents of class Composer\\\\Package\\\\Locker constructor expects string, string\\|false given\\.$#" count: 1 @@ -3002,7 +2837,7 @@ parameters: - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" - count: 5 + count: 3 path: ../src/Composer/Factory.php - @@ -3625,21 +3460,11 @@ parameters: count: 1 path: ../src/Composer/Package/Comparer/Comparer.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 2 - path: ../src/Composer/Package/Comparer/Comparer.php - - message: "#^PHPDoc type Composer\\\\Package\\\\CompletePackage of property Composer\\\\Package\\\\CompleteAliasPackage\\:\\:\\$aliasOf is not the same as PHPDoc type Composer\\\\Package\\\\BasePackage of overridden property Composer\\\\Package\\\\AliasPackage\\:\\:\\$aliasOf\\.$#" count: 1 path: ../src/Composer/Package/CompleteAliasPackage.php - - - message: "#^Only booleans are allowed in an if condition, DateTime\\|null given\\.$#" - count: 1 - path: ../src/Composer/Package/Dumper/ArrayDumper.php - - message: "#^Only booleans are allowed in an if condition, array\\\\>\\|null given\\.$#" count: 2 @@ -3700,11 +3525,6 @@ parameters: count: 1 path: ../src/Composer/Package/Loader/ArrayLoader.php - - - message: "#^Method Composer\\\\Package\\\\Loader\\\\ArrayLoader\\:\\:createObject\\(\\) should return Composer\\\\Package\\\\CompletePackage but returns PackageClass of Composer\\\\Package\\\\CompletePackageInterface\\.$#" - count: 1 - path: ../src/Composer/Package/Loader/ArrayLoader.php - - message: "#^Only booleans are allowed in &&, string\\|false given on the left side\\.$#" count: 1 @@ -3786,23 +3606,18 @@ parameters: path: ../src/Composer/Package/Loader/RootPackageLoader.php - - message: "#^Parameter \\#2 \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\RootPackageLoader\\:\\:load\\(\\) should be contravariant with parameter \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\ArrayLoader\\:\\:load\\(\\)$#" - count: 1 - path: ../src/Composer/Package/Loader/RootPackageLoader.php - - - - message: "#^Parameter \\#2 \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\RootPackageLoader\\:\\:load\\(\\) should be contravariant with parameter \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\LoaderInterface\\:\\:load\\(\\)$#" + message: "#^Parameter \\#2 \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\RootPackageLoader\\:\\:load\\(\\) should be contravariant with parameter \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\ArrayLoader\\:\\:load\\(\\)$#" count: 1 path: ../src/Composer/Package/Loader/RootPackageLoader.php - - message: "#^Parameter \\#2 \\$path of method Composer\\\\Package\\\\Version\\\\VersionGuesser\\:\\:guessVersion\\(\\) expects string, string\\|false given\\.$#" + message: "#^Parameter \\#2 \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\RootPackageLoader\\:\\:load\\(\\) should be contravariant with parameter \\$class \\(class\\-string\\\\) of method Composer\\\\Package\\\\Loader\\\\LoaderInterface\\:\\:load\\(\\)$#" count: 1 path: ../src/Composer/Package/Loader/RootPackageLoader.php - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" - count: 2 + count: 1 path: ../src/Composer/Package/Loader/RootPackageLoader.php - @@ -4080,11 +3895,6 @@ parameters: count: 1 path: ../src/Composer/Platform/Runtime.php - - - message: "#^Cannot call method getInstallationManager\\(\\) on Composer\\\\Composer\\|null\\.$#" - count: 1 - path: ../src/Composer/Plugin/PluginManager.php - - message: "#^Casting to array\\ something that's already array\\\\.$#" count: 1 @@ -4115,11 +3925,6 @@ parameters: count: 1 path: ../src/Composer/Plugin/PluginManager.php - - - message: "#^Only booleans are allowed in a ternary operator condition, Composer\\\\Composer\\|null given\\.$#" - count: 1 - path: ../src/Composer/Plugin/PluginManager.php - - message: "#^Only booleans are allowed in a ternary operator condition, array\\ given\\.$#" count: 1 @@ -4137,7 +3942,7 @@ parameters: - message: "#^Only booleans are allowed in an if condition, Composer\\\\Repository\\\\InstalledRepositoryInterface\\|null given\\.$#" - count: 3 + count: 2 path: ../src/Composer/Plugin/PluginManager.php - @@ -4475,11 +4280,6 @@ parameters: count: 1 path: ../src/Composer/Repository/FilesystemRepository.php - - - message: "#^Parameter \\#1 \\$path of function realpath expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Repository/FilesystemRepository.php - - message: "#^Parameter \\#1 \\$path of method Composer\\\\Util\\\\Filesystem\\:\\:normalizePath\\(\\) expects string, string\\|false given\\.$#" count: 2 @@ -4647,7 +4447,7 @@ parameters: - message: "#^Parameter \\#2 \\$prettyVersion of method Composer\\\\Repository\\\\PlatformRepository\\:\\:addLibrary\\(\\) expects string, string\\|null given\\.$#" - count: 4 + count: 3 path: ../src/Composer/Repository/PlatformRepository.php - @@ -4670,11 +4470,6 @@ parameters: count: 1 path: ../src/Composer/Repository/RepositoryFactory.php - - - message: "#^Method Composer\\\\Repository\\\\RepositoryFactory\\:\\:generateRepositoryName\\(\\) should return string but returns int\\|string\\.$#" - count: 1 - path: ../src/Composer/Repository/RepositoryFactory.php - - message: "#^Only booleans are allowed in a negated boolean, Composer\\\\Config\\|null given\\.$#" count: 1 @@ -4790,11 +4585,6 @@ parameters: count: 10 path: ../src/Composer/Repository/Vcs/GitBitbucketDriver.php - - - message: "#^Only booleans are allowed in an if condition, mixed given\\.$#" - count: 1 - path: ../src/Composer/Repository/Vcs/GitBitbucketDriver.php - - message: "#^Property Composer\\\\Repository\\\\Vcs\\\\GitBitbucketDriver\\:\\:\\$branches \\(array\\\\) does not accept array\\\\.$#" count: 1 @@ -4915,11 +4705,6 @@ parameters: count: 1 path: ../src/Composer/Repository/Vcs/GitHubDriver.php - - - message: "#^Only booleans are allowed in an if condition, mixed given\\.$#" - count: 1 - path: ../src/Composer/Repository/Vcs/GitHubDriver.php - - message: "#^Only booleans are allowed in an if condition, string\\|null given\\.$#" count: 2 @@ -4992,7 +4777,7 @@ parameters: - message: "#^Only booleans are allowed in an if condition, mixed given\\.$#" - count: 2 + count: 1 path: ../src/Composer/Repository/Vcs/GitLabDriver.php - @@ -5170,11 +4955,6 @@ parameters: count: 1 path: ../src/Composer/Repository/Vcs/VcsDriver.php - - - message: "#^Only booleans are allowed in &&, DateTime\\|null given on the right side\\.$#" - count: 1 - path: ../src/Composer/Repository/Vcs/VcsDriver.php - - message: "#^Only booleans are allowed in &&, string\\|false given on the right side\\.$#" count: 1 @@ -5220,11 +5000,6 @@ parameters: count: 1 path: ../src/Composer/Repository/VcsRepository.php - - - message: "#^Only booleans are allowed in a negated boolean, array given\\.$#" - count: 2 - path: ../src/Composer/Repository/VcsRepository.php - - message: "#^Only booleans are allowed in a negated boolean, array\\ given\\.$#" count: 1 @@ -5460,11 +5235,6 @@ parameters: count: 1 path: ../src/Composer/Util/Filesystem.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Util/Filesystem.php - - message: "#^Parameter \\#1 \\$fp of function fclose expects resource, resource\\|false given\\.$#" count: 4 @@ -5885,11 +5655,6 @@ parameters: count: 1 path: ../src/Composer/Util/Http/RequestProxy.php - - - message: "#^Casting to int something that's already int\\.$#" - count: 1 - path: ../src/Composer/Util/Http/Response.php - - message: "#^Argument of an invalid type array\\\\>\\|string supplied for foreach, only iterables are supported\\.$#" count: 1 @@ -5985,11 +5750,6 @@ parameters: count: 1 path: ../src/Composer/Util/HttpDownloader.php - - - message: "#^Parameter \\#2 \\$code of class Composer\\\\Util\\\\Http\\\\Response constructor expects int, int\\|null given\\.$#" - count: 2 - path: ../src/Composer/Util/HttpDownloader.php - - message: "#^Parameter \\#4 \\$body of class Composer\\\\Util\\\\Http\\\\Response constructor expects string\\|null, bool\\|string given\\.$#" count: 1 @@ -6115,11 +5875,6 @@ parameters: count: 2 path: ../src/Composer/Util/Perforce.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Util/Perforce.php - - message: "#^Parameter \\#1 \\$fp of function fclose expects resource, resource\\|false given\\.$#" count: 2 @@ -6415,16 +6170,6 @@ parameters: count: 1 path: ../src/Composer/Util/Svn.php - - - message: "#^Parameter \\#2 \\$cwd of method Composer\\\\Util\\\\Svn\\:\\:executeWithAuthRetry\\(\\) expects string, string\\|null given\\.$#" - count: 2 - path: ../src/Composer/Util/Svn.php - - - - message: "#^Parameter \\#4 \\$path of method Composer\\\\Util\\\\Svn\\:\\:executeWithAuthRetry\\(\\) expects string, string\\|null given\\.$#" - count: 1 - path: ../src/Composer/Util/Svn.php - - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" count: 1 @@ -6595,11 +6340,6 @@ parameters: count: 3 path: ../tests/Composer/Test/Autoload/AutoloadGeneratorTest.php - - - message: "#^Property Composer\\\\Test\\\\Autoload\\\\AutoloadGeneratorTest\\:\\:\\$origDir \\(string\\) does not accept string\\|false\\.$#" - count: 1 - path: ../tests/Composer/Test/Autoload/AutoloadGeneratorTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:ensureDirectoryExistsAndClear\\(\\)\\.$#" count: 1 @@ -6650,16 +6390,6 @@ parameters: count: 2 path: ../tests/Composer/Test/ConfigTest.php - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setProvides\\(\\)\\.$#" - count: 2 - path: ../tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setReplaces\\(\\)\\.$#" - count: 3 - path: ../tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php - - message: "#^Casting to string something that's already string\\.$#" count: 3 @@ -6700,11 +6430,6 @@ parameters: count: 1 path: ../tests/Composer/Test/DependencyResolver/PoolBuilderTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/DependencyResolver/PoolBuilderTest.php - - message: "#^Parameter \\#1 \\$filename of function file_get_contents expects string, string\\|false given\\.$#" count: 1 @@ -6775,26 +6500,6 @@ parameters: count: 1 path: ../tests/Composer/Test/DependencyResolver/RuleTest.php - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setConflicts\\(\\)\\.$#" - count: 2 - path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setProvides\\(\\)\\.$#" - count: 3 - path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setReplaces\\(\\)\\.$#" - count: 9 - path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setRequires\\(\\)\\.$#" - count: 46 - path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - message: "#^Cannot access property \\$testFlagLearnedPositiveLiteral on Composer\\\\DependencyResolver\\\\Solver\\|null\\.$#" count: 2 @@ -6805,36 +6510,6 @@ parameters: count: 8 path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - - message: "#^Parameter \\#1 \\$package of method Composer\\\\Test\\\\TestCase\\:\\:getAliasPackage\\(\\) expects Composer\\\\Package\\\\Package, Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage given\\.$#" - count: 5 - path: ../tests/Composer/Test/DependencyResolver/SolverTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setExtra\\(\\)\\.$#" - count: 2 - path: ../tests/Composer/Test/DependencyResolver/TransactionTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setProvides\\(\\)\\.$#" - count: 1 - path: ../tests/Composer/Test/DependencyResolver/TransactionTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setRequires\\(\\)\\.$#" - count: 3 - path: ../tests/Composer/Test/DependencyResolver/TransactionTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setType\\(\\)\\.$#" - count: 2 - path: ../tests/Composer/Test/DependencyResolver/TransactionTest.php - - - - message: "#^Parameter \\#1 \\$package of method Composer\\\\Test\\\\TestCase\\:\\:getAliasPackage\\(\\) expects Composer\\\\Package\\\\Package, Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage given\\.$#" - count: 4 - path: ../tests/Composer/Test/DependencyResolver/TransactionTest.php - - message: "#^Only booleans are allowed in a ternary operator condition, int\\<0, max\\>\\|false given\\.$#" count: 1 @@ -6850,11 +6525,6 @@ parameters: count: 6 path: ../tests/Composer/Test/Downloader/FileDownloaderTest.php - - - message: "#^Parameter \\#1 \\$promises of method Composer\\\\Util\\\\Loop\\:\\:wait\\(\\) expects array\\, array\\ given\\.$#" - count: 5 - path: ../tests/Composer/Test/Downloader/FileDownloaderTest.php - - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" count: 3 @@ -6905,21 +6575,11 @@ parameters: count: 1 path: ../tests/Composer/Test/Downloader/XzDownloaderTest.php - - - message: "#^Parameter \\#1 \\$promises of method Composer\\\\Util\\\\Loop\\:\\:wait\\(\\) expects array\\, array\\ given\\.$#" - count: 1 - path: ../tests/Composer/Test/Downloader/XzDownloaderTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#" count: 1 path: ../tests/Composer/Test/Downloader/ZipDownloaderTest.php - - - message: "#^Parameter \\#1 \\$promises of method Composer\\\\Util\\\\Loop\\:\\:wait\\(\\) expects array\\, array\\ given\\.$#" - count: 1 - path: ../tests/Composer/Test/Downloader/ZipDownloaderTest.php - - message: "#^Only booleans are allowed in a negated boolean, string\\|false given\\.$#" count: 2 @@ -6930,11 +6590,6 @@ parameters: count: 1 path: ../tests/Composer/Test/EventDispatcher/EventDispatcherTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/EventDispatcher/EventDispatcherTest.php - - message: "#^Parameter \\#2 \\$haystack of static method PHPUnit\\\\Framework\\\\Assert\\:\\:assertStringContainsString\\(\\) expects string, string\\|false given\\.$#" count: 1 @@ -6988,21 +6643,11 @@ parameters: count: 1 path: ../tests/Composer/Test/Installer/InstallerEventTest.php - - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:ensureDirectoryExistsAndClear\\(\\)\\.$#" - count: 2 - path: ../tests/Composer/Test/Installer/LibraryInstallerTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#" count: 1 path: ../tests/Composer/Test/Installer/LibraryInstallerTest.php - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setRequires\\(\\)\\.$#" - count: 4 - path: ../tests/Composer/Test/InstallerTest.php - - message: "#^Call to function is_array\\(\\) with array\\ will always evaluate to true\\.$#" count: 1 @@ -7083,11 +6728,6 @@ parameters: count: 1 path: ../tests/Composer/Test/InstallerTest.php - - - message: "#^Property Composer\\\\Test\\\\InstallerTest\\:\\:\\$prevCwd \\(string\\) does not accept string\\|false\\.$#" - count: 1 - path: ../tests/Composer/Test/InstallerTest.php - - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" count: 5 @@ -7113,16 +6753,6 @@ parameters: count: 1 path: ../tests/Composer/Test/Json/JsonManipulatorTest.php - - - message: "#^Parameter \\#1 \\$message of class Composer\\\\Json\\\\JsonValidationException constructor expects string, string\\|null given\\.$#" - count: 1 - path: ../tests/Composer/Test/Json/JsonValidationExceptionTest.php - - - - message: "#^Parameter \\#2 \\$errors of class Composer\\\\Json\\\\JsonValidationException constructor expects array\\, array\\\\|null given\\.$#" - count: 1 - path: ../tests/Composer/Test/Json/JsonValidationExceptionTest.php - - message: "#^Offset 'url' on array\\{url\\: string, options\\?\\: array, status\\?\\: int, body\\?\\: string, headers\\?\\: array\\\\} on left side of \\?\\? always exists and is not nullable\\.$#" count: 1 @@ -7173,11 +6803,6 @@ parameters: count: 2 path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php - - - message: "#^Parameter \\#2 \\$cwd of method Composer\\\\Test\\\\Mock\\\\ProcessExecutorMock\\:\\:doExecute\\(\\) expects string, string\\|null given\\.$#" - count: 4 - path: ../tests/Composer/Test/Mock/ProcessExecutorMock.php - - message: "#^Composer\\\\Test\\\\Mock\\\\VersionGuesserMock\\:\\:__construct\\(\\) does not call parent constructor from Composer\\\\Package\\\\Version\\\\VersionGuesser\\.$#" count: 1 @@ -7198,61 +6823,31 @@ parameters: count: 1 path: ../tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 8 - path: ../tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#" count: 1 path: ../tests/Composer/Test/Package/Archiver/ArchiverTest.php - - - message: "#^Parameter \\#1 \\$url of method Composer\\\\Package\\\\Package\\:\\:setSourceUrl\\(\\) expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Package/Archiver/ArchiverTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#" count: 2 path: ../tests/Composer/Test/Package/Archiver/PharArchiverTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Package/Archiver/PharArchiverTest.php - - message: "#^Parameter \\#1 \\$sources of method Composer\\\\Package\\\\Archiver\\\\PharArchiver\\:\\:archive\\(\\) expects string, string\\|null given\\.$#" count: 2 path: ../tests/Composer/Test/Package/Archiver/PharArchiverTest.php - - - message: "#^Parameter \\#3 \\$currentWorkDir of method Composer\\\\Test\\\\Package\\\\Archiver\\\\PharArchiverTest\\:\\:writeFile\\(\\) expects string, string\\|false given\\.$#" - count: 5 - path: ../tests/Composer/Test/Package/Archiver/PharArchiverTest.php - - message: "#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#" count: 1 path: ../tests/Composer/Test/Package/Archiver/ZipArchiverTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Package/Archiver/ZipArchiverTest.php - - message: "#^Parameter \\#1 \\$sources of method Composer\\\\Package\\\\Archiver\\\\ZipArchiver\\:\\:archive\\(\\) expects string, string\\|null given\\.$#" count: 1 path: ../tests/Composer/Test/Package/Archiver/ZipArchiverTest.php - - - message: "#^Parameter \\#3 \\$currentWorkDir of method Composer\\\\Test\\\\Package\\\\Archiver\\\\ZipArchiverTest\\:\\:writeFile\\(\\) expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Package/Archiver/ZipArchiverTest.php - - message: "#^Implicit array creation is not allowed \\- variable \\$provider does not exist\\.$#" count: 1 @@ -7260,7 +6855,7 @@ parameters: - message: "#^Short ternary operator is not allowed\\. Use null coalesce operator if applicable or consider using long ternary\\.$#" - count: 2 + count: 1 path: ../tests/Composer/Test/Package/Dumper/ArrayDumperTest.php - @@ -7353,16 +6948,6 @@ parameters: count: 1 path: ../tests/Composer/Test/Question/StrictConfirmationQuestionTest.php - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setType\\(\\)\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/ArrayRepositoryTest.php - - - - message: "#^Parameter \\#1 \\$package of method Composer\\\\Test\\\\TestCase\\:\\:getAliasPackage\\(\\) expects Composer\\\\Package\\\\Package, Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage given\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/ArrayRepositoryTest.php - - message: "#^Cannot call method getDistType\\(\\) on Composer\\\\Package\\\\BasePackage\\|null\\.$#" count: 1 @@ -7388,34 +6973,14 @@ parameters: count: 1 path: ../tests/Composer/Test/Repository/CompositeRepositoryTest.php - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setType\\(\\)\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/FilesystemRepositoryTest.php - - message: "#^Dynamic call to static method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\)\\.$#" count: 1 path: ../tests/Composer/Test/Repository/FilesystemRepositoryTest.php - - - message: "#^Parameter \\#1 \\$package of method Composer\\\\Test\\\\TestCase\\:\\:getAliasPackage\\(\\) expects Composer\\\\Package\\\\Package, Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage given\\.$#" - count: 2 - path: ../tests/Composer/Test/Repository/FilesystemRepositoryTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setProvides\\(\\)\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/InstalledRepositoryTest.php - - - - message: "#^Call to an undefined method Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage\\:\\:setReplaces\\(\\)\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/InstalledRepositoryTest.php - - message: "#^Parameter \\#1 \\$path of function realpath expects string, string\\|false given\\.$#" - count: 3 + count: 2 path: ../tests/Composer/Test/Repository/PathRepositoryTest.php - @@ -7523,21 +7088,6 @@ parameters: count: 1 path: ../tests/Composer/Test/Repository/VcsRepositoryTest.php - - - message: "#^Parameter \\#1 \\$directory of function chdir expects string, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/VcsRepositoryTest.php - - - - message: "#^Parameter \\#3 \\$cwd of method Composer\\\\Util\\\\ProcessExecutor\\:\\:execute\\(\\) expects string\\|null, string\\|false given\\.$#" - count: 1 - path: ../tests/Composer/Test/Repository/VcsRepositoryTest.php - - - - message: "#^Method Composer\\\\Test\\\\TestCase\\:\\:getPackage\\(\\) should return Composer\\\\Package\\\\CompleteAliasPackage\\|Composer\\\\Package\\\\CompletePackage but returns PackageClass of Composer\\\\Package\\\\PackageInterface\\.$#" - count: 1 - path: ../tests/Composer/Test/TestCase.php - - message: "#^Method Composer\\\\Test\\\\TestCase\\:\\:getUniqueTmpDirectory\\(\\) should return string but returns string\\|false\\.$#" count: 1 @@ -7575,7 +7125,7 @@ parameters: - message: "#^Only booleans are allowed in an if condition, string given\\.$#" - count: 2 + count: 1 path: ../tests/Composer/Test/Util/Http/ProxyManagerTest.php - diff --git a/src/Composer/Autoload/AutoloadGenerator.php b/src/Composer/Autoload/AutoloadGenerator.php index d3560bfcf1b4..5485565e0dd0 100644 --- a/src/Composer/Autoload/AutoloadGenerator.php +++ b/src/Composer/Autoload/AutoloadGenerator.php @@ -89,7 +89,7 @@ public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = * @param bool $devMode * @return void */ - public function setDevMode($devMode = true) + public function setDevMode(bool $devMode = true) { $this->devMode = (bool) $devMode; } @@ -100,7 +100,7 @@ public function setDevMode($devMode = true) * @param bool $classMapAuthoritative * @return void */ - public function setClassMapAuthoritative($classMapAuthoritative) + public function setClassMapAuthoritative(bool $classMapAuthoritative) { $this->classMapAuthoritative = (bool) $classMapAuthoritative; } @@ -112,7 +112,7 @@ public function setClassMapAuthoritative($classMapAuthoritative) * @param string|null $apcuPrefix * @return void */ - public function setApcu($apcu, $apcuPrefix = null) + public function setApcu(bool $apcu, ?string $apcuPrefix = null) { $this->apcu = (bool) $apcu; $this->apcuPrefix = $apcuPrefix !== null ? (string) $apcuPrefix : $apcuPrefix; @@ -124,7 +124,7 @@ public function setApcu($apcu, $apcuPrefix = null) * @param bool $runScripts * @return void */ - public function setRunScripts($runScripts = true) + public function setRunScripts(bool $runScripts = true) { $this->runScripts = (bool) $runScripts; } @@ -163,7 +163,7 @@ public function setPlatformRequirementFilter(PlatformRequirementFilterInterface * @return int * @throws \Seld\JsonLint\ParsingException */ - public function dump(Config $config, InstalledRepositoryInterface $localRepo, RootPackageInterface $rootPackage, InstallationManager $installationManager, $targetDir, $scanPsrPackages = false, $suffix = '') + public function dump(Config $config, InstalledRepositoryInterface $localRepo, RootPackageInterface $rootPackage, InstallationManager $installationManager, string $targetDir, bool $scanPsrPackages = false, string $suffix = '') { if ($this->classMapAuthoritative) { // Force scanPsrPackages when classmap is authoritative @@ -200,7 +200,7 @@ public function dump(Config $config, InstalledRepositoryInterface $localRepo, Ro // Do not remove double realpath() calls. // Fixes failing Windows realpath() implementation. // See https://bugs.php.net/bug.php?id=72738 - $basePath = $filesystem->normalizePath(realpath(realpath(getcwd()))); + $basePath = $filesystem->normalizePath(realpath(realpath(Platform::getCwd()))); $vendorPath = $filesystem->normalizePath(realpath(realpath($config->get('vendor-dir')))); $useGlobalIncludePath = (bool) $config->get('use-include-path'); $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true'; @@ -433,15 +433,15 @@ public static function autoload(\$class) * @param string $basePath * @param string $vendorPath * @param string $dir - * @param ?array $excluded - * @param ?string $namespaceFilter - * @param ?string $autoloadType + * @param null|array $excluded + * @param null|string $namespaceFilter + * @param null|string $autoloadType * @param array $classMap * @param array> $ambiguousClasses * @param array $scannedFiles * @return array */ - private function addClassMapCode(Filesystem $filesystem, $basePath, $vendorPath, $dir, $excluded, $namespaceFilter, $autoloadType, array $classMap, array &$ambiguousClasses, array &$scannedFiles): array + private function addClassMapCode(Filesystem $filesystem, string $basePath, string $vendorPath, string $dir, ?array $excluded, ?string $namespaceFilter, ?string $autoloadType, array $classMap, array &$ambiguousClasses, array &$scannedFiles): array { foreach ($this->generateClassMap($dir, $excluded, $namespaceFilter, $autoloadType, true, $scannedFiles) as $class => $path) { $pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n"; @@ -457,14 +457,14 @@ private function addClassMapCode(Filesystem $filesystem, $basePath, $vendorPath, /** * @param string $dir - * @param ?array $excluded - * @param ?string $namespaceFilter - * @param ?string $autoloadType + * @param null|array $excluded + * @param null|string $namespaceFilter + * @param null|string $autoloadType * @param bool $showAmbiguousWarning * @param array $scannedFiles * @return array */ - private function generateClassMap($dir, $excluded, $namespaceFilter, $autoloadType, $showAmbiguousWarning, array &$scannedFiles): array + private function generateClassMap(string $dir, ?array $excluded, ?string $namespaceFilter, ?string $autoloadType, bool $showAmbiguousWarning, array &$scannedFiles): array { if ($excluded) { // filter excluded patterns here to only use those matching $dir @@ -586,10 +586,10 @@ public function parseAutoloads(array $packageMap, PackageInterface $rootPackage, * Registers an autoloader based on an autoload-map returned by parseAutoloads * * @param array $autoloads see parseAutoloads return value - * @param ?string $vendorDir + * @param null|string $vendorDir * @return ClassLoader */ - public function createLoader(array $autoloads, $vendorDir = null) + public function createLoader(array $autoloads, ?string $vendorDir = null) { $loader = new ClassLoader($vendorDir); @@ -632,7 +632,7 @@ public function createLoader(array $autoloads, $vendorDir = null) * @param string $appBaseDirCode * @return ?string */ - protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode) + protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { $includePaths = array(); @@ -680,7 +680,7 @@ protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem * @param string $appBaseDirCode * @return ?string */ - protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode) + protected function getIncludeFilesFile(array $files, Filesystem $filesystem, string $basePath, string $vendorPath, string $vendorPathCode, string $appBaseDirCode) { $filesCode = ''; foreach ($files as $fileIdentifier => $functionFile) { @@ -712,7 +712,7 @@ protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $ba * @param string $path * @return string */ - protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path) + protected function getPathCode(Filesystem $filesystem, string $basePath, string $vendorPath, string $path) { if (!$filesystem->isAbsolutePath($path)) { $path = $basePath . '/' . $path; @@ -748,7 +748,7 @@ protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $ * @param string[] $devPackageNames * @return ?string */ - protected function getPlatformCheck(array $packageMap, $checkPlatform, array $devPackageNames) + protected function getPlatformCheck(array $packageMap, bool $checkPlatform, array $devPackageNames) { $lowestPhpVersion = Bound::zero(); $requiredExtensions = array(); @@ -906,7 +906,7 @@ protected function getPlatformCheck(array $packageMap, $checkPlatform, array $de * @param string $suffix * @return string */ - protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix) + protected function getAutoloadFile(string $vendorPathToTargetDirCode, string $suffix) { $lastChar = $vendorPathToTargetDirCode[strlen($vendorPathToTargetDirCode) - 1]; if ("'" === $lastChar || '"' === $lastChar) { @@ -930,7 +930,7 @@ protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix) /** * @param bool $useClassMap * @param bool $useIncludePath - * @param ?string $targetDirLoader + * @param null|string $targetDirLoader * @param bool $useIncludeFiles * @param string $vendorPathCode unused in this method * @param string $appBaseDirCode unused in this method @@ -940,7 +940,7 @@ protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix) * @param bool $checkPlatform * @return string */ - protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $checkPlatform) + protected function getAutoloadRealFile(bool $useClassMap, bool $useIncludePath, ?string $targetDirLoader, bool $useIncludeFiles, string $vendorPathCode, string $appBaseDirCode, string $suffix, bool $useGlobalIncludePath, string $prependAutoloader, bool $checkPlatform) { $file = <<
|array>|array */ - protected function parseAutoloadsType(array $packageMap, $type, RootPackageInterface $rootPackage) + protected function parseAutoloadsType(array $packageMap, string $type, RootPackageInterface $rootPackage) { $autoloads = array(); @@ -1240,7 +1240,7 @@ function ($matches) use (&$updir): string { $path ); if (empty($installPath)) { - $installPath = strtr(getcwd(), '\\', '/'); + $installPath = strtr(Platform::getCwd(), '\\', '/'); } $resolvedPath = realpath($installPath . '/' . $updir); @@ -1271,7 +1271,7 @@ function ($matches) use (&$updir): string { * @param string $path * @return string */ - protected function getFileIdentifier(PackageInterface $package, $path) + protected function getFileIdentifier(PackageInterface $package, string $path) { return md5($package->getName() . ':' . $path); } @@ -1364,12 +1364,7 @@ protected function sortPackageMap(array $packageMap) } } -/** - * @param string $fileIdentifier - * @param string $file - * @return void - */ -function composerRequire($fileIdentifier, $file) +function composerRequire(string $fileIdentifier, string $file): void { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; diff --git a/src/Composer/Autoload/ClassMapGenerator.php b/src/Composer/Autoload/ClassMapGenerator.php index 8a2db56818f1..84f946440963 100644 --- a/src/Composer/Autoload/ClassMapGenerator.php +++ b/src/Composer/Autoload/ClassMapGenerator.php @@ -19,6 +19,7 @@ namespace Composer\Autoload; use Composer\Pcre\Preg; +use Composer\Util\Platform; use Symfony\Component\Finder\Finder; use Composer\IO\IOInterface; use Composer\Util\Filesystem; @@ -35,10 +36,10 @@ class ClassMapGenerator * Generate a class map file * * @param \Traversable|array $dirs Directories or a single path to search in - * @param string $file The name of the class map file + * @param string $file The name of the class map file * @return void */ - public static function dump($dirs, $file): void + public static function dump(iterable $dirs, string $file): void { $maps = array(); @@ -55,13 +56,13 @@ public static function dump($dirs, $file): void * @param \Traversable<\SplFileInfo>|string|array $path The path to search in or an iterator * @param string $excluded Regex that matches file paths to be excluded from the classmap * @param ?IOInterface $io IO object - * @param ?string $namespace Optional namespace prefix to filter by - * @param ?string $autoloadType psr-0|psr-4 Optional autoload standard to use mapping rules + * @param null|string $namespace Optional namespace prefix to filter by + * @param null|string $autoloadType psr-0|psr-4 Optional autoload standard to use mapping rules * @param array $scannedFiles * @return array A class map array * @throws \RuntimeException When the path is neither an existing file nor directory */ - public static function createMap($path, $excluded = null, IOInterface $io = null, $namespace = null, $autoloadType = null, &$scannedFiles = array()): array + public static function createMap($path, string $excluded = null, IOInterface $io = null, ?string $namespace = null, ?string $autoloadType = null, array &$scannedFiles = array()): array { $basePath = $path; if (is_string($path)) { @@ -81,7 +82,7 @@ public static function createMap($path, $excluded = null, IOInterface $io = null $map = array(); $filesystem = new Filesystem(); - $cwd = realpath(getcwd()); + $cwd = realpath(Platform::getCwd()); foreach ($path as $file) { $filePath = $file->getPathname(); @@ -157,7 +158,7 @@ public static function createMap($path, $excluded = null, IOInterface $io = null * @param ?IOInterface $io IO object * @return array valid classes */ - private static function filterByNamespace($classes, $filePath, $baseNamespace, $namespaceType, $basePath, $io): array + private static function filterByNamespace(array $classes, string $filePath, string $baseNamespace, string $namespaceType, string $basePath, ?IOInterface $io): array { $validClasses = array(); $rejectedClasses = array(); @@ -198,7 +199,7 @@ private static function filterByNamespace($classes, $filePath, $baseNamespace, $ if (empty($validClasses)) { foreach ($rejectedClasses as $class) { if ($io) { - $io->writeError("Class $class located in ".Preg::replace('{^'.preg_quote(getcwd()).'}', '.', $filePath, 1)." does not comply with $namespaceType autoloading standard. Skipping."); + $io->writeError("Class $class located in ".Preg::replace('{^'.preg_quote(Platform::getCwd()).'}', '.', $filePath, 1)." does not comply with $namespaceType autoloading standard. Skipping."); } } @@ -215,7 +216,7 @@ private static function filterByNamespace($classes, $filePath, $baseNamespace, $ * @throws \RuntimeException * @return array The found classes */ - private static function findClasses($path): array + private static function findClasses(string $path): array { $extraTypes = self::getExtraTypes(); diff --git a/src/Composer/Autoload/PhpFileCleaner.php b/src/Composer/Autoload/PhpFileCleaner.php index 8fc077418b99..f1e6048b25b6 100644 --- a/src/Composer/Autoload/PhpFileCleaner.php +++ b/src/Composer/Autoload/PhpFileCleaner.php @@ -51,7 +51,7 @@ class PhpFileCleaner * @param string[] $types * @return void */ - public static function setTypeConfig($types): void + public static function setTypeConfig(array $types): void { foreach ($types as $type) { self::$typeConfig[$type[0]] = array( @@ -68,7 +68,7 @@ public static function setTypeConfig($types): void * @param string $contents * @param int $maxMatches */ - public function __construct($contents, $maxMatches) + public function __construct(string $contents, int $maxMatches) { $this->contents = $contents; $this->len = \strlen($this->contents); @@ -168,7 +168,7 @@ private function skipToPhp(): void * @param string $delimiter * @return void */ - private function skipString($delimiter): void + private function skipString(string $delimiter): void { $this->index += 1; while ($this->index < $this->len) { @@ -217,7 +217,7 @@ private function skipToNewline(): void * @param string $delimiter * @return void */ - private function skipHeredoc($delimiter): void + private function skipHeredoc(string $delimiter): void { $firstDelimiterChar = $delimiter[0]; $delimiterLength = \strlen($delimiter); @@ -260,14 +260,14 @@ private function skipHeredoc($delimiter): void * @param string $char * @return bool */ - private function peek($char): bool + private function peek(string $char): bool { return $this->index + 1 < $this->len && $this->contents[$this->index + 1] === $char; } /** * @param non-empty-string $regex - * @param ?array $match + * @param null|array $match * @return bool */ private function match($regex, array &$match = null): bool diff --git a/src/Composer/Cache.php b/src/Composer/Cache.php index 64c016f31066..0f8dc6aa4630 100644 --- a/src/Composer/Cache.php +++ b/src/Composer/Cache.php @@ -48,7 +48,7 @@ class Cache * @param Filesystem $filesystem optional filesystem instance * @param bool $readOnly whether the cache is in readOnly mode */ - public function __construct(IOInterface $io, $cacheDir, $allowlist = 'a-z0-9.', Filesystem $filesystem = null, $readOnly = false) + public function __construct(IOInterface $io, string $cacheDir, string $allowlist = 'a-z0-9.', Filesystem $filesystem = null, bool $readOnly = false) { $this->io = $io; $this->root = rtrim($cacheDir, '/\\') . '/'; @@ -66,7 +66,7 @@ public function __construct(IOInterface $io, $cacheDir, $allowlist = 'a-z0-9.', * * @return void */ - public function setReadOnly($readOnly) + public function setReadOnly(bool $readOnly) { $this->readOnly = (bool) $readOnly; } @@ -84,7 +84,7 @@ public function isReadOnly() * * @return bool */ - public static function isUsable($path) + public static function isUsable(string $path) { return !Preg::isMatch('{(^|[\\\\/])(\$null|nul|NUL|/dev/null)([\\\\/]|$)}', $path); } @@ -122,7 +122,7 @@ public function getRoot() * * @return string|false */ - public function read($file) + public function read(string $file) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -142,7 +142,7 @@ public function read($file) * * @return bool */ - public function write($file, $contents) + public function write(string $file, string $contents) { if ($this->isEnabled() && !$this->readOnly) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -186,7 +186,7 @@ public function write($file, $contents) * * @return bool */ - public function copyFrom($file, $source) + public function copyFrom(string $file, string $source) { if ($this->isEnabled() && !$this->readOnly) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -212,7 +212,7 @@ public function copyFrom($file, $source) * * @return bool */ - public function copyTo($file, $target) + public function copyTo(string $file, string $target) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -256,7 +256,7 @@ public function gcIsNecessary() * * @return bool */ - public function remove($file) + public function remove(string $file) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -287,7 +287,7 @@ public function clear() * @return int|false * @phpstan-return int<0, max>|false */ - public function getAge($file) + public function getAge(string $file) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -305,7 +305,7 @@ public function getAge($file) * * @return bool */ - public function gc($ttl, $maxSize) + public function gc(int $ttl, int $maxSize) { if ($this->isEnabled()) { $expire = new \DateTime(); @@ -340,7 +340,7 @@ public function gc($ttl, $maxSize) * * @return string|false */ - public function sha1($file) + public function sha1(string $file) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); @@ -357,7 +357,7 @@ public function sha1($file) * * @return string|false */ - public function sha256($file) + public function sha256(string $file) { if ($this->isEnabled()) { $file = Preg::replace('{[^'.$this->allowlist.']}i', '-', $file); diff --git a/src/Composer/Command/ArchiveCommand.php b/src/Composer/Command/ArchiveCommand.php index b785f4ea4fdc..db302b8651a2 100644 --- a/src/Composer/Command/ArchiveCommand.php +++ b/src/Composer/Command/ArchiveCommand.php @@ -25,6 +25,7 @@ use Composer\Plugin\PluginEvents; use Composer\Util\Filesystem; use Composer\Util\Loop; +use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -136,7 +137,7 @@ protected function archive(IOInterface $io, Config $config, ?string $packageName $io->writeError('Creating the archive into "'.$dest.'".'); $packagePath = $archiveManager->archive($package, $format, $dest, $fileName, $ignoreFilters); $fs = new Filesystem; - $shortPath = $fs->findShortestPath(getcwd(), $packagePath, true); + $shortPath = $fs->findShortestPath(Platform::getCwd(), $packagePath, true); $io->writeError('Created: ', false); $io->write(strlen($shortPath) < strlen($packagePath) ? $shortPath : $packagePath); @@ -150,7 +151,7 @@ protected function archive(IOInterface $io, Config $config, ?string $packageName * * @return (BasePackage&CompletePackageInterface)|false */ - protected function selectPackage(IOInterface $io, $packageName, $version = null) + protected function selectPackage(IOInterface $io, string $packageName, ?string $version = null) { $io->writeError('Searching for the specified package.'); diff --git a/src/Composer/Command/BaseCommand.php b/src/Composer/Command/BaseCommand.php index 22a290c1d3b0..c06e3ffa5b16 100644 --- a/src/Composer/Command/BaseCommand.php +++ b/src/Composer/Command/BaseCommand.php @@ -70,7 +70,7 @@ public function getApplication(): Application * @return Composer|null * @deprecated since Composer 2.3.0 use requireComposer or tryComposer depending on whether you have $required set to true or false */ - public function getComposer($required = true, $disablePlugins = null, $disableScripts = null) + public function getComposer(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null) { if ($required) { return $this->requireComposer($disablePlugins, $disableScripts); @@ -226,7 +226,7 @@ protected function initialize(InputInterface $input, OutputInterface $output) * * @return bool[] An array composed of the preferSource and preferDist values */ - protected function getPreferredInstallOptions(Config $config, InputInterface $input, $keepVcsRequiresPreferSource = false) + protected function getPreferredInstallOptions(Config $config, InputInterface $input, bool $keepVcsRequiresPreferSource = false) { $preferSource = false; $preferDist = false; diff --git a/src/Composer/Command/BaseDependencyCommand.php b/src/Composer/Command/BaseDependencyCommand.php index 224d2739e9e6..c2597e7c7cbe 100644 --- a/src/Composer/Command/BaseDependencyCommand.php +++ b/src/Composer/Command/BaseDependencyCommand.php @@ -50,7 +50,7 @@ class BaseDependencyCommand extends BaseCommand * @param bool $inverted Whether to invert matching process (why-not vs why behaviour) * @return int Exit code of the operation. */ - protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false): int + protected function doExecute(InputInterface $input, OutputInterface $output, bool $inverted = false): int { // Emit command event on startup $composer = $this->requireComposer(); @@ -197,7 +197,7 @@ protected function initStyles(OutputInterface $output): void * * @return void */ - protected function printTree($results, $prefix = '', $level = 1): void + protected function printTree(array $results, string $prefix = '', int $level = 1): void { $count = count($results); $idx = 0; @@ -223,7 +223,7 @@ protected function printTree($results, $prefix = '', $level = 1): void * * @return void */ - private function writeTreeLine($line): void + private function writeTreeLine(string $line): void { $io = $this->getIO(); if (!$io->isDecorated()) { diff --git a/src/Composer/Command/CheckPlatformReqsCommand.php b/src/Composer/Command/CheckPlatformReqsCommand.php index 8e525e7bf01f..54e1e9ba171e 100644 --- a/src/Composer/Command/CheckPlatformReqsCommand.php +++ b/src/Composer/Command/CheckPlatformReqsCommand.php @@ -174,7 +174,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * * @return void */ - protected function printTable(OutputInterface $output, $results): void + protected function printTable(OutputInterface $output, array $results): void { $rows = array(); foreach ($results as $result) { diff --git a/src/Composer/Command/ConfigCommand.php b/src/Composer/Command/ConfigCommand.php index 3e51a45995b1..3285fd3b40c8 100644 --- a/src/Composer/Command/ConfigCommand.php +++ b/src/Composer/Command/ConfigCommand.php @@ -175,7 +175,7 @@ protected function initialize(InputInterface $input, OutputInterface $output): v if ( ($configFile === 'composer.json' || $configFile === './composer.json') && !file_exists($configFile) - && realpath(getcwd()) === realpath($this->config->get('home')) + && realpath(Platform::getCwd()) === realpath($this->config->get('home')) ) { file_put_contents($configFile, "{\n}\n"); } @@ -810,7 +810,7 @@ function ($vals) { * * @return void */ - protected function handleSingleValue($key, array $callbacks, array $values, $method): void + protected function handleSingleValue(string $key, array $callbacks, array $values, string $method): void { list($validator, $normalizer) = $callbacks; if (1 !== count($values)) { @@ -845,7 +845,7 @@ protected function handleSingleValue($key, array $callbacks, array $values, $met * * @return void */ - protected function handleMultiValue($key, array $callbacks, array $values, $method): void + protected function handleMultiValue(string $key, array $callbacks, array $values, string $method): void { list($validator, $normalizer) = $callbacks; if (true !== $validation = $validator($values)) { @@ -868,7 +868,7 @@ protected function handleMultiValue($key, array $callbacks, array $values, $meth * * @return void */ - protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null, $showSource = false): void + protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, ?string $k = null, bool $showSource = false): void { $origK = $k; $io = $this->getIO(); diff --git a/src/Composer/Command/CreateProjectCommand.php b/src/Composer/Command/CreateProjectCommand.php index d7dcaeaae52b..4b185a6445da 100644 --- a/src/Composer/Command/CreateProjectCommand.php +++ b/src/Composer/Command/CreateProjectCommand.php @@ -187,9 +187,9 @@ protected function execute(InputInterface $input, OutputInterface $output): int * @return int * @throws \Exception */ - public function installProject(IOInterface $io, Config $config, InputInterface $input, $packageName = null, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $noInstall = false, PlatformRequirementFilterInterface $platformRequirementFilter = null, $secureHttp = true, $addRepository = false): int + public function installProject(IOInterface $io, Config $config, InputInterface $input, ?string $packageName = null, ?string $directory = null, ?string $packageVersion = null, ?string $stability = 'stable', bool $preferSource = false, bool $preferDist = false, bool $installDevPackages = false, $repositories = null, bool $disablePlugins = false, bool $disableScripts = false, bool $noProgress = false, bool $noInstall = false, PlatformRequirementFilterInterface $platformRequirementFilter = null, bool $secureHttp = true, bool $addRepository = false): int { - $oldCwd = getcwd(); + $oldCwd = Platform::getCwd(); if ($repositories !== null && !is_array($repositories)) { $repositories = (array) $repositories; @@ -284,7 +284,7 @@ public function installProject(IOInterface $io, Config $config, InputInterface $ ) ) { $finder = new Finder(); - $finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false); + $finder->depth(0)->directories()->in(Platform::getCwd())->ignoreVCS(false)->ignoreDotFiles(false); foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg', '.fslckout', '_FOSSIL_') as $vcsName) { $finder->name($vcsName); } @@ -350,7 +350,7 @@ public function installProject(IOInterface $io, Config $config, InputInterface $ * @return bool * @throws \Exception */ - protected function installRootPackage(IOInterface $io, Config $config, $packageName, PlatformRequirementFilterInterface $platformRequirementFilter, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, array $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $secureHttp = true): bool + protected function installRootPackage(IOInterface $io, Config $config, string $packageName, PlatformRequirementFilterInterface $platformRequirementFilter, ?string $directory = null, ?string $packageVersion = null, ?string $stability = 'stable', bool $preferSource = false, bool $preferDist = false, bool $installDevPackages = false, array $repositories = null, bool $disablePlugins = false, bool $disableScripts = false, bool $noProgress = false, bool $secureHttp = true): bool { if (!$secureHttp) { $config->merge(array('config' => array('secure-http' => false)), Config::SOURCE_COMMAND); @@ -366,16 +366,16 @@ protected function installRootPackage(IOInterface $io, Config $config, $packageN // if no directory was specified, use the 2nd part of the package name if (null === $directory) { $parts = explode("/", $name, 2); - $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts); + $directory = Platform::getCwd() . DIRECTORY_SEPARATOR . array_pop($parts); } $process = new ProcessExecutor($io); $fs = new Filesystem($process); if (!$fs->isAbsolutePath($directory)) { - $directory = getcwd() . DIRECTORY_SEPARATOR . $directory; + $directory = Platform::getCwd() . DIRECTORY_SEPARATOR . $directory; } - $io->writeError('Creating a "' . $packageName . '" project at "' . $fs->findShortestPath(getcwd(), $directory, true) . '"'); + $io->writeError('Creating a "' . $packageName . '" project at "' . $fs->findShortestPath(Platform::getCwd(), $directory, true) . '"'); if (file_exists($directory)) { if (!is_dir($directory)) { diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index 75bec936aeb0..8ed6ed0f46cc 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -52,7 +52,7 @@ class DiagnoseCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('diagnose') @@ -245,7 +245,7 @@ private function checkGit() * * @return string|string[]|true */ - private function checkHttp($proto, Config $config) + private function checkHttp(string $proto, Config $config) { $result = $this->checkConnectivity(); if ($result !== true) { @@ -315,7 +315,7 @@ private function checkHttpProxy() * * @return string|true|\Exception */ - private function checkGithubOauth($domain, $token) + private function checkGithubOauth(string $domain, string $token) { $result = $this->checkConnectivity(); if ($result !== true) { @@ -346,7 +346,7 @@ private function checkGithubOauth($domain, $token) * @throws TransportException * @return mixed|string */ - private function getGithubRateLimit($domain, $token = null) + private function getGithubRateLimit(string $domain, string $token = null) { $result = $this->checkConnectivity(); if ($result !== true) { diff --git a/src/Composer/Command/ExecCommand.php b/src/Composer/Command/ExecCommand.php index 8ff06afd4180..ac3ed11ab544 100644 --- a/src/Composer/Command/ExecCommand.php +++ b/src/Composer/Command/ExecCommand.php @@ -95,7 +95,7 @@ protected function execute(InputInterface $input, OutputInterface $output) // If the CWD was modified, we restore it to what it was initially, as it was // most likely modified by the global command, and we want exec to run in the local working directory // not the global one - if (getcwd() !== $this->getApplication()->getInitialWorkingDirectory()) { + if (getcwd() !== $this->getApplication()->getInitialWorkingDirectory() && $this->getApplication()->getInitialWorkingDirectory() !== false) { try { chdir($this->getApplication()->getInitialWorkingDirectory()); } catch (\Exception $e) { diff --git a/src/Composer/Command/HomeCommand.php b/src/Composer/Command/HomeCommand.php index b83f31e03340..798d654dfc6c 100644 --- a/src/Composer/Command/HomeCommand.php +++ b/src/Composer/Command/HomeCommand.php @@ -101,7 +101,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * @param bool $showOnly * @return bool */ - private function handlePackage(CompletePackageInterface $package, $showHomepage, $showOnly): bool + private function handlePackage(CompletePackageInterface $package, bool $showHomepage, bool $showOnly): bool { $support = $package->getSupport(); $url = $support['source'] ?? $package->getSourceUrl(); @@ -128,7 +128,7 @@ private function handlePackage(CompletePackageInterface $package, $showHomepage, * @param string $url * @return void */ - private function openBrowser($url): void + private function openBrowser(string $url): void { $url = ProcessExecutor::escape($url); diff --git a/src/Composer/Command/InitCommand.php b/src/Composer/Command/InitCommand.php index 8b67c26abc1f..1d4dea29bc14 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -456,11 +456,10 @@ function ($value) use ($autoload) { } /** - * @private * @param string $author * @return array{name: string, email: string|null} */ - public function parseAuthorString($author) + private function parseAuthorString(string $author): array { if (Preg::isMatch('/^(?P[- .,\p{L}\p{N}\p{Mn}\'’"()]+)(?:\s+<(?P.+?)>)?$/u', $author, $match)) { $hasEmail = isset($match['email']) && '' !== $match['email']; @@ -485,7 +484,7 @@ public function parseAuthorString($author) * * @return array */ - protected function formatAuthors($author) + protected function formatAuthors(string $author): array { $author = $this->parseAuthorString($author); if (null === $author['email']) { @@ -504,7 +503,7 @@ protected function formatAuthors($author) * * @return string|null */ - public function namespaceFromPackageName($packageName) + public function namespaceFromPackageName(string $packageName): ?string { if (!$packageName || strpos($packageName, '/') === false) { return null; @@ -526,7 +525,7 @@ function ($part): string { /** * @return array */ - protected function getGitConfig() + protected function getGitConfig(): array { if (null !== $this->gitConfig) { return $this->gitConfig; @@ -567,7 +566,7 @@ protected function getGitConfig() * * @return bool */ - protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor') + protected function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor'): bool { if (!file_exists($ignoreFile)) { return false; @@ -591,7 +590,7 @@ protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor') * * @return void */ - protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/') + protected function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/'): void { $contents = ""; if (file_exists($ignoreFile)) { @@ -610,7 +609,7 @@ protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/') * * @return bool */ - protected function isValidEmail($email) + protected function isValidEmail(string $email): bool { // assume it's valid if we can't validate it if (!function_exists('filter_var')) { @@ -652,7 +651,7 @@ private function runDumpAutoloadCommand(OutputInterface $output): void * @param array> $options * @return bool */ - private function hasDependencies($options): bool + private function hasDependencies(array $options): bool { $requires = (array) $options['require']; $devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : array(); diff --git a/src/Composer/Command/LicensesCommand.php b/src/Composer/Command/LicensesCommand.php index f59034282a84..b51292742f99 100644 --- a/src/Composer/Command/LicensesCommand.php +++ b/src/Composer/Command/LicensesCommand.php @@ -163,7 +163,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * @param array $bucket * @return array */ - private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()): array + private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, array $bucket = array()): array { $requires = array_keys($package->getRequires()); diff --git a/src/Composer/Command/RequireCommand.php b/src/Composer/Command/RequireCommand.php index 5ad66a7949d6..5a65ccec91eb 100644 --- a/src/Composer/Command/RequireCommand.php +++ b/src/Composer/Command/RequireCommand.php @@ -296,7 +296,7 @@ protected function execute(InputInterface $input, OutputInterface $output) * @param string $requireKey * @return string[] */ - private function getInconsistentRequireKeys(array $newRequirements, $requireKey): array + private function getInconsistentRequireKeys(array $newRequirements, string $requireKey): array { $requireKeys = $this->getPackagesByRequireKey(); $inconsistentRequirements = array(); @@ -335,15 +335,6 @@ private function getPackagesByRequireKey(): array ); } - /** - * @private - * @return void - */ - public function markSolverComplete() - { - $this->dependencyResolutionCompleted = true; - } - /** * @param array $requirements * @param string $requireKey @@ -351,14 +342,16 @@ public function markSolverComplete() * @return int * @throws \Exception */ - private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, $requireKey, $removeKey): int + private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, string $requireKey, string $removeKey): int { // Update packages $this->resetComposer(); $composer = $this->requireComposer(); $this->dependencyResolutionCompleted = false; - $composer->getEventDispatcher()->addListener(InstallerEvents::PRE_OPERATIONS_EXEC, array($this, 'markSolverComplete'), 10000); + $composer->getEventDispatcher()->addListener(InstallerEvents::PRE_OPERATIONS_EXEC, function (): void { + $this->dependencyResolutionCompleted = true; + }, 10000); if ($input->getOption('dry-run')) { $rootPackage = $composer->getPackage(); @@ -449,7 +442,7 @@ private function doUpdate(InputInterface $input, OutputInterface $output, IOInte * @param bool $sortPackages * @return bool */ - private function updateFileCleanly(JsonFile $json, array $new, $requireKey, $removeKey, $sortPackages): bool + private function updateFileCleanly(JsonFile $json, array $new, string $requireKey, string $removeKey, bool $sortPackages): bool { $contents = file_get_contents($json->getPath()); @@ -480,7 +473,7 @@ protected function interact(InputInterface $input, OutputInterface $output): voi * @param bool $hardExit * @return void */ - public function revertComposerFile($hardExit = true) + public function revertComposerFile(bool $hardExit = true): void { $io = $this->getIO(); diff --git a/src/Composer/Command/ScriptAliasCommand.php b/src/Composer/Command/ScriptAliasCommand.php index 2c98c9a66f56..793127f8c07a 100644 --- a/src/Composer/Command/ScriptAliasCommand.php +++ b/src/Composer/Command/ScriptAliasCommand.php @@ -27,14 +27,10 @@ class ScriptAliasCommand extends BaseCommand /** @var string */ private $description; - /** - * @param string $script - * @param string $description - */ - public function __construct($script, $description) + public function __construct(string $script, ?string $description) { $this->script = $script; - $this->description = empty($description) ? 'Runs the '.$script.' script as defined in composer.json.' : $description; + $this->description = $description ?? 'Runs the '.$script.' script as defined in composer.json.'; parent::__construct(); } diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index 06b0d2d0d528..38c0e4cdde93 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -397,7 +397,7 @@ protected function fetchKeys(IOInterface $io, Config $config): void * @return int * @throws FilesystemException */ - protected function rollback(OutputInterface $output, $rollbackDir, $localFilename): int + protected function rollback(OutputInterface $output, string $rollbackDir, string $localFilename): int { $rollbackVersion = $this->getLastBackupVersion($rollbackDir); if (!$rollbackVersion) { @@ -431,7 +431,7 @@ protected function rollback(OutputInterface $output, $rollbackDir, $localFilenam * @throws FilesystemException If the file cannot be moved * @return bool Whether the phar is valid and has been moved */ - protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null): bool + protected function setLocalPhar(string $localFilename, string $newFilename, string $backupTarget = null): bool { $io = $this->getIO(); @chmod($newFilename, fileperms($localFilename)); @@ -483,7 +483,7 @@ protected function setLocalPhar($localFilename, $newFilename, $backupTarget = nu * * @return void */ - protected function cleanBackups($rollbackDir, $except = null): void + protected function cleanBackups(string $rollbackDir, ?string $except = null): void { $finder = $this->getOldInstallationFinder($rollbackDir); $io = $this->getIO(); @@ -503,7 +503,7 @@ protected function cleanBackups($rollbackDir, $except = null): void * @param string $rollbackDir * @return string|false */ - protected function getLastBackupVersion($rollbackDir) + protected function getLastBackupVersion(string $rollbackDir) { $finder = $this->getOldInstallationFinder($rollbackDir); $finder->sortByName(); @@ -520,7 +520,7 @@ protected function getLastBackupVersion($rollbackDir) * @param string $rollbackDir * @return Finder */ - protected function getOldInstallationFinder($rollbackDir): Finder + protected function getOldInstallationFinder(string $rollbackDir): Finder { return Finder::create() ->depth(0) @@ -541,7 +541,7 @@ protected function getOldInstallationFinder($rollbackDir): Finder * @throws \Exception * @return bool If the operation succeeded */ - protected function validatePhar($pharFile, &$error): bool + protected function validatePhar(string $pharFile, ?string &$error): bool { if (ini_get('phar.readonly')) { return true; @@ -590,7 +590,7 @@ protected function isWindowsNonAdminUser(): bool * @param string $newFilename The downloaded or backup phar * @return bool Whether composer.phar has been updated */ - protected function tryAsWindowsAdmin($localFilename, $newFilename): bool + protected function tryAsWindowsAdmin(string $localFilename, string $newFilename): bool { $io = $this->getIO(); diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php index ae9350f1e2cb..8b11a8e33156 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -223,7 +223,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('no-dev')) { $packages = $this->filterRequiredPackages($installedRepo, $rootPkg); - $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg): \Composer\Package\PackageInterface { + $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg): PackageInterface { return clone $pkg; }, $packages)))); } @@ -294,7 +294,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ( $input->getOption('outdated') && $input->getOption('strict') - && $latestPackage + && null !== $latestPackage && $latestPackage->getFullPrettyVersion() !== $package->getFullPrettyVersion() && (!$latestPackage instanceof CompletePackageInterface || !$latestPackage->isAbandoned()) ) { @@ -415,7 +415,7 @@ protected function execute(InputInterface $input, OutputInterface $output) foreach ($packages[$type] as $package) { if (is_object($package)) { $latestPackage = $this->findLatestPackage($package, $composer, $platformRepo, $showMinorOnly, $platformReqFilter); - if ($latestPackage === false) { + if ($latestPackage === null) { continue; } @@ -602,7 +602,7 @@ protected function execute(InputInterface $input, OutputInterface $output) /** * @return string[] */ - protected function getRootRequires() + protected function getRootRequires(): array { $rootPackage = $this->requireComposer()->getPackage(); @@ -628,7 +628,7 @@ protected function getVersionStyle(PackageInterface $latestPackage, PackageInter * @throws \InvalidArgumentException * @return array{CompletePackageInterface|null, array} */ - protected function getPackage(InstalledRepository $installedRepo, RepositoryInterface $repos, $name, $version = null) + protected function getPackage(InstalledRepository $installedRepo, RepositoryInterface $repos, string $name, $version = null): array { $name = strtolower($name); $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version; @@ -677,7 +677,7 @@ protected function getPackage(InstalledRepository $installedRepo, RepositoryInte * * @return void */ - protected function printPackageInfo(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null) + protected function printPackageInfo(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null): void { $io = $this->getIO(); @@ -705,7 +705,7 @@ protected function printPackageInfo(CompletePackageInterface $package, array $ve * * @return void */ - protected function printMeta(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null) + protected function printMeta(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null): void { $io = $this->getIO(); $io->write('name : ' . $package->getPrettyName()); @@ -773,7 +773,7 @@ protected function printMeta(CompletePackageInterface $package, array $versions, * * @return void */ - protected function printVersions(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo) + protected function printVersions(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo): void { $versions = array_keys($versions); $versions = Semver::rsort($versions); @@ -802,7 +802,7 @@ protected function printVersions(CompletePackageInterface $package, array $versi * * @return void */ - protected function printLinks(CompletePackageInterface $package, $linkType, $title = null) + protected function printLinks(CompletePackageInterface $package, string $linkType, string $title = null): void { $title = $title ?: $linkType; $io = $this->getIO(); @@ -820,7 +820,7 @@ protected function printLinks(CompletePackageInterface $package, $linkType, $tit * * @return void */ - protected function printLicenses(CompletePackageInterface $package) + protected function printLicenses(CompletePackageInterface $package): void { $spdxLicenses = new SpdxLicenses(); @@ -852,7 +852,7 @@ protected function printLicenses(CompletePackageInterface $package) * * @return void */ - protected function printPackageInfoAsJson(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null) + protected function printPackageInfoAsJson(CompletePackageInterface $package, array $versions, InstalledRepository $installedRepo, PackageInterface $latestPackage = null): void { $json = array( 'name' => $package->getPrettyName(), @@ -923,7 +923,7 @@ protected function printPackageInfoAsJson(CompletePackageInterface $package, arr * @param array $versions * @return array */ - private function appendVersions($json, array $versions): array + private function appendVersions(array $json, array $versions): array { uasort($versions, 'version_compare'); $versions = array_keys(array_reverse($versions)); @@ -936,7 +936,7 @@ private function appendVersions($json, array $versions): array * @param array $json * @return array */ - private function appendLicenses($json, CompletePackageInterface $package): array + private function appendLicenses(array $json, CompletePackageInterface $package): array { if ($licenses = $package->getLicense()) { $spdxLicenses = new SpdxLicenses(); @@ -963,7 +963,7 @@ private function appendLicenses($json, CompletePackageInterface $package): array * @param array $json * @return array */ - private function appendAutoload($json, CompletePackageInterface $package): array + private function appendAutoload(array $json, CompletePackageInterface $package): array { if ($package->getAutoload()) { $autoload = array(); @@ -996,7 +996,7 @@ private function appendAutoload($json, CompletePackageInterface $package): array * @param array $json * @return array */ - private function appendLinks($json, CompletePackageInterface $package): array + private function appendLinks(array $json, CompletePackageInterface $package): array { foreach (Link::$TYPES as $linkType) { $json = $this->appendLink($json, $package, $linkType); @@ -1010,7 +1010,7 @@ private function appendLinks($json, CompletePackageInterface $package): array * @param string $linkType * @return array */ - private function appendLink($json, CompletePackageInterface $package, $linkType): array + private function appendLink(array $json, CompletePackageInterface $package, string $linkType): array { $links = $package->{'get' . ucfirst($linkType)}(); @@ -1030,7 +1030,7 @@ private function appendLink($json, CompletePackageInterface $package, $linkType) * * @return void */ - protected function initStyles(OutputInterface $output) + protected function initStyles(OutputInterface $output): void { $this->colors = array( 'green', @@ -1052,7 +1052,7 @@ protected function initStyles(OutputInterface $output) * @param array> $arrayTree * @return void */ - protected function displayPackageTree(array $arrayTree) + protected function displayPackageTree(array $arrayTree): void { $io = $this->getIO(); foreach ($arrayTree as $package) { @@ -1101,7 +1101,7 @@ protected function generatePackageTree( PackageInterface $package, InstalledRepository $installedRepo, RepositoryInterface $remoteRepos - ) { + ): array { $requires = $package->getRequires(); ksort($requires); $children = array(); @@ -1147,9 +1147,9 @@ protected function generatePackageTree( protected function displayTree( $package, array $packagesInTree, - $previousTreeBar = '├', - $level = 1 - ) { + string $previousTreeBar = '├', + int $level = 1 + ): void { $previousTreeBar = str_replace('├', '│', $previousTreeBar); if (is_array($package) && isset($package['requires'])) { $requires = $package['requires']; @@ -1197,12 +1197,12 @@ protected function displayTree( * @return array>|string>> */ protected function addTree( - $name, + string $name, Link $link, InstalledRepository $installedRepo, RepositoryInterface $remoteRepos, array $packagesInTree - ) { + ): array { $children = array(); list($package) = $this->getPackage( $installedRepo, @@ -1240,7 +1240,7 @@ protected function addTree( * @param string $updateStatus * @return string */ - private function updateStatusToVersionStyle($updateStatus): string + private function updateStatusToVersionStyle(string $updateStatus): string { // 'up-to-date' is printed green // 'semver-safe-update' is printed red @@ -1275,7 +1275,7 @@ private function getUpdateStatus(PackageInterface $latestPackage, PackageInterfa * * @return void */ - private function writeTreeLine($line): void + private function writeTreeLine(string $line): void { $io = $this->getIO(); if (!$io->isDecorated()) { @@ -1287,10 +1287,8 @@ private function writeTreeLine($line): void /** * Given a package, this finds the latest package matching it - * - * @return PackageInterface|false */ - private function findLatestPackage(PackageInterface $package, Composer $composer, PlatformRepository $platformRepo, bool $minorOnly, PlatformRequirementFilterInterface $platformReqFilter) + private function findLatestPackage(PackageInterface $package, Composer $composer, PlatformRepository $platformRepo, bool $minorOnly, PlatformRequirementFilterInterface $platformReqFilter): ?PackageInterface { // find the latest version allowed in this repo set $name = $package->getName(); @@ -1320,7 +1318,7 @@ private function findLatestPackage(PackageInterface $package, Composer $composer $candidate = $candidate->getAliasOf(); } - return $candidate; + return $candidate !== false ? $candidate : null; } /** @@ -1342,7 +1340,7 @@ private function getRepositorySet(Composer $composer): RepositorySet * @param array $bucket * @return array */ - private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()): array + private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, array $bucket = array()): array { $requires = $package->getRequires(); diff --git a/src/Composer/Command/UpdateCommand.php b/src/Composer/Command/UpdateCommand.php index 39decf7888e3..2250f225af16 100644 --- a/src/Composer/Command/UpdateCommand.php +++ b/src/Composer/Command/UpdateCommand.php @@ -312,7 +312,7 @@ private function getPackagesInteractively(IOInterface $io, InputInterface $input * @param string $constraint * @return Link */ - private function appendConstraintToLink(Link $link, $constraint): Link + private function appendConstraintToLink(Link $link, string $constraint): Link { $parser = new VersionParser; $oldPrettyString = $link->getConstraint()->getPrettyString(); diff --git a/src/Composer/Command/ValidateCommand.php b/src/Composer/Command/ValidateCommand.php index 8c5ad5aeab33..e91008f5c138 100644 --- a/src/Composer/Command/ValidateCommand.php +++ b/src/Composer/Command/ValidateCommand.php @@ -169,7 +169,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int * * @return void */ - private function outputResult(IOInterface $io, $name, &$errors, &$warnings, $checkPublish = false, $publishErrors = array(), $checkLock = false, $lockErrors = array(), $printSchemaUrl = false): void + private function outputResult(IOInterface $io, string $name, array &$errors, array &$warnings, bool $checkPublish = false, array $publishErrors = array(), bool $checkLock = false, array $lockErrors = array(), bool $printSchemaUrl = false): void { $doPrintSchemaUrl = false; diff --git a/src/Composer/Compiler.php b/src/Composer/Compiler.php index 6bf2504686a8..76bc5ce7cc31 100644 --- a/src/Composer/Compiler.php +++ b/src/Composer/Compiler.php @@ -44,7 +44,7 @@ class Compiler * * @throws \RuntimeException */ - public function compile($pharFile = 'composer.phar'): void + public function compile(string $pharFile = 'composer.phar'): void { if (file_exists($pharFile)) { unlink($pharFile); @@ -201,7 +201,7 @@ public function compile($pharFile = 'composer.phar'): void * @param \SplFileInfo $file * @return string */ - private function getRelativeFilePath($file): string + private function getRelativeFilePath(\SplFileInfo $file): string { $realPath = $file->getRealPath(); $pathPrefix = dirname(__DIR__, 2).DIRECTORY_SEPARATOR; @@ -217,7 +217,7 @@ private function getRelativeFilePath($file): string * * @return void */ - private function addFile(\Phar $phar, \SplFileInfo $file, $strip = true): void + private function addFile(\Phar $phar, \SplFileInfo $file, bool $strip = true): void { $path = $this->getRelativeFilePath($file); $content = file_get_contents($file); @@ -258,7 +258,7 @@ private function addComposerBin(\Phar $phar): void * @param string $source A PHP string * @return string The PHP string with the whitespace removed */ - private function stripWhitespace($source): string + private function stripWhitespace(string $source): string { if (!function_exists('token_get_all')) { return $source; diff --git a/src/Composer/Config.php b/src/Composer/Config.php index 24423a0a4824..935cd38da872 100644 --- a/src/Composer/Config.php +++ b/src/Composer/Config.php @@ -111,10 +111,10 @@ class Config private $sourceOfConfigValue = array(); /** - * @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings - * @param string $baseDir Optional base directory of the config + * @param bool $useEnvironment Use COMPOSER_ environment variables to replace config settings + * @param ?string $baseDir Optional base directory of the config */ - public function __construct($useEnvironment = true, $baseDir = null) + public function __construct(bool $useEnvironment = true, ?string $baseDir = null) { // load defaults $this->config = static::$defaultConfig; @@ -126,7 +126,7 @@ public function __construct($useEnvironment = true, $baseDir = null) $this->repositories = static::$defaultRepositories; $this->useEnvironment = (bool) $useEnvironment; - $this->baseDir = $baseDir; + $this->baseDir = is_string($baseDir) && '' !== $baseDir ? $baseDir : null; foreach ($this->config as $configKey => $configValue) { $this->setSourceOfConfigValue($configValue, $configKey, self::SOURCE_DEFAULT); @@ -177,7 +177,7 @@ public function getAuthConfigSource(): ConfigSourceInterface * * @return void */ - public function merge($config, $source = self::SOURCE_UNKNOWN): void + public function merge(array $config, string $source = self::SOURCE_UNKNOWN): void { // override defaults with given config if (!empty($config['config']) && is_array($config['config'])) { @@ -277,7 +277,7 @@ public function getRepositories(): array * * @return mixed */ - public function get($key, $flags = 0) + public function get(string $key, int $flags = 0) { switch ($key) { // strings/paths with env var and {$refs} support @@ -441,7 +441,7 @@ public function get($key, $flags = 0) * * @return array */ - public function all($flags = 0): array + public function all(int $flags = 0): array { $all = array( 'repositories' => $this->getRepositories(), @@ -457,7 +457,7 @@ public function all($flags = 0): array * @param string $key * @return string */ - public function getSourceOfValue($key): string + public function getSourceOfValue(string $key): string { $this->get($key); @@ -471,7 +471,7 @@ public function getSourceOfValue($key): string * * @return void */ - private function setSourceOfConfigValue($configValue, $path, $source): void + private function setSourceOfConfigValue($configValue, string $path, string $source): void { $this->sourceOfConfigValue[$path] = $source; @@ -499,7 +499,7 @@ public function raw(): array * @param string $key * @return bool */ - public function has($key): bool + public function has(string $key): bool { return array_key_exists($key, $this->config); } @@ -512,7 +512,7 @@ public function has($key): bool * * @return string|int|null */ - private function process($value, $flags) + private function process($value, int $flags) { if (!is_string($value)) { return $value; @@ -531,9 +531,9 @@ private function process($value, $flags) * @param string $path * @return string */ - private function realpath($path): string + private function realpath(string $path): string { - if (Preg::isMatch('{^(?:/|[a-z]:|[a-z0-9.]+://)}i', $path)) { + if (Preg::isMatch('{^(?:/|[a-z]:|[a-z0-9.]+://|\\\\\\\\)}i', $path)) { return $path; } @@ -549,7 +549,7 @@ private function realpath($path): string * @param string $var * @return string|bool */ - private function getComposerEnv($var) + private function getComposerEnv(string $var) { if ($this->useEnvironment) { return Platform::getEnv($var); @@ -563,7 +563,7 @@ private function getComposerEnv($var) * * @return void */ - private function disableRepoByName($name): void + private function disableRepoByName(string $name): void { if (isset($this->repositories[$name])) { unset($this->repositories[$name]); @@ -580,7 +580,7 @@ private function disableRepoByName($name): void * * @return void */ - public function prohibitUrlByConfig($url, IOInterface $io = null): void + public function prohibitUrlByConfig(string $url, IOInterface $io = null): void { // Return right away if the URL is malformed or custom (see issue #5173) if (false === filter_var($url, FILTER_VALIDATE_URL)) { diff --git a/src/Composer/Config/ConfigSourceInterface.php b/src/Composer/Config/ConfigSourceInterface.php index a50975442d83..7cb590de67f7 100644 --- a/src/Composer/Config/ConfigSourceInterface.php +++ b/src/Composer/Config/ConfigSourceInterface.php @@ -29,7 +29,7 @@ interface ConfigSourceInterface * * @return void */ - public function addRepository($name, $config, $append = true); + public function addRepository(string $name, $config, bool $append = true): void; /** * Remove a repository @@ -38,7 +38,7 @@ public function addRepository($name, $config, $append = true); * * @return void */ - public function removeRepository($name); + public function removeRepository(string $name): void; /** * Add a config setting @@ -48,7 +48,7 @@ public function removeRepository($name); * * @return void */ - public function addConfigSetting($name, $value); + public function addConfigSetting(string $name, $value): void; /** * Remove a config setting @@ -57,7 +57,7 @@ public function addConfigSetting($name, $value); * * @return void */ - public function removeConfigSetting($name); + public function removeConfigSetting(string $name): void; /** * Add a property @@ -67,7 +67,7 @@ public function removeConfigSetting($name); * * @return void */ - public function addProperty($name, $value); + public function addProperty(string $name, $value): void; /** * Remove a property @@ -76,7 +76,7 @@ public function addProperty($name, $value); * * @return void */ - public function removeProperty($name); + public function removeProperty(string $name): void; /** * Add a package link @@ -87,7 +87,7 @@ public function removeProperty($name); * * @return void */ - public function addLink($type, $name, $value); + public function addLink(string $type, string $name, string $value): void; /** * Remove a package link @@ -97,12 +97,12 @@ public function addLink($type, $name, $value); * * @return void */ - public function removeLink($type, $name); + public function removeLink(string $type, string $name): void; /** * Gives a user-friendly name to this source (file path or so) * * @return string */ - public function getName(); + public function getName(): string; } diff --git a/src/Composer/Config/JsonConfigSource.php b/src/Composer/Config/JsonConfigSource.php index 84de4f32c9fd..cb04bc6e9a4c 100644 --- a/src/Composer/Config/JsonConfigSource.php +++ b/src/Composer/Config/JsonConfigSource.php @@ -43,7 +43,7 @@ class JsonConfigSource implements ConfigSourceInterface * @param JsonFile $file * @param bool $authConfig */ - public function __construct(JsonFile $file, $authConfig = false) + public function __construct(JsonFile $file, bool $authConfig = false) { $this->file = $file; $this->authConfig = $authConfig; @@ -52,7 +52,7 @@ public function __construct(JsonFile $file, $authConfig = false) /** * @inheritDoc */ - public function getName() + public function getName(): string { return $this->file->getPath(); } @@ -60,7 +60,7 @@ public function getName() /** * @inheritDoc */ - public function addRepository($name, $config, $append = true) + public function addRepository(string $name, $config, bool $append = true): void { $this->manipulateJson('addRepository', function (&$config, $repo, $repoConfig) use ($append): void { // if converting from an array format to hashmap format, and there is a {"packagist.org":false} repo, we have @@ -89,7 +89,7 @@ public function addRepository($name, $config, $append = true) /** * @inheritDoc */ - public function removeRepository($name) + public function removeRepository(string $name): void { $this->manipulateJson('removeRepository', function (&$config, $repo): void { unset($config['repositories'][$repo]); @@ -99,7 +99,7 @@ public function removeRepository($name) /** * @inheritDoc */ - public function addConfigSetting($name, $value) + public function addConfigSetting(string $name, $value): void { $authConfig = $this->authConfig; $this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig): void { @@ -119,7 +119,7 @@ public function addConfigSetting($name, $value) /** * @inheritDoc */ - public function removeConfigSetting($name) + public function removeConfigSetting(string $name): void { $authConfig = $this->authConfig; $this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig): void { @@ -139,7 +139,7 @@ public function removeConfigSetting($name) /** * @inheritDoc */ - public function addProperty($name, $value) + public function addProperty(string $name, $value): void { $this->manipulateJson('addProperty', function (&$config, $key, $val): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { @@ -162,7 +162,7 @@ public function addProperty($name, $value) /** * @inheritDoc */ - public function removeProperty($name) + public function removeProperty(string $name): void { $this->manipulateJson('removeProperty', function (&$config, $key): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { @@ -185,7 +185,7 @@ public function removeProperty($name) /** * @inheritDoc */ - public function addLink($type, $name, $value) + public function addLink(string $type, string $name, string $value): void { $this->manipulateJson('addLink', function (&$config, $type, $name, $value): void { $config[$type][$name] = $value; @@ -195,7 +195,7 @@ public function addLink($type, $name, $value) /** * @inheritDoc */ - public function removeLink($type, $name) + public function removeLink(string $type, string $name): void { $this->manipulateJson('removeSubNode', function (&$config, $type, $name): void { unset($config[$type][$name]); @@ -214,7 +214,7 @@ public function removeLink($type, $name) * * @return void */ - private function manipulateJson($method, $fallback, ...$args): void + private function manipulateJson(string $method, callable $fallback, ...$args): void { if ($this->file->exists()) { if (!is_writable($this->file->getPath())) { @@ -297,7 +297,7 @@ private function manipulateJson($method, $fallback, ...$args): void * @param mixed $value * @return int */ - private function arrayUnshiftRef(&$array, &$value): int + private function arrayUnshiftRef(array &$array, &$value): int { $return = array_unshift($array, ''); $array[0] = &$value; diff --git a/src/Composer/Console/Application.php b/src/Composer/Console/Application.php index 5bf8f6ffca9e..f2fac34fceed 100644 --- a/src/Composer/Console/Application.php +++ b/src/Composer/Console/Application.php @@ -74,7 +74,7 @@ class Application extends BaseApplication private $disableScriptsByDefault = false; /** - * @var string Store the initial working directory at startup time + * @var string|false Store the initial working directory at startup time */ private $initialWorkingDirectory; @@ -151,10 +151,11 @@ public function doRun(InputInterface $input, OutputInterface $output): int // switch working dir if ($newWorkDir = $this->getNewWorkingDir($input)) { - $oldWorkingDir = getcwd(); + $oldWorkingDir = Platform::getCwd(true); chdir($newWorkDir); $this->initialWorkingDirectory = $newWorkDir; - $io->writeError('Changed CWD to ' . getcwd(), true, IOInterface::DEBUG); + $cwd = Platform::getCwd(true); + $io->writeError('Changed CWD to ' . ($cwd !== '' ? $cwd : $newWorkDir), true, IOInterface::DEBUG); } // determine command name to be executed without including plugin commands @@ -171,7 +172,7 @@ public function doRun(InputInterface $input, OutputInterface $output): int // prompt user for dir change if no composer.json is present in current dir if ($io->isInteractive() && !$newWorkDir && !in_array($commandName, array('', 'list', 'init', 'about', 'help', 'diagnose', 'self-update', 'global', 'create-project', 'outdated'), true) && !file_exists(Factory::getComposerFile()) && ($useParentDirIfNoJsonAvailable = $this->getUseParentDirConfigValue()) !== false) { - $dir = dirname(getcwd()); + $dir = dirname(Platform::getCwd(true)); $home = realpath(Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE') ?: '/'); // abort when we reach the home dir or top of the filesystem @@ -183,7 +184,7 @@ public function doRun(InputInterface $input, OutputInterface $output): int } else { $io->writeError('Always want to use the parent dir? Use "composer config --global use-parent-dir true" to change the default.'); } - $oldWorkingDir = getcwd(); + $oldWorkingDir = Platform::getCwd(true); chdir($dir); } break; @@ -330,7 +331,7 @@ function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknow $result = parent::doRun($input, $output); // chdir back to $oldWorkingDir if set - if (isset($oldWorkingDir)) { + if (isset($oldWorkingDir) && '' !== $oldWorkingDir) { Silencer::call('chdir', $oldWorkingDir); } @@ -422,9 +423,9 @@ private function hintCommonErrors(\Exception $exception): void * @param bool|null $disableScripts * @throws JsonValidationException * @throws \InvalidArgumentException - * @return ?\Composer\Composer If $required is true then the return value is guaranteed + * @return ?Composer If $required is true then the return value is guaranteed */ - public function getComposer($required = true, $disablePlugins = null, $disableScripts = null) + public function getComposer(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null): ?Composer { if (null === $disablePlugins) { $disablePlugins = $this->disablePluginsByDefault; @@ -459,7 +460,7 @@ public function getComposer($required = true, $disablePlugins = null, $disableSc * * @return void */ - public function resetComposer() + public function resetComposer(): void { $this->composer = null; if (method_exists($this->getIO(), 'resetAuthentications')) { @@ -470,7 +471,7 @@ public function resetComposer() /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -585,7 +586,7 @@ private function getPluginCommands(): array /** * Get the working directory at startup time * - * @return string + * @return string|false */ public function getInitialWorkingDirectory() { diff --git a/src/Composer/Console/GithubActionError.php b/src/Composer/Console/GithubActionError.php index 578ac8ecad21..d73b55851618 100644 --- a/src/Composer/Console/GithubActionError.php +++ b/src/Composer/Console/GithubActionError.php @@ -34,7 +34,7 @@ public function __construct(IOInterface $io) * * @return void */ - public function emit($message, $file = null, $line = null): void + public function emit(string $message, ?string $file = null, ?int $line = null): void { if (Platform::getEnv('GITHUB_ACTIONS') && !Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING')) { $message = $this->escapeData($message); @@ -55,7 +55,7 @@ public function emit($message, $file = null, $line = null): void * @param string $data * @return string */ - private function escapeData($data): string + private function escapeData(string $data): string { // see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L80-L85 $data = str_replace("%", '%25', $data); @@ -69,7 +69,7 @@ private function escapeData($data): string * @param string $property * @return string */ - private function escapeProperty($property): string + private function escapeProperty(string $property): string { // see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L87-L94 $property = str_replace("%", '%25', $property); diff --git a/src/Composer/DependencyResolver/Decisions.php b/src/Composer/DependencyResolver/Decisions.php index 8740cf7bf773..f9e3490244c3 100644 --- a/src/Composer/DependencyResolver/Decisions.php +++ b/src/Composer/DependencyResolver/Decisions.php @@ -43,7 +43,7 @@ public function __construct(Pool $pool) * @param int $level * @return void */ - public function decide($literal, $level, Rule $why): void + public function decide(int $literal, int $level, Rule $why): void { $this->addDecision($literal, $level); $this->decisionQueue[] = array( @@ -56,7 +56,7 @@ public function decide($literal, $level, Rule $why): void * @param int $literal * @return bool */ - public function satisfy($literal): bool + public function satisfy(int $literal): bool { $packageId = abs($literal); @@ -70,7 +70,7 @@ public function satisfy($literal): bool * @param int $literal * @return bool */ - public function conflict($literal): bool + public function conflict(int $literal): bool { $packageId = abs($literal); @@ -84,7 +84,7 @@ public function conflict($literal): bool * @param int $literalOrPackageId * @return bool */ - public function decided($literalOrPackageId): bool + public function decided(int $literalOrPackageId): bool { return !empty($this->decisionMap[abs($literalOrPackageId)]); } @@ -93,7 +93,7 @@ public function decided($literalOrPackageId): bool * @param int $literalOrPackageId * @return bool */ - public function undecided($literalOrPackageId): bool + public function undecided(int $literalOrPackageId): bool { return empty($this->decisionMap[abs($literalOrPackageId)]); } @@ -102,7 +102,7 @@ public function undecided($literalOrPackageId): bool * @param int $literalOrPackageId * @return bool */ - public function decidedInstall($literalOrPackageId): bool + public function decidedInstall(int $literalOrPackageId): bool { $packageId = abs($literalOrPackageId); @@ -113,7 +113,7 @@ public function decidedInstall($literalOrPackageId): bool * @param int $literalOrPackageId * @return int */ - public function decisionLevel($literalOrPackageId): int + public function decisionLevel(int $literalOrPackageId): int { $packageId = abs($literalOrPackageId); if (isset($this->decisionMap[$packageId])) { @@ -127,7 +127,7 @@ public function decisionLevel($literalOrPackageId): int * @param int $literalOrPackageId * @return Rule|null */ - public function decisionRule($literalOrPackageId): ?Rule + public function decisionRule(int $literalOrPackageId): ?Rule { $packageId = abs($literalOrPackageId); @@ -144,7 +144,7 @@ public function decisionRule($literalOrPackageId): ?Rule * @param int $queueOffset * @return array{0: int, 1: Rule} a literal and decision reason */ - public function atOffset($queueOffset): array + public function atOffset(int $queueOffset): array { return $this->decisionQueue[$queueOffset]; } @@ -153,7 +153,7 @@ public function atOffset($queueOffset): array * @param int $queueOffset * @return bool */ - public function validOffset($queueOffset): bool + public function validOffset(int $queueOffset): bool { return $queueOffset >= 0 && $queueOffset < \count($this->decisionQueue); } @@ -188,7 +188,7 @@ public function reset(): void * @param int $offset * @return void */ - public function resetToOffset($offset): void + public function resetToOffset(int $offset): void { while (\count($this->decisionQueue) > $offset + 1) { $decision = array_pop($this->decisionQueue); @@ -252,7 +252,7 @@ public function isEmpty(): bool * @param int $level * @return void */ - protected function addDecision($literal, $level): void + protected function addDecision(int $literal, int $level): void { $packageId = abs($literal); @@ -288,7 +288,7 @@ public function toString(Pool $pool = null): string return $str; } - public function __toString() + public function __toString(): string { return $this->toString(); } diff --git a/src/Composer/DependencyResolver/DefaultPolicy.php b/src/Composer/DependencyResolver/DefaultPolicy.php index e9add445ffbd..e7610eb228c0 100644 --- a/src/Composer/DependencyResolver/DefaultPolicy.php +++ b/src/Composer/DependencyResolver/DefaultPolicy.php @@ -32,7 +32,7 @@ class DefaultPolicy implements PolicyInterface * @param bool $preferStable * @param bool $preferLowest */ - public function __construct($preferStable = false, $preferLowest = false) + public function __construct(bool $preferStable = false, bool $preferLowest = false) { $this->preferStable = $preferStable; $this->preferLowest = $preferLowest; @@ -44,7 +44,7 @@ public function __construct($preferStable = false, $preferLowest = false) * * @phpstan-param Constraint::STR_OP_* $operator */ - public function versionCompare(PackageInterface $a, PackageInterface $b, $operator): bool + public function versionCompare(PackageInterface $a, PackageInterface $b, string $operator): bool { if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) { return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB]; @@ -61,7 +61,7 @@ public function versionCompare(PackageInterface $a, PackageInterface $b, $operat * @param string $requiredPackage * @return int[] */ - public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null): array + public function selectPreferredPackages(Pool $pool, array $literals, string $requiredPackage = null): array { $packages = $this->groupLiteralsByName($pool, $literals); @@ -90,7 +90,7 @@ public function selectPreferredPackages(Pool $pool, array $literals, $requiredPa * @param int[] $literals * @return array */ - protected function groupLiteralsByName(Pool $pool, $literals): array + protected function groupLiteralsByName(Pool $pool, array $literals): array { $packages = array(); foreach ($literals as $literal) { @@ -107,11 +107,11 @@ protected function groupLiteralsByName(Pool $pool, $literals): array /** * @protected - * @param ?string $requiredPackage + * @param null|string $requiredPackage * @param bool $ignoreReplace * @return int */ - public function compareByPriority(Pool $pool, BasePackage $a, BasePackage $b, $requiredPackage = null, $ignoreReplace = false): int + public function compareByPriority(Pool $pool, BasePackage $a, BasePackage $b, ?string $requiredPackage = null, bool $ignoreReplace = false): int { // prefer aliases to the original package if ($a->getName() === $b->getName()) { @@ -182,7 +182,7 @@ protected function replaces(BasePackage $source, BasePackage $target): bool * @param int[] $literals * @return int[] */ - protected function pruneToBestVersion(Pool $pool, $literals): array + protected function pruneToBestVersion(Pool $pool, array $literals): array { $operator = $this->preferLowest ? '<' : '>'; $bestLiterals = array($literals[0]); diff --git a/src/Composer/DependencyResolver/GenericRule.php b/src/Composer/DependencyResolver/GenericRule.php index c86aa19cb5dd..ab010db0ed0b 100644 --- a/src/Composer/DependencyResolver/GenericRule.php +++ b/src/Composer/DependencyResolver/GenericRule.php @@ -77,7 +77,7 @@ public function isAssertion(): bool * * @return string */ - public function __toString() + public function __toString(): string { $result = $this->isDisabled() ? 'disabled(' : '('; diff --git a/src/Composer/DependencyResolver/LockTransaction.php b/src/Composer/DependencyResolver/LockTransaction.php index 4d04a5cd680c..3b3da5df29a5 100644 --- a/src/Composer/DependencyResolver/LockTransaction.php +++ b/src/Composer/DependencyResolver/LockTransaction.php @@ -106,7 +106,7 @@ public function setNonDevPackages(LockTransaction $extractionResult): void * @param bool $updateMirrors * @return BasePackage[] */ - public function getNewLockPackages($devMode, $updateMirrors = false): array + public function getNewLockPackages(bool $devMode, bool $updateMirrors = false): array { $packages = array(); foreach ($this->resultPackages[$devMode ? 'dev' : 'non-dev'] as $package) { @@ -119,7 +119,7 @@ public function getNewLockPackages($devMode, $updateMirrors = false): array if ($presentPackage->getSourceReference() && $presentPackage->getSourceType() === $package->getSourceType()) { $package->setSourceDistReferences($presentPackage->getSourceReference()); } - if ($presentPackage->getReleaseDate() && $package instanceof Package) { + if ($presentPackage->getReleaseDate() !== null && $package instanceof Package) { $package->setReleaseDate($presentPackage->getReleaseDate()); } } @@ -137,7 +137,7 @@ public function getNewLockPackages($devMode, $updateMirrors = false): array * @param array $aliases * @return array */ - public function getAliases($aliases): array + public function getAliases(array $aliases): array { $usedAliases = array(); diff --git a/src/Composer/DependencyResolver/MultiConflictRule.php b/src/Composer/DependencyResolver/MultiConflictRule.php index a7fcb0036b98..104d578a821f 100644 --- a/src/Composer/DependencyResolver/MultiConflictRule.php +++ b/src/Composer/DependencyResolver/MultiConflictRule.php @@ -96,7 +96,7 @@ public function disable(): void * * @return string */ - public function __toString() + public function __toString(): string { // TODO multi conflict? $result = $this->isDisabled() ? 'disabled(multi(' : '(multi('; diff --git a/src/Composer/DependencyResolver/Operation/InstallOperation.php b/src/Composer/DependencyResolver/Operation/InstallOperation.php index 1fe8c0d36504..7f66d17e9c4b 100644 --- a/src/Composer/DependencyResolver/Operation/InstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/InstallOperation.php @@ -38,7 +38,7 @@ public function __construct(PackageInterface $package) * * @return PackageInterface */ - public function getPackage() + public function getPackage(): PackageInterface { return $this->package; } @@ -46,7 +46,7 @@ public function getPackage() /** * @inheritDoc */ - public function show($lock) + public function show($lock): string { return self::format($this->package, $lock); } @@ -55,7 +55,7 @@ public function show($lock) * @param bool $lock * @return string */ - public static function format(PackageInterface $package, $lock = false) + public static function format(PackageInterface $package, bool $lock = false): string { return ($lock ? 'Locking ' : 'Installing ').''.$package->getPrettyName().' ('.$package->getFullPrettyVersion().')'; } diff --git a/src/Composer/DependencyResolver/Operation/OperationInterface.php b/src/Composer/DependencyResolver/Operation/OperationInterface.php index b0cc29b6d67d..4cc70987d195 100644 --- a/src/Composer/DependencyResolver/Operation/OperationInterface.php +++ b/src/Composer/DependencyResolver/Operation/OperationInterface.php @@ -32,7 +32,7 @@ public function getOperationType(); * @param bool $lock Whether this is an operation on the lock file * @return string */ - public function show($lock); + public function show(bool $lock); /** * Serializes the operation in a human readable format diff --git a/src/Composer/DependencyResolver/Operation/SolverOperation.php b/src/Composer/DependencyResolver/Operation/SolverOperation.php index ad8855d2c4f3..5aa0957a75d0 100644 --- a/src/Composer/DependencyResolver/Operation/SolverOperation.php +++ b/src/Composer/DependencyResolver/Operation/SolverOperation.php @@ -26,7 +26,7 @@ abstract class SolverOperation implements OperationInterface * * @return string */ - public function getOperationType() + public function getOperationType(): string { return static::TYPE; } diff --git a/src/Composer/DependencyResolver/Operation/UninstallOperation.php b/src/Composer/DependencyResolver/Operation/UninstallOperation.php index 35e7ed753e25..7b4ff8ddb3f0 100644 --- a/src/Composer/DependencyResolver/Operation/UninstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/UninstallOperation.php @@ -55,7 +55,7 @@ public function show($lock): string * @param bool $lock * @return string */ - public static function format(PackageInterface $package, $lock = false): string + public static function format(PackageInterface $package, bool $lock = false): string { return 'Removing '.$package->getPrettyName().' ('.$package->getFullPrettyVersion().')'; } diff --git a/src/Composer/DependencyResolver/Operation/UpdateOperation.php b/src/Composer/DependencyResolver/Operation/UpdateOperation.php index dbfb3d310b0b..e674376f5fc3 100644 --- a/src/Composer/DependencyResolver/Operation/UpdateOperation.php +++ b/src/Composer/DependencyResolver/Operation/UpdateOperation.php @@ -76,7 +76,7 @@ public function show($lock): string * @param bool $lock * @return string */ - public static function format(PackageInterface $initialPackage, PackageInterface $targetPackage, $lock = false): string + public static function format(PackageInterface $initialPackage, PackageInterface $targetPackage, bool $lock = false): string { $fromVersion = $initialPackage->getFullPrettyVersion(); $toVersion = $targetPackage->getFullPrettyVersion(); diff --git a/src/Composer/DependencyResolver/PolicyInterface.php b/src/Composer/DependencyResolver/PolicyInterface.php index 4651ceb4d705..714041dc0a7d 100644 --- a/src/Composer/DependencyResolver/PolicyInterface.php +++ b/src/Composer/DependencyResolver/PolicyInterface.php @@ -26,12 +26,12 @@ interface PolicyInterface * * @phpstan-param Constraint::STR_OP_* $operator */ - public function versionCompare(PackageInterface $a, PackageInterface $b, $operator): bool; + public function versionCompare(PackageInterface $a, PackageInterface $b, string $operator): bool; /** * @param int[] $literals - * @param ?string $requiredPackage + * @param null|string $requiredPackage * @return int[] */ - public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null): array; + public function selectPreferredPackages(Pool $pool, array $literals, ?string $requiredPackage = null): array; } diff --git a/src/Composer/DependencyResolver/Pool.php b/src/Composer/DependencyResolver/Pool.php index 9a1a73b3c953..1abbc6382b89 100644 --- a/src/Composer/DependencyResolver/Pool.php +++ b/src/Composer/DependencyResolver/Pool.php @@ -60,7 +60,7 @@ public function __construct(array $packages = array(), array $unacceptableFixedO * @param string $name * @return array */ - public function getRemovedVersions($name, ConstraintInterface $constraint): array + public function getRemovedVersions(string $name, ConstraintInterface $constraint): array { if (!isset($this->removedVersions[$name])) { return array(); @@ -80,7 +80,7 @@ public function getRemovedVersions($name, ConstraintInterface $constraint): arra * @param string $objectHash * @return array */ - public function getRemovedVersionsByPackage($objectHash): array + public function getRemovedVersionsByPackage(string $objectHash): array { if (!isset($this->removedVersionsByPackage[$objectHash])) { return array(); @@ -122,7 +122,7 @@ public function getPackages(): array * @param int $id * @return BasePackage */ - public function packageById($id): BasePackage + public function packageById(int $id): BasePackage { return $this->packages[$id - 1]; } @@ -143,7 +143,7 @@ public function count(): int * packages must match or null to return all * @return BasePackage[] A set of packages */ - public function whatProvides($name, ConstraintInterface $constraint = null): array + public function whatProvides(string $name, ConstraintInterface $constraint = null): array { $key = (string) $constraint; if (isset($this->providerCache[$name][$key])) { @@ -159,7 +159,7 @@ public function whatProvides($name, ConstraintInterface $constraint = null): arr * packages must match or null to return all * @return BasePackage[] */ - private function computeWhatProvides($name, ConstraintInterface $constraint = null): array + private function computeWhatProvides(string $name, ConstraintInterface $constraint = null): array { if (!isset($this->packageByName[$name])) { return array(); @@ -180,7 +180,7 @@ private function computeWhatProvides($name, ConstraintInterface $constraint = nu * @param int $literal * @return BasePackage */ - public function literalToPackage($literal): BasePackage + public function literalToPackage(int $literal): BasePackage { $packageId = abs($literal); @@ -192,7 +192,7 @@ public function literalToPackage($literal): BasePackage * @param array $installedMap * @return string */ - public function literalToPrettyString($literal, $installedMap): string + public function literalToPrettyString(int $literal, array $installedMap): string { $package = $this->literalToPackage($literal); @@ -212,7 +212,7 @@ public function literalToPrettyString($literal, $installedMap): string * @param string $name Name of the package to be matched * @return bool */ - public function match(BasePackage $candidate, $name, ConstraintInterface $constraint = null): bool + public function match(BasePackage $candidate, string $name, ConstraintInterface $constraint = null): bool { $candidateName = $candidate->getName(); $candidateVersion = $candidate->getVersion(); @@ -268,7 +268,7 @@ public function getUnacceptableFixedOrLockedPackages(): array return $this->unacceptableFixedOrLockedPackages; } - public function __toString() + public function __toString(): string { $str = "Pool:\n"; diff --git a/src/Composer/DependencyResolver/PoolBuilder.php b/src/Composer/DependencyResolver/PoolBuilder.php index 9766557e6c35..52c831dc569f 100644 --- a/src/Composer/DependencyResolver/PoolBuilder.php +++ b/src/Composer/DependencyResolver/PoolBuilder.php @@ -300,7 +300,7 @@ public function buildPool(array $repositories, Request $request): Pool * @param string $name * @return void */ - private function markPackageNameForLoading(Request $request, $name, ConstraintInterface $constraint): void + private function markPackageNameForLoading(Request $request, string $name, ConstraintInterface $constraint): void { // Skip platform requires at this stage if (PlatformRepository::isPlatformPackage($name)) { @@ -396,7 +396,7 @@ private function loadPackagesMarkedForLoading(Request $request, array $repositor * @param RepositoryInterface[] $repositories * @return void */ - private function loadPackage(Request $request, array $repositories, BasePackage $package, $propagateUpdate): void + private function loadPackage(Request $request, array $repositories, BasePackage $package, bool $propagateUpdate): void { $index = $this->indexCounter++; $this->packages[$index] = $package; @@ -501,7 +501,7 @@ private function loadPackage(Request $request, array $repositories, BasePackage * @param string $name packageName * @return bool */ - private function isRootRequire(Request $request, $name): bool + private function isRootRequire(Request $request, string $name): bool { $rootRequires = $request->getRequires(); @@ -512,7 +512,7 @@ private function isRootRequire(Request $request, $name): bool * @param string $name * @return string[] */ - private function getSkippedRootRequires(Request $request, $name): array + private function getSkippedRootRequires(Request $request, string $name): array { if (!isset($this->skippedLoad[$name])) { return array(); @@ -602,7 +602,7 @@ private function warnAboutNonMatchingUpdateAllowList(Request $request): void * @param string $name * @return void */ - private function unlockPackage(Request $request, array $repositories, $name): void + private function unlockPackage(Request $request, array $repositories, string $name): void { foreach ($this->skippedLoad[$name] as $packageOrReplacer) { // if we unfixed a replaced package name, we also need to unfix the replacer itself @@ -668,7 +668,7 @@ private function unlockPackage(Request $request, array $repositories, $name): vo * @param int $index * @return void */ - private function removeLoadedPackage(Request $request, array $repositories, BasePackage $package, $index): void + private function removeLoadedPackage(Request $request, array $repositories, BasePackage $package, int $index): void { $repoIndex = array_search($package->getRepository(), $repositories, true); diff --git a/src/Composer/DependencyResolver/PoolOptimizer.php b/src/Composer/DependencyResolver/PoolOptimizer.php index 5c77eda79f66..6d9b1dd12452 100644 --- a/src/Composer/DependencyResolver/PoolOptimizer.php +++ b/src/Composer/DependencyResolver/PoolOptimizer.php @@ -322,7 +322,7 @@ private function calculateDependencyHash(BasePackage $package): string * @param int $id * @return void */ - private function markPackageForRemoval($id): void + private function markPackageForRemoval(int $id): void { // We are not allowed to remove packages if they have been marked as irremovable if (isset($this->irremovablePackages[$id])) { @@ -337,7 +337,7 @@ private function markPackageForRemoval($id): void * @param array> $packageIdenticalDefinitionLookup * @return void */ - private function keepPackage(BasePackage $package, $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup): void + private function keepPackage(BasePackage $package, array $identicalDefinitionsPerPackage, array $packageIdenticalDefinitionLookup): void { unset($this->packagesToRemove[$package->id]); diff --git a/src/Composer/DependencyResolver/Problem.php b/src/Composer/DependencyResolver/Problem.php index 77e2975c87f0..44ad896a9dba 100644 --- a/src/Composer/DependencyResolver/Problem.php +++ b/src/Composer/DependencyResolver/Problem.php @@ -77,7 +77,7 @@ public function getReasons(): array * @param array $learnedPool * @return string */ - public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string + public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = array(), array $learnedPool = array()): string { // TODO doesn't this entirely defeat the purpose of the problem sections? what's the point of sections? $reasons = call_user_func_array('array_merge', array_reverse($this->reasons)); @@ -117,7 +117,7 @@ public function getPrettyString(RepositorySet $repositorySet, Request $request, * @return string * @internal */ - public static function formatDeduplicatedRules($rules, $indent, RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string + public static function formatDeduplicatedRules(array $rules, string $indent, RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = array(), array $learnedPool = array()): string { $messages = array(); $templates = array(); @@ -185,7 +185,7 @@ public function isCausedByLock(RepositorySet $repositorySet, Request $request, P * @param Rule $reason The reason descriptor * @return void */ - protected function addReason($id, Rule $reason): void + protected function addReason(string $id, Rule $reason): void { // TODO: if a rule is part of a problem description in two sections, isn't this going to remove a message // that is important to understand the issue? @@ -210,7 +210,7 @@ public function nextSection(): void * @param string $packageName * @return array{0: string, 1: string} */ - public static function getMissingPackageReason(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $packageName, ConstraintInterface $constraint = null): array + public static function getMissingPackageReason(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, string $packageName, ConstraintInterface $constraint = null): array { if (PlatformRepository::isPlatformPackage($packageName)) { // handle php/php-*/hhvm @@ -382,7 +382,7 @@ public static function getMissingPackageReason(RepositorySet $repositorySet, Req * @param bool $useRemovedVersionGroup * @return string */ - public static function getPackageList(array $packages, $isVerbose, Pool $pool = null, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false): string + public static function getPackageList(array $packages, bool $isVerbose, Pool $pool = null, ConstraintInterface $constraint = null, bool $useRemovedVersionGroup = false): string { $prepared = array(); $hasDefaultBranch = array(); @@ -427,7 +427,7 @@ public static function getPackageList(array $packages, $isVerbose, Pool $pool = * @param string $version the effective runtime version of the platform package * @return ?string a version string or null if it appears the package was artificially disabled */ - private static function getPlatformPackageVersion(Pool $pool, $packageName, $version): ?string + private static function getPlatformPackageVersion(Pool $pool, string $packageName, string $version): ?string { $available = $pool->whatProvides($packageName); @@ -471,7 +471,7 @@ private static function getPlatformPackageVersion(Pool $pool, $packageName, $ver * @param int $maxDev * @return list a list of pretty versions and '...' where versions were removed */ - private static function condenseVersionList(array $versions, $max, $maxDev = 16): array + private static function condenseVersionList(array $versions, int $max, int $maxDev = 16): array { if (count($versions) <= $max) { return $versions; @@ -527,7 +527,7 @@ private static function hasMultipleNames(array $packages): bool * @param string $reason * @return array{0: string, 1: string} */ - private static function computeCheckForLowerPrioRepo(Pool $pool, $isVerbose, $packageName, array $higherRepoPackages, array $allReposPackages, $reason, ConstraintInterface $constraint = null): array + private static function computeCheckForLowerPrioRepo(Pool $pool, bool $isVerbose, string $packageName, array $higherRepoPackages, array $allReposPackages, string $reason, ConstraintInterface $constraint = null): array { $nextRepoPackages = array(); $nextRepo = null; diff --git a/src/Composer/DependencyResolver/Request.php b/src/Composer/DependencyResolver/Request.php index 508a8f0b2d94..dde4972f5b85 100644 --- a/src/Composer/DependencyResolver/Request.php +++ b/src/Composer/DependencyResolver/Request.php @@ -64,7 +64,7 @@ public function __construct(LockArrayRepository $lockedRepository = null) * @param string $packageName * @return void */ - public function requireName($packageName, ConstraintInterface $constraint = null): void + public function requireName(string $packageName, ConstraintInterface $constraint = null): void { $packageName = strtolower($packageName); @@ -135,7 +135,7 @@ public function unlockPackage(BasePackage $package): void * @param false|self::UPDATE_* $updateAllowTransitiveDependencies * @return void */ - public function setUpdateAllowList($updateAllowList, $updateAllowTransitiveDependencies): void + public function setUpdateAllowList(array $updateAllowList, $updateAllowTransitiveDependencies): void { $this->updateAllowList = $updateAllowList; $this->updateAllowTransitiveDependencies = $updateAllowTransitiveDependencies; @@ -222,7 +222,7 @@ public function getFixedOrLockedPackages(): array * Some locked packages may not be in the pool, * so they have a package->id of -1 */ - public function getPresentMap($packageIds = false): array + public function getPresentMap(bool $packageIds = false): array { $presentMap = array(); diff --git a/src/Composer/DependencyResolver/Rule.php b/src/Composer/DependencyResolver/Rule.php index 1e2d08daa949..bcf32fb03fd0 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -78,7 +78,7 @@ abstract public function getLiterals(): array; */ abstract public function getHash(); - abstract public function __toString(); + abstract public function __toString(): string; /** * @param Rule $rule @@ -267,7 +267,7 @@ public function getSourcePackage(Pool $pool): BasePackage * @param array $learnedPool * @return string */ - public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string + public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, array $installedMap = array(), array $learnedPool = array()): string { $literals = $this->getLiterals(); @@ -484,7 +484,7 @@ public function getPrettyString(RepositorySet $repositorySet, Request $request, * @param bool $useRemovedVersionGroup * @return string */ - protected function formatPackagesUnique(Pool $pool, array $packages, $isVerbose, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false): string + protected function formatPackagesUnique(Pool $pool, array $packages, bool $isVerbose, ConstraintInterface $constraint = null, bool $useRemovedVersionGroup = false): string { foreach ($packages as $index => $package) { if (!\is_object($package)) { diff --git a/src/Composer/DependencyResolver/Rule2Literals.php b/src/Composer/DependencyResolver/Rule2Literals.php index f07d011fc88a..9545686c8687 100644 --- a/src/Composer/DependencyResolver/Rule2Literals.php +++ b/src/Composer/DependencyResolver/Rule2Literals.php @@ -31,7 +31,7 @@ class Rule2Literals extends Rule * * @phpstan-param ReasonData $reasonData */ - public function __construct($literal1, $literal2, $reason, $reasonData) + public function __construct(int $literal1, int $literal2, $reason, $reasonData) { parent::__construct($reason, $reasonData); @@ -108,7 +108,7 @@ public function isAssertion(): bool * * @return string */ - public function __toString() + public function __toString(): string { $result = $this->isDisabled() ? 'disabled(' : '('; diff --git a/src/Composer/DependencyResolver/RuleSet.php b/src/Composer/DependencyResolver/RuleSet.php index 68c2b7905d34..d430b46a9339 100644 --- a/src/Composer/DependencyResolver/RuleSet.php +++ b/src/Composer/DependencyResolver/RuleSet.php @@ -112,7 +112,7 @@ public function count(): int * @param int $id * @return Rule */ - public function ruleById($id): Rule + public function ruleById(int $id): Rule { return $this->ruleById[$id]; } @@ -181,7 +181,7 @@ public function getTypes(): array * @param bool $isVerbose * @return string */ - public function getPrettyString(RepositorySet $repositorySet = null, Request $request = null, Pool $pool = null, $isVerbose = false): string + public function getPrettyString(RepositorySet $repositorySet = null, Request $request = null, Pool $pool = null, bool $isVerbose = false): string { $string = "\n"; foreach ($this->rules as $type => $rules) { @@ -195,7 +195,7 @@ public function getPrettyString(RepositorySet $repositorySet = null, Request $re return $string; } - public function __toString() + public function __toString(): string { return $this->getPrettyString(); } diff --git a/src/Composer/DependencyResolver/RuleSetGenerator.php b/src/Composer/DependencyResolver/RuleSetGenerator.php index 71f86864b53f..d170db1e3b48 100644 --- a/src/Composer/DependencyResolver/RuleSetGenerator.php +++ b/src/Composer/DependencyResolver/RuleSetGenerator.php @@ -80,7 +80,7 @@ protected function createRequireRule(BasePackage $package, array $providers, $re * @param BasePackage[] $packages The set of packages to choose from * @param Rule::RULE_* $reason A RULE_* constant describing the reason for * generating this rule - * @param array $reasonData Additional data like the root require or fix request info + * @param mixed $reasonData Additional data like the root require or fix request info * @return Rule The generated rule * * @phpstan-param ReasonData $reasonData diff --git a/src/Composer/DependencyResolver/RuleWatchChain.php b/src/Composer/DependencyResolver/RuleWatchChain.php index a540326863bc..f6bab35473b2 100644 --- a/src/Composer/DependencyResolver/RuleWatchChain.php +++ b/src/Composer/DependencyResolver/RuleWatchChain.php @@ -29,7 +29,7 @@ class RuleWatchChain extends \SplDoublyLinkedList * @param int $offset The offset to seek to. * @return void */ - public function seek($offset): void + public function seek(int $offset): void { $this->rewind(); for ($i = 0; $i < $offset; $i++, $this->next()); diff --git a/src/Composer/DependencyResolver/RuleWatchGraph.php b/src/Composer/DependencyResolver/RuleWatchGraph.php index 03da05ce256e..0b74a9888439 100644 --- a/src/Composer/DependencyResolver/RuleWatchGraph.php +++ b/src/Composer/DependencyResolver/RuleWatchGraph.php @@ -88,7 +88,7 @@ public function insert(RuleWatchNode $node): void * register decisions resulting from propagation * @return Rule|null If a conflict is found the conflicting rule is returned */ - public function propagateLiteral($decidedLiteral, $level, Decisions $decisions): ?Rule + public function propagateLiteral(int $decidedLiteral, int $level, Decisions $decisions): ?Rule { // we invert the decided literal here, example: // A was decided => (-A|B) now requires B to be true, so we look for @@ -156,7 +156,7 @@ public function propagateLiteral($decidedLiteral, $level, Decisions $decisions): * @param RuleWatchNode $node The rule node to be moved * @return void */ - protected function moveWatch($fromLiteral, $toLiteral, RuleWatchNode $node): void + protected function moveWatch(int $fromLiteral, int $toLiteral, RuleWatchNode $node): void { if (!isset($this->watchChains[$toLiteral])) { $this->watchChains[$toLiteral] = new RuleWatchChain; diff --git a/src/Composer/DependencyResolver/RuleWatchNode.php b/src/Composer/DependencyResolver/RuleWatchNode.php index 136ac4a86f61..d1e027cd2b2d 100644 --- a/src/Composer/DependencyResolver/RuleWatchNode.php +++ b/src/Composer/DependencyResolver/RuleWatchNode.php @@ -91,7 +91,7 @@ public function getRule(): Rule * @param int $literal The watched literal that should not be returned * @return int A literal */ - public function getOtherWatch($literal): int + public function getOtherWatch(int $literal): int { if ($this->watch1 == $literal) { return $this->watch2; @@ -107,7 +107,7 @@ public function getOtherWatch($literal): int * @param int $to The literal to be watched now * @return void */ - public function moveWatch($from, $to): void + public function moveWatch(int $from, int $to): void { if ($this->watch1 == $from) { $this->watch1 = $to; diff --git a/src/Composer/DependencyResolver/Solver.php b/src/Composer/DependencyResolver/Solver.php index 43f253969fff..e90c3b67e731 100644 --- a/src/Composer/DependencyResolver/Solver.php +++ b/src/Composer/DependencyResolver/Solver.php @@ -233,7 +233,7 @@ public function solve(Request $request, PlatformRequirementFilterInterface $plat * @param int $level * @return Rule|null A rule on conflict, otherwise null. */ - protected function propagate($level): ?Rule + protected function propagate(int $level): ?Rule { while ($this->decisions->validOffset($this->propagateIndex)) { $decision = $this->decisions->atOffset($this->propagateIndex); @@ -261,7 +261,7 @@ protected function propagate($level): ?Rule * * @return void */ - private function revert($level): void + private function revert(int $level): void { while (!$this->decisions->isEmpty()) { $literal = $this->decisions->lastLiteral(); @@ -302,7 +302,7 @@ private function revert($level): void * @param string|int $literal * @return int */ - private function setPropagateLearn($level, $literal, Rule $rule): int + private function setPropagateLearn(int $level, $literal, Rule $rule): int { $level++; @@ -351,7 +351,7 @@ private function setPropagateLearn($level, $literal, Rule $rule): int * @param int[] $decisionQueue * @return int */ - private function selectAndInstall($level, array $decisionQueue, Rule $rule): int + private function selectAndInstall(int $level, array $decisionQueue, Rule $rule): int { // choose best package to install from decisionQueue $literals = $this->policy->selectPreferredPackages($this->pool, $decisionQueue, $rule->getRequiredPackage()); @@ -370,7 +370,7 @@ private function selectAndInstall($level, array $decisionQueue, Rule $rule): int * @param int $level * @return array{int, int, GenericRule, int} */ - protected function analyze($level, Rule $rule): array + protected function analyze(int $level, Rule $rule): array { $analyzedRule = $rule; $ruleLevel = 1; diff --git a/src/Composer/DependencyResolver/SolverBugException.php b/src/Composer/DependencyResolver/SolverBugException.php index 31932a2658d4..0a8d453ee818 100644 --- a/src/Composer/DependencyResolver/SolverBugException.php +++ b/src/Composer/DependencyResolver/SolverBugException.php @@ -20,7 +20,7 @@ class SolverBugException extends \RuntimeException /** * @param string $message */ - public function __construct($message) + public function __construct(string $message) { parent::__construct( $message."\nThis exception was most likely caused by a bug in Composer.\n". diff --git a/src/Composer/DependencyResolver/SolverProblemsException.php b/src/Composer/DependencyResolver/SolverProblemsException.php index fb5dfdde8e73..9e4896e07daf 100644 --- a/src/Composer/DependencyResolver/SolverProblemsException.php +++ b/src/Composer/DependencyResolver/SolverProblemsException.php @@ -46,7 +46,7 @@ public function __construct(array $problems, array $learnedPool) * @param bool $isDevExtraction * @return string */ - public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $isDevExtraction = false): string + public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, bool $isVerbose, bool $isDevExtraction = false): string { $installedMap = $request->getPresentMap(true); $missingExtensions = array(); diff --git a/src/Composer/DependencyResolver/Transaction.php b/src/Composer/DependencyResolver/Transaction.php index 2d3272c51a59..184855e7389f 100644 --- a/src/Composer/DependencyResolver/Transaction.php +++ b/src/Composer/DependencyResolver/Transaction.php @@ -50,7 +50,7 @@ class Transaction * @param PackageInterface[] $presentPackages * @param PackageInterface[] $resultPackages */ - public function __construct($presentPackages, $resultPackages) + public function __construct(array $presentPackages, array $resultPackages) { $this->presentPackages = $presentPackages; $this->setResultPackageMaps($resultPackages); @@ -69,7 +69,7 @@ public function getOperations(): array * @param PackageInterface[] $resultPackages * @return void */ - private function setResultPackageMaps($resultPackages): void + private function setResultPackageMaps(array $resultPackages): void { $packageSort = function (PackageInterface $a, PackageInterface $b): int { // sort alias packages by the same name behind their non alias version diff --git a/src/Composer/Downloader/ArchiveDownloader.php b/src/Composer/Downloader/ArchiveDownloader.php index 152dfb9c4ff5..fc19004143bc 100644 --- a/src/Composer/Downloader/ArchiveDownloader.php +++ b/src/Composer/Downloader/ArchiveDownloader.php @@ -13,6 +13,7 @@ namespace Composer\Downloader; use Composer\Package\PackageInterface; +use Composer\Util\Platform; use Symfony\Component\Finder\Finder; use React\Promise\PromiseInterface; use Composer\DependencyResolver\Operation\InstallOperation; @@ -32,9 +33,9 @@ abstract class ArchiveDownloader extends FileDownloader protected $cleanupExecuted = array(); /** - * @return PromiseInterface|null + * @return PromiseInterface */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { unset($this->cleanupExecuted[$package->getName()]); @@ -42,9 +43,9 @@ public function prepare($type, PackageInterface $package, $path, PackageInterfac } /** - * @return PromiseInterface|null + * @return PromiseInterface */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { $this->cleanupExecuted[$package->getName()] = true; @@ -61,7 +62,7 @@ public function cleanup($type, PackageInterface $package, $path, PackageInterfac * @throws \RuntimeException * @throws \UnexpectedValueException */ - public function install(PackageInterface $package, $path, $output = true) + public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface { if ($output) { $this->io->writeError(" - " . InstallOperation::format($package) . $this->getInstallOperationAppendix($package, $path)); @@ -83,7 +84,7 @@ public function install(PackageInterface $package, $path, $output = true) $this->addCleanupPath($package, $temporaryDir); // avoid cleaning up $path if installing in "." for eg create-project as we can not // delete the directory we are currently in on windows - if (!is_dir($path) || realpath($path) !== getcwd()) { + if (!is_dir($path) || realpath($path) !== Platform::getCwd()) { $this->addCleanupPath($package, $path); } @@ -98,7 +99,7 @@ public function install(PackageInterface $package, $path, $output = true) // clean up $filesystem->removeDirectory($temporaryDir); - if (is_dir($path) && realpath($path) !== getcwd()) { + if (is_dir($path) && realpath($path) !== Platform::getCwd()) { $filesystem->removeDirectory($path); } $this->removeCleanupPath($package, $temporaryDir); @@ -112,10 +113,6 @@ public function install(PackageInterface $package, $path, $output = true) throw $e; } - if (!$promise instanceof PromiseInterface) { - $promise = \React\Promise\resolve(); - } - return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path): \React\Promise\PromiseInterface { $filesystem->unlink($fileName); @@ -214,7 +211,7 @@ public function install(PackageInterface $package, $path, $output = true) /** * @inheritDoc */ - protected function getInstallOperationAppendix(PackageInterface $package, $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { return ': Extracting archive'; } @@ -226,7 +223,6 @@ protected function getInstallOperationAppendix(PackageInterface $package, $path) * @param string $path Directory * * @throws \UnexpectedValueException If can not extract downloaded file to path - * @return PromiseInterface|null */ - abstract protected function extract(PackageInterface $package, $file, $path); + abstract protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface; } diff --git a/src/Composer/Downloader/ChangeReportInterface.php b/src/Composer/Downloader/ChangeReportInterface.php index 3fb1dc5d08a5..a41cce8939ef 100644 --- a/src/Composer/Downloader/ChangeReportInterface.php +++ b/src/Composer/Downloader/ChangeReportInterface.php @@ -28,5 +28,5 @@ interface ChangeReportInterface * @param string $path package directory * @return string|null changes or null */ - public function getLocalChanges(PackageInterface $package, $path); + public function getLocalChanges(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index 41e61e0ad218..f34a73d379cf 100644 --- a/src/Composer/Downloader/DownloadManager.php +++ b/src/Composer/Downloader/DownloadManager.php @@ -46,7 +46,7 @@ class DownloadManager * @param bool $preferSource prefer downloading from source * @param Filesystem|null $filesystem custom Filesystem object */ - public function __construct(IOInterface $io, $preferSource = false, Filesystem $filesystem = null) + public function __construct(IOInterface $io, bool $preferSource = false, Filesystem $filesystem = null) { $this->io = $io; $this->preferSource = $preferSource; @@ -59,7 +59,7 @@ public function __construct(IOInterface $io, $preferSource = false, Filesystem $ * @param bool $preferSource prefer downloading from source * @return DownloadManager */ - public function setPreferSource($preferSource): DownloadManager + public function setPreferSource(bool $preferSource): self { $this->preferSource = $preferSource; @@ -72,7 +72,7 @@ public function setPreferSource($preferSource): DownloadManager * @param bool $preferDist prefer downloading from dist * @return DownloadManager */ - public function setPreferDist($preferDist): DownloadManager + public function setPreferDist(bool $preferDist): self { $this->preferDist = $preferDist; @@ -86,7 +86,7 @@ public function setPreferDist($preferDist): DownloadManager * * @return DownloadManager */ - public function setPreferences(array $preferences): DownloadManager + public function setPreferences(array $preferences): self { $this->packagePreferences = $preferences; @@ -100,7 +100,7 @@ public function setPreferences(array $preferences): DownloadManager * @param DownloaderInterface $downloader downloader instance * @return DownloadManager */ - public function setDownloader($type, DownloaderInterface $downloader): DownloadManager + public function setDownloader(string $type, DownloaderInterface $downloader): self { $type = strtolower($type); $this->downloaders[$type] = $downloader; @@ -115,7 +115,7 @@ public function setDownloader($type, DownloaderInterface $downloader): DownloadM * @throws \InvalidArgumentException if downloader for provided type is not registered * @return DownloaderInterface */ - public function getDownloader($type): DownloaderInterface + public function getDownloader(string $type): DownloaderInterface { $type = strtolower($type); if (!isset($this->downloaders[$type])) { @@ -184,7 +184,7 @@ public function getDownloaderType(DownloaderInterface $downloader): string * @throws \RuntimeException * @return PromiseInterface */ - public function download(PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): PromiseInterface + public function download(PackageInterface $package, string $targetDir, PackageInterface $prevPackage = null): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $this->filesystem->ensureDirectoryExists(dirname($targetDir)); @@ -229,9 +229,6 @@ public function download(PackageInterface $package, $targetDir, PackageInterface } catch (\Exception $e) { return $handleError($e); } - if (!$result instanceof PromiseInterface) { - return \React\Promise\resolve($result); - } $res = $result->then(function ($res) { return $res; @@ -251,9 +248,9 @@ public function download(PackageInterface $package, $targetDir, PackageInterface * @param string $targetDir target dir * @param PackageInterface|null $prevPackage previous package instance in case of updates * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function prepare($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): ?PromiseInterface + public function prepare(string $type, PackageInterface $package, string $targetDir, PackageInterface $prevPackage = null): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -272,9 +269,9 @@ public function prepare($type, PackageInterface $package, $targetDir, PackageInt * * @throws \InvalidArgumentException if package have no urls to download from * @throws \RuntimeException - * @return PromiseInterface|null + * @return PromiseInterface */ - public function install(PackageInterface $package, $targetDir): ?PromiseInterface + public function install(PackageInterface $package, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -293,9 +290,9 @@ public function install(PackageInterface $package, $targetDir): ?PromiseInterfac * @param string $targetDir target dir * * @throws \InvalidArgumentException if initial package is not installed - * @return PromiseInterface|null + * @return PromiseInterface */ - public function update(PackageInterface $initial, PackageInterface $target, $targetDir): ?PromiseInterface + public function update(PackageInterface $initial, PackageInterface $target, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($target); @@ -330,18 +327,10 @@ public function update(PackageInterface $initial, PackageInterface $target, $tar // if downloader type changed, or update failed and user asks for reinstall, // we wipe the dir and do a new install instead of updating it $promise = $initialDownloader->remove($initial, $targetDir); - if ($promise instanceof PromiseInterface) { - return $promise->then(function ($res) use ($target, $targetDir): PromiseInterface { - $promise = $this->install($target, $targetDir); - if ($promise instanceof PromiseInterface) { - return $promise; - } - - return \React\Promise\resolve(); - }); - } - return $this->install($target, $targetDir); + return $promise->then(function ($res) use ($target, $targetDir): PromiseInterface { + return $this->install($target, $targetDir); + }); } /** @@ -350,9 +339,9 @@ public function update(PackageInterface $initial, PackageInterface $target, $tar * @param PackageInterface $package package instance * @param string $targetDir target dir * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function remove(PackageInterface $package, $targetDir): ?PromiseInterface + public function remove(PackageInterface $package, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -371,9 +360,9 @@ public function remove(PackageInterface $package, $targetDir): ?PromiseInterface * @param string $targetDir target dir * @param PackageInterface|null $prevPackage previous package instance in case of updates * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function cleanup($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): ?PromiseInterface + public function cleanup(string $type, PackageInterface $package, string $targetDir, PackageInterface $prevPackage = null): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -461,7 +450,7 @@ private function getAvailableSources(PackageInterface $package, PackageInterface * * @return string */ - private function normalizeTargetDir($dir): string + private function normalizeTargetDir(string $dir): string { if ($dir === '\\' || $dir === '/') { return $dir; diff --git a/src/Composer/Downloader/DownloaderInterface.php b/src/Composer/Downloader/DownloaderInterface.php index b19f902a8ce7..0b540d4b65b6 100644 --- a/src/Composer/Downloader/DownloaderInterface.php +++ b/src/Composer/Downloader/DownloaderInterface.php @@ -28,15 +28,15 @@ interface DownloaderInterface * * @return string "source" or "dist" */ - public function getInstallationSource(); + public function getInstallationSource(): string; /** * This should do any network-related tasks to prepare for an upcoming install/update * * @param string $path download path - * @return PromiseInterface|null + * @return PromiseInterface */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface; /** * Do anything that needs to be done between all downloads have been completed and the actual operation is executed @@ -50,18 +50,18 @@ public function download(PackageInterface $package, $path, PackageInterface $pre * @param PackageInterface $package package instance * @param string $path download path * @param PackageInterface $prevPackage previous package instance in case of an update - * @return PromiseInterface|null + * @return PromiseInterface */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface; /** * Installs specific package into specific folder. * * @param PackageInterface $package package instance * @param string $path download path - * @return PromiseInterface|null + * @return PromiseInterface */ - public function install(PackageInterface $package, $path); + public function install(PackageInterface $package, string $path): PromiseInterface; /** * Updates specific package in specific folder from initial to target version. @@ -69,18 +69,18 @@ public function install(PackageInterface $package, $path); * @param PackageInterface $initial initial package * @param PackageInterface $target updated package * @param string $path download path - * @return PromiseInterface|null + * @return PromiseInterface */ - public function update(PackageInterface $initial, PackageInterface $target, $path); + public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface; /** * Removes specific package from specific folder. * * @param PackageInterface $package package instance * @param string $path download path - * @return PromiseInterface|null + * @return PromiseInterface */ - public function remove(PackageInterface $package, $path); + public function remove(PackageInterface $package, string $path): PromiseInterface; /** * Do anything to cleanup changes applied in the prepare or install/update/uninstall steps @@ -93,7 +93,7 @@ public function remove(PackageInterface $package, $path); * @param PackageInterface $package package instance * @param string $path download path * @param PackageInterface $prevPackage previous package instance in case of an update - * @return PromiseInterface|null + * @return PromiseInterface */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface; } diff --git a/src/Composer/Downloader/DvcsDownloaderInterface.php b/src/Composer/Downloader/DvcsDownloaderInterface.php index 7fbd4ee3e653..45c9b86c5ce5 100644 --- a/src/Composer/Downloader/DvcsDownloaderInterface.php +++ b/src/Composer/Downloader/DvcsDownloaderInterface.php @@ -28,5 +28,5 @@ interface DvcsDownloaderInterface * @param string $path package directory * @return string|null changes or null */ - public function getUnpushedChanges(PackageInterface $package, $path); + public function getUnpushedChanges(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index ab347d23da37..c1858d9b8985 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -27,6 +27,7 @@ use Composer\Plugin\PreFileDownloadEvent; use Composer\EventDispatcher\EventDispatcher; use Composer\Util\Filesystem; +use Composer\Util\Platform; use Composer\Util\Silencer; use Composer\Util\HttpDownloader; use Composer\Util\Url as UrlUtil; @@ -65,11 +66,9 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface public static $downloadMetadata = array(); /** - * @private this is only public for php 5.3 support in closures - * * @var array Map of package name to cache key */ - public $lastCacheWrites = array(); + private $lastCacheWrites = array(); /** @var array Map of package name to list of paths */ private $additionalCleanupPaths = array(); @@ -102,7 +101,7 @@ public function __construct(IOInterface $io, Config $config, HttpDownloader $htt /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): string { return 'dist'; } @@ -112,7 +111,7 @@ public function getInstallationSource() * * @param bool $output */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true) + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $output = true): PromiseInterface { if (!$package->getDistUrl()) { throw new \InvalidArgumentException('The given package is missing url information'); @@ -295,7 +294,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre /** * @inheritDoc */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { return \React\Promise\resolve(); } @@ -303,7 +302,7 @@ public function prepare($type, PackageInterface $package, $path, PackageInterfac /** * @inheritDoc */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { $fileName = $this->getFileName($package, $path); if (file_exists($fileName)) { @@ -323,7 +322,7 @@ public function cleanup($type, PackageInterface $package, $path, PackageInterfac } foreach ($dirsToCleanUp as $dir) { - if (is_dir($dir) && $this->filesystem->isDirEmpty($dir) && realpath($dir) !== getcwd()) { + if (is_dir($dir) && $this->filesystem->isDirEmpty($dir) && realpath($dir) !== Platform::getCwd()) { $this->filesystem->removeDirectoryPhp($dir); } } @@ -336,7 +335,7 @@ public function cleanup($type, PackageInterface $package, $path, PackageInterfac * * @param bool $output */ - public function install(PackageInterface $package, $path, $output = true) + public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface { if ($output) { $this->io->writeError(" - " . InstallOperation::format($package)); @@ -362,7 +361,7 @@ public function install(PackageInterface $package, $path, $output = true) /** * @return void */ - protected function clearLastCacheWrite(PackageInterface $package) + protected function clearLastCacheWrite(PackageInterface $package): void { if ($this->cache && isset($this->lastCacheWrites[$package->getName()])) { $this->cache->remove($this->lastCacheWrites[$package->getName()]); @@ -375,7 +374,7 @@ protected function clearLastCacheWrite(PackageInterface $package) * * @return void */ - protected function addCleanupPath(PackageInterface $package, $path) + protected function addCleanupPath(PackageInterface $package, string $path): void { $this->additionalCleanupPaths[$package->getName()][] = $path; } @@ -385,7 +384,7 @@ protected function addCleanupPath(PackageInterface $package, $path) * * @return void */ - protected function removeCleanupPath(PackageInterface $package, $path) + protected function removeCleanupPath(PackageInterface $package, string $path): void { if (isset($this->additionalCleanupPaths[$package->getName()])) { $idx = array_search($path, $this->additionalCleanupPaths[$package->getName()]); @@ -398,22 +397,14 @@ protected function removeCleanupPath(PackageInterface $package, $path) /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, $path) + public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface { $this->io->writeError(" - " . UpdateOperation::format($initial, $target) . $this->getInstallOperationAppendix($target, $path)); $promise = $this->remove($initial, $path, false); - if (!$promise instanceof PromiseInterface) { - $promise = \React\Promise\resolve(); - } return $promise->then(function () use ($target, $path): PromiseInterface { - $promise = $this->install($target, $path, false); - if ($promise instanceof PromiseInterface) { - return $promise; - } - - return \React\Promise\resolve(); + return $this->install($target, $path, false); }); } @@ -422,7 +413,7 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat * * @param bool $output */ - public function remove(PackageInterface $package, $path, $output = true) + public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface { if ($output) { $this->io->writeError(" - " . UninstallOperation::format($package)); @@ -443,7 +434,7 @@ public function remove(PackageInterface $package, $path, $output = true) * @param string $path download path * @return string file name */ - protected function getFileName(PackageInterface $package, $path) + protected function getFileName(PackageInterface $package, string $path): string { return rtrim($this->config->get('vendor-dir').'/composer/tmp-'.md5($package.spl_object_hash($package)).'.'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_EXTENSION), '.'); } @@ -455,7 +446,7 @@ protected function getFileName(PackageInterface $package, $path) * @param string $path download path * @return string */ - protected function getInstallOperationAppendix(PackageInterface $package, $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { return ''; } @@ -468,7 +459,7 @@ protected function getInstallOperationAppendix(PackageInterface $package, $path) * @throws \RuntimeException If any problem with the url * @return string url */ - protected function processUrl(PackageInterface $package, $url) + protected function processUrl(PackageInterface $package, string $url): string { if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) { throw new \RuntimeException('You must enable the openssl extension to download files via https'); @@ -485,7 +476,7 @@ protected function processUrl(PackageInterface $package, $url) * @inheritDoc * @throws \RuntimeException */ - public function getLocalChanges(PackageInterface $package, $targetDir) + public function getLocalChanges(PackageInterface $package, string $targetDir): ?string { $prevIO = $this->io; diff --git a/src/Composer/Downloader/FilesystemException.php b/src/Composer/Downloader/FilesystemException.php index f297e4b98d27..f9d4e6fbece4 100644 --- a/src/Composer/Downloader/FilesystemException.php +++ b/src/Composer/Downloader/FilesystemException.php @@ -24,7 +24,7 @@ class FilesystemException extends \Exception * @param int $code * @param \Exception|null $previous */ - public function __construct($message = '', $code = 0, \Exception $previous = null) + public function __construct(string $message = '', int $code = 0, \Exception $previous = null) { parent::__construct("Filesystem exception: \n".$message, $code, $previous); } diff --git a/src/Composer/Downloader/FossilDownloader.php b/src/Composer/Downloader/FossilDownloader.php index 662828b84f19..13bd3d25b7c6 100644 --- a/src/Composer/Downloader/FossilDownloader.php +++ b/src/Composer/Downloader/FossilDownloader.php @@ -25,7 +25,7 @@ class FossilDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { return \React\Promise\resolve(); } @@ -33,7 +33,7 @@ protected function doDownload(PackageInterface $package, $path, $url, PackageInt /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -61,7 +61,7 @@ protected function doInstall(PackageInterface $package, $path, $url): ?PromiseIn /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -84,7 +84,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path): ?string + public function getLocalChanges(PackageInterface $package, string $path): ?string { if (!$this->hasMetadataRepository($path)) { return null; @@ -98,7 +98,7 @@ public function getLocalChanges(PackageInterface $package, $path): ?string /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path): string + protected function getCommitLogs(string $fromReference, string $toReference, string $path): string { $command = sprintf('fossil timeline -t ci -W 0 -n 0 before %s', ProcessExecutor::escape($toReference)); @@ -122,7 +122,7 @@ protected function getCommitLogs($fromReference, $toReference, $path): string /** * @inheritDoc */ - protected function hasMetadataRepository($path): bool + protected function hasMetadataRepository(string $path): bool { return is_file($path . '/.fslckout') || is_file($path . '/_FOSSIL_'); } diff --git a/src/Composer/Downloader/GitDownloader.php b/src/Composer/Downloader/GitDownloader.php index 7f7d74c9f275..a842a6ea33a2 100644 --- a/src/Composer/Downloader/GitDownloader.php +++ b/src/Composer/Downloader/GitDownloader.php @@ -58,7 +58,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null) + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { GitUtil::cleanEnv(); @@ -83,7 +83,7 @@ protected function doDownload(PackageInterface $package, $path, $url, PackageInt /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url) + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -114,7 +114,7 @@ protected function doInstall(PackageInterface $package, $path, $url) $this->io->writeError($msg); - $commandCallable = function ($url) use ($path, $command, $cachePath): string { + $commandCallable = function (string $url) use ($path, $command, $cachePath): string { return str_replace( array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'), array( @@ -148,7 +148,7 @@ protected function doInstall(PackageInterface $package, $path, $url) /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -213,7 +213,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path) + public function getLocalChanges(PackageInterface $package, string $path): ?string { GitUtil::cleanEnv(); if (!$this->hasMetadataRepository($path)) { @@ -231,7 +231,7 @@ public function getLocalChanges(PackageInterface $package, $path) /** * @return null|string */ - public function getUnpushedChanges(PackageInterface $package, $path) + public function getUnpushedChanges(PackageInterface $package, string $path): ?string { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -328,7 +328,7 @@ public function getUnpushedChanges(PackageInterface $package, $path) /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, $path, $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -415,7 +415,7 @@ protected function cleanChanges(PackageInterface $package, $path, $update) /** * @inheritDoc */ - protected function reapplyChanges($path) + protected function reapplyChanges(string $path): void { $path = $this->normalizePath($path); if (!empty($this->hasStashedChanges[$path])) { @@ -438,7 +438,7 @@ protected function reapplyChanges($path) * @throws \RuntimeException * @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found */ - protected function updateToCommit(PackageInterface $package, $path, $reference, $prettyVersion) + protected function updateToCommit(PackageInterface $package, string $path, string $reference, string $prettyVersion): ?string { $force = !empty($this->hasDiscardedChanges[$path]) || !empty($this->hasStashedChanges[$path]) ? '-f ' : ''; @@ -505,7 +505,7 @@ protected function updateToCommit(PackageInterface $package, $path, $reference, * * @return void */ - protected function updateOriginUrl($path, $url) + protected function updateOriginUrl(string $path, string $url): void { $this->process->execute(sprintf('git remote set-url origin -- %s', ProcessExecutor::escape($url)), $output, $path); $this->setPushUrl($path, $url); @@ -517,7 +517,7 @@ protected function updateOriginUrl($path, $url) * * @return void */ - protected function setPushUrl($path, $url) + protected function setPushUrl(string $path, string $url): void { // set push url for github projects if (Preg::isMatch('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) { @@ -534,7 +534,7 @@ protected function setPushUrl($path, $url) /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path) + protected function getCommitLogs(string $fromReference, string $toReference, string $path): string { $path = $this->normalizePath($path); $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"'.GitUtil::getNoShowSignatureFlag($this->process), ProcessExecutor::escape($fromReference), ProcessExecutor::escape($toReference)); @@ -553,7 +553,7 @@ protected function getCommitLogs($fromReference, $toReference, $path) * * @throws \RuntimeException */ - protected function discardChanges($path) + protected function discardChanges(string $path): PromiseInterface { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git clean -df && git reset --hard', $output, $path)) { @@ -572,7 +572,7 @@ protected function discardChanges($path) * * @throws \RuntimeException */ - protected function stashChanges($path) + protected function stashChanges(string $path): PromiseInterface { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git stash --include-untracked', $output, $path)) { @@ -591,7 +591,7 @@ protected function stashChanges($path) * * @throws \RuntimeException */ - protected function viewDiff($path) + protected function viewDiff(string $path): void { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git diff HEAD', $output, $path)) { @@ -606,7 +606,7 @@ protected function viewDiff($path) * * @return string */ - protected function normalizePath($path) + protected function normalizePath(string $path): string { if (Platform::isWindows() && strlen($path) > 0) { $basePath = $path; @@ -630,7 +630,7 @@ protected function normalizePath($path) /** * @inheritDoc */ - protected function hasMetadataRepository($path) + protected function hasMetadataRepository(string $path): bool { $path = $this->normalizePath($path); @@ -641,7 +641,7 @@ protected function hasMetadataRepository($path) * @param string $reference * @return string */ - protected function getShortHash($reference) + protected function getShortHash(string $reference): string { if (!$this->io->isVerbose() && Preg::isMatch('{^[0-9a-f]{40}$}', $reference)) { return substr($reference, 0, 10); diff --git a/src/Composer/Downloader/GzipDownloader.php b/src/Composer/Downloader/GzipDownloader.php index 5826078a026f..8949037ec7f5 100644 --- a/src/Composer/Downloader/GzipDownloader.php +++ b/src/Composer/Downloader/GzipDownloader.php @@ -24,7 +24,7 @@ */ class GzipDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { $filename = pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_FILENAME); $targetFilepath = $path . DIRECTORY_SEPARATOR . $filename; @@ -60,7 +60,7 @@ protected function extract(PackageInterface $package, $file, $path): ?PromiseInt * * @return void */ - private function extractUsingExt($file, $targetFilepath): void + private function extractUsingExt(string $file, string $targetFilepath): void { $archiveFile = gzopen($file, 'rb'); $targetFile = fopen($targetFilepath, 'wb'); diff --git a/src/Composer/Downloader/HgDownloader.php b/src/Composer/Downloader/HgDownloader.php index d7db15a230f1..0537103b1073 100644 --- a/src/Composer/Downloader/HgDownloader.php +++ b/src/Composer/Downloader/HgDownloader.php @@ -25,7 +25,7 @@ class HgDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { if (null === HgUtils::getVersion($this->process)) { throw new \RuntimeException('hg was not found in your PATH, skipping source download'); @@ -37,11 +37,11 @@ protected function doDownload(PackageInterface $package, $path, $url, PackageInt /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { $hgUtils = new HgUtils($this->io, $this->config, $this->process); - $cloneCommand = function ($url) use ($path): string { + $cloneCommand = function (string $url) use ($path): string { return sprintf('hg clone -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path)); }; @@ -59,7 +59,7 @@ protected function doInstall(PackageInterface $package, $path, $url): ?PromiseIn /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { $hgUtils = new HgUtils($this->io, $this->config, $this->process); @@ -82,7 +82,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path): ?string + public function getLocalChanges(PackageInterface $package, string $path): ?string { if (!is_dir($path.'/.hg')) { return null; @@ -96,7 +96,7 @@ public function getLocalChanges(PackageInterface $package, $path): ?string /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path): string + protected function getCommitLogs(string $fromReference, string $toReference, string $path): string { $command = sprintf('hg log -r %s:%s --style compact', ProcessExecutor::escape($fromReference), ProcessExecutor::escape($toReference)); @@ -110,7 +110,7 @@ protected function getCommitLogs($fromReference, $toReference, $path): string /** * @inheritDoc */ - protected function hasMetadataRepository($path): bool + protected function hasMetadataRepository(string $path): bool { return is_dir($path . '/.hg'); } diff --git a/src/Composer/Downloader/PathDownloader.php b/src/Composer/Downloader/PathDownloader.php index 9c24383c77f8..c85cbef0f944 100644 --- a/src/Composer/Downloader/PathDownloader.php +++ b/src/Composer/Downloader/PathDownloader.php @@ -39,7 +39,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @inheritDoc */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true): ?PromiseInterface + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $output = true): PromiseInterface { $path = Filesystem::trimTrailingSlash($path); $url = $package->getDistUrl(); @@ -75,7 +75,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre /** * @inheritDoc */ - public function install(PackageInterface $package, $path, $output = true): ?PromiseInterface + public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface { $path = Filesystem::trimTrailingSlash($path); $url = $package->getDistUrl(); @@ -113,7 +113,7 @@ public function install(PackageInterface $package, $path, $output = true): ?Prom } else { $absolutePath = $path; if (!$this->filesystem->isAbsolutePath($absolutePath)) { - $absolutePath = getcwd() . DIRECTORY_SEPARATOR . $path; + $absolutePath = Platform::getCwd() . DIRECTORY_SEPARATOR . $path; } $shortestPath = $this->filesystem->findShortestPath($absolutePath, $realUrl); $path = rtrim($path, "/"); @@ -161,7 +161,7 @@ public function install(PackageInterface $package, $path, $output = true): ?Prom /** * @inheritDoc */ - public function remove(PackageInterface $package, $path, $output = true): ?PromiseInterface + public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface { $path = Filesystem::trimTrailingSlash($path); /** @@ -190,8 +190,8 @@ public function remove(PackageInterface $package, $path, $output = true): ?Promi // not using realpath here as we do not want to resolve the symlink to the original dist url // it points to $fs = new Filesystem; - $absPath = $fs->isAbsolutePath($path) ? $path : getcwd() . '/' . $path; - $absDistUrl = $fs->isAbsolutePath($package->getDistUrl()) ? $package->getDistUrl() : getcwd() . '/' . $package->getDistUrl(); + $absPath = $fs->isAbsolutePath($path) ? $path : Platform::getCwd() . '/' . $path; + $absDistUrl = $fs->isAbsolutePath($package->getDistUrl()) ? $package->getDistUrl() : Platform::getCwd() . '/' . $package->getDistUrl(); if ($fs->normalizePath($absPath) === $fs->normalizePath($absDistUrl)) { if ($output) { $this->io->writeError(" - " . UninstallOperation::format($package).", source is still present in $path"); @@ -206,7 +206,7 @@ public function remove(PackageInterface $package, $path, $output = true): ?Promi /** * @inheritDoc */ - public function getVcsReference(PackageInterface $package, $path): ?string + public function getVcsReference(PackageInterface $package, string $path): ?string { $path = Filesystem::trimTrailingSlash($path); $parser = new VersionParser; @@ -224,7 +224,7 @@ public function getVcsReference(PackageInterface $package, $path): ?string /** * @inheritDoc */ - protected function getInstallOperationAppendix(PackageInterface $package, $path): string + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { $realUrl = realpath($package->getDistUrl()); @@ -250,7 +250,7 @@ protected function getInstallOperationAppendix(PackageInterface $package, $path) * * @phpstan-return array{self::STRATEGY_*, non-empty-list} */ - private function computeAllowedStrategies(array $transportOptions) + private function computeAllowedStrategies(array $transportOptions): array { // When symlink transport option is null, both symlink and mirror are allowed $currentStrategy = self::STRATEGY_SYMLINK; diff --git a/src/Composer/Downloader/PerforceDownloader.php b/src/Composer/Downloader/PerforceDownloader.php index ae603a83274e..559d6ba4a67e 100644 --- a/src/Composer/Downloader/PerforceDownloader.php +++ b/src/Composer/Downloader/PerforceDownloader.php @@ -28,7 +28,7 @@ class PerforceDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { return \React\Promise\resolve(); } @@ -36,7 +36,7 @@ protected function doDownload(PackageInterface $package, $path, $url, PackageInt /** * @inheritDoc */ - public function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface + public function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { $ref = $package->getSourceReference(); $label = $this->getLabelFromSourceReference((string) $ref); @@ -58,7 +58,7 @@ public function doInstall(PackageInterface $package, $path, $url): ?PromiseInter * * @return string|null */ - private function getLabelFromSourceReference($ref): ?string + private function getLabelFromSourceReference(string $ref): ?string { $pos = strpos($ref, '@'); if (false !== $pos) { @@ -74,7 +74,7 @@ private function getLabelFromSourceReference($ref): ?string * * @return void */ - public function initPerforce(PackageInterface $package, $path, $url): void + public function initPerforce(PackageInterface $package, string $path, string $url): void { if (!empty($this->perforce)) { $this->perforce->initializePath($path); @@ -101,7 +101,7 @@ private function getRepoConfig(VcsRepository $repository): array /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { return $this->doInstall($target, $path, $url); } @@ -109,7 +109,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path): ?string + public function getLocalChanges(PackageInterface $package, string $path): ?string { $this->io->writeError('Perforce driver does not check for local changes before overriding'); @@ -119,7 +119,7 @@ public function getLocalChanges(PackageInterface $package, $path): ?string /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path): string + protected function getCommitLogs(string $fromReference, string $toReference, string $path): string { return $this->perforce->getCommitLogs($fromReference, $toReference); } @@ -135,7 +135,7 @@ public function setPerforce(Perforce $perforce): void /** * @inheritDoc */ - protected function hasMetadataRepository($path): bool + protected function hasMetadataRepository(string $path): bool { return true; } diff --git a/src/Composer/Downloader/PharDownloader.php b/src/Composer/Downloader/PharDownloader.php index b91b2ec1e4bd..76517fcd74a5 100644 --- a/src/Composer/Downloader/PharDownloader.php +++ b/src/Composer/Downloader/PharDownloader.php @@ -25,7 +25,7 @@ class PharDownloader extends ArchiveDownloader /** * @inheritDoc */ - protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { // Can throw an UnexpectedValueException $archive = new \Phar($file); diff --git a/src/Composer/Downloader/RarDownloader.php b/src/Composer/Downloader/RarDownloader.php index ea9c636049c4..ef697d797757 100644 --- a/src/Composer/Downloader/RarDownloader.php +++ b/src/Composer/Downloader/RarDownloader.php @@ -28,7 +28,7 @@ */ class RarDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { $processError = null; diff --git a/src/Composer/Downloader/SvnDownloader.php b/src/Composer/Downloader/SvnDownloader.php index 7dd58493ed8a..056add89c842 100644 --- a/src/Composer/Downloader/SvnDownloader.php +++ b/src/Composer/Downloader/SvnDownloader.php @@ -31,7 +31,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null) + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { SvnUtil::cleanEnv(); $util = new SvnUtil($url, $this->io, $this->config, $this->process); @@ -45,7 +45,7 @@ protected function doDownload(PackageInterface $package, $path, $url, PackageInt /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url) + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { SvnUtil::cleanEnv(); $ref = $package->getSourceReference(); @@ -67,7 +67,7 @@ protected function doInstall(PackageInterface $package, $path, $url) /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { SvnUtil::cleanEnv(); $ref = $target->getSourceReference(); @@ -91,7 +91,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path) + public function getLocalChanges(PackageInterface $package, string $path): ?string { if (!$this->hasMetadataRepository($path)) { return null; @@ -114,7 +114,7 @@ public function getLocalChanges(PackageInterface $package, $path) * @throws \RuntimeException * @return string */ - protected function execute(PackageInterface $package, $baseUrl, $command, $url, $cwd = null, $path = null) + protected function execute(PackageInterface $package, string $baseUrl, string $command, string $url, string $cwd = null, string $path = null): string { $util = new SvnUtil($baseUrl, $this->io, $this->config, $this->process); $util->setCacheCredentials($this->cacheCredentials); @@ -130,7 +130,7 @@ protected function execute(PackageInterface $package, $baseUrl, $command, $url, /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, $path, $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface { if (!$changes = $this->getLocalChanges($package, $path)) { return \React\Promise\resolve(); @@ -191,7 +191,7 @@ protected function cleanChanges(PackageInterface $package, $path, $update) /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path) + protected function getCommitLogs(string $fromReference, string $toReference, string $path): string { if (Preg::isMatch('{@(\d+)$}', $fromReference) && Preg::isMatch('{@(\d+)$}', $toReference)) { // retrieve the svn base url from the checkout folder @@ -236,7 +236,7 @@ protected function getCommitLogs($fromReference, $toReference, $path) * * @return PromiseInterface */ - protected function discardChanges($path) + protected function discardChanges(string $path): PromiseInterface { if (0 !== $this->process->execute('svn revert -R .', $output, $path)) { throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput()); @@ -248,7 +248,7 @@ protected function discardChanges($path) /** * @inheritDoc */ - protected function hasMetadataRepository($path) + protected function hasMetadataRepository(string $path): bool { return is_dir($path.'/.svn'); } diff --git a/src/Composer/Downloader/TarDownloader.php b/src/Composer/Downloader/TarDownloader.php index da4c98289428..92998aac65fc 100644 --- a/src/Composer/Downloader/TarDownloader.php +++ b/src/Composer/Downloader/TarDownloader.php @@ -13,6 +13,7 @@ namespace Composer\Downloader; use Composer\Package\PackageInterface; +use React\Promise\PromiseInterface; /** * Downloader for tar files: tar, tar.gz or tar.bz2 @@ -24,7 +25,7 @@ class TarDownloader extends ArchiveDownloader /** * @inheritDoc */ - protected function extract(PackageInterface $package, $file, $path) + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { // Can throw an UnexpectedValueException $archive = new \PharData($file); diff --git a/src/Composer/Downloader/TransportException.php b/src/Composer/Downloader/TransportException.php index e36028670649..89719becf4f8 100644 --- a/src/Composer/Downloader/TransportException.php +++ b/src/Composer/Downloader/TransportException.php @@ -31,7 +31,7 @@ class TransportException extends \RuntimeException * * @return void */ - public function setHeaders($headers): void + public function setHeaders(array $headers): void { $this->headers = $headers; } @@ -45,11 +45,11 @@ public function getHeaders(): ?array } /** - * @param ?string $response + * @param null|string $response * * @return void */ - public function setResponse($response): void + public function setResponse(?string $response): void { $this->response = $response; } diff --git a/src/Composer/Downloader/VcsCapableDownloaderInterface.php b/src/Composer/Downloader/VcsCapableDownloaderInterface.php index 39203d5a5d5b..38d12c689e0e 100644 --- a/src/Composer/Downloader/VcsCapableDownloaderInterface.php +++ b/src/Composer/Downloader/VcsCapableDownloaderInterface.php @@ -28,5 +28,5 @@ interface VcsCapableDownloaderInterface * @param string $path package directory * @return string|null reference or null */ - public function getVcsReference(PackageInterface $package, $path); + public function getVcsReference(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/VcsDownloader.php b/src/Composer/Downloader/VcsDownloader.php index 836925b66246..12f5140f57e7 100644 --- a/src/Composer/Downloader/VcsDownloader.php +++ b/src/Composer/Downloader/VcsDownloader.php @@ -52,7 +52,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): string { return 'source'; } @@ -60,7 +60,7 @@ public function getInstallationSource() /** * @inheritDoc */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { if (!$package->getSourceReference()) { throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information'); @@ -93,7 +93,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre /** * @inheritDoc */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { if ($type === 'update') { $this->cleanChanges($prevPackage, $path, true); @@ -110,7 +110,7 @@ public function prepare($type, PackageInterface $package, $path, PackageInterfac /** * @inheritDoc */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { if ($type === 'update' && isset($this->hasCleanedChanges[$prevPackage->getUniqueName()])) { $this->reapplyChanges($path); @@ -123,7 +123,7 @@ public function cleanup($type, PackageInterface $package, $path, PackageInterfac /** * @inheritDoc */ - public function install(PackageInterface $package, $path) + public function install(PackageInterface $package, string $path): PromiseInterface { if (!$package->getSourceReference()) { throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information'); @@ -158,7 +158,7 @@ public function install(PackageInterface $package, $path) /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, $path) + public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface { if (!$target->getSourceReference()) { throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information'); @@ -194,12 +194,12 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat $message = 'Pulling in changes:'; $logs = $this->getCommitLogs($initial->getSourceReference(), $target->getSourceReference(), $path); - if (!trim($logs)) { + if ('' === trim($logs)) { $message = 'Rolling back changes:'; $logs = $this->getCommitLogs($target->getSourceReference(), $initial->getSourceReference(), $path); } - if (trim($logs)) { + if ('' !== trim($logs)) { $logs = implode("\n", array_map(function ($line): string { return ' ' . $line; }, explode("\n", $logs))); @@ -222,13 +222,13 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat /** * @inheritDoc */ - public function remove(PackageInterface $package, $path) + public function remove(PackageInterface $package, string $path): PromiseInterface { $this->io->writeError(" - " . UninstallOperation::format($package)); $promise = $this->filesystem->removeDirectoryAsync($path); - return $promise->then(function ($result) use ($path) { + return $promise->then(function (bool $result) use ($path) { if (!$result) { throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); } @@ -238,7 +238,7 @@ public function remove(PackageInterface $package, $path) /** * @inheritDoc */ - public function getVcsReference(PackageInterface $package, $path) + public function getVcsReference(PackageInterface $package, string $path): ?string { $parser = new VersionParser; $guesser = new VersionGuesser($this->config, $this->process, $parser); @@ -264,7 +264,7 @@ public function getVcsReference(PackageInterface $package, $path) * * @throws \RuntimeException in case the operation must be aborted */ - protected function cleanChanges(PackageInterface $package, $path, $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface { // the default implementation just fails if there are any changes, override in child classes to provide stash-ability if (null !== $this->getLocalChanges($package, $path)) { @@ -283,7 +283,7 @@ protected function cleanChanges(PackageInterface $package, $path, $update) * * @throws \RuntimeException in case the operation must be aborted or the patch does not apply cleanly */ - protected function reapplyChanges($path) + protected function reapplyChanges(string $path): void { } @@ -295,9 +295,9 @@ protected function reapplyChanges($path) * @param string $url package url * @param PackageInterface|null $prevPackage previous package (in case of an update) * - * @return PromiseInterface|null + * @return PromiseInterface */ - abstract protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null); + abstract protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface; /** * Downloads specific package into specific folder. @@ -306,9 +306,9 @@ abstract protected function doDownload(PackageInterface $package, $path, $url, P * @param string $path download path * @param string $url package url * - * @return PromiseInterface|null + * @return PromiseInterface */ - abstract protected function doInstall(PackageInterface $package, $path, $url); + abstract protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface; /** * Updates specific package in specific folder from initial to target version. @@ -318,9 +318,9 @@ abstract protected function doInstall(PackageInterface $package, $path, $url); * @param string $path download path * @param string $url package url * - * @return PromiseInterface|null + * @return PromiseInterface */ - abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url); + abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface; /** * Fetches the commit logs between two commits @@ -330,7 +330,7 @@ abstract protected function doUpdate(PackageInterface $initial, PackageInterface * @param string $path the package path * @return string */ - abstract protected function getCommitLogs($fromReference, $toReference, $path); + abstract protected function getCommitLogs(string $fromReference, string $toReference, string $path): string; /** * Checks if VCS metadata repository has been initialized @@ -339,7 +339,7 @@ abstract protected function getCommitLogs($fromReference, $toReference, $path); * @param string $path * @return bool */ - abstract protected function hasMetadataRepository($path); + abstract protected function hasMetadataRepository(string $path): bool; /** * @param string[] $urls diff --git a/src/Composer/Downloader/XzDownloader.php b/src/Composer/Downloader/XzDownloader.php index 2072b05e3f30..50325603e480 100644 --- a/src/Composer/Downloader/XzDownloader.php +++ b/src/Composer/Downloader/XzDownloader.php @@ -24,7 +24,7 @@ */ class XzDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { $command = 'tar -xJf ' . ProcessExecutor::escape($file) . ' -C ' . ProcessExecutor::escape($path); diff --git a/src/Composer/Downloader/ZipDownloader.php b/src/Composer/Downloader/ZipDownloader.php index a1f297a9d3b9..e532bdcdd2e7 100644 --- a/src/Composer/Downloader/ZipDownloader.php +++ b/src/Composer/Downloader/ZipDownloader.php @@ -17,6 +17,7 @@ use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Symfony\Component\Process\ExecutableFinder; +use Symfony\Component\Process\Process; use React\Promise\PromiseInterface; use ZipArchive; @@ -38,7 +39,7 @@ class ZipDownloader extends ArchiveDownloader /** * @inheritDoc */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true) + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $output = true): PromiseInterface { if (null === self::$unzipCommands) { self::$unzipCommands = array(); @@ -105,7 +106,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre * @param string $path Path where to extract file * @return PromiseInterface */ - private function extractWithSystemUnzip(PackageInterface $package, $file, $path): PromiseInterface + private function extractWithSystemUnzip(PackageInterface $package, string $file, string $path): PromiseInterface { // Force Exception throwing if the other alternative extraction method is not available $isLastChance = !self::$hasZipArchive; @@ -127,7 +128,7 @@ private function extractWithSystemUnzip(PackageInterface $package, $file, $path) $executable = $commandSpec[0]; $io = $this->io; - $tryFallback = function ($processError) use ($isLastChance, $io, $file, $path, $package, $executable): \React\Promise\PromiseInterface { + $tryFallback = function (\Throwable $processError) use ($isLastChance, $io, $file, $path, $package, $executable): \React\Promise\PromiseInterface { if ($isLastChance) { throw $processError; } @@ -148,7 +149,7 @@ private function extractWithSystemUnzip(PackageInterface $package, $file, $path) try { $promise = $this->process->executeAsync($command); - return $promise->then(function ($process) use ($tryFallback, $command, $package, $file) { + return $promise->then(function (Process $process) use ($tryFallback, $command, $package, $file) { if (!$process->isSuccessful()) { if (isset($this->cleanupExecuted[$package->getName()])) { throw new \RuntimeException('Failed to extract '.$package->getName().' as the installation was aborted by another package operation.'); @@ -172,7 +173,7 @@ private function extractWithSystemUnzip(PackageInterface $package, $file, $path) * @param string $path Path where to extract file * @return PromiseInterface */ - private function extractWithZipArchive(PackageInterface $package, $file, $path): PromiseInterface + private function extractWithZipArchive(PackageInterface $package, string $file, string $path): PromiseInterface { $processError = null; $zipArchive = $this->zipArchiveObject ?: new ZipArchive(); @@ -205,9 +206,9 @@ private function extractWithZipArchive(PackageInterface $package, $file, $path): * * @param string $file File to extract * @param string $path Path where to extract file - * @return PromiseInterface|null + * @return PromiseInterface */ - protected function extract(PackageInterface $package, $file, $path) + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { return $this->extractWithSystemUnzip($package, $file, $path); } @@ -219,7 +220,7 @@ protected function extract(PackageInterface $package, $file, $path) * @param string $file * @return string */ - protected function getErrorMessage($retval, $file) + protected function getErrorMessage(int $retval, string $file): string { switch ($retval) { case ZipArchive::ER_EXISTS: diff --git a/src/Composer/EventDispatcher/Event.php b/src/Composer/EventDispatcher/Event.php index 8563809f58d8..a3f2294ef057 100644 --- a/src/Composer/EventDispatcher/Event.php +++ b/src/Composer/EventDispatcher/Event.php @@ -46,7 +46,7 @@ class Event * @param string[] $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ - public function __construct($name, array $args = array(), array $flags = array()) + public function __construct(string $name, array $args = array(), array $flags = array()) { $this->name = $name; $this->args = $args; @@ -58,7 +58,7 @@ public function __construct($name, array $args = array(), array $flags = array() * * @return string The event name */ - public function getName() + public function getName(): string { return $this->name; } @@ -68,7 +68,7 @@ public function getName() * * @return string[] The event arguments */ - public function getArguments() + public function getArguments(): array { return $this->args; } @@ -78,7 +78,7 @@ public function getArguments() * * @return mixed[] The event flags */ - public function getFlags() + public function getFlags(): array { return $this->flags; } @@ -88,7 +88,7 @@ public function getFlags() * * @return bool Whether propagation has been stopped */ - public function isPropagationStopped() + public function isPropagationStopped(): bool { return $this->propagationStopped; } @@ -98,7 +98,7 @@ public function isPropagationStopped() * * @return void */ - public function stopPropagation() + public function stopPropagation(): void { $this->propagationStopped = true; } diff --git a/src/Composer/EventDispatcher/EventDispatcher.php b/src/Composer/EventDispatcher/EventDispatcher.php index ea6d517927b5..d0cd437bd66b 100644 --- a/src/Composer/EventDispatcher/EventDispatcher.php +++ b/src/Composer/EventDispatcher/EventDispatcher.php @@ -12,7 +12,6 @@ namespace Composer\EventDispatcher; -use Composer\Autoload\AutoloadGenerator; use Composer\DependencyResolver\Transaction; use Composer\Installer\InstallerEvent; use Composer\IO\IOInterface; @@ -82,7 +81,7 @@ public function __construct(PartialComposer $composer, IOInterface $io, ProcessE * @param bool $runScripts * @return $this */ - public function setRunScripts($runScripts = true) + public function setRunScripts(bool $runScripts = true): self { $this->runScripts = (bool) $runScripts; @@ -97,7 +96,7 @@ public function setRunScripts($runScripts = true) * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ - public function dispatch($eventName, Event $event = null) + public function dispatch(string $eventName, Event $event = null): int { if (null === $event) { $event = new Event($eventName); @@ -116,7 +115,7 @@ public function dispatch($eventName, Event $event = null) * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ - public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array()) + public function dispatchScript(string $eventName, bool $devMode = false, array $additionalArgs = array(), array $flags = array()): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -135,7 +134,7 @@ public function dispatchScript($eventName, $devMode = false, $additionalArgs = a * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ - public function dispatchPackageEvent($eventName, $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation) + public function dispatchPackageEvent(string $eventName, bool $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -153,7 +152,7 @@ public function dispatchPackageEvent($eventName, $devMode, RepositoryInterface $ * @return int return code of the executed script if any, for php scripts a false return * value is changed to 1, anything else to 0 */ - public function dispatchInstallerEvent($eventName, $devMode, $executeOperations, Transaction $transaction) + public function dispatchInstallerEvent(string $eventName, bool $devMode, bool $executeOperations, Transaction $transaction): int { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -343,7 +342,7 @@ protected function doDispatch(Event $event) * * @return int */ - protected function executeTty($exec) + protected function executeTty(string $exec): int { if ($this->io->isInteractive()) { return $this->process->executeTty($exec); @@ -355,7 +354,7 @@ protected function executeTty($exec) /** * @return string */ - protected function getPhpExecCommand() + protected function getPhpExecCommand(): string { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(false); @@ -378,7 +377,7 @@ protected function getPhpExecCommand() * * @return mixed */ - protected function executeEventPhpScript($className, $methodName, Event $event) + protected function executeEventPhpScript(string $className, string $methodName, Event $event) { if ($this->io->isVerbose()) { $this->io->writeError(sprintf('> %s: %s::%s', $event->getName(), $className, $methodName)); @@ -398,7 +397,7 @@ protected function executeEventPhpScript($className, $methodName, Event $event) * * @return void */ - public function addListener($eventName, $listener, $priority = 0) + public function addListener(string $eventName, callable $listener, int $priority = 0): void { $this->listeners[$eventName][$priority][] = $listener; } @@ -408,7 +407,7 @@ public function addListener($eventName, $listener, $priority = 0) * * @return void */ - public function removeListener($listener) + public function removeListener($listener): void { foreach ($this->listeners as $eventName => $priorities) { foreach ($priorities as $priority => $listeners) { @@ -430,7 +429,7 @@ public function removeListener($listener) * * @return void */ - public function addSubscriber(EventSubscriberInterface $subscriber) + public function addSubscriber(EventSubscriberInterface $subscriber): void { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { @@ -451,7 +450,7 @@ public function addSubscriber(EventSubscriberInterface $subscriber) * @param Event $event * @return array All listeners: callables and scripts */ - protected function getListeners(Event $event) + protected function getListeners(Event $event): array { $scriptListeners = $this->runScripts ? $this->getScriptListeners($event) : array(); @@ -472,7 +471,7 @@ protected function getListeners(Event $event) * @param Event $event * @return bool */ - public function hasEventListeners(Event $event) + public function hasEventListeners(Event $event): bool { $listeners = $this->getListeners($event); @@ -485,7 +484,7 @@ public function hasEventListeners(Event $event) * @param Event $event Event object * @return string[] Listeners */ - protected function getScriptListeners(Event $event) + protected function getScriptListeners(Event $event): array { $package = $this->composer->getPackage(); $scripts = $package->getScripts(); @@ -520,7 +519,7 @@ protected function getScriptListeners(Event $event) * @param string $callable * @return bool */ - protected function isPhpScript($callable) + protected function isPhpScript(string $callable): bool { return false === strpos($callable, ' ') && false !== strpos($callable, '::'); } @@ -531,7 +530,7 @@ protected function isPhpScript($callable) * @param string $callable * @return bool */ - protected function isComposerScript($callable) + protected function isComposerScript(string $callable): bool { return strpos($callable, '@') === 0 && strpos($callable, '@php ') !== 0 && strpos($callable, '@putenv ') !== 0; } @@ -543,7 +542,7 @@ protected function isComposerScript($callable) * @throws \RuntimeException * @return int */ - protected function pushEvent(Event $event) + protected function pushEvent(Event $event): int { $eventName = $event->getName(); if (in_array($eventName, $this->eventStack)) { @@ -558,7 +557,7 @@ protected function pushEvent(Event $event) * * @return string|null */ - protected function popEvent() + protected function popEvent(): ?string { return array_pop($this->eventStack); } diff --git a/src/Composer/Factory.php b/src/Composer/Factory.php index e6ef47563ee6..c6980057c8a9 100644 --- a/src/Composer/Factory.php +++ b/src/Composer/Factory.php @@ -164,7 +164,7 @@ protected static function getDataDir(string $home): string public static function createConfig(IOInterface $io = null, ?string $cwd = null): Config { - $cwd = $cwd ?: (string) getcwd(); + $cwd = $cwd ?? Platform::getCwd(true); $config = new Config(true, $cwd); @@ -278,7 +278,7 @@ public static function createOutput(): ConsoleOutput */ public function createComposer(IOInterface $io, $localConfig = null, bool $disablePlugins = false, ?string $cwd = null, bool $fullLoad = true, bool $disableScripts = false) { - $cwd = $cwd ?: (string) getcwd(); + $cwd = $cwd ?? Platform::getCwd(true); // load Composer configuration if (null === $localConfig) { @@ -454,7 +454,7 @@ public static function createGlobal(IOInterface $io, bool $disablePlugins = fals * * @return void */ - protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, $vendorDir, RootPackageInterface $rootPackage, ProcessExecutor $process = null): void + protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, string $vendorDir, RootPackageInterface $rootPackage, ProcessExecutor $process = null): void { $fs = null; if ($process) { @@ -621,7 +621,7 @@ public static function create(IOInterface $io, $config = null, bool $disablePlug * @param mixed[] $options Array of options passed directly to HttpDownloader constructor * @return HttpDownloader */ - public static function createHttpDownloader(IOInterface $io, Config $config, $options = array()): HttpDownloader + public static function createHttpDownloader(IOInterface $io, Config $config, array $options = array()): HttpDownloader { static $warned = false; $disableTls = false; diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php index ca37baea42f8..db779c3c1716 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php @@ -20,7 +20,7 @@ final class IgnoreAllPlatformRequirementFilter implements PlatformRequirementFil * @param string $req * @return bool */ - public function isIgnored($req): bool + public function isIgnored(string $req): bool { return PlatformRepository::isPlatformPackage($req); } diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php index e51d59b39f12..5a146bfe318b 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php @@ -55,7 +55,7 @@ public function __construct(array $reqList) * @param string $req * @return bool */ - public function isIgnored($req): bool + public function isIgnored(string $req): bool { if (!PlatformRepository::isPlatformPackage($req)) { return false; @@ -68,7 +68,7 @@ public function isIgnored($req): bool * @param string $req * @return ConstraintInterface */ - public function filterConstraint($req, ConstraintInterface $constraint): ConstraintInterface + public function filterConstraint(string $req, ConstraintInterface $constraint): ConstraintInterface { if (!PlatformRepository::isPlatformPackage($req)) { return $constraint; diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php index 2262326c328b..882275b41313 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php @@ -18,7 +18,7 @@ final class IgnoreNothingPlatformRequirementFilter implements PlatformRequiremen * @param string $req * @return false */ - public function isIgnored($req): bool + public function isIgnored(string $req): bool { return false; } diff --git a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php index 52cf83e16829..de0fc234a5f9 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php +++ b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php @@ -18,5 +18,5 @@ interface PlatformRequirementFilterInterface * @param string $req * @return bool */ - public function isIgnored($req): bool; + public function isIgnored(string $req): bool; } diff --git a/src/Composer/IO/BaseIO.php b/src/Composer/IO/BaseIO.php index 7c951f2c6c96..807e0ee3a2bf 100644 --- a/src/Composer/IO/BaseIO.php +++ b/src/Composer/IO/BaseIO.php @@ -69,7 +69,7 @@ public function setAuthentication($repositoryName, $username, $password = null) /** * @inheritDoc */ - public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL) + public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->write($messages, $newline, $verbosity); } @@ -77,7 +77,7 @@ public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL) /** * @inheritDoc */ - public function writeErrorRaw($messages, $newline = true, $verbosity = self::NORMAL) + public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->writeError($messages, $newline, $verbosity); } @@ -91,7 +91,7 @@ public function writeErrorRaw($messages, $newline = true, $verbosity = self::NOR * * @return void */ - protected function checkAndSetAuthentication($repositoryName, $username, $password = null) + protected function checkAndSetAuthentication(string $repositoryName, string $username, string $password = null) { if ($this->hasAuthentication($repositoryName)) { $auth = $this->getAuthentication($repositoryName); diff --git a/src/Composer/IO/BufferIO.php b/src/Composer/IO/BufferIO.php index 4d7242120fcb..0e9b44a2594f 100644 --- a/src/Composer/IO/BufferIO.php +++ b/src/Composer/IO/BufferIO.php @@ -35,7 +35,7 @@ class BufferIO extends ConsoleIO * @param int $verbosity * @param OutputFormatterInterface|null $formatter */ - public function __construct($input = '', $verbosity = StreamOutput::VERBOSITY_NORMAL, OutputFormatterInterface $formatter = null) + public function __construct(string $input = '', int $verbosity = StreamOutput::VERBOSITY_NORMAL, OutputFormatterInterface $formatter = null) { $input = new StringInput($input); $input->setInteractive(false); diff --git a/src/Composer/IO/ConsoleIO.php b/src/Composer/IO/ConsoleIO.php index 2fd2cb178e97..b63baca77892 100644 --- a/src/Composer/IO/ConsoleIO.php +++ b/src/Composer/IO/ConsoleIO.php @@ -71,7 +71,7 @@ public function __construct(InputInterface $input, OutputInterface $output, Help * * @return void */ - public function enableDebugging($startTime) + public function enableDebugging(float $startTime) { $this->startTime = $startTime; } @@ -119,7 +119,7 @@ public function isDebug() /** * @inheritDoc */ - public function write($messages, $newline = true, $verbosity = self::NORMAL) + public function write($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, false, $verbosity); } @@ -127,7 +127,7 @@ public function write($messages, $newline = true, $verbosity = self::NORMAL) /** * @inheritDoc */ - public function writeError($messages, $newline = true, $verbosity = self::NORMAL) + public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, true, $verbosity); } @@ -135,7 +135,7 @@ public function writeError($messages, $newline = true, $verbosity = self::NORMAL /** * @inheritDoc */ - public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL) + public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, false, $verbosity, true); } @@ -143,7 +143,7 @@ public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL) /** * @inheritDoc */ - public function writeErrorRaw($messages, $newline = true, $verbosity = self::NORMAL) + public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL) { $this->doWrite($messages, $newline, true, $verbosity, true); } @@ -157,7 +157,7 @@ public function writeErrorRaw($messages, $newline = true, $verbosity = self::NOR * * @return void */ - private function doWrite($messages, $newline, $stderr, $verbosity, $raw = false): void + private function doWrite($messages, bool $newline, bool $stderr, int $verbosity, bool $raw = false): void { $sfVerbosity = $this->verbosityMap[$verbosity]; if ($sfVerbosity > $this->output->getVerbosity()) { @@ -194,7 +194,7 @@ private function doWrite($messages, $newline, $stderr, $verbosity, $raw = false) /** * @inheritDoc */ - public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL) + public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL) { $this->doOverwrite($messages, $newline, $size, false, $verbosity); } @@ -202,7 +202,7 @@ public function overwrite($messages, $newline = true, $size = null, $verbosity = /** * @inheritDoc */ - public function overwriteError($messages, $newline = true, $size = null, $verbosity = self::NORMAL) + public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL) { $this->doOverwrite($messages, $newline, $size, true, $verbosity); } @@ -216,7 +216,7 @@ public function overwriteError($messages, $newline = true, $size = null, $verbos * * @return void */ - private function doOverwrite($messages, $newline, $size, $stderr, $verbosity): void + private function doOverwrite($messages, bool $newline, ?int $size, bool $stderr, int $verbosity): void { // messages can be an array, let's convert it to string anyway $messages = implode($newline ? "\n" : '', (array) $messages); @@ -258,7 +258,7 @@ private function doOverwrite($messages, $newline, $size, $stderr, $verbosity): v * @param int $max * @return ProgressBar */ - public function getProgressBar($max = 0) + public function getProgressBar(int $max = 0) { return new ProgressBar($this->getErrorOutput(), $max); } diff --git a/src/Composer/IO/IOInterface.php b/src/Composer/IO/IOInterface.php index 0837309d5487..66fe735db3a5 100644 --- a/src/Composer/IO/IOInterface.php +++ b/src/Composer/IO/IOInterface.php @@ -72,7 +72,7 @@ public function isDecorated(); * * @return void */ - public function write($messages, $newline = true, $verbosity = self::NORMAL); + public function write($messages, bool $newline = true, int $verbosity = self::NORMAL); /** * Writes a message to the error output. @@ -83,7 +83,7 @@ public function write($messages, $newline = true, $verbosity = self::NORMAL); * * @return void */ - public function writeError($messages, $newline = true, $verbosity = self::NORMAL); + public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL); /** * Writes a message to the output, without formatting it. @@ -94,7 +94,7 @@ public function writeError($messages, $newline = true, $verbosity = self::NORMAL * * @return void */ - public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL); + public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL); /** * Writes a message to the error output, without formatting it. @@ -105,7 +105,7 @@ public function writeRaw($messages, $newline = true, $verbosity = self::NORMAL); * * @return void */ - public function writeErrorRaw($messages, $newline = true, $verbosity = self::NORMAL); + public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL); /** * Overwrites a previous message to the output. @@ -117,7 +117,7 @@ public function writeErrorRaw($messages, $newline = true, $verbosity = self::NOR * * @return void */ - public function overwrite($messages, $newline = true, $size = null, $verbosity = self::NORMAL); + public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL); /** * Overwrites a previous message to the error output. @@ -129,7 +129,7 @@ public function overwrite($messages, $newline = true, $size = null, $verbosity = * * @return void */ - public function overwriteError($messages, $newline = true, $size = null, $verbosity = self::NORMAL); + public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL); /** * Asks a question to the user. @@ -140,7 +140,7 @@ public function overwriteError($messages, $newline = true, $size = null, $verbos * @throws \RuntimeException If there is no data to read in the input stream * @return mixed The user answer */ - public function ask($question, $default = null); + public function ask(string $question, $default = null); /** * Asks a confirmation to the user. @@ -152,7 +152,7 @@ public function ask($question, $default = null); * * @return bool true if the user has confirmed, false otherwise */ - public function askConfirmation($question, $default = true); + public function askConfirmation(string $question, bool $default = true); /** * Asks for a value and validates the response. @@ -169,7 +169,7 @@ public function askConfirmation($question, $default = true); * @throws \Exception When any of the validators return an error * @return mixed */ - public function askAndValidate($question, $validator, $attempts = null, $default = null); + public function askAndValidate(string $question, callable $validator, ?int $attempts = null, $default = null); /** * Asks a question to the user and hide the answer. @@ -178,7 +178,7 @@ public function askAndValidate($question, $validator, $attempts = null, $default * * @return string|null The answer */ - public function askAndHideAnswer($question); + public function askAndHideAnswer(string $question); /** * Asks the user to select a value. @@ -193,7 +193,7 @@ public function askAndHideAnswer($question); * @throws \InvalidArgumentException * @return int|string|string[]|bool The selected value or values (the key of the choices array) */ - public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false); + public function select(string $question, array $choices, $default, $attempts = false, string $errorMessage = 'Value "%s" is invalid', bool $multiselect = false); /** * Get all authentication information entered. @@ -209,7 +209,7 @@ public function getAuthentications(); * * @return bool */ - public function hasAuthentication($repositoryName); + public function hasAuthentication(string $repositoryName); /** * Get the username and password of repository. @@ -218,18 +218,18 @@ public function hasAuthentication($repositoryName); * * @return array{username: string|null, password: string|null} */ - public function getAuthentication($repositoryName); + public function getAuthentication(string $repositoryName); /** * Set the authentication information for the repository. * - * @param string $repositoryName The unique name of repository - * @param string $username The username - * @param ?string $password The password + * @param string $repositoryName The unique name of repository + * @param string $username The username + * @param null|string $password The password * * @return void */ - public function setAuthentication($repositoryName, $username, $password = null); + public function setAuthentication(string $repositoryName, string $username, ?string $password = null); /** * Loads authentications from a config instance diff --git a/src/Composer/IO/NullIO.php b/src/Composer/IO/NullIO.php index 278b945b365a..88c4a8c74bba 100644 --- a/src/Composer/IO/NullIO.php +++ b/src/Composer/IO/NullIO.php @@ -62,28 +62,28 @@ public function isDecorated(): bool /** * @inheritDoc */ - public function write($messages, $newline = true, $verbosity = self::NORMAL): void + public function write($messages, bool $newline = true, int $verbosity = self::NORMAL): void { } /** * @inheritDoc */ - public function writeError($messages, $newline = true, $verbosity = self::NORMAL): void + public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL): void { } /** * @inheritDoc */ - public function overwrite($messages, $newline = true, $size = 80, $verbosity = self::NORMAL): void + public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL): void { } /** * @inheritDoc */ - public function overwriteError($messages, $newline = true, $size = 80, $verbosity = self::NORMAL): void + public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL): void { } diff --git a/src/Composer/InstalledVersions.php b/src/Composer/InstalledVersions.php index d50e0c9fcc47..41bc143c1148 100644 --- a/src/Composer/InstalledVersions.php +++ b/src/Composer/InstalledVersions.php @@ -21,6 +21,8 @@ * 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 { diff --git a/src/Composer/Installer.php b/src/Composer/Installer.php index 18b798d7b923..d72525b334bd 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -386,7 +386,7 @@ public function run(): int * @return int * @phpstan-return self::ERROR_* */ - protected function doUpdate(InstalledRepositoryInterface $localRepo, $doInstall): int + protected function doUpdate(InstalledRepositoryInterface $localRepo, bool $doInstall): int { $platformRepo = $this->createPlatformRepo(true); $aliases = $this->getRootAliases(true); @@ -648,7 +648,7 @@ protected function extractDevPackages(LockTransaction $lockTransaction, Platform * @return int exit code * @phpstan-return self::ERROR_* */ - protected function doInstall(InstalledRepositoryInterface $localRepo, $alreadySolved = false): int + protected function doInstall(InstalledRepositoryInterface $localRepo, bool $alreadySolved = false): int { $this->io->writeError('Installing dependencies from lock file'.($this->devMode ? ' (including require-dev)' : '').''); @@ -769,7 +769,7 @@ protected function doInstall(InstalledRepositoryInterface $localRepo, $alreadySo * * @return PlatformRepository */ - protected function createPlatformRepo($forUpdate): PlatformRepository + protected function createPlatformRepo(bool $forUpdate): PlatformRepository { if ($forUpdate) { $platformOverrides = $this->config->get('platform') ?: array(); @@ -789,7 +789,7 @@ protected function createPlatformRepo($forUpdate): PlatformRepository * * @phpstan-param list $rootAliases */ - private function createRepositorySet($forUpdate, PlatformRepository $platformRepo, array $rootAliases = array(), $lockedRepository = null): RepositorySet + private function createRepositorySet(bool $forUpdate, PlatformRepository $platformRepo, array $rootAliases = array(), ?RepositoryInterface $lockedRepository = null): RepositorySet { if ($forUpdate) { $minimumStability = $this->package->getMinimumStability(); @@ -858,7 +858,7 @@ private function createRepositorySet($forUpdate, PlatformRepository $platformRep * * @return DefaultPolicy */ - private function createPolicy($forUpdate): DefaultPolicy + private function createPolicy(bool $forUpdate): DefaultPolicy { $preferStable = null; $preferLowest = null; @@ -919,7 +919,7 @@ private function createRequest(RootPackageInterface $rootPackage, PlatformReposi * * @return void */ - private function requirePackagesForUpdate(Request $request, LockArrayRepository $lockedRepository = null, $includeDevRequires = true): void + private function requirePackagesForUpdate(Request $request, LockArrayRepository $lockedRepository = null, bool $includeDevRequires = true): void { // if we're updating mirrors we want to keep exactly the same versions installed which are in the lock file, but we want current remote metadata if ($this->updateMirrors) { @@ -953,7 +953,7 @@ private function requirePackagesForUpdate(Request $request, LockArrayRepository * * @phpstan-return list */ - private function getRootAliases($forUpdate): array + private function getRootAliases(bool $forUpdate): array { if ($forUpdate) { $aliases = $this->package->getAliases(); @@ -1030,7 +1030,7 @@ private function createPoolOptimizer(PolicyInterface $policy): ?PoolOptimizer * @param Composer $composer * @return Installer */ - public static function create(IOInterface $io, Composer $composer): Installer + public static function create(IOInterface $io, Composer $composer): self { return new static( $io, @@ -1049,7 +1049,7 @@ public static function create(IOInterface $io, Composer $composer): Installer * @param RepositoryInterface $additionalFixedRepository * @return $this */ - public function setAdditionalFixedRepository(RepositoryInterface $additionalFixedRepository) + public function setAdditionalFixedRepository(RepositoryInterface $additionalFixedRepository): self { $this->additionalFixedRepository = $additionalFixedRepository; @@ -1062,7 +1062,7 @@ public function setAdditionalFixedRepository(RepositoryInterface $additionalFixe * @param bool $dryRun * @return Installer */ - public function setDryRun($dryRun = true): Installer + public function setDryRun(bool $dryRun = true): self { $this->dryRun = (bool) $dryRun; @@ -1085,7 +1085,7 @@ public function isDryRun(): bool * @param bool $preferSource * @return Installer */ - public function setPreferSource($preferSource = true): Installer + public function setPreferSource(bool $preferSource = true): self { $this->preferSource = (bool) $preferSource; @@ -1098,7 +1098,7 @@ public function setPreferSource($preferSource = true): Installer * @param bool $preferDist * @return Installer */ - public function setPreferDist($preferDist = true): Installer + public function setPreferDist(bool $preferDist = true): self { $this->preferDist = (bool) $preferDist; @@ -1111,7 +1111,7 @@ public function setPreferDist($preferDist = true): Installer * @param bool $optimizeAutoloader * @return Installer */ - public function setOptimizeAutoloader($optimizeAutoloader): Installer + public function setOptimizeAutoloader(bool $optimizeAutoloader): self { $this->optimizeAutoloader = (bool) $optimizeAutoloader; if (!$this->optimizeAutoloader) { @@ -1130,7 +1130,7 @@ public function setOptimizeAutoloader($optimizeAutoloader): Installer * @param bool $classMapAuthoritative * @return Installer */ - public function setClassMapAuthoritative($classMapAuthoritative): Installer + public function setClassMapAuthoritative(bool $classMapAuthoritative): self { $this->classMapAuthoritative = (bool) $classMapAuthoritative; if ($this->classMapAuthoritative) { @@ -1148,7 +1148,7 @@ public function setClassMapAuthoritative($classMapAuthoritative): Installer * @param string|null $apcuAutoloaderPrefix * @return Installer */ - public function setApcuAutoloader($apcuAutoloader, $apcuAutoloaderPrefix = null): Installer + public function setApcuAutoloader(bool $apcuAutoloader, ?string $apcuAutoloaderPrefix = null): self { $this->apcuAutoloader = $apcuAutoloader; $this->apcuAutoloaderPrefix = $apcuAutoloaderPrefix; @@ -1162,7 +1162,7 @@ public function setApcuAutoloader($apcuAutoloader, $apcuAutoloaderPrefix = null) * @param bool $update * @return Installer */ - public function setUpdate($update): Installer + public function setUpdate(bool $update): self { $this->update = (bool) $update; @@ -1175,7 +1175,7 @@ public function setUpdate($update): Installer * @param bool $install * @return Installer */ - public function setInstall($install): Installer + public function setInstall(bool $install): self { $this->install = (bool) $install; @@ -1188,7 +1188,7 @@ public function setInstall($install): Installer * @param bool $devMode * @return Installer */ - public function setDevMode($devMode = true): Installer + public function setDevMode(bool $devMode = true): self { $this->devMode = (bool) $devMode; @@ -1203,7 +1203,7 @@ public function setDevMode($devMode = true): Installer * @param bool $dumpAutoloader * @return Installer */ - public function setDumpAutoloader($dumpAutoloader = true): Installer + public function setDumpAutoloader(bool $dumpAutoloader = true): self { $this->dumpAutoloader = (bool) $dumpAutoloader; @@ -1219,7 +1219,7 @@ public function setDumpAutoloader($dumpAutoloader = true): Installer * @return Installer * @deprecated Use setRunScripts(false) on the EventDispatcher instance being injected instead */ - public function setRunScripts($runScripts = true): Installer + public function setRunScripts(bool $runScripts = true): self { $this->runScripts = (bool) $runScripts; @@ -1232,7 +1232,7 @@ public function setRunScripts($runScripts = true): Installer * @param Config $config * @return Installer */ - public function setConfig(Config $config): Installer + public function setConfig(Config $config): self { $this->config = $config; @@ -1245,7 +1245,7 @@ public function setConfig(Config $config): Installer * @param bool $verbose * @return Installer */ - public function setVerbose($verbose = true): Installer + public function setVerbose(bool $verbose = true): self { $this->verbose = (bool) $verbose; @@ -1275,7 +1275,7 @@ public function isVerbose(): bool * * @deprecated use setPlatformRequirementFilter instead */ - public function setIgnorePlatformRequirements($ignorePlatformReqs): Installer + public function setIgnorePlatformRequirements($ignorePlatformReqs): self { trigger_error('Installer::setIgnorePlatformRequirements is deprecated since Composer 2.2, use setPlatformRequirementFilter instead.', E_USER_DEPRECATED); @@ -1286,7 +1286,7 @@ public function setIgnorePlatformRequirements($ignorePlatformReqs): Installer * @param PlatformRequirementFilterInterface $platformRequirementFilter * @return Installer */ - public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter): Installer + public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter): self { $this->platformRequirementFilter = $platformRequirementFilter; @@ -1299,7 +1299,7 @@ public function setPlatformRequirementFilter(PlatformRequirementFilterInterface * @param bool $updateMirrors * @return Installer */ - public function setUpdateMirrors($updateMirrors): Installer + public function setUpdateMirrors(bool $updateMirrors): self { $this->updateMirrors = $updateMirrors; @@ -1314,7 +1314,7 @@ public function setUpdateMirrors($updateMirrors): Installer * * @return Installer */ - public function setUpdateAllowList(array $packages): Installer + public function setUpdateAllowList(array $packages): self { $this->updateAllowList = array_flip(array_map('strtolower', $packages)); @@ -1330,7 +1330,7 @@ public function setUpdateAllowList(array $packages): Installer * @param int $updateAllowTransitiveDependencies One of the UPDATE_ constants on the Request class * @return Installer */ - public function setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies): Installer + public function setUpdateAllowTransitiveDependencies(int $updateAllowTransitiveDependencies): self { if (!in_array($updateAllowTransitiveDependencies, array(Request::UPDATE_ONLY_LISTED, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS), true)) { throw new \RuntimeException("Invalid value for updateAllowTransitiveDependencies supplied"); @@ -1347,7 +1347,7 @@ public function setUpdateAllowTransitiveDependencies($updateAllowTransitiveDepen * @param bool $preferStable * @return Installer */ - public function setPreferStable($preferStable = true): Installer + public function setPreferStable(bool $preferStable = true): self { $this->preferStable = (bool) $preferStable; @@ -1360,7 +1360,7 @@ public function setPreferStable($preferStable = true): Installer * @param bool $preferLowest * @return Installer */ - public function setPreferLowest($preferLowest = true): Installer + public function setPreferLowest(bool $preferLowest = true): self { $this->preferLowest = (bool) $preferLowest; @@ -1375,7 +1375,7 @@ public function setPreferLowest($preferLowest = true): Installer * @param bool $writeLock * @return Installer */ - public function setWriteLock($writeLock = true): Installer + public function setWriteLock(bool $writeLock = true): self { $this->writeLock = (bool) $writeLock; @@ -1390,7 +1390,7 @@ public function setWriteLock($writeLock = true): Installer * @param bool $executeOperations * @return Installer */ - public function setExecuteOperations($executeOperations = true): Installer + public function setExecuteOperations(bool $executeOperations = true): self { $this->executeOperations = (bool) $executeOperations; @@ -1406,7 +1406,7 @@ public function setExecuteOperations($executeOperations = true): Installer * * @return Installer */ - public function disablePlugins(): Installer + public function disablePlugins(): self { $this->installationManager->disablePlugins(); @@ -1417,7 +1417,7 @@ public function disablePlugins(): Installer * @param SuggestedPackagesReporter $suggestedPackagesReporter * @return Installer */ - public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter): Installer + public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter): self { $this->suggestedPackagesReporter = $suggestedPackagesReporter; diff --git a/src/Composer/Installer/BinaryInstaller.php b/src/Composer/Installer/BinaryInstaller.php index 4af59ad233a2..05f3c0b341e7 100644 --- a/src/Composer/Installer/BinaryInstaller.php +++ b/src/Composer/Installer/BinaryInstaller.php @@ -47,7 +47,7 @@ class BinaryInstaller * @param Filesystem $filesystem * @param string|null $vendorDir */ - public function __construct(IOInterface $io, $binDir, $binCompat, Filesystem $filesystem = null, $vendorDir = null) + public function __construct(IOInterface $io, string $binDir, string $binCompat, Filesystem $filesystem = null, ?string $vendorDir = null) { $this->binDir = $binDir; $this->binCompat = $binCompat; @@ -62,7 +62,7 @@ public function __construct(IOInterface $io, $binDir, $binCompat, Filesystem $fi * * @return void */ - public function installBinaries(PackageInterface $package, $installPath, $warnOnOverwrite = true): void + public function installBinaries(PackageInterface $package, string $installPath, bool $warnOnOverwrite = true): void { $binaries = $this->getBinaries($package); if (!$binaries) { @@ -149,7 +149,7 @@ public function removeBinaries(PackageInterface $package): void * * @return string */ - public static function determineBinaryCaller($bin): string + public static function determineBinaryCaller(string $bin): string { if ('.bat' === substr($bin, -4) || '.exe' === substr($bin, -4)) { return 'call'; @@ -180,7 +180,7 @@ protected function getBinaries(PackageInterface $package): array * * @return void */ - protected function installFullBinaries($binPath, $link, $bin, PackageInterface $package): void + protected function installFullBinaries(string $binPath, string $link, string $bin, PackageInterface $package): void { // add unixy support for cygwin and similar environments if ('.bat' !== substr($binPath, -4)) { @@ -202,7 +202,7 @@ protected function installFullBinaries($binPath, $link, $bin, PackageInterface $ * * @return void */ - protected function installUnixyProxyBinaries($binPath, $link): void + protected function installUnixyProxyBinaries(string $binPath, string $link): void { file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link)); Silencer::call('chmod', $link, 0777 & ~umask()); @@ -223,7 +223,7 @@ protected function initializeBinDir(): void * * @return string */ - protected function generateWindowsProxyCode($bin, $link): string + protected function generateWindowsProxyCode(string $bin, string $link): string { $binPath = $this->filesystem->findShortestPath($link, $bin); $caller = self::determineBinaryCaller($bin); @@ -252,7 +252,7 @@ protected function generateWindowsProxyCode($bin, $link): string * * @return string */ - protected function generateUnixyProxyCode($bin, $link): string + protected function generateUnixyProxyCode(string $bin, string $link): string { $binPath = $this->filesystem->findShortestPath($link, $bin); diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index 788d367e77b4..8200080b3163 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -63,7 +63,7 @@ public function __construct(Loop $loop, IOInterface $io, EventDispatcher $eventD /** * @return void */ - public function reset() + public function reset(): void { $this->notifiablePackages = array(); FileDownloader::$downloadMetadata = array(); @@ -76,7 +76,7 @@ public function reset() * * @return void */ - public function addInstaller(InstallerInterface $installer) + public function addInstaller(InstallerInterface $installer): void { array_unshift($this->installers, $installer); $this->cache = array(); @@ -89,7 +89,7 @@ public function addInstaller(InstallerInterface $installer) * * @return void */ - public function removeInstaller(InstallerInterface $installer) + public function removeInstaller(InstallerInterface $installer): void { if (false !== ($key = array_search($installer, $this->installers, true))) { array_splice($this->installers, $key, 1); @@ -106,7 +106,7 @@ public function removeInstaller(InstallerInterface $installer) * * @return void */ - public function disablePlugins() + public function disablePlugins(): void { foreach ($this->installers as $i => $installer) { if (!$installer instanceof PluginInstaller) { @@ -125,7 +125,7 @@ public function disablePlugins() * @throws \InvalidArgumentException if installer for provided type is not registered * @return InstallerInterface */ - public function getInstaller($type) + public function getInstaller(string $type): InstallerInterface { $type = strtolower($type); @@ -150,7 +150,7 @@ public function getInstaller($type) * * @return bool */ - public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) + public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool { if ($package instanceof AliasPackage) { return $repo->hasPackage($package) && $this->isPackageInstalled($repo, $package->getAliasOf()); @@ -167,7 +167,7 @@ public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageIn * * @return void */ - public function ensureBinariesPresence(PackageInterface $package) + public function ensureBinariesPresence(PackageInterface $package): void { try { $installer = $this->getInstaller($package->getType()); @@ -192,7 +192,7 @@ public function ensureBinariesPresence(PackageInterface $package) * * @return void */ - public function execute(InstalledRepositoryInterface $repo, array $operations, $devMode = true, $runScripts = true) + public function execute(InstalledRepositoryInterface $repo, array $operations, bool $devMode = true, bool $runScripts = true): void { /** @var PromiseInterface[] */ $cleanupPromises = array(); @@ -316,7 +316,7 @@ public function execute(InstalledRepositoryInterface $repo, array $operations, $ * * @return void */ - private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, array $operations, array &$cleanupPromises, $devMode, $runScripts, array $allOperations): void + private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, array $operations, array &$cleanupPromises, bool $devMode, bool $runScripts, array $allOperations): void { $promises = array(); @@ -400,7 +400,7 @@ private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, arr * * @return void */ - private function executeBatch(InstalledRepositoryInterface $repo, array $operations, array $cleanupPromises, $devMode, $runScripts, array $allOperations): void + private function executeBatch(InstalledRepositoryInterface $repo, array $operations, array $cleanupPromises, bool $devMode, bool $runScripts, array $allOperations): void { $promises = array(); $postExecCallbacks = array(); @@ -511,7 +511,7 @@ private function waitOnPromises(array $promises): void * * @return PromiseInterface|null */ - public function install(InstalledRepositoryInterface $repo, InstallOperation $operation) + public function install(InstalledRepositoryInterface $repo, InstallOperation $operation): ?PromiseInterface { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); @@ -529,7 +529,7 @@ public function install(InstalledRepositoryInterface $repo, InstallOperation $op * * @return PromiseInterface|null */ - public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation) + public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface { $initial = $operation->getInitialPackage(); $target = $operation->getTargetPackage(); @@ -553,7 +553,7 @@ public function update(InstalledRepositoryInterface $repo, UpdateOperation $oper if ($promise instanceof PromiseInterface) { return $promise; } - + return \React\Promise\resolve(); }); } @@ -569,7 +569,7 @@ public function update(InstalledRepositoryInterface $repo, UpdateOperation $oper * * @return PromiseInterface|null */ - public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation) + public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation): ?PromiseInterface { $package = $operation->getPackage(); $installer = $this->getInstaller($package->getType()); @@ -585,7 +585,7 @@ public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation * * @return void */ - public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation) + public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void { $package = $operation->getPackage(); @@ -602,7 +602,7 @@ public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAlias * * @return void */ - public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation) + public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void { $package = $operation->getPackage(); @@ -615,7 +615,7 @@ public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAli * @param PackageInterface $package * @return string path */ - public function getInstallPath(PackageInterface $package) + public function getInstallPath(PackageInterface $package): string { $installer = $this->getInstaller($package->getType()); @@ -627,7 +627,7 @@ public function getInstallPath(PackageInterface $package) * * @return void */ - public function setOutputProgress($outputProgress) + public function setOutputProgress(bool $outputProgress): void { $this->outputProgress = $outputProgress; } @@ -635,7 +635,7 @@ public function setOutputProgress($outputProgress) /** * @return void */ - public function notifyInstalls(IOInterface $io) + public function notifyInstalls(IOInterface $io): void { $promises = array(); diff --git a/src/Composer/Installer/InstallerEvent.php b/src/Composer/Installer/InstallerEvent.php index ee81754d9eea..cafd0dc1b31a 100644 --- a/src/Composer/Installer/InstallerEvent.php +++ b/src/Composer/Installer/InstallerEvent.php @@ -54,7 +54,7 @@ class InstallerEvent extends Event * @param bool $executeOperations * @param Transaction $transaction */ - public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, $executeOperations, Transaction $transaction) + public function __construct(string $eventName, Composer $composer, IOInterface $io, bool $devMode, bool $executeOperations, Transaction $transaction) { parent::__construct($eventName); @@ -68,7 +68,7 @@ public function __construct($eventName, Composer $composer, IOInterface $io, $de /** * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -76,7 +76,7 @@ public function getComposer() /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -84,7 +84,7 @@ public function getIO() /** * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } @@ -92,7 +92,7 @@ public function isDevMode() /** * @return bool */ - public function isExecutingOperations() + public function isExecutingOperations(): bool { return $this->executeOperations; } @@ -100,7 +100,7 @@ public function isExecutingOperations() /** * @return Transaction|null */ - public function getTransaction() + public function getTransaction(): ?Transaction { return $this->transaction; } diff --git a/src/Composer/Installer/InstallerInterface.php b/src/Composer/Installer/InstallerInterface.php index fd3015e83f2a..8ddbed4e6d81 100644 --- a/src/Composer/Installer/InstallerInterface.php +++ b/src/Composer/Installer/InstallerInterface.php @@ -31,7 +31,7 @@ interface InstallerInterface * @param string $packageType * @return bool */ - public function supports($packageType); + public function supports(string $packageType); /** * Checks that provided package is installed. @@ -65,7 +65,7 @@ public function download(PackageInterface $package, PackageInterface $prevPackag * @param PackageInterface $prevPackage previous package instance in case of an update * @return PromiseInterface|null */ - public function prepare($type, PackageInterface $package, PackageInterface $prevPackage = null); + public function prepare(string $type, PackageInterface $package, PackageInterface $prevPackage = null); /** * Installs specific package. @@ -108,7 +108,7 @@ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $ * @param PackageInterface $prevPackage previous package instance in case of an update * @return PromiseInterface|null */ - public function cleanup($type, PackageInterface $package, PackageInterface $prevPackage = null); + public function cleanup(string $type, PackageInterface $package, PackageInterface $prevPackage = null); /** * Returns the absolute installation path of a package. diff --git a/src/Composer/Installer/LibraryInstaller.php b/src/Composer/Installer/LibraryInstaller.php index f5525341d948..7d88a6d9b083 100644 --- a/src/Composer/Installer/LibraryInstaller.php +++ b/src/Composer/Installer/LibraryInstaller.php @@ -56,7 +56,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface * @param Filesystem $filesystem * @param BinaryInstaller $binaryInstaller */ - public function __construct(IOInterface $io, PartialComposer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null) + public function __construct(IOInterface $io, PartialComposer $composer, ?string $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null) { $this->composer = $composer; $this->downloadManager = $composer instanceof Composer ? $composer->getDownloadManager() : null; diff --git a/src/Composer/Installer/PackageEvent.php b/src/Composer/Installer/PackageEvent.php index ac91459432e5..55029fb9319f 100644 --- a/src/Composer/Installer/PackageEvent.php +++ b/src/Composer/Installer/PackageEvent.php @@ -66,7 +66,7 @@ class PackageEvent extends Event * @param OperationInterface[] $operations * @param OperationInterface $operation */ - public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation) + public function __construct(string $eventName, Composer $composer, IOInterface $io, bool $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation) { parent::__construct($eventName); @@ -81,7 +81,7 @@ public function __construct($eventName, Composer $composer, IOInterface $io, $de /** * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -89,7 +89,7 @@ public function getComposer() /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -97,7 +97,7 @@ public function getIO() /** * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } @@ -105,7 +105,7 @@ public function isDevMode() /** * @return RepositoryInterface */ - public function getLocalRepo() + public function getLocalRepo(): RepositoryInterface { return $this->localRepo; } @@ -113,7 +113,7 @@ public function getLocalRepo() /** * @return OperationInterface[] */ - public function getOperations() + public function getOperations(): array { return $this->operations; } @@ -123,7 +123,7 @@ public function getOperations() * * @return OperationInterface */ - public function getOperation() + public function getOperation(): OperationInterface { return $this->operation; } diff --git a/src/Composer/Installer/ProjectInstaller.php b/src/Composer/Installer/ProjectInstaller.php index 7e31fdaf99c6..60c499f95db1 100644 --- a/src/Composer/Installer/ProjectInstaller.php +++ b/src/Composer/Installer/ProjectInstaller.php @@ -36,7 +36,7 @@ class ProjectInstaller implements InstallerInterface /** * @param string $installPath */ - public function __construct($installPath, DownloadManager $dm, Filesystem $fs) + public function __construct(string $installPath, DownloadManager $dm, Filesystem $fs) { $this->installPath = rtrim(strtr($installPath, '\\', '/'), '/').'/'; $this->downloadManager = $dm; @@ -49,7 +49,7 @@ public function __construct($installPath, DownloadManager $dm, Filesystem $fs) * @param string $packageType * @return bool */ - public function supports($packageType): bool + public function supports(string $packageType): bool { return true; } diff --git a/src/Composer/Installer/SuggestedPackagesReporter.php b/src/Composer/Installer/SuggestedPackagesReporter.php index 17e51b5f6567..3b1c92651b32 100644 --- a/src/Composer/Installer/SuggestedPackagesReporter.php +++ b/src/Composer/Installer/SuggestedPackagesReporter.php @@ -63,7 +63,7 @@ public function getPackages(): array * @param string $reason Reason the target package to be suggested * @return SuggestedPackagesReporter */ - public function addPackage($source, $target, $reason): SuggestedPackagesReporter + public function addPackage(string $source, string $target, string $reason): SuggestedPackagesReporter { $this->suggestedPackages[] = array( 'source' => $source, @@ -104,7 +104,7 @@ public function addSuggestionsFromPackage(PackageInterface $package): SuggestedP * @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown * @return void */ - public function output($mode, InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null): void + public function output(int $mode, InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null): void { $suggestedPackages = $this->getFilteredSuggestions($installedRepo, $onlyDependentsOf); @@ -220,7 +220,7 @@ private function getFilteredSuggestions(InstalledRepository $installedRepo = nul * @param string $string * @return string */ - private function escapeOutput($string): string + private function escapeOutput(string $string): string { return OutputFormatter::escape( $this->removeControlCharacters($string) @@ -231,7 +231,7 @@ private function escapeOutput($string): string * @param string $string * @return string */ - private function removeControlCharacters($string): string + private function removeControlCharacters(string $string): string { return Preg::replace( '/[[:cntrl:]]/', diff --git a/src/Composer/Json/JsonFile.php b/src/Composer/Json/JsonFile.php index aa81fb61a62a..3ec407f8a7e5 100644 --- a/src/Composer/Json/JsonFile.php +++ b/src/Composer/Json/JsonFile.php @@ -55,7 +55,7 @@ class JsonFile * @param ?IOInterface $io * @throws \InvalidArgumentException */ - public function __construct($path, HttpDownloader $httpDownloader = null, IOInterface $io = null) + public function __construct(string $path, HttpDownloader $httpDownloader = null, IOInterface $io = null) { $this->path = $path; @@ -69,7 +69,7 @@ public function __construct($path, HttpDownloader $httpDownloader = null, IOInte /** * @return string */ - public function getPath() + public function getPath(): string { return $this->path; } @@ -79,7 +79,7 @@ public function getPath() * * @return bool */ - public function exists() + public function exists(): bool { return is_file($this->path); } @@ -124,7 +124,7 @@ public function read() * @throws \UnexpectedValueException|\Exception * @return void */ - public function write(array $hash, $options = JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) + public function write(array $hash, int $options = JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) { if ($this->path === 'php://memory') { file_put_contents($this->path, static::encode($hash, $options)); @@ -169,7 +169,7 @@ public function write(array $hash, $options = JSON_UNESCAPED_SLASHES | JSON_PRET * @param string $content * @return int|false */ - private function filePutContentsIfModified($path, $content) + private function filePutContentsIfModified(string $path, string $content) { $currentContent = @file_get_contents($path); if (!$currentContent || ($currentContent != $content)) { @@ -188,7 +188,7 @@ private function filePutContentsIfModified($path, $content) * @throws ParsingException * @return bool true on success */ - public function validateSchema($schema = self::STRICT_SCHEMA, $schemaFile = null) + public function validateSchema(int $schema = self::STRICT_SCHEMA, ?string $schemaFile = null): bool { $content = file_get_contents($this->path); $data = json_decode($content); @@ -239,7 +239,7 @@ public function validateSchema($schema = self::STRICT_SCHEMA, $schemaFile = null * @param int $options json_encode options (defaults to JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) * @return string Encoded json */ - public static function encode($data, $options = 448) + public static function encode($data, int $options = 448) { $json = json_encode($data, $options); if (false === $json) { @@ -256,7 +256,7 @@ public static function encode($data, $options = 448) * @throws \RuntimeException * @return void */ - private static function throwEncodeError($code): void + private static function throwEncodeError(int $code): void { switch ($code) { case JSON_ERROR_DEPTH: @@ -281,13 +281,13 @@ private static function throwEncodeError($code): void /** * Parses json string and returns hash. * - * @param ?string $json json string + * @param null|string $json json string * @param string $file the json file * * @throws ParsingException * @return mixed */ - public static function parseJson($json, $file = null) + public static function parseJson(?string $json, string $file = null) { if (null === $json) { return null; @@ -309,7 +309,7 @@ public static function parseJson($json, $file = null) * @throws ParsingException * @return bool true on success */ - protected static function validateSyntax($json, $file = null) + protected static function validateSyntax(string $json, string $file = null): bool { $parser = new JsonParser(); $result = $parser->lint($json); diff --git a/src/Composer/Json/JsonFormatter.php b/src/Composer/Json/JsonFormatter.php index dd705db78f3b..de6882689511 100644 --- a/src/Composer/Json/JsonFormatter.php +++ b/src/Composer/Json/JsonFormatter.php @@ -38,7 +38,7 @@ class JsonFormatter * @param bool $unescapeSlashes Un escape slashes * @return string */ - public static function format($json, $unescapeUnicode, $unescapeSlashes): string + public static function format(string $json, bool $unescapeUnicode, bool $unescapeSlashes): string { $result = ''; $pos = 0; diff --git a/src/Composer/Json/JsonManipulator.php b/src/Composer/Json/JsonManipulator.php index 8a309086d6de..4a8781c648ef 100644 --- a/src/Composer/Json/JsonManipulator.php +++ b/src/Composer/Json/JsonManipulator.php @@ -41,7 +41,7 @@ class JsonManipulator /** * @param string $contents */ - public function __construct($contents) + public function __construct(string $contents) { $contents = trim($contents); if ($contents === '') { @@ -58,7 +58,7 @@ public function __construct($contents) /** * @return string */ - public function getContents() + public function getContents(): string { return $this->contents . $this->newline; } @@ -70,7 +70,7 @@ public function getContents() * @param bool $sortPackages * @return bool */ - public function addLink($type, $package, $constraint, $sortPackages = false) + public function addLink(string $type, string $package, string $constraint, bool $sortPackages = false): bool { $decoded = JsonFile::parseJson($this->contents); @@ -165,12 +165,12 @@ private function sortPackages(array &$packages = array()): void } /** - * @param string $name - * @param array $config - * @param bool $append + * @param string $name + * @param array|false $config + * @param bool $append * @return bool */ - public function addRepository($name, $config, $append = true) + public function addRepository(string $name, $config, bool $append = true): bool { return $this->addSubNode('repositories', $name, $config, $append); } @@ -179,7 +179,7 @@ public function addRepository($name, $config, $append = true) * @param string $name * @return bool */ - public function removeRepository($name) + public function removeRepository(string $name): bool { return $this->removeSubNode('repositories', $name); } @@ -189,7 +189,7 @@ public function removeRepository($name) * @param mixed $value * @return bool */ - public function addConfigSetting($name, $value) + public function addConfigSetting(string $name, $value): bool { return $this->addSubNode('config', $name, $value); } @@ -198,7 +198,7 @@ public function addConfigSetting($name, $value) * @param string $name * @return bool */ - public function removeConfigSetting($name) + public function removeConfigSetting(string $name): bool { return $this->removeSubNode('config', $name); } @@ -208,7 +208,7 @@ public function removeConfigSetting($name) * @param mixed $value * @return bool */ - public function addProperty($name, $value) + public function addProperty(string $name, $value): bool { if (strpos($name, 'suggest.') === 0) { return $this->addSubNode('suggest', substr($name, 8), $value); @@ -229,7 +229,7 @@ public function addProperty($name, $value) * @param string $name * @return bool */ - public function removeProperty($name) + public function removeProperty(string $name): bool { if (strpos($name, 'suggest.') === 0) { return $this->removeSubNode('suggest', substr($name, 8)); @@ -253,7 +253,7 @@ public function removeProperty($name) * @param bool $append * @return bool */ - public function addSubNode($mainNode, $name, $value, $append = true) + public function addSubNode(string $mainNode, string $name, $value, bool $append = true): bool { $decoded = JsonFile::parseJson($this->contents); @@ -363,7 +363,7 @@ public function addSubNode($mainNode, $name, $value, $append = true) * @param string $name * @return bool */ - public function removeSubNode($mainNode, $name) + public function removeSubNode(string $mainNode, string $name): bool { $decoded = JsonFile::parseJson($this->contents); @@ -468,7 +468,7 @@ public function removeSubNode($mainNode, $name) * @param mixed $content * @return bool */ - public function addMainKey($key, $content) + public function addMainKey(string $key, $content): bool { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); @@ -512,7 +512,7 @@ public function addMainKey($key, $content) * @param string $key * @return bool */ - public function removeMainKey($key) + public function removeMainKey(string $key): bool { $decoded = JsonFile::parseJson($this->contents); @@ -549,7 +549,7 @@ public function removeMainKey($key) * @param string $key * @return bool */ - public function removeMainKeyIfEmpty($key) + public function removeMainKeyIfEmpty(string $key): bool { $decoded = JsonFile::parseJson($this->contents); @@ -569,7 +569,7 @@ public function removeMainKeyIfEmpty($key) * @param int $depth * @return string */ - public function format($data, $depth = 0) + public function format($data, int $depth = 0): string { if (is_array($data)) { reset($data); @@ -597,7 +597,7 @@ public function format($data, $depth = 0) /** * @return void */ - protected function detectIndenting() + protected function detectIndenting(): void { if (Preg::isMatch('{^([ \t]+)"}m', $this->contents, $match)) { $this->indent = $match[1]; diff --git a/src/Composer/Json/JsonValidationException.php b/src/Composer/Json/JsonValidationException.php index 35f61d32d94d..1187b2f99d71 100644 --- a/src/Composer/Json/JsonValidationException.php +++ b/src/Composer/Json/JsonValidationException.php @@ -28,7 +28,7 @@ class JsonValidationException extends Exception * @param string $message * @param string[] $errors */ - public function __construct($message, array $errors = array(), Exception $previous = null) + public function __construct(string $message, array $errors = array(), Exception $previous = null) { $this->errors = $errors; parent::__construct((string) $message, 0, $previous); diff --git a/src/Composer/Package/AliasPackage.php b/src/Composer/Package/AliasPackage.php index 5c2645eb1da1..332c1fe05ac5 100644 --- a/src/Composer/Package/AliasPackage.php +++ b/src/Composer/Package/AliasPackage.php @@ -56,7 +56,7 @@ class AliasPackage extends BasePackage * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ - public function __construct(BasePackage $aliasOf, $version, $prettyVersion) + public function __construct(BasePackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf->getName()); @@ -159,14 +159,10 @@ public function getDevRequires(): array * Stores whether this is an alias created by an aliasing in the requirements of the root package or not * * Use by the policy for sorting manually aliased packages first, see #576 - * - * @param bool $value - * - * @return mixed */ - public function setRootPackageAlias($value) + public function setRootPackageAlias(bool $value): void { - return $this->rootPackageAlias = $value; + $this->rootPackageAlias = $value; } /** @@ -225,7 +221,7 @@ public function hasSelfVersionRequires(): bool return $this->hasSelfVersionRequires; } - public function __toString() + public function __toString(): string { return parent::__toString().' ('.($this->rootPackageAlias ? 'root ' : ''). 'alias of '.$this->aliasOf->getVersion().')'; } @@ -249,7 +245,7 @@ public function getExtra(): array return $this->aliasOf->getExtra(); } - public function setInstallationSource($type): void + public function setInstallationSource(?string $type): void { $this->aliasOf->setInstallationSource($type); } @@ -279,12 +275,12 @@ public function getSourceReference(): ?string return $this->aliasOf->getSourceReference(); } - public function setSourceReference($reference): void + public function setSourceReference(?string $reference): void { $this->aliasOf->setSourceReference($reference); } - public function setSourceMirrors($mirrors): void + public function setSourceMirrors(?array $mirrors): void { $this->aliasOf->setSourceMirrors($mirrors); } @@ -314,7 +310,7 @@ public function getDistReference(): ?string return $this->aliasOf->getDistReference(); } - public function setDistReference($reference): void + public function setDistReference(?string $reference): void { $this->aliasOf->setDistReference($reference); } @@ -334,7 +330,7 @@ public function getTransportOptions(): array return $this->aliasOf->getTransportOptions(); } - public function setDistMirrors($mirrors): void + public function setDistMirrors(?array $mirrors): void { $this->aliasOf->setDistMirrors($mirrors); } @@ -359,7 +355,7 @@ public function getIncludePaths(): array return $this->aliasOf->getIncludePaths(); } - public function getReleaseDate(): ?\DateTime + public function getReleaseDate(): ?\DateTimeInterface { return $this->aliasOf->getReleaseDate(); } @@ -384,17 +380,17 @@ public function isDefaultBranch(): bool return $this->aliasOf->isDefaultBranch(); } - public function setDistUrl($url): void + public function setDistUrl(?string $url): void { $this->aliasOf->setDistUrl($url); } - public function setDistType($type): void + public function setDistType(?string $type): void { $this->aliasOf->setDistType($type); } - public function setSourceDistReferences($reference): void + public function setSourceDistReferences(string $reference): void { $this->aliasOf->setSourceDistReferences($reference); } diff --git a/src/Composer/Package/Archiver/ArchivableFilesFilter.php b/src/Composer/Package/Archiver/ArchivableFilesFilter.php index 9a5be1a197db..8af84271d668 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFilter.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFilter.php @@ -40,7 +40,7 @@ public function accept(): bool * * @return void */ - public function addEmptyDir(PharData $phar, $sources): void + public function addEmptyDir(PharData $phar, string $sources): void { foreach ($this->dirs as $filepath) { $localname = str_replace($sources . "/", '', $filepath); diff --git a/src/Composer/Package/Archiver/ArchivableFilesFinder.php b/src/Composer/Package/Archiver/ArchivableFilesFinder.php index 31e81e295fa8..fd589d7a2a67 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFinder.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFinder.php @@ -40,7 +40,7 @@ class ArchivableFilesFinder extends \FilterIterator * @param string[] $excludes Composer's own exclude rules from composer.json * @param bool $ignoreFilters Ignore filters when looking for files */ - public function __construct($sources, array $excludes, $ignoreFilters = false) + public function __construct(string $sources, array $excludes, bool $ignoreFilters = false) { $fs = new Filesystem(); diff --git a/src/Composer/Package/Archiver/ArchiveManager.php b/src/Composer/Package/Archiver/ArchiveManager.php index de8ff52e8a67..c7f5def613b1 100644 --- a/src/Composer/Package/Archiver/ArchiveManager.php +++ b/src/Composer/Package/Archiver/ArchiveManager.php @@ -68,7 +68,7 @@ public function addArchiver(ArchiverInterface $archiver): void * * @return $this */ - public function setOverwriteFiles($overwriteFiles) + public function setOverwriteFiles(bool $overwriteFiles): self { $this->overwriteFiles = $overwriteFiles; @@ -121,7 +121,7 @@ public function getPackageFilename(CompletePackageInterface $package): string * @throws \RuntimeException * @return string The path of the created archive */ - public function archive(CompletePackageInterface $package, $format, $targetDir, $fileName = null, $ignoreFilters = false): string + public function archive(CompletePackageInterface $package, string $format, string $targetDir, ?string $fileName = null, bool $ignoreFilters = false): string { if (empty($format)) { throw new \InvalidArgumentException('Format must be specified'); diff --git a/src/Composer/Package/Archiver/ArchiverInterface.php b/src/Composer/Package/Archiver/ArchiverInterface.php index a9038ca76c1e..f18e8b45f2c5 100644 --- a/src/Composer/Package/Archiver/ArchiverInterface.php +++ b/src/Composer/Package/Archiver/ArchiverInterface.php @@ -30,7 +30,7 @@ interface ArchiverInterface * * @return string The path to the written archive file */ - public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false): string; + public function archive(string $sources, string $target, string $format, array $excludes = array(), bool $ignoreFilters = false): string; /** * Format supported by the archiver. @@ -40,5 +40,5 @@ public function archive($sources, $target, $format, array $excludes = array(), $ * * @return bool true if the format is supported by the archiver */ - public function supports($format, $sourceType): bool; + public function supports(string $format, string $sourceType): bool; } diff --git a/src/Composer/Package/Archiver/BaseExcludeFilter.php b/src/Composer/Package/Archiver/BaseExcludeFilter.php index 2fbd22796a48..21a8db5d81f9 100644 --- a/src/Composer/Package/Archiver/BaseExcludeFilter.php +++ b/src/Composer/Package/Archiver/BaseExcludeFilter.php @@ -33,7 +33,7 @@ abstract class BaseExcludeFilter /** * @param string $sourcePath Directory containing sources to be filtered */ - public function __construct($sourcePath) + public function __construct(string $sourcePath) { $this->sourcePath = $sourcePath; $this->excludePatterns = array(); @@ -49,7 +49,7 @@ public function __construct($sourcePath) * * @return bool Whether the file should be excluded */ - public function filter($relativePath, $exclude): bool + public function filter(string $relativePath, bool $exclude): bool { foreach ($this->excludePatterns as $patternData) { list($pattern, $negate, $stripLeadingSlash) = $patternData; @@ -80,7 +80,7 @@ public function filter($relativePath, $exclude): bool * * @return array Exclude patterns to be used in filter() */ - protected function parseLines(array $lines, $lineParser): array + protected function parseLines(array $lines, callable $lineParser): array { return array_filter( array_map( @@ -108,7 +108,7 @@ function ($pattern): bool { * * @return array Exclude patterns */ - protected function generatePatterns($rules): array + protected function generatePatterns(array $rules): array { $patterns = array(); foreach ($rules as $rule) { @@ -125,7 +125,7 @@ protected function generatePatterns($rules): array * * @return array{0: non-empty-string, 1: bool, 2: bool} An exclude pattern */ - protected function generatePattern($rule): array + protected function generatePattern(string $rule): array { $negate = false; $pattern = ''; diff --git a/src/Composer/Package/Archiver/ComposerExcludeFilter.php b/src/Composer/Package/Archiver/ComposerExcludeFilter.php index 3a5a5179dcc2..07d1e162dd06 100644 --- a/src/Composer/Package/Archiver/ComposerExcludeFilter.php +++ b/src/Composer/Package/Archiver/ComposerExcludeFilter.php @@ -23,7 +23,7 @@ class ComposerExcludeFilter extends BaseExcludeFilter * @param string $sourcePath Directory containing sources to be filtered * @param string[] $excludeRules An array of exclude rules from composer.json */ - public function __construct($sourcePath, array $excludeRules) + public function __construct(string $sourcePath, array $excludeRules) { parent::__construct($sourcePath); $this->excludePatterns = $this->generatePatterns($excludeRules); diff --git a/src/Composer/Package/Archiver/GitExcludeFilter.php b/src/Composer/Package/Archiver/GitExcludeFilter.php index 351ca4e7def1..d81dc7693514 100644 --- a/src/Composer/Package/Archiver/GitExcludeFilter.php +++ b/src/Composer/Package/Archiver/GitExcludeFilter.php @@ -28,7 +28,7 @@ class GitExcludeFilter extends BaseExcludeFilter * * @param string $sourcePath */ - public function __construct($sourcePath) + public function __construct(string $sourcePath) { parent::__construct($sourcePath); @@ -50,7 +50,7 @@ public function __construct($sourcePath) * * @return array{0: string, 1: bool, 2: bool}|null An exclude pattern for filter() */ - public function parseGitAttributesLine($line): ?array + public function parseGitAttributesLine(string $line): ?array { $parts = Preg::split('#\s+#', $line); diff --git a/src/Composer/Package/BasePackage.php b/src/Composer/Package/BasePackage.php index f46cec9fdf64..35be9e75ada5 100644 --- a/src/Composer/Package/BasePackage.php +++ b/src/Composer/Package/BasePackage.php @@ -68,7 +68,7 @@ abstract class BasePackage implements PackageInterface * * @param string $name The package's name */ - public function __construct($name) + public function __construct(string $name) { $this->prettyName = $name; $this->name = strtolower($name); @@ -78,7 +78,7 @@ public function __construct($name) /** * @inheritDoc */ - public function getName() + public function getName(): string { return $this->name; } @@ -86,7 +86,7 @@ public function getName() /** * @inheritDoc */ - public function getPrettyName() + public function getPrettyName(): string { return $this->prettyName; } @@ -94,7 +94,7 @@ public function getPrettyName() /** * @inheritDoc */ - public function getNames($provides = true) + public function getNames($provides = true): array { $names = array( $this->getName() => true, @@ -116,7 +116,7 @@ public function getNames($provides = true) /** * @inheritDoc */ - public function setId($id) + public function setId(int $id): void { $this->id = $id; } @@ -124,7 +124,7 @@ public function setId($id) /** * @inheritDoc */ - public function getId() + public function getId(): int { return $this->id; } @@ -132,7 +132,7 @@ public function getId() /** * @inheritDoc */ - public function setRepository(RepositoryInterface $repository) + public function setRepository(RepositoryInterface $repository): void { if ($this->repository && $repository !== $this->repository) { throw new \LogicException('A package can only be added to one repository'); @@ -143,7 +143,7 @@ public function setRepository(RepositoryInterface $repository) /** * @inheritDoc */ - public function getRepository() + public function getRepository(): ?RepositoryInterface { return $this->repository; } @@ -153,7 +153,7 @@ public function getRepository() * * @return bool */ - public function isPlatform() + public function isPlatform(): bool { return $this->getRepository() instanceof PlatformRepository; } @@ -163,7 +163,7 @@ public function isPlatform() * * @return string */ - public function getUniqueName() + public function getUniqueName(): string { return $this->getName().'-'.$this->getVersion(); } @@ -171,7 +171,7 @@ public function getUniqueName() /** * @return bool */ - public function equals(PackageInterface $package) + public function equals(PackageInterface $package): bool { $self = $this; if ($this instanceof AliasPackage) { @@ -189,12 +189,12 @@ public function equals(PackageInterface $package) * * @return string */ - public function __toString() + public function __toString(): string { return $this->getUniqueName(); } - public function getPrettyString() + public function getPrettyString(): string { return $this->getPrettyName().' '.$this->getPrettyVersion(); } @@ -202,7 +202,7 @@ public function getPrettyString() /** * @inheritDoc */ - public function getFullPrettyVersion($truncate = true, $displayMode = PackageInterface::DISPLAY_SOURCE_REF_IF_DEV) + public function getFullPrettyVersion(bool $truncate = true, int $displayMode = PackageInterface::DISPLAY_SOURCE_REF_IF_DEV): string { if ($displayMode === PackageInterface::DISPLAY_SOURCE_REF_IF_DEV && (!$this->isDev() || !\in_array($this->getSourceType(), array('hg', 'git'))) @@ -239,7 +239,7 @@ public function getFullPrettyVersion($truncate = true, $displayMode = PackageInt * * @phpstan-return self::STABILITY_* */ - public function getStabilityPriority() + public function getStabilityPriority(): int { return self::$stabilities[$this->getStability()]; } @@ -257,7 +257,7 @@ public function __clone() * @param non-empty-string $wrap Wrap the cleaned string by the given string * @return non-empty-string */ - public static function packageNameToRegexp($allowPattern, $wrap = '{^%s$}i') + public static function packageNameToRegexp(string $allowPattern, string $wrap = '{^%s$}i'): string { $cleanedAllowPattern = str_replace('\\*', '.*', preg_quote($allowPattern)); @@ -271,7 +271,7 @@ public static function packageNameToRegexp($allowPattern, $wrap = '{^%s$}i') * @param non-empty-string $wrap * @return non-empty-string */ - public static function packageNamesToRegexp(array $packageNames, $wrap = '{^(?:%s)$}iD') + public static function packageNamesToRegexp(array $packageNames, string $wrap = '{^(?:%s)$}iD'): string { $packageNames = array_map( function ($packageName): string { diff --git a/src/Composer/Package/Comparer/Comparer.php b/src/Composer/Package/Comparer/Comparer.php index d7c2a5fc7d97..d9d5a20f10ca 100644 --- a/src/Composer/Package/Comparer/Comparer.php +++ b/src/Composer/Package/Comparer/Comparer.php @@ -12,6 +12,8 @@ namespace Composer\Package\Comparer; +use Composer\Util\Platform; + /** * class Comparer * @@ -31,7 +33,7 @@ class Comparer * * @return void */ - public function setSource($source): void + public function setSource(string $source): void { $this->source = $source; } @@ -41,7 +43,7 @@ public function setSource($source): void * * @return void */ - public function setUpdate($update): void + public function setUpdate(string $update): void { $this->update = $update; } @@ -52,7 +54,7 @@ public function setUpdate($update): void * * @return array{changed?: string[], removed?: string[], added?: string[]}|string|false false if no change, string only if $toString is true */ - public function getChanged($toString = false, $explicated = false) + public function getChanged(bool $toString = false, bool $explicated = false) { $changed = $this->changed; if (!count($changed)) { @@ -87,7 +89,7 @@ public function doCompare(): void $source = array(); $destination = array(); $this->changed = array(); - $currentDirectory = getcwd(); + $currentDirectory = Platform::getCwd(); chdir($this->source); $source = $this->doTree('.', $source); if (!is_array($source)) { @@ -122,11 +124,11 @@ public function doCompare(): void /** * @param string $dir - * @param mixed $array + * @param mixed[] $array * * @return array>|false */ - private function doTree($dir, &$array) + private function doTree(string $dir, array &$array) { if ($dh = opendir($dir)) { while ($file = readdir($dh)) { diff --git a/src/Composer/Package/CompleteAliasPackage.php b/src/Composer/Package/CompleteAliasPackage.php index ea2dfad45454..f69ad6298e7b 100644 --- a/src/Composer/Package/CompleteAliasPackage.php +++ b/src/Composer/Package/CompleteAliasPackage.php @@ -27,7 +27,7 @@ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterf * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ - public function __construct(CompletePackage $aliasOf, $version, $prettyVersion) + public function __construct(CompletePackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf, $version, $prettyVersion); } @@ -85,7 +85,7 @@ public function getDescription(): ?string return $this->aliasOf->getDescription(); } - public function setDescription($description): void + public function setDescription(?string $description): void { $this->aliasOf->setDescription($description); } @@ -95,7 +95,7 @@ public function getHomepage(): ?string return $this->aliasOf->getHomepage(); } - public function setHomepage($homepage): void + public function setHomepage(?string $homepage): void { $this->aliasOf->setHomepage($homepage); } @@ -150,7 +150,7 @@ public function getArchiveName(): ?string return $this->aliasOf->getArchiveName(); } - public function setArchiveName($name): void + public function setArchiveName(?string $name): void { $this->aliasOf->setArchiveName($name); } diff --git a/src/Composer/Package/CompletePackage.php b/src/Composer/Package/CompletePackage.php index 5a6ec4cb2c3e..666f3b0c749f 100644 --- a/src/Composer/Package/CompletePackage.php +++ b/src/Composer/Package/CompletePackage.php @@ -47,7 +47,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setScripts(array $scripts) + public function setScripts(array $scripts): void { $this->scripts = $scripts; } @@ -55,7 +55,7 @@ public function setScripts(array $scripts) /** * @inheritDoc */ - public function getScripts() + public function getScripts(): array { return $this->scripts; } @@ -63,7 +63,7 @@ public function getScripts() /** * @inheritDoc */ - public function setRepositories(array $repositories) + public function setRepositories(array $repositories): void { $this->repositories = $repositories; } @@ -71,7 +71,7 @@ public function setRepositories(array $repositories) /** * @inheritDoc */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -79,7 +79,7 @@ public function getRepositories() /** * @inheritDoc */ - public function setLicense(array $license) + public function setLicense(array $license): void { $this->license = $license; } @@ -87,7 +87,7 @@ public function setLicense(array $license) /** * @inheritDoc */ - public function getLicense() + public function getLicense(): array { return $this->license; } @@ -95,7 +95,7 @@ public function getLicense() /** * @inheritDoc */ - public function setKeywords(array $keywords) + public function setKeywords(array $keywords): void { $this->keywords = $keywords; } @@ -103,7 +103,7 @@ public function setKeywords(array $keywords) /** * @inheritDoc */ - public function getKeywords() + public function getKeywords(): array { return $this->keywords; } @@ -111,7 +111,7 @@ public function getKeywords() /** * @inheritDoc */ - public function setAuthors(array $authors) + public function setAuthors(array $authors): void { $this->authors = $authors; } @@ -119,7 +119,7 @@ public function setAuthors(array $authors) /** * @inheritDoc */ - public function getAuthors() + public function getAuthors(): array { return $this->authors; } @@ -127,7 +127,7 @@ public function getAuthors() /** * @inheritDoc */ - public function setDescription($description) + public function setDescription(?string $description): void { $this->description = $description; } @@ -135,7 +135,7 @@ public function setDescription($description) /** * @inheritDoc */ - public function getDescription() + public function getDescription(): ?string { return $this->description; } @@ -143,7 +143,7 @@ public function getDescription() /** * @inheritDoc */ - public function setHomepage($homepage) + public function setHomepage(?string $homepage): void { $this->homepage = $homepage; } @@ -151,7 +151,7 @@ public function setHomepage($homepage) /** * @inheritDoc */ - public function getHomepage() + public function getHomepage(): ?string { return $this->homepage; } @@ -159,7 +159,7 @@ public function getHomepage() /** * @inheritDoc */ - public function setSupport(array $support) + public function setSupport(array $support): void { $this->support = $support; } @@ -167,7 +167,7 @@ public function setSupport(array $support) /** * @inheritDoc */ - public function getSupport() + public function getSupport(): array { return $this->support; } @@ -175,7 +175,7 @@ public function getSupport() /** * @inheritDoc */ - public function setFunding(array $funding) + public function setFunding(array $funding): void { $this->funding = $funding; } @@ -183,7 +183,7 @@ public function setFunding(array $funding) /** * @inheritDoc */ - public function getFunding() + public function getFunding(): array { return $this->funding; } @@ -191,7 +191,7 @@ public function getFunding() /** * @inheritDoc */ - public function isAbandoned() + public function isAbandoned(): bool { return (bool) $this->abandoned; } @@ -199,7 +199,7 @@ public function isAbandoned() /** * @inheritDoc */ - public function setAbandoned($abandoned) + public function setAbandoned($abandoned): void { $this->abandoned = $abandoned; } @@ -207,7 +207,7 @@ public function setAbandoned($abandoned) /** * @inheritDoc */ - public function getReplacementPackage() + public function getReplacementPackage(): ?string { return \is_string($this->abandoned) ? $this->abandoned : null; } @@ -215,7 +215,7 @@ public function getReplacementPackage() /** * @inheritDoc */ - public function setArchiveName($name) + public function setArchiveName(?string $name): void { $this->archiveName = $name; } @@ -223,7 +223,7 @@ public function setArchiveName($name) /** * @inheritDoc */ - public function getArchiveName() + public function getArchiveName(): ?string { return $this->archiveName; } @@ -231,7 +231,7 @@ public function getArchiveName() /** * @inheritDoc */ - public function setArchiveExcludes(array $excludes) + public function setArchiveExcludes(array $excludes): void { $this->archiveExcludes = $excludes; } @@ -239,7 +239,7 @@ public function setArchiveExcludes(array $excludes) /** * @inheritDoc */ - public function getArchiveExcludes() + public function getArchiveExcludes(): array { return $this->archiveExcludes; } diff --git a/src/Composer/Package/CompletePackageInterface.php b/src/Composer/Package/CompletePackageInterface.php index 00e4a088e8d3..35db9e3cb2fc 100644 --- a/src/Composer/Package/CompletePackageInterface.php +++ b/src/Composer/Package/CompletePackageInterface.php @@ -15,6 +15,8 @@ /** * Defines package metadata that is not necessarily needed for solving and installing packages * + * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. + * * @author Nils Adermann */ interface CompletePackageInterface extends PackageInterface @@ -24,20 +26,20 @@ interface CompletePackageInterface extends PackageInterface * * @return array Map of script name to array of handlers */ - public function getScripts(); + public function getScripts(): array; /** * @param array $scripts * @return void */ - public function setScripts(array $scripts); + public function setScripts(array $scripts): void; /** * Returns an array of repositories * * @return mixed[] Repositories */ - public function getRepositories(); + public function getRepositories(): array; /** * Set the repositories @@ -45,14 +47,14 @@ public function getRepositories(); * @param mixed[] $repositories * @return void */ - public function setRepositories(array $repositories); + public function setRepositories(array $repositories): void; /** * Returns the package license, e.g. MIT, BSD, GPL * * @return string[] The package licenses */ - public function getLicense(); + public function getLicense(): array; /** * Set the license @@ -60,14 +62,14 @@ public function getLicense(); * @param string[] $license * @return void */ - public function setLicense(array $license); + public function setLicense(array $license): void; /** * Returns an array of keywords relating to the package * * @return string[] */ - public function getKeywords(); + public function getKeywords(): array; /** * Set the keywords @@ -75,14 +77,14 @@ public function getKeywords(); * @param string[] $keywords * @return void */ - public function setKeywords(array $keywords); + public function setKeywords(array $keywords): void; /** * Returns the package description * * @return ?string */ - public function getDescription(); + public function getDescription(): ?string; /** * Set the description @@ -90,14 +92,14 @@ public function getDescription(); * @param string $description * @return void */ - public function setDescription($description); + public function setDescription(string $description): void; /** * Returns the package homepage * * @return ?string */ - public function getHomepage(); + public function getHomepage(): ?string; /** * Set the homepage @@ -105,7 +107,7 @@ public function getHomepage(); * @param string $homepage * @return void */ - public function setHomepage($homepage); + public function setHomepage(string $homepage): void; /** * Returns an array of authors of the package @@ -114,7 +116,7 @@ public function setHomepage($homepage); * * @return array */ - public function getAuthors(); + public function getAuthors(): array; /** * Set the authors @@ -122,14 +124,14 @@ public function getAuthors(); * @param array $authors * @return void */ - public function setAuthors(array $authors); + public function setAuthors(array $authors): void; /** * Returns the support information * * @return array{issues?: string, forum?: string, wiki?: string, source?: string, email?: string, irc?: string, docs?: string, rss?: string, chat?: string} */ - public function getSupport(); + public function getSupport(): array; /** * Set the support information @@ -137,7 +139,7 @@ public function getSupport(); * @param array{issues?: string, forum?: string, wiki?: string, source?: string, email?: string, irc?: string, docs?: string, rss?: string, chat?: string} $support * @return void */ - public function setSupport(array $support); + public function setSupport(array $support): void; /** * Returns an array of funding options for the package @@ -146,7 +148,7 @@ public function setSupport(array $support); * * @return array */ - public function getFunding(); + public function getFunding(): array; /** * Set the funding @@ -154,34 +156,34 @@ public function getFunding(); * @param array $funding * @return void */ - public function setFunding(array $funding); + public function setFunding(array $funding): void; /** * Returns if the package is abandoned or not * * @return bool */ - public function isAbandoned(); + public function isAbandoned(): bool; /** * If the package is abandoned and has a suggested replacement, this method returns it * * @return string|null */ - public function getReplacementPackage(); + public function getReplacementPackage(): ?string; /** * @param bool|string $abandoned * @return void */ - public function setAbandoned($abandoned); + public function setAbandoned($abandoned): void; /** * Returns default base filename for archive * * @return ?string */ - public function getArchiveName(); + public function getArchiveName(): ?string; /** * Sets default base filename for archive @@ -189,14 +191,14 @@ public function getArchiveName(); * @param string $name * @return void */ - public function setArchiveName($name); + public function setArchiveName(string $name): void; /** * Returns a list of patterns to exclude from package archives * * @return string[] */ - public function getArchiveExcludes(); + public function getArchiveExcludes(): array; /** * Sets a list of patterns to be excluded from archives @@ -204,5 +206,5 @@ public function getArchiveExcludes(); * @param string[] $excludes * @return void */ - public function setArchiveExcludes(array $excludes); + public function setArchiveExcludes(array $excludes): void; } diff --git a/src/Composer/Package/Dumper/ArrayDumper.php b/src/Composer/Package/Dumper/ArrayDumper.php index fd54a516fa69..e5ca23985499 100644 --- a/src/Composer/Package/Dumper/ArrayDumper.php +++ b/src/Composer/Package/Dumper/ArrayDumper.php @@ -87,7 +87,7 @@ public function dump(PackageInterface $package): array $data['suggest'] = $packages; } - if ($package->getReleaseDate()) { + if ($package->getReleaseDate() instanceof \DateTimeInterface) { $data['time'] = $package->getReleaseDate()->format(DATE_RFC3339); } diff --git a/src/Composer/Package/Link.php b/src/Composer/Package/Link.php index 8e613a565b85..481988c154f1 100644 --- a/src/Composer/Package/Link.php +++ b/src/Composer/Package/Link.php @@ -21,22 +21,22 @@ */ class Link { - const TYPE_REQUIRE = 'requires'; - const TYPE_DEV_REQUIRE = 'devRequires'; - const TYPE_PROVIDE = 'provides'; - const TYPE_CONFLICT = 'conflicts'; - const TYPE_REPLACE = 'replaces'; + public const TYPE_REQUIRE = 'requires'; + public const TYPE_DEV_REQUIRE = 'devRequires'; + public const TYPE_PROVIDE = 'provides'; + public const TYPE_CONFLICT = 'conflicts'; + public const TYPE_REPLACE = 'replaces'; /** * Special type * @internal */ - const TYPE_DOES_NOT_REQUIRE = 'does not require'; + public const TYPE_DOES_NOT_REQUIRE = 'does not require'; /** * TODO should be marked private once 5.3 is dropped * @private */ - const TYPE_UNKNOWN = 'relates to'; + private const TYPE_UNKNOWN = 'relates to'; /** * Will be converted into a constant once the min PHP version allows this @@ -89,11 +89,11 @@ class Link * @param string|null $prettyConstraint */ public function __construct( - $source, - $target, + string $source, + string $target, ConstraintInterface $constraint, $description = self::TYPE_UNKNOWN, - $prettyConstraint = null + ?string $prettyConstraint = null ) { $this->source = strtolower($source); $this->target = strtolower($target); @@ -150,7 +150,7 @@ public function getPrettyConstraint(): string /** * @return string */ - public function __toString() + public function __toString(): string { return $this->source.' '.$this->description.' '.$this->target.' ('.$this->constraint.')'; } diff --git a/src/Composer/Package/Loader/ArrayLoader.php b/src/Composer/Package/Loader/ArrayLoader.php index 16cede400e21..cd1f9e2bac73 100644 --- a/src/Composer/Package/Loader/ArrayLoader.php +++ b/src/Composer/Package/Loader/ArrayLoader.php @@ -37,7 +37,7 @@ class ArrayLoader implements LoaderInterface /** * @param bool $loadOptions */ - public function __construct(VersionParser $parser = null, $loadOptions = false) + public function __construct(VersionParser $parser = null, bool $loadOptions = false) { if (!$parser) { $parser = new VersionParser; @@ -49,7 +49,7 @@ public function __construct(VersionParser $parser = null, $loadOptions = false) /** * @inheritDoc */ - public function load(array $config, $class = 'Composer\Package\CompletePackage') + public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage { if ($class !== 'Composer\Package\CompletePackage' && $class !== 'Composer\Package\RootPackage') { trigger_error('The $class arg is deprecated, please reach out to Composer maintainers ASAP if you still need this.', E_USER_DEPRECATED); @@ -81,7 +81,7 @@ public function load(array $config, $class = 'Composer\Package\CompletePackage') * * @return list */ - public function loadPackages(array $versions) + public function loadPackages(array $versions): array { $packages = array(); $linkCache = array(); @@ -99,7 +99,7 @@ public function loadPackages(array $versions) } /** - * @template PackageClass of CompletePackageInterface + * @template PackageClass of CompletePackage * * @param mixed[] $config package data * @param string $class FQCN to be instantiated @@ -108,7 +108,7 @@ public function loadPackages(array $versions) * * @phpstan-param class-string $class */ - private function createObject(array $config, $class) + private function createObject(array $config, string $class): CompletePackage { if (!isset($config['name'])) { throw new \UnexpectedValueException('Unknown package has no name defined ('.json_encode($config).').'); @@ -141,7 +141,7 @@ private function createObject(array $config, $class) * * @return RootPackage|RootAliasPackage|CompletePackage|CompleteAliasPackage */ - private function configureObject(PackageInterface $package, array $config) + private function configureObject(PackageInterface $package, array $config): BasePackage { if (!$package instanceof CompletePackage) { throw new \LogicException('ArrayLoader expects instances of the Composer\Package\CompletePackage class to function correctly'); @@ -321,7 +321,7 @@ private function configureObject(PackageInterface $package, array $config) * * @return void */ - private function configureCachedLinks(&$linkCache, $package, array $config): void + private function configureCachedLinks(array &$linkCache, PackageInterface $package, array $config): void { $name = $package->getName(); $prettyVersion = $package->getPrettyVersion(); @@ -366,7 +366,7 @@ private function configureCachedLinks(&$linkCache, $package, array $config): voi * * @phpstan-param Link::TYPE_* $description */ - public function parseLinks($source, $sourceVersion, $description, $links) + public function parseLinks(string $source, string $sourceVersion, string $description, array $links): array { $res = array(); foreach ($links as $target => $constraint) { @@ -385,7 +385,7 @@ public function parseLinks($source, $sourceVersion, $description, $links) * @param string $prettyConstraint constraint string * @return Link */ - private function createLink($source, $sourceVersion, $description, $target, $prettyConstraint): Link + private function createLink(string $source, string $sourceVersion, string $description, string $target, string $prettyConstraint): Link { if (!\is_string($prettyConstraint)) { throw new \UnexpectedValueException('Link constraint in '.$source.' '.$description.' > '.$target.' should be a string, got '.\gettype($prettyConstraint) . ' (' . var_export($prettyConstraint, true) . ')'); @@ -406,7 +406,7 @@ private function createLink($source, $sourceVersion, $description, $target, $pre * * @return string|null normalized version of the branch alias or null if there is none */ - public function getBranchAlias(array $config) + public function getBranchAlias(array $config): ?string { if (strpos($config['version'], 'dev-') !== 0 && '-dev' !== substr($config['version'], -4)) { return null; diff --git a/src/Composer/Package/Loader/JsonLoader.php b/src/Composer/Package/Loader/JsonLoader.php index 9e9ae689efeb..4bfeaff8b8ba 100644 --- a/src/Composer/Package/Loader/JsonLoader.php +++ b/src/Composer/Package/Loader/JsonLoader.php @@ -13,8 +13,11 @@ namespace Composer\Package\Loader; use Composer\Json\JsonFile; +use Composer\Package\BasePackage; use Composer\Package\CompletePackage; use Composer\Package\CompleteAliasPackage; +use Composer\Package\RootPackage; +use Composer\Package\RootAliasPackage; /** * @author Konstantin Kudryashiv @@ -31,9 +34,9 @@ public function __construct(LoaderInterface $loader) /** * @param string|JsonFile $json A filename, json string or JsonFile instance to load the package from - * @return CompletePackage|CompleteAliasPackage + * @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage */ - public function load($json) + public function load($json): BasePackage { if ($json instanceof JsonFile) { $config = $json->read(); diff --git a/src/Composer/Package/Loader/LoaderInterface.php b/src/Composer/Package/Loader/LoaderInterface.php index 9a89d68aaacd..c81176ded91d 100644 --- a/src/Composer/Package/Loader/LoaderInterface.php +++ b/src/Composer/Package/Loader/LoaderInterface.php @@ -17,6 +17,7 @@ use Composer\Package\CompleteAliasPackage; use Composer\Package\RootAliasPackage; use Composer\Package\RootPackage; +use Composer\Package\BasePackage; /** * Defines a loader that takes an array to create package instances @@ -28,14 +29,12 @@ interface LoaderInterface /** * Converts a package from an array to a real instance * - * @template PackageClass of CompletePackageInterface - * * @param mixed[] $config package data * @param string $class FQCN to be instantiated * * @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage * - * @phpstan-param class-string $class + * @phpstan-param class-string $class */ - public function load(array $config, $class = 'Composer\Package\CompletePackage'); + public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage; } diff --git a/src/Composer/Package/Loader/RootPackageLoader.php b/src/Composer/Package/Loader/RootPackageLoader.php index 9c0c47c8f36b..89eb276368e3 100644 --- a/src/Composer/Package/Loader/RootPackageLoader.php +++ b/src/Composer/Package/Loader/RootPackageLoader.php @@ -61,15 +61,13 @@ public function __construct(RepositoryManager $manager, Config $config, VersionP /** * @inheritDoc * - * @template PackageClass of RootPackage - * * @param string|null $cwd * * @return RootPackage|RootAliasPackage * - * @phpstan-param class-string $class + * @phpstan-param class-string $class */ - public function load(array $config, $class = 'Composer\Package\RootPackage', $cwd = null) + public function load(array $config, string $class = 'Composer\Package\RootPackage', ?string $cwd = null): BasePackage { if ($class !== 'Composer\Package\RootPackage') { trigger_error('The $class arg is deprecated, please reach out to Composer maintainers ASAP if you still need this.', E_USER_DEPRECATED); @@ -88,7 +86,7 @@ public function load(array $config, $class = 'Composer\Package\RootPackage', $cw if (Platform::getEnv('COMPOSER_ROOT_VERSION')) { $config['version'] = Platform::getEnv('COMPOSER_ROOT_VERSION'); } else { - $versionData = $this->versionGuesser->guessVersion($config, $cwd ?: getcwd()); + $versionData = $this->versionGuesser->guessVersion($config, $cwd ?? Platform::getCwd(true)); if ($versionData) { $config['version'] = $versionData['pretty_version']; $config['version_normalized'] = $versionData['version']; @@ -224,7 +222,7 @@ private function extractAliases(array $requires, array $aliases): array * @phpstan-param array $stabilityFlags * @phpstan-return array */ - public static function extractStabilityFlags(array $requires, $minimumStability, array $stabilityFlags): array + public static function extractStabilityFlags(array $requires, string $minimumStability, array $stabilityFlags): array { $stabilities = BasePackage::$stabilities; /** @var int $minimumStability */ diff --git a/src/Composer/Package/Loader/ValidatingArrayLoader.php b/src/Composer/Package/Loader/ValidatingArrayLoader.php index 2a1278448255..997287f4424c 100644 --- a/src/Composer/Package/Loader/ValidatingArrayLoader.php +++ b/src/Composer/Package/Loader/ValidatingArrayLoader.php @@ -45,7 +45,7 @@ class ValidatingArrayLoader implements LoaderInterface * @param true $strictName * @param int $flags */ - public function __construct(LoaderInterface $loader, $strictName = true, VersionParser $parser = null, $flags = 0) + public function __construct(LoaderInterface $loader, bool $strictName = true, VersionParser $parser = null, int $flags = 0) { $this->loader = $loader; $this->versionParser = $parser ?: new VersionParser(); @@ -59,7 +59,7 @@ public function __construct(LoaderInterface $loader, $strictName = true, Version /** * @inheritDoc */ - public function load(array $config, $class = 'Composer\Package\CompletePackage') + public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage { $this->errors = array(); $this->warnings = array(); @@ -450,7 +450,7 @@ public function getErrors(): array * * @return string|null */ - public static function hasPackageNamingError($name, $isLink = false): ?string + public static function hasPackageNamingError(string $name, bool $isLink = false): ?string { if (PlatformRepository::isPlatformPackage($name)) { return null; @@ -494,7 +494,7 @@ public static function hasPackageNamingError($name, $isLink = false): ?string * @phpstan-param non-empty-string $property * @phpstan-param non-empty-string $regex */ - private function validateRegex($property, $regex, $mandatory = false): bool + private function validateRegex(string $property, string $regex, bool $mandatory = false): bool { if (!$this->validateString($property, $mandatory)) { return false; @@ -523,7 +523,7 @@ private function validateRegex($property, $regex, $mandatory = false): bool * * @phpstan-param non-empty-string $property */ - private function validateString($property, $mandatory = false): bool + private function validateString(string $property, bool $mandatory = false): bool { if (isset($this->config[$property]) && !is_string($this->config[$property])) { $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given'; @@ -552,7 +552,7 @@ private function validateString($property, $mandatory = false): bool * * @phpstan-param non-empty-string $property */ - private function validateArray($property, $mandatory = false): bool + private function validateArray(string $property, bool $mandatory = false): bool { if (isset($this->config[$property]) && !is_array($this->config[$property])) { $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given'; @@ -583,7 +583,7 @@ private function validateArray($property, $mandatory = false): bool * @phpstan-param non-empty-string $property * @phpstan-param non-empty-string|null $regex */ - private function validateFlatArray($property, $regex = null, $mandatory = false): bool + private function validateFlatArray(string $property, ?string $regex = null, bool $mandatory = false): bool { if (!$this->validateArray($property, $mandatory)) { return false; @@ -617,7 +617,7 @@ private function validateFlatArray($property, $regex = null, $mandatory = false) * * @phpstan-param non-empty-string $property */ - private function validateUrl($property, $mandatory = false): bool + private function validateUrl(string $property, bool $mandatory = false): bool { if (!$this->validateString($property, $mandatory)) { return false; diff --git a/src/Composer/Package/Locker.php b/src/Composer/Package/Locker.php index 1702d2ba906f..6dc77cf5bfad 100644 --- a/src/Composer/Package/Locker.php +++ b/src/Composer/Package/Locker.php @@ -60,7 +60,7 @@ class Locker * @param InstallationManager $installationManager installation manager instance * @param string $composerFileContents The contents of the composer file */ - public function __construct(IOInterface $io, JsonFile $lockFile, InstallationManager $installationManager, $composerFileContents, ProcessExecutor $process = null) + public function __construct(IOInterface $io, JsonFile $lockFile, InstallationManager $installationManager, string $composerFileContents, ProcessExecutor $process = null) { $this->lockFile = $lockFile; $this->installationManager = $installationManager; @@ -78,7 +78,7 @@ public function __construct(IOInterface $io, JsonFile $lockFile, InstallationMan * * @return string */ - public static function getContentHash($composerFileContents): string + public static function getContentHash(string $composerFileContents): string { $content = JsonFile::parseJson($composerFileContents, 'composer.json'); @@ -156,7 +156,7 @@ public function isFresh(): bool * @throws \RuntimeException * @return \Composer\Repository\LockArrayRepository */ - public function getLockedRepository($withDevReqs = false): \Composer\Repository\LockArrayRepository + public function getLockedRepository(bool $withDevReqs = false): LockArrayRepository { $lockData = $this->getLockData(); $packages = new LockArrayRepository(); @@ -224,7 +224,7 @@ public function getDevPackageNames(): array * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned * @return \Composer\Package\Link[] */ - public function getPlatformRequirements($withDevReqs = false): array + public function getPlatformRequirements(bool $withDevReqs = false): array { $lockData = $this->getLockData(); $requirements = array(); @@ -353,7 +353,7 @@ public function getLockData(): array * * @phpstan-param list $aliases */ - public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest, array $platformOverrides, $write = true): bool + public function setLockData(array $packages, ?array $devPackages, array $platformReqs, array $platformDevReqs, array $aliases, string $minimumStability, array $stabilityFlags, bool $preferStable, bool $preferLowest, array $platformOverrides, bool $write = true): bool { // keep old default branch names normalized to DEFAULT_BRANCH_ALIAS for BC as that is how Composer 1 outputs the lock file // when loading the lock file the version is anyway ignored in Composer 2, so it has no adverse effect diff --git a/src/Composer/Package/Package.php b/src/Composer/Package/Package.php index 7549c40085a7..90dc0688fdb6 100644 --- a/src/Composer/Package/Package.php +++ b/src/Composer/Package/Package.php @@ -54,7 +54,7 @@ class Package extends BasePackage protected $version; /** @var string */ protected $prettyVersion; - /** @var ?\DateTime */ + /** @var ?\DateTimeInterface */ protected $releaseDate; /** @var mixed[] */ protected $extra = array(); @@ -106,7 +106,7 @@ class Package extends BasePackage * @param string $version The package's version * @param string $prettyVersion The package's non-normalized version */ - public function __construct($name, $version, $prettyVersion) + public function __construct(string $name, string $version, string $prettyVersion) { parent::__construct($name); @@ -120,7 +120,7 @@ public function __construct($name, $version, $prettyVersion) /** * @inheritDoc */ - public function isDev() + public function isDev(): bool { return $this->dev; } @@ -130,7 +130,7 @@ public function isDev() * * @return void */ - public function setType($type) + public function setType(string $type): void { $this->type = $type; } @@ -138,7 +138,7 @@ public function setType($type) /** * @inheritDoc */ - public function getType() + public function getType(): string { return $this->type ?: 'library'; } @@ -146,17 +146,15 @@ public function getType() /** * @inheritDoc */ - public function getStability() + public function getStability(): string { return $this->stability; } /** - * @param string $targetDir - * * @return void */ - public function setTargetDir($targetDir) + public function setTargetDir(?string $targetDir): void { $this->targetDir = $targetDir; } @@ -164,7 +162,7 @@ public function setTargetDir($targetDir) /** * @inheritDoc */ - public function getTargetDir() + public function getTargetDir(): ?string { if (null === $this->targetDir) { return null; @@ -178,7 +176,7 @@ public function getTargetDir() * * @return void */ - public function setExtra(array $extra) + public function setExtra(array $extra): void { $this->extra = $extra; } @@ -186,7 +184,7 @@ public function setExtra(array $extra) /** * @inheritDoc */ - public function getExtra() + public function getExtra(): array { return $this->extra; } @@ -196,7 +194,7 @@ public function getExtra() * * @return void */ - public function setBinaries(array $binaries) + public function setBinaries(array $binaries): void { $this->binaries = $binaries; } @@ -204,7 +202,7 @@ public function setBinaries(array $binaries) /** * @inheritDoc */ - public function getBinaries() + public function getBinaries(): array { return $this->binaries; } @@ -214,7 +212,7 @@ public function getBinaries() * * @return void */ - public function setInstallationSource($type) + public function setInstallationSource(?string $type): void { $this->installationSource = $type; } @@ -222,17 +220,15 @@ public function setInstallationSource($type) /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): ?string { return $this->installationSource; } /** - * @param string $type - * * @return void */ - public function setSourceType($type) + public function setSourceType(?string $type): void { $this->sourceType = $type; } @@ -240,17 +236,15 @@ public function setSourceType($type) /** * @inheritDoc */ - public function getSourceType() + public function getSourceType(): ?string { return $this->sourceType; } /** - * @param string $url - * * @return void */ - public function setSourceUrl($url) + public function setSourceUrl(?string $url): void { $this->sourceUrl = $url; } @@ -258,17 +252,15 @@ public function setSourceUrl($url) /** * @inheritDoc */ - public function getSourceUrl() + public function getSourceUrl(): ?string { return $this->sourceUrl; } /** - * @param string $reference - * * @return void */ - public function setSourceReference($reference) + public function setSourceReference(?string $reference): void { $this->sourceReference = $reference; } @@ -276,17 +268,15 @@ public function setSourceReference($reference) /** * @inheritDoc */ - public function getSourceReference() + public function getSourceReference(): ?string { return $this->sourceReference; } /** - * @inheritDoc - * * @return void */ - public function setSourceMirrors($mirrors) + public function setSourceMirrors(?array $mirrors): void { $this->sourceMirrors = $mirrors; } @@ -294,7 +284,7 @@ public function setSourceMirrors($mirrors) /** * @inheritDoc */ - public function getSourceMirrors() + public function getSourceMirrors(): ?array { return $this->sourceMirrors; } @@ -302,7 +292,7 @@ public function getSourceMirrors() /** * @inheritDoc */ - public function getSourceUrls() + public function getSourceUrls(): array { return $this->getUrls($this->sourceUrl, $this->sourceMirrors, $this->sourceReference, $this->sourceType, 'source'); } @@ -312,7 +302,7 @@ public function getSourceUrls() * * @return void */ - public function setDistType($type) + public function setDistType(?string $type): void { $this->distType = $type; } @@ -320,7 +310,7 @@ public function setDistType($type) /** * @inheritDoc */ - public function getDistType() + public function getDistType(): ?string { return $this->distType; } @@ -330,7 +320,7 @@ public function getDistType() * * @return void */ - public function setDistUrl($url) + public function setDistUrl(?string $url): void { $this->distUrl = $url; } @@ -338,7 +328,7 @@ public function setDistUrl($url) /** * @inheritDoc */ - public function getDistUrl() + public function getDistUrl(): ?string { return $this->distUrl; } @@ -348,7 +338,7 @@ public function getDistUrl() * * @return void */ - public function setDistReference($reference) + public function setDistReference(?string $reference): void { $this->distReference = $reference; } @@ -356,7 +346,7 @@ public function setDistReference($reference) /** * @inheritDoc */ - public function getDistReference() + public function getDistReference(): ?string { return $this->distReference; } @@ -366,7 +356,7 @@ public function getDistReference() * * @return void */ - public function setDistSha1Checksum($sha1checksum) + public function setDistSha1Checksum(?string $sha1checksum): void { $this->distSha1Checksum = $sha1checksum; } @@ -374,17 +364,15 @@ public function setDistSha1Checksum($sha1checksum) /** * @inheritDoc */ - public function getDistSha1Checksum() + public function getDistSha1Checksum(): ?string { return $this->distSha1Checksum; } /** - * @inheritDoc - * * @return void */ - public function setDistMirrors($mirrors) + public function setDistMirrors(?array $mirrors): void { $this->distMirrors = $mirrors; } @@ -392,7 +380,7 @@ public function setDistMirrors($mirrors) /** * @inheritDoc */ - public function getDistMirrors() + public function getDistMirrors(): ?array { return $this->distMirrors; } @@ -400,7 +388,7 @@ public function getDistMirrors() /** * @inheritDoc */ - public function getDistUrls() + public function getDistUrls(): array { return $this->getUrls($this->distUrl, $this->distMirrors, $this->distReference, $this->distType, 'dist'); } @@ -408,7 +396,7 @@ public function getDistUrls() /** * @inheritDoc */ - public function getTransportOptions() + public function getTransportOptions(): array { return $this->transportOptions; } @@ -416,7 +404,7 @@ public function getTransportOptions() /** * @inheritDoc */ - public function setTransportOptions(array $options) + public function setTransportOptions(array $options): void { $this->transportOptions = $options; } @@ -424,7 +412,7 @@ public function setTransportOptions(array $options) /** * @inheritDoc */ - public function getVersion() + public function getVersion(): string { return $this->version; } @@ -432,19 +420,15 @@ public function getVersion() /** * @inheritDoc */ - public function getPrettyVersion() + public function getPrettyVersion(): string { return $this->prettyVersion; } /** - * Set the releaseDate - * - * @param \DateTime $releaseDate - * * @return void */ - public function setReleaseDate(\DateTime $releaseDate) + public function setReleaseDate(?\DateTimeInterface $releaseDate): void { $this->releaseDate = $releaseDate; } @@ -452,7 +436,7 @@ public function setReleaseDate(\DateTime $releaseDate) /** * @inheritDoc */ - public function getReleaseDate() + public function getReleaseDate(): ?\DateTimeInterface { return $this->releaseDate; } @@ -464,7 +448,7 @@ public function getReleaseDate() * * @return void */ - public function setRequires(array $requires) + public function setRequires(array $requires): void { if (isset($requires[0])) { // @phpstan-ignore-line $requires = $this->convertLinksToMap($requires, 'setRequires'); @@ -476,7 +460,7 @@ public function setRequires(array $requires) /** * @inheritDoc */ - public function getRequires() + public function getRequires(): array { return $this->requires; } @@ -488,7 +472,7 @@ public function getRequires() * * @return void */ - public function setConflicts(array $conflicts) + public function setConflicts(array $conflicts): void { if (isset($conflicts[0])) { // @phpstan-ignore-line $conflicts = $this->convertLinksToMap($conflicts, 'setConflicts'); @@ -501,7 +485,7 @@ public function setConflicts(array $conflicts) * @inheritDoc * @return array */ - public function getConflicts() + public function getConflicts(): array { return $this->conflicts; } @@ -513,7 +497,7 @@ public function getConflicts() * * @return void */ - public function setProvides(array $provides) + public function setProvides(array $provides): void { if (isset($provides[0])) { // @phpstan-ignore-line $provides = $this->convertLinksToMap($provides, 'setProvides'); @@ -526,7 +510,7 @@ public function setProvides(array $provides) * @inheritDoc * @return array */ - public function getProvides() + public function getProvides(): array { return $this->provides; } @@ -538,7 +522,7 @@ public function getProvides() * * @return void */ - public function setReplaces(array $replaces) + public function setReplaces(array $replaces): void { if (isset($replaces[0])) { // @phpstan-ignore-line $replaces = $this->convertLinksToMap($replaces, 'setReplaces'); @@ -551,7 +535,7 @@ public function setReplaces(array $replaces) * @inheritDoc * @return array */ - public function getReplaces() + public function getReplaces(): array { return $this->replaces; } @@ -563,7 +547,7 @@ public function getReplaces() * * @return void */ - public function setDevRequires(array $devRequires) + public function setDevRequires(array $devRequires): void { if (isset($devRequires[0])) { // @phpstan-ignore-line $devRequires = $this->convertLinksToMap($devRequires, 'setDevRequires'); @@ -575,7 +559,7 @@ public function setDevRequires(array $devRequires) /** * @inheritDoc */ - public function getDevRequires() + public function getDevRequires(): array { return $this->devRequires; } @@ -587,7 +571,7 @@ public function getDevRequires() * * @return void */ - public function setSuggests(array $suggests) + public function setSuggests(array $suggests): void { $this->suggests = $suggests; } @@ -595,7 +579,7 @@ public function setSuggests(array $suggests) /** * @inheritDoc */ - public function getSuggests() + public function getSuggests(): array { return $this->suggests; } @@ -609,7 +593,7 @@ public function getSuggests() * * @phpstan-param AutoloadRules $autoload */ - public function setAutoload(array $autoload) + public function setAutoload(array $autoload): void { $this->autoload = $autoload; } @@ -617,7 +601,7 @@ public function setAutoload(array $autoload) /** * @inheritDoc */ - public function getAutoload() + public function getAutoload(): array { return $this->autoload; } @@ -631,7 +615,7 @@ public function getAutoload() * * @phpstan-param DevAutoloadRules $devAutoload */ - public function setDevAutoload(array $devAutoload) + public function setDevAutoload(array $devAutoload): void { $this->devAutoload = $devAutoload; } @@ -639,7 +623,7 @@ public function setDevAutoload(array $devAutoload) /** * @inheritDoc */ - public function getDevAutoload() + public function getDevAutoload(): array { return $this->devAutoload; } @@ -651,7 +635,7 @@ public function getDevAutoload() * * @return void */ - public function setIncludePaths(array $includePaths) + public function setIncludePaths(array $includePaths): void { $this->includePaths = $includePaths; } @@ -659,7 +643,7 @@ public function setIncludePaths(array $includePaths) /** * @inheritDoc */ - public function getIncludePaths() + public function getIncludePaths(): array { return $this->includePaths; } @@ -671,7 +655,7 @@ public function getIncludePaths() * * @return void */ - public function setNotificationUrl($notificationUrl) + public function setNotificationUrl(string $notificationUrl): void { $this->notificationUrl = $notificationUrl; } @@ -679,7 +663,7 @@ public function setNotificationUrl($notificationUrl) /** * @inheritDoc */ - public function getNotificationUrl() + public function getNotificationUrl(): ?string { return $this->notificationUrl; } @@ -689,7 +673,7 @@ public function getNotificationUrl() * * @return void */ - public function setIsDefaultBranch($defaultBranch) + public function setIsDefaultBranch(bool $defaultBranch): void { $this->isDefaultBranch = $defaultBranch; } @@ -697,7 +681,7 @@ public function setIsDefaultBranch($defaultBranch) /** * @inheritDoc */ - public function isDefaultBranch() + public function isDefaultBranch(): bool { return $this->isDefaultBranch; } @@ -705,7 +689,7 @@ public function isDefaultBranch() /** * @inheritDoc */ - public function setSourceDistReferences($reference) + public function setSourceDistReferences(string $reference): void { $this->setSourceReference($reference); @@ -731,7 +715,7 @@ public function setSourceDistReferences($reference) * * @return void */ - public function replaceVersion($version, $prettyVersion) + public function replaceVersion(string $version, string $prettyVersion): void { $this->version = $version; $this->prettyVersion = $prettyVersion; @@ -751,7 +735,7 @@ public function replaceVersion($version, $prettyVersion) * * @phpstan-param list|null $mirrors */ - protected function getUrls($url, $mirrors, $ref, $type, $urlType) + protected function getUrls(?string $url, ?array $mirrors, ?string $ref, ?string $type, string $urlType): array { if (!$url) { return array(); @@ -788,7 +772,7 @@ protected function getUrls($url, $mirrors, $ref, $type, $urlType) * @param string $source * @return array */ - private function convertLinksToMap(array $links, $source): array + private function convertLinksToMap(array $links, string $source): array { trigger_error('Package::'.$source.' must be called with a map of lowercased package name => Link object, got a indexed array, this is deprecated and you should fix your usage.'); $newLinks = array(); diff --git a/src/Composer/Package/PackageInterface.php b/src/Composer/Package/PackageInterface.php index a566298c8c78..31a0e78fb8f9 100644 --- a/src/Composer/Package/PackageInterface.php +++ b/src/Composer/Package/PackageInterface.php @@ -17,6 +17,8 @@ /** * Defines the essential information a package has that is used during solving/installation * + * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. + * * @author Jordi Boggiano * * @phpstan-type AutoloadRules array{psr-0?: array, psr-4?: array, classmap?: list, files?: list, exclude-from-classmap?: list} @@ -33,14 +35,14 @@ interface PackageInterface * * @return string package name */ - public function getName(); + public function getName(): string; /** * Returns the package's pretty (i.e. with proper case) name * * @return string package name */ - public function getPrettyName(); + public function getPrettyName(): string; /** * Returns a set of names that could refer to this package @@ -52,7 +54,7 @@ public function getPrettyName(); * * @return string[] An array of strings referring to this package */ - public function getNames($provides = true); + public function getNames(bool $provides = true): array; /** * Allows the solver to set an id for this package to refer to it. @@ -61,52 +63,52 @@ public function getNames($provides = true); * * @return void */ - public function setId($id); + public function setId(int $id): void; /** * Retrieves the package's id set through setId * * @return int The previously set package id */ - public function getId(); + public function getId(): int; /** * Returns whether the package is a development virtual package or a concrete one * * @return bool */ - public function isDev(); + public function isDev(): bool; /** * Returns the package type, e.g. library * * @return string The package type */ - public function getType(); + public function getType(): string; /** * Returns the package targetDir property * * @return ?string The package targetDir */ - public function getTargetDir(); + public function getTargetDir(): ?string; /** * Returns the package extra data * * @return mixed[] The package extra data */ - public function getExtra(); + public function getExtra(): array; /** * Sets source from which this package was installed (source/dist). * - * @param string $type source/dist + * @param ?string $type source/dist * @phpstan-param 'source'|'dist'|null $type * * @return void */ - public function setInstallationSource($type); + public function setInstallationSource(?string $type): void; /** * Returns source from which this package was installed (source/dist). @@ -114,110 +116,110 @@ public function setInstallationSource($type); * @return ?string source/dist * @phpstan-return 'source'|'dist'|null */ - public function getInstallationSource(); + public function getInstallationSource(): ?string; /** * Returns the repository type of this package, e.g. git, svn * * @return ?string The repository type */ - public function getSourceType(); + public function getSourceType(): ?string; /** * Returns the repository url of this package, e.g. git://github.com/naderman/composer.git * * @return ?string The repository url */ - public function getSourceUrl(); + public function getSourceUrl(): ?string; /** * Returns the repository urls of this package including mirrors, e.g. git://github.com/naderman/composer.git * * @return string[] */ - public function getSourceUrls(); + public function getSourceUrls(): array; /** * Returns the repository reference of this package, e.g. master, 1.0.0 or a commit hash for git * * @return ?string The repository reference */ - public function getSourceReference(); + public function getSourceReference(): ?string; /** * Returns the source mirrors of this package * * @return ?array */ - public function getSourceMirrors(); + public function getSourceMirrors(): ?array; /** - * @param ?array $mirrors + * @param null|array $mirrors * @return void */ - public function setSourceMirrors($mirrors); + public function setSourceMirrors(?array $mirrors): void; /** * Returns the type of the distribution archive of this version, e.g. zip, tarball * * @return ?string The repository type */ - public function getDistType(); + public function getDistType(): ?string; /** * Returns the url of the distribution archive of this version * * @return ?string */ - public function getDistUrl(); + public function getDistUrl(): ?string; /** * Returns the urls of the distribution archive of this version, including mirrors * * @return string[] */ - public function getDistUrls(); + public function getDistUrls(): array; /** * Returns the reference of the distribution archive of this version, e.g. master, 1.0.0 or a commit hash for git * * @return ?string */ - public function getDistReference(); + public function getDistReference(): ?string; /** * Returns the sha1 checksum for the distribution archive of this version * * @return ?string */ - public function getDistSha1Checksum(); + public function getDistSha1Checksum(): ?string; /** * Returns the dist mirrors of this package * * @return ?array */ - public function getDistMirrors(); + public function getDistMirrors(): ?array; /** - * @param ?array $mirrors + * @param null|array $mirrors * @return void */ - public function setDistMirrors($mirrors); + public function setDistMirrors(?array $mirrors): void; /** * Returns the version of this package * * @return string version */ - public function getVersion(); + public function getVersion(): string; /** * Returns the pretty (i.e. non-normalized) version string of this package * * @return string version */ - public function getPrettyVersion(); + public function getPrettyVersion(): string; /** * Returns the pretty version string plus a git or hg commit hash of this package @@ -230,14 +232,14 @@ public function getPrettyVersion(); * * @phpstan-param self::DISPLAY_SOURCE_REF_IF_DEV|self::DISPLAY_SOURCE_REF|self::DISPLAY_DIST_REF $displayMode */ - public function getFullPrettyVersion($truncate = true, $displayMode = self::DISPLAY_SOURCE_REF_IF_DEV); + public function getFullPrettyVersion(bool $truncate = true, int $displayMode = self::DISPLAY_SOURCE_REF_IF_DEV): string; /** * Returns the release date of the package * - * @return ?\DateTime + * @return ?\DateTimeInterface */ - public function getReleaseDate(); + public function getReleaseDate(): ?\DateTimeInterface; /** * Returns the stability of this package: one of (dev, alpha, beta, RC, stable) @@ -246,7 +248,7 @@ public function getReleaseDate(); * * @phpstan-return 'stable'|'RC'|'beta'|'alpha'|'dev' */ - public function getStability(); + public function getStability(): string; /** * Returns a set of links to packages which need to be installed before @@ -254,7 +256,7 @@ public function getStability(); * * @return array A map of package links defining required packages, indexed by the require package's name */ - public function getRequires(); + public function getRequires(): array; /** * Returns a set of links to packages which must not be installed at the @@ -262,7 +264,7 @@ public function getRequires(); * * @return Link[] An array of package links defining conflicting packages */ - public function getConflicts(); + public function getConflicts(): array; /** * Returns a set of links to virtual packages that are provided through @@ -270,7 +272,7 @@ public function getConflicts(); * * @return Link[] An array of package links defining provided packages */ - public function getProvides(); + public function getProvides(): array; /** * Returns a set of links to packages which can alternatively be @@ -278,7 +280,7 @@ public function getProvides(); * * @return Link[] An array of package links defining replaced packages */ - public function getReplaces(); + public function getReplaces(): array; /** * Returns a set of links to packages which are required to develop @@ -286,7 +288,7 @@ public function getReplaces(); * * @return array A map of package links defining packages required for development, indexed by the require package's name */ - public function getDevRequires(); + public function getDevRequires(): array; /** * Returns a set of package names and reasons why they are useful in @@ -295,7 +297,7 @@ public function getDevRequires(); * @return array An array of package suggestions with descriptions * @phpstan-return array */ - public function getSuggests(); + public function getSuggests(): array; /** * Returns an associative array of autoloading rules @@ -308,7 +310,7 @@ public function getSuggests(); * @return array Mapping of autoloading rules * @phpstan-return AutoloadRules */ - public function getAutoload(); + public function getAutoload(): array; /** * Returns an associative array of dev autoloading rules @@ -321,7 +323,7 @@ public function getAutoload(); * @return array Mapping of dev autoloading rules * @phpstan-return DevAutoloadRules */ - public function getDevAutoload(); + public function getDevAutoload(): array; /** * Returns a list of directories which should get added to PHP's @@ -329,7 +331,7 @@ public function getDevAutoload(); * * @return string[] */ - public function getIncludePaths(); + public function getIncludePaths(): array; /** * Stores a reference to the repository that owns the package @@ -338,61 +340,61 @@ public function getIncludePaths(); * * @return void */ - public function setRepository(RepositoryInterface $repository); + public function setRepository(RepositoryInterface $repository): void; /** * Returns a reference to the repository that owns the package * * @return ?RepositoryInterface */ - public function getRepository(); + public function getRepository(): ?RepositoryInterface; /** * Returns the package binaries * * @return string[] */ - public function getBinaries(); + public function getBinaries(): array; /** * Returns package unique name, constructed from name and version. * * @return string */ - public function getUniqueName(); + public function getUniqueName(): string; /** * Returns the package notification url * * @return ?string */ - public function getNotificationUrl(); + public function getNotificationUrl(): ?string; /** * Converts the package into a readable and unique string * * @return string */ - public function __toString(); + public function __toString(): string; /** * Converts the package into a pretty readable string * * @return string */ - public function getPrettyString(); + public function getPrettyString(): string; /** * @return bool */ - public function isDefaultBranch(); + public function isDefaultBranch(): bool; /** * Returns a list of options to download package dist files * * @return mixed[] */ - public function getTransportOptions(); + public function getTransportOptions(): array; /** * Configures the list of options to download package dist files @@ -401,42 +403,32 @@ public function getTransportOptions(); * * @return void */ - public function setTransportOptions(array $options); + public function setTransportOptions(array $options): void; /** - * @param string $reference - * * @return void */ - public function setSourceReference($reference); + public function setSourceReference(?string $reference): void; /** - * @param string $url - * * @return void */ - public function setDistUrl($url); + public function setDistUrl(?string $url): void; /** - * @param string $type - * * @return void */ - public function setDistType($type); + public function setDistType(?string $type): void; /** - * @param string $reference - * * @return void */ - public function setDistReference($reference); + public function setDistReference(?string $reference): void; /** * Set dist and source references and update dist URL for ones that contain a reference * - * @param string $reference - * * @return void */ - public function setSourceDistReferences($reference); + public function setSourceDistReferences(string $reference): void; } diff --git a/src/Composer/Package/RootAliasPackage.php b/src/Composer/Package/RootAliasPackage.php index adf69b6b0cf9..7c780189fae5 100644 --- a/src/Composer/Package/RootAliasPackage.php +++ b/src/Composer/Package/RootAliasPackage.php @@ -27,7 +27,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf * @param string $version The version the alias must report * @param string $prettyVersion The alias's non-normalized version */ - public function __construct(RootPackage $aliasOf, $version, $prettyVersion) + public function __construct(RootPackage $aliasOf, string $version, string $prettyVersion) { parent::__construct($aliasOf, $version, $prettyVersion); } diff --git a/src/Composer/Package/RootPackage.php b/src/Composer/Package/RootPackage.php index 38375dc73648..07bd31d6fe87 100644 --- a/src/Composer/Package/RootPackage.php +++ b/src/Composer/Package/RootPackage.php @@ -35,9 +35,9 @@ class RootPackage extends CompletePackage implements RootPackageInterface protected $aliases = array(); /** - * {@inerhitDoc} + * @inheritDoc */ - public function setMinimumStability($minimumStability): void + public function setMinimumStability(string $minimumStability): void { $this->minimumStability = $minimumStability; } @@ -67,9 +67,9 @@ public function getStabilityFlags(): array } /** - * {@inerhitDoc} + * @inheritDoc */ - public function setPreferStable($preferStable): void + public function setPreferStable(bool $preferStable): void { $this->preferStable = $preferStable; } @@ -83,7 +83,7 @@ public function getPreferStable(): bool } /** - * {@inerhitDoc} + * @inheritDoc */ public function setConfig(array $config): void { @@ -99,7 +99,7 @@ public function getConfig(): array } /** - * {@inerhitDoc} + * @inheritDoc */ public function setReferences(array $references): void { @@ -115,7 +115,7 @@ public function getReferences(): array } /** - * {@inerhitDoc} + * @inheritDoc */ public function setAliases(array $aliases): void { diff --git a/src/Composer/Package/RootPackageInterface.php b/src/Composer/Package/RootPackageInterface.php index 32cc44750f88..9e74e4ddc8f3 100644 --- a/src/Composer/Package/RootPackageInterface.php +++ b/src/Composer/Package/RootPackageInterface.php @@ -15,6 +15,8 @@ /** * Defines additional fields that are only needed for the root package * + * PackageInterface & derivatives are considered internal, you may use them in type hints but extending/implementing them is not recommended and not supported. Things may change without notice. + * * @author Jordi Boggiano * * @phpstan-import-type AutoloadRules from PackageInterface @@ -27,14 +29,14 @@ interface RootPackageInterface extends CompletePackageInterface * * @return array */ - public function getAliases(); + public function getAliases(): array; /** * Returns the minimum stability of the package * * @return string */ - public function getMinimumStability(); + public function getMinimumStability(): string; /** * Returns the stability flags to apply to dependencies @@ -43,7 +45,7 @@ public function getMinimumStability(); * * @return array */ - public function getStabilityFlags(); + public function getStabilityFlags(): array; /** * Returns a set of package names and source references that must be enforced on them @@ -52,21 +54,21 @@ public function getStabilityFlags(); * * @return array */ - public function getReferences(); + public function getReferences(): array; /** * Returns true if the root package prefers picking stable packages over unstable ones * * @return bool */ - public function getPreferStable(); + public function getPreferStable(): bool; /** * Returns the root package's configuration * * @return mixed[] */ - public function getConfig(); + public function getConfig(): array; /** * Set the required packages @@ -75,7 +77,7 @@ public function getConfig(); * * @return void */ - public function setRequires(array $requires); + public function setRequires(array $requires): void; /** * Set the recommended packages @@ -84,7 +86,7 @@ public function setRequires(array $requires); * * @return void */ - public function setDevRequires(array $devRequires); + public function setDevRequires(array $devRequires): void; /** * Set the conflicting packages @@ -93,7 +95,7 @@ public function setDevRequires(array $devRequires); * * @return void */ - public function setConflicts(array $conflicts); + public function setConflicts(array $conflicts): void; /** * Set the provided virtual packages @@ -102,7 +104,7 @@ public function setConflicts(array $conflicts); * * @return void */ - public function setProvides(array $provides); + public function setProvides(array $provides): void; /** * Set the packages this one replaces @@ -111,7 +113,7 @@ public function setProvides(array $provides); * * @return void */ - public function setReplaces(array $replaces); + public function setReplaces(array $replaces): void; /** * Set the repositories @@ -120,7 +122,7 @@ public function setReplaces(array $replaces); * * @return void */ - public function setRepositories(array $repositories); + public function setRepositories(array $repositories): void; /** * Set the autoload mapping @@ -130,7 +132,7 @@ public function setRepositories(array $repositories); * * @return void */ - public function setAutoload(array $autoload); + public function setAutoload(array $autoload): void; /** * Set the dev autoload mapping @@ -140,7 +142,7 @@ public function setAutoload(array $autoload); * * @return void */ - public function setDevAutoload(array $devAutoload); + public function setDevAutoload(array $devAutoload): void; /** * Set the stabilityFlags @@ -149,7 +151,7 @@ public function setDevAutoload(array $devAutoload); * * @return void */ - public function setStabilityFlags(array $stabilityFlags); + public function setStabilityFlags(array $stabilityFlags): void; /** * Set the minimumStability @@ -158,7 +160,7 @@ public function setStabilityFlags(array $stabilityFlags); * * @return void */ - public function setMinimumStability($minimumStability); + public function setMinimumStability(string $minimumStability): void; /** * Set the preferStable @@ -167,7 +169,7 @@ public function setMinimumStability($minimumStability); * * @return void */ - public function setPreferStable($preferStable); + public function setPreferStable(bool $preferStable): void; /** * Set the config @@ -176,7 +178,7 @@ public function setPreferStable($preferStable); * * @return void */ - public function setConfig(array $config); + public function setConfig(array $config): void; /** * Set the references @@ -185,7 +187,7 @@ public function setConfig(array $config); * * @return void */ - public function setReferences(array $references); + public function setReferences(array $references): void; /** * Set the aliases @@ -194,7 +196,7 @@ public function setReferences(array $references); * * @return void */ - public function setAliases(array $aliases); + public function setAliases(array $aliases): void; /** * Set the suggested packages @@ -203,12 +205,12 @@ public function setAliases(array $aliases); * * @return void */ - public function setSuggests(array $suggests); + public function setSuggests(array $suggests): void; /** * @param mixed[] $extra * * @return void */ - public function setExtra(array $extra); + public function setExtra(array $extra): void; } diff --git a/src/Composer/Package/Version/StabilityFilter.php b/src/Composer/Package/Version/StabilityFilter.php index 81f4ec063fbe..4280d7499d0d 100644 --- a/src/Composer/Package/Version/StabilityFilter.php +++ b/src/Composer/Package/Version/StabilityFilter.php @@ -30,7 +30,7 @@ class StabilityFilter * @param string $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev' * @return bool true if any package name is acceptable */ - public static function isPackageAcceptable(array $acceptableStabilities, array $stabilityFlags, array $names, $stability): bool + public static function isPackageAcceptable(array $acceptableStabilities, array $stabilityFlags, array $names, string $stability): bool { foreach ($names as $name) { // allow if package matches the package-specific stability flag diff --git a/src/Composer/Package/Version/VersionGuesser.php b/src/Composer/Package/Version/VersionGuesser.php index d5b0bf90792e..30961de4be97 100644 --- a/src/Composer/Package/Version/VersionGuesser.php +++ b/src/Composer/Package/Version/VersionGuesser.php @@ -66,7 +66,7 @@ public function __construct(Config $config, ProcessExecutor $process, SemverVers * @return array|null * @phpstan-return Version|null */ - public function guessVersion(array $packageConfig, $path): ?array + public function guessVersion(array $packageConfig, string $path): ?array { if (!function_exists('proc_open')) { return null; @@ -126,7 +126,7 @@ private function postprocess(array $versionData): array * * @return array{version: string|null, commit: string|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null} */ - private function guessGitVersion(array $packageConfig, $path): array + private function guessGitVersion(array $packageConfig, string $path): array { GitUtil::cleanEnv(); $commit = null; @@ -211,7 +211,7 @@ private function guessGitVersion(array $packageConfig, $path): array * * @return array{version: string, pretty_version: string}|null */ - private function versionFromGitTags($path): ?array + private function versionFromGitTags(string $path): ?array { // try to fetch current version from git tags if (0 === $this->process->execute('git describe --exact-match --tags', $output, $path)) { @@ -232,7 +232,7 @@ private function versionFromGitTags($path): ?array * * @return array{version: string|null, commit: ''|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null}|null */ - private function guessHgVersion(array $packageConfig, $path): ?array + private function guessHgVersion(array $packageConfig, string $path): ?array { // try to fetch current version from hg branch if (0 === $this->process->execute('hg branch', $output, $path)) { @@ -276,7 +276,7 @@ private function guessHgVersion(array $packageConfig, $path): ?array * * @return array{version: string|null, pretty_version: string|null} */ - private function guessFeatureVersion(array $packageConfig, $version, array $branches, $scmCmdline, $path): array + private function guessFeatureVersion(array $packageConfig, ?string $version, array $branches, string $scmCmdline, string $path): array { $prettyVersion = $version; @@ -340,7 +340,7 @@ private function guessFeatureVersion(array $packageConfig, $version, array $bran * * @return bool */ - private function isFeatureBranch(array $packageConfig, $branchName): bool + private function isFeatureBranch(array $packageConfig, ?string $branchName): bool { $nonFeatureBranches = ''; if (!empty($packageConfig['non-feature-branches'])) { @@ -355,7 +355,7 @@ private function isFeatureBranch(array $packageConfig, $branchName): bool * * @return array{version: string|null, commit: '', pretty_version: string|null} */ - private function guessFossilVersion($path): array + private function guessFossilVersion(string $path): array { $version = null; $prettyVersion = null; @@ -385,7 +385,7 @@ private function guessFossilVersion($path): array * * @return array{version: string, commit: '', pretty_version: string}|null */ - private function guessSvnVersion(array $packageConfig, $path): ?array + private function guessSvnVersion(array $packageConfig, string $path): ?array { SvnUtil::cleanEnv(); diff --git a/src/Composer/Package/Version/VersionParser.php b/src/Composer/Package/Version/VersionParser.php index 2d11bf0e42d5..faa5002c785c 100644 --- a/src/Composer/Package/Version/VersionParser.php +++ b/src/Composer/Package/Version/VersionParser.php @@ -28,7 +28,7 @@ class VersionParser extends SemverVersionParser /** * @inheritDoc */ - public function parseConstraints($constraints) + public function parseConstraints($constraints): ConstraintInterface { if (!isset(self::$constraints[$constraints])) { self::$constraints[$constraints] = parent::parseConstraints($constraints); @@ -47,7 +47,7 @@ public function parseConstraints($constraints) * * @return list */ - public function parseNameVersionPairs(array $pairs) + public function parseNameVersionPairs(array $pairs): array { $pairs = array_values($pairs); $result = array(); @@ -76,7 +76,7 @@ public function parseNameVersionPairs(array $pairs) * * @return bool */ - public static function isUpgrade($normalizedFrom, $normalizedTo) + public static function isUpgrade(string $normalizedFrom, string $normalizedTo): bool { if ($normalizedFrom === $normalizedTo) { return true; diff --git a/src/Composer/Package/Version/VersionSelector.php b/src/Composer/Package/Version/VersionSelector.php index 431bdb851167..cc8fe238239e 100644 --- a/src/Composer/Package/Version/VersionSelector.php +++ b/src/Composer/Package/Version/VersionSelector.php @@ -68,7 +68,7 @@ public function __construct(RepositorySet $repositorySet, PlatformRepository $pl * @param int $repoSetFlags* * @return PackageInterface|false */ - public function findBestCandidate($packageName, $targetPackageVersion = null, $preferredStability = 'stable', $platformRequirementFilter = null, $repoSetFlags = 0) + public function findBestCandidate(string $packageName, string $targetPackageVersion = null, string $preferredStability = 'stable', $platformRequirementFilter = null, int $repoSetFlags = 0) { if (!isset(BasePackage::$stabilities[$preferredStability])) { // If you get this, maybe you are still relying on the Composer 1.x signature where the 3rd arg was the php version @@ -211,7 +211,7 @@ public function findRecommendedRequireVersion(PackageInterface $package): string * * @return string */ - private function transformVersion($version, $prettyVersion, $stability): string + private function transformVersion(string $version, string $prettyVersion, string $stability): string { // attempt to transform 2.1.1 to 2.1 // this allows you to upgrade through minor versions diff --git a/src/Composer/Platform/Runtime.php b/src/Composer/Platform/Runtime.php index a5d228027c0c..6ccdbf546b07 100644 --- a/src/Composer/Platform/Runtime.php +++ b/src/Composer/Platform/Runtime.php @@ -20,7 +20,7 @@ class Runtime * * @return bool */ - public function hasConstant($constant, $class = null): bool + public function hasConstant(string $constant, ?string $class = null): bool { return defined(ltrim($class.'::'.$constant, ':')); } @@ -31,7 +31,7 @@ public function hasConstant($constant, $class = null): bool * * @return mixed */ - public function getConstant($constant, $class = null) + public function getConstant(string $constant, ?string $class = null) { return constant(ltrim($class.'::'.$constant, ':')); } @@ -41,7 +41,7 @@ public function getConstant($constant, $class = null) * * @return bool */ - public function hasFunction($fn): bool + public function hasFunction(string $fn): bool { return function_exists($fn); } @@ -52,7 +52,7 @@ public function hasFunction($fn): bool * * @return mixed */ - public function invoke($callable, array $arguments = array()) + public function invoke(callable $callable, array $arguments = array()) { return call_user_func_array($callable, $arguments); } @@ -62,7 +62,7 @@ public function invoke($callable, array $arguments = array()) * * @return bool */ - public function hasClass($class): bool + public function hasClass(string $class): bool { return class_exists($class, false); } @@ -74,7 +74,7 @@ public function hasClass($class): bool * @return object * @throws \ReflectionException */ - public function construct($class, array $arguments = array()): object + public function construct(string $class, array $arguments = array()): object { if (empty($arguments)) { return new $class; @@ -96,7 +96,7 @@ public function getExtensions(): array * * @return string */ - public function getExtensionVersion($extension): string + public function getExtensionVersion(string $extension): string { return phpversion($extension); } @@ -107,7 +107,7 @@ public function getExtensionVersion($extension): string * @return string * @throws \ReflectionException */ - public function getExtensionInfo($extension): string + public function getExtensionInfo(string $extension): string { $reflector = new \ReflectionExtension($extension); diff --git a/src/Composer/Platform/Version.php b/src/Composer/Platform/Version.php index d2b4d117163c..0731a1cec0b1 100644 --- a/src/Composer/Platform/Version.php +++ b/src/Composer/Platform/Version.php @@ -21,10 +21,10 @@ class Version { /** * @param string $opensslVersion - * @param bool $isFips + * @param bool $isFips Set by the method * @return string|null */ - public static function parseOpenssl($opensslVersion, &$isFips): ?string + public static function parseOpenssl(string $opensslVersion, ?bool &$isFips): ?string { $isFips = false; @@ -43,7 +43,7 @@ public static function parseOpenssl($opensslVersion, &$isFips): ?string * @param string $libjpegVersion * @return string|null */ - public static function parseLibjpeg($libjpegVersion): ?string + public static function parseLibjpeg(string $libjpegVersion): ?string { if (!Preg::isMatch('/^(?\d+)(?[a-z]*)$/', $libjpegVersion, $matches)) { return null; @@ -56,7 +56,7 @@ public static function parseLibjpeg($libjpegVersion): ?string * @param string $zoneinfoVersion * @return string|null */ - public static function parseZoneinfoVersion($zoneinfoVersion): ?string + public static function parseZoneinfoVersion(string $zoneinfoVersion): ?string { if (!Preg::isMatch('/^(?\d{4})(?[a-z]*)$/', $zoneinfoVersion, $matches)) { return null; @@ -71,7 +71,7 @@ public static function parseZoneinfoVersion($zoneinfoVersion): ?string * @param string $alpha * @return int */ - private static function convertAlphaVersionToIntVersion($alpha): int + private static function convertAlphaVersionToIntVersion(string $alpha): int { return strlen($alpha) * (-ord('a') + 1) + array_sum(array_map('ord', str_split($alpha))); } @@ -80,7 +80,7 @@ private static function convertAlphaVersionToIntVersion($alpha): int * @param int $versionId * @return string */ - public static function convertLibxpmVersionId($versionId): string + public static function convertLibxpmVersionId(int $versionId): string { return self::convertVersionId($versionId, 100); } @@ -89,7 +89,7 @@ public static function convertLibxpmVersionId($versionId): string * @param int $versionId * @return string */ - public static function convertOpenldapVersionId($versionId): string + public static function convertOpenldapVersionId(int $versionId): string { return self::convertVersionId($versionId, 100); } @@ -100,7 +100,7 @@ public static function convertOpenldapVersionId($versionId): string * * @return string */ - private static function convertVersionId($versionId, $base): string + private static function convertVersionId(int $versionId, int $base): string { return sprintf( '%d.%d.%d', diff --git a/src/Composer/Plugin/CommandEvent.php b/src/Composer/Plugin/CommandEvent.php index 650757ff9047..03d621eb5454 100644 --- a/src/Composer/Plugin/CommandEvent.php +++ b/src/Composer/Plugin/CommandEvent.php @@ -48,7 +48,7 @@ class CommandEvent extends Event * @param mixed[] $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ - public function __construct($name, $commandName, $input, $output, array $args = array(), array $flags = array()) + public function __construct(string $name, string $commandName, InputInterface $input, OutputInterface $output, array $args = array(), array $flags = array()) { parent::__construct($name, $args, $flags); $this->commandName = $commandName; diff --git a/src/Composer/Plugin/PluginManager.php b/src/Composer/Plugin/PluginManager.php index b849de107fc2..537f3b6ecc5d 100644 --- a/src/Composer/Plugin/PluginManager.php +++ b/src/Composer/Plugin/PluginManager.php @@ -13,7 +13,6 @@ namespace Composer\Plugin; use Composer\Composer; -use Composer\Autoload\AutoloadGenerator; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\Installer\InstallerInterface; use Composer\IO\IOInterface; @@ -150,7 +149,7 @@ public function getGlobalComposer(): ?PartialComposer * * @throws \UnexpectedValueException */ - public function registerPackage(PackageInterface $package, $failOnMissingClasses = false, $isGlobalPlugin = false): void + public function registerPackage(PackageInterface $package, bool $failOnMissingClasses = false, bool $isGlobalPlugin = false): void { if ($this->disablePlugins) { return; @@ -383,7 +382,7 @@ protected function getPluginApiVersion(): string * * @return void */ - public function addPlugin(PluginInterface $plugin, $isGlobalPlugin = false, PackageInterface $sourcePackage = null): void + public function addPlugin(PluginInterface $plugin, bool $isGlobalPlugin = false, PackageInterface $sourcePackage = null): void { if ($sourcePackage === null) { trigger_error('Calling PluginManager::addPlugin without $sourcePackage is deprecated, if you are using this please get in touch with us to explain the use case', E_USER_DEPRECATED); @@ -467,7 +466,7 @@ public function uninstallPlugin(PluginInterface $plugin): void * * @throws \RuntimeException */ - private function loadRepository(RepositoryInterface $repo, $isGlobalRepo): void + private function loadRepository(RepositoryInterface $repo, bool $isGlobalRepo): void { $packages = $repo->getPackages(); $sortedPackages = PackageSorter::sortPackages($packages); @@ -494,7 +493,7 @@ private function loadRepository(RepositoryInterface $repo, $isGlobalRepo): void * * @return void */ - private function deactivateRepository(RepositoryInterface $repo, $isGlobalRepo): void + private function deactivateRepository(RepositoryInterface $repo, bool $isGlobalRepo): void { $packages = $repo->getPackages(); $sortedPackages = array_reverse(PackageSorter::sortPackages($packages)); @@ -543,13 +542,14 @@ private function collectDependencies(InstalledRepository $installedRepo, array $ * * @return string Install path */ - private function getInstallPath(PackageInterface $package, $global = false): string + private function getInstallPath(PackageInterface $package, bool $global = false): string { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } assert(null !== $this->globalComposer); + return $this->globalComposer->getInstallationManager()->getInstallPath($package); } @@ -559,7 +559,7 @@ private function getInstallPath(PackageInterface $package, $global = false): str * @throws \RuntimeException On empty or non-string implementation class name value * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it */ - protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability): ?string + protected function getCapabilityImplementationClassName(PluginInterface $plugin, string $capability): ?string { if (!($plugin instanceof Capable)) { return null; @@ -666,7 +666,7 @@ private function parseAllowedPlugins($allowPluginsConfig): ?array * @param bool $isGlobalPlugin * @return bool */ - private function isPluginAllowed($package, $isGlobalPlugin): bool + private function isPluginAllowed(string $package, bool $isGlobalPlugin): bool { static $warned = array(); $rules = $isGlobalPlugin ? $this->allowGlobalPluginRules : $this->allowPluginRules; diff --git a/src/Composer/Plugin/PostFileDownloadEvent.php b/src/Composer/Plugin/PostFileDownloadEvent.php index 80489af9df0e..5fecd9b0155a 100644 --- a/src/Composer/Plugin/PostFileDownloadEvent.php +++ b/src/Composer/Plugin/PostFileDownloadEvent.php @@ -57,7 +57,7 @@ class PostFileDownloadEvent extends Event * @param string $type The type (package or metadata). * @param mixed $context Additional context for the download. */ - public function __construct($name, $fileName, $checksum, $url, $type, $context = null) + public function __construct(string $name, ?string $fileName, ?string $checksum, string $url, string $type, $context = null) { /** @phpstan-ignore-next-line */ if ($context === null && $type instanceof PackageInterface) { @@ -127,7 +127,7 @@ public function getContext() * @return \Composer\Package\PackageInterface|null The package. * @deprecated Use getContext instead */ - public function getPackage(): ?\Composer\Package\PackageInterface + public function getPackage(): ?PackageInterface { trigger_error('PostFileDownloadEvent::getPackage is deprecated since Composer 2.1, use getContext instead.', E_USER_DEPRECATED); $context = $this->getContext(); diff --git a/src/Composer/Plugin/PreCommandRunEvent.php b/src/Composer/Plugin/PreCommandRunEvent.php index 2c534a68eb8e..bb0d9a9a4ff7 100644 --- a/src/Composer/Plugin/PreCommandRunEvent.php +++ b/src/Composer/Plugin/PreCommandRunEvent.php @@ -39,7 +39,7 @@ class PreCommandRunEvent extends Event * @param InputInterface $input * @param string $command The command about to be executed */ - public function __construct($name, InputInterface $input, $command) + public function __construct(string $name, InputInterface $input, string $command) { parent::__construct($name); $this->input = $input; diff --git a/src/Composer/Plugin/PreFileDownloadEvent.php b/src/Composer/Plugin/PreFileDownloadEvent.php index 5b9b0307a039..762952840abe 100644 --- a/src/Composer/Plugin/PreFileDownloadEvent.php +++ b/src/Composer/Plugin/PreFileDownloadEvent.php @@ -61,7 +61,7 @@ class PreFileDownloadEvent extends Event * @param string $type * @param mixed $context */ - public function __construct($name, HttpDownloader $httpDownloader, $processedUrl, $type, $context = null) + public function __construct(string $name, HttpDownloader $httpDownloader, string $processedUrl, string $type, $context = null) { parent::__construct($name); $this->httpDownloader = $httpDownloader; @@ -95,7 +95,7 @@ public function getProcessedUrl(): string * * @return void */ - public function setProcessedUrl($processedUrl): void + public function setProcessedUrl(string $processedUrl): void { $this->processedUrl = $processedUrl; } @@ -117,7 +117,7 @@ public function getCustomCacheKey(): ?string * * @return void */ - public function setCustomCacheKey($customCacheKey): void + public function setCustomCacheKey(?string $customCacheKey): void { $this->customCacheKey = $customCacheKey; } diff --git a/src/Composer/Plugin/PrePoolCreateEvent.php b/src/Composer/Plugin/PrePoolCreateEvent.php index d64e96d95e52..c647378ac8cf 100644 --- a/src/Composer/Plugin/PrePoolCreateEvent.php +++ b/src/Composer/Plugin/PrePoolCreateEvent.php @@ -76,7 +76,7 @@ class PrePoolCreateEvent extends Event * @phpstan-param array> $rootAliases * @phpstan-param array $rootReferences */ - public function __construct($name, array $repositories, Request $request, array $acceptableStabilities, array $stabilityFlags, array $rootAliases, array $rootReferences, array $packages, array $unacceptableFixedPackages) + public function __construct(string $name, array $repositories, Request $request, array $acceptableStabilities, array $stabilityFlags, array $rootAliases, array $rootReferences, array $packages, array $unacceptableFixedPackages) { parent::__construct($name); diff --git a/src/Composer/Question/StrictConfirmationQuestion.php b/src/Composer/Question/StrictConfirmationQuestion.php index bcb339bda44e..c656a6126227 100644 --- a/src/Composer/Question/StrictConfirmationQuestion.php +++ b/src/Composer/Question/StrictConfirmationQuestion.php @@ -38,7 +38,7 @@ class StrictConfirmationQuestion extends Question * @param non-empty-string $trueAnswerRegex A regex to match the "yes" answer * @param non-empty-string $falseAnswerRegex A regex to match the "no" answer */ - public function __construct($question, $default = true, $trueAnswerRegex = '/^y(?:es)?$/i', $falseAnswerRegex = '/^no?$/i') + public function __construct(string $question, bool $default = true, string $trueAnswerRegex = '/^y(?:es)?$/i', string $falseAnswerRegex = '/^no?$/i') { parent::__construct($question, (bool) $default); diff --git a/src/Composer/Repository/ArrayRepository.php b/src/Composer/Repository/ArrayRepository.php index 5186164453ba..d1a10e3ea287 100644 --- a/src/Composer/Repository/ArrayRepository.php +++ b/src/Composer/Repository/ArrayRepository.php @@ -97,7 +97,7 @@ public function loadPackages(array $packageMap, array $acceptableStabilities, ar /** * @inheritDoc */ - public function findPackage($name, $constraint) + public function findPackage(string $name, $constraint) { $name = strtolower($name); @@ -121,7 +121,7 @@ public function findPackage($name, $constraint) /** * @inheritDoc */ - public function findPackages($name, $constraint = null) + public function findPackages(string $name, $constraint = null) { // normalize name $name = strtolower($name); @@ -146,7 +146,7 @@ public function findPackages($name, $constraint = null) /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null) + public function search(string $query, int $mode = 0, ?string $type = null) { if ($mode === self::SEARCH_FULLTEXT) { $regex = '{(?:'.implode('|', Preg::split('{\s+}', preg_quote($query))).')}i'; @@ -237,7 +237,7 @@ public function addPackage(PackageInterface $package) /** * @inheritDoc */ - public function getProviders($packageName) + public function getProviders(string $packageName) { $result = array(); @@ -266,7 +266,7 @@ public function getProviders($packageName) * * @return AliasPackage|CompleteAliasPackage */ - protected function createAliasPackage(BasePackage $package, $alias, $prettyAlias) + protected function createAliasPackage(BasePackage $package, string $alias, string $prettyAlias) { while ($package instanceof AliasPackage) { $package = $package->getAliasOf(); diff --git a/src/Composer/Repository/ArtifactRepository.php b/src/Composer/Repository/ArtifactRepository.php index 7db28bcabeb8..0739ba1bcfaf 100644 --- a/src/Composer/Repository/ArtifactRepository.php +++ b/src/Composer/Repository/ArtifactRepository.php @@ -73,7 +73,7 @@ protected function initialize() * * @return void */ - private function scanDirectory($path): void + private function scanDirectory(string $path): void { $io = $this->io; diff --git a/src/Composer/Repository/ComposerRepository.php b/src/Composer/Repository/ComposerRepository.php index 9e6adbaf6ac3..22f8c5548ff9 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -187,7 +187,7 @@ public function getRepoConfig() /** * @inheritDoc */ - public function findPackage($name, $constraint) + public function findPackage(string $name, $constraint) { // this call initializes loadRootServerFile which is needed for the rest below to work $hasProviders = $this->hasProviders(); @@ -227,7 +227,7 @@ public function findPackage($name, $constraint) /** * @inheritDoc */ - public function findPackages($name, $constraint = null) + public function findPackages(string $name, $constraint = null) { // this call initializes loadRootServerFile which is needed for the rest below to work $hasProviders = $this->hasProviders(); @@ -271,7 +271,7 @@ public function findPackages($name, $constraint = null) * * @return BasePackage|array|null */ - private function filterPackages(array $packages, $constraint = null, $returnFirstMatch = false) + private function filterPackages(array $packages, ?ConstraintInterface $constraint = null, bool $returnFirstMatch = false) { if (null === $constraint) { if ($returnFirstMatch) { @@ -341,7 +341,7 @@ public function getPackages() * * @return string[] */ - public function getPackageNames($packageFilter = null) + public function getPackageNames(?string $packageFilter = null) { $hasProviders = $this->hasProviders(); @@ -431,7 +431,7 @@ private function getVendorNames(): array * @param string|null $packageFilter * @return list */ - private function loadPackageList($packageFilter = null): array + private function loadPackageList(?string $packageFilter = null): array { if (null === $this->listUrl) { throw new \LogicException('Make sure to call loadRootServerFile before loadPackageList'); @@ -532,7 +532,7 @@ public function loadPackages(array $packageNameMap, array $acceptableStabilities /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null) + public function search(string $query, int $mode = 0, ?string $type = null) { $this->loadRootServerFile(600); @@ -598,7 +598,7 @@ public function search($query, $mode = 0, $type = null) return parent::search($query, $mode); } - public function getProviders($packageName) + public function getProviders(string $packageName) { $this->loadRootServerFile(); $result = array(); @@ -661,10 +661,7 @@ private function getProviderNames(): array return array(); } - /** - * @return void - */ - protected function configurePackageTransportOptions(PackageInterface $package) + protected function configurePackageTransportOptions(PackageInterface $package): void { foreach ($package->getDistUrls() as $url) { if (strpos($url, $this->baseUrl) === 0) { @@ -695,7 +692,7 @@ private function hasProviders(): bool * * @return array */ - private function whatProvides($name, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()): array + private function whatProvides(string $name, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()): array { $packagesSource = null; if (!$this->hasPartialPackages() || !isset($this->partialPackagesByName[$name])) { @@ -973,7 +970,7 @@ private function loadAsyncPackages(array $packageNames, array $acceptableStabili * * @return bool */ - private function isVersionAcceptable($constraint, $name, $versionData, array $acceptableStabilities = null, array $stabilityFlags = null): bool + private function isVersionAcceptable(?ConstraintInterface $constraint, string $name, array $versionData, array $acceptableStabilities = null, array $stabilityFlags = null): bool { $versions = array($versionData['version_normalized']); @@ -1014,7 +1011,7 @@ private function getPackagesJsonUrl(): string * @param int|null $rootMaxAge * @return array */ - protected function loadRootServerFile($rootMaxAge = null) + protected function loadRootServerFile(?int $rootMaxAge = null): array { if (null !== $this->rootData) { return $this->rootData; @@ -1136,7 +1133,7 @@ protected function loadRootServerFile($rootMaxAge = null) * * @return string */ - private function canonicalizeUrl($url): string + private function canonicalizeUrl(string $url): string { if ('/' === $url[0]) { if (Preg::isMatch('{^[^:]++://[^/]*+}', $this->url, $matches)) { @@ -1206,7 +1203,7 @@ private function loadProviderListings($data): void * * @return mixed[] */ - private function loadIncludes($data): array + private function loadIncludes(array $data): array { $packages = array(); @@ -1251,7 +1248,7 @@ private function loadIncludes($data): array * * @return list */ - private function createPackages(array $packages, $source = null): array + private function createPackages(array $packages, ?string $source = null): array { if (!$packages) { return array(); @@ -1288,7 +1285,7 @@ private function createPackages(array $packages, $source = null): array * * @return array */ - protected function fetchFile($filename, $cacheKey = null, $sha256 = null, $storeLastModifiedTime = false) + protected function fetchFile(string $filename, ?string $cacheKey = null, ?string $sha256 = null, bool $storeLastModifiedTime = false) { if (null === $cacheKey) { $cacheKey = $filename; @@ -1395,7 +1392,7 @@ protected function fetchFile($filename, $cacheKey = null, $sha256 = null, $store * * @return array|true */ - private function fetchFileIfLastModified($filename, $cacheKey, $lastModifiedTime) + private function fetchFileIfLastModified(string $filename, string $cacheKey, string $lastModifiedTime) { try { $options = $this->options; @@ -1459,7 +1456,7 @@ private function fetchFileIfLastModified($filename, $cacheKey, $lastModifiedTime * @param string $cacheKey * @param string|null $lastModifiedTime */ - private function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null): PromiseInterface + private function asyncFetchFile(string $filename, string $cacheKey, ?string $lastModifiedTime = null): PromiseInterface { if (isset($this->packagesNotFoundCache[$filename])) { return \React\Promise\resolve(array('packages' => array())); @@ -1589,7 +1586,7 @@ private function initializePartialPackages(): void * @param string $name * @return bool true if the package name is present in availablePackages or matched by availablePackagePatterns */ - protected function lazyProvidersRepoContains($name) + protected function lazyProvidersRepoContains(string $name) { if (!$this->hasAvailablePackageList) { throw new \LogicException('lazyProvidersRepoContains should not be called unless hasAvailablePackageList is true'); diff --git a/src/Composer/Repository/CompositeRepository.php b/src/Composer/Repository/CompositeRepository.php index e34ce7357995..3d31aa1debdc 100644 --- a/src/Composer/Repository/CompositeRepository.php +++ b/src/Composer/Repository/CompositeRepository.php @@ -125,7 +125,7 @@ public function loadPackages(array $packageMap, array $acceptableStabilities, ar /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null): array + public function search(string $query, int $mode = 0, ?string $type = null): array { $matches = array(); foreach ($this->repositories as $repository) { diff --git a/src/Composer/Repository/FilesystemRepository.php b/src/Composer/Repository/FilesystemRepository.php index ea9a0eeb1eac..81745ed7bc86 100644 --- a/src/Composer/Repository/FilesystemRepository.php +++ b/src/Composer/Repository/FilesystemRepository.php @@ -19,6 +19,7 @@ use Composer\Package\Dumper\ArrayDumper; use Composer\Installer\InstallationManager; use Composer\Util\Filesystem; +use Composer\Util\Platform; /** * Filesystem repository. @@ -46,7 +47,7 @@ class FilesystemRepository extends WritableArrayRepository * @param bool $dumpVersions * @param ?RootPackageInterface $rootPackage Must be provided if $dumpVersions is true */ - public function __construct(JsonFile $repositoryFile, $dumpVersions = false, RootPackageInterface $rootPackage = null, Filesystem $filesystem = null) + public function __construct(JsonFile $repositoryFile, bool $dumpVersions = false, RootPackageInterface $rootPackage = null, Filesystem $filesystem = null) { parent::__construct(); $this->file = $repositoryFile; @@ -115,7 +116,7 @@ public function reload() /** * Writes writable repository. */ - public function write($devMode, InstallationManager $installationManager) + public function write(bool $devMode, InstallationManager $installationManager) { $data = array('packages' => array(), 'dev' => $devMode, 'dev-package-names' => array()); $dumper = new ArrayDumper(); @@ -134,7 +135,7 @@ public function write($devMode, InstallationManager $installationManager) $path = $installationManager->getInstallPath($package); $installPath = null; if ('' !== $path && null !== $path) { - $normalizedPath = $this->filesystem->normalizePath($this->filesystem->isAbsolutePath($path) ? $path : getcwd() . '/' . $path); + $normalizedPath = $this->filesystem->normalizePath($this->filesystem->isAbsolutePath($path) ? $path : Platform::getCwd() . '/' . $path); $installPath = $this->filesystem->findShortestPath($repoDir, $normalizedPath, true); } $installPaths[$package->getName()] = $installPath; @@ -173,7 +174,7 @@ public function write($devMode, InstallationManager $installationManager) * * @return string */ - private function dumpToPhpCode(array $array = array(), $level = 0): string + private function dumpToPhpCode(array $array = array(), int $level = 0): string { $lines = "array(\n"; $level++; @@ -211,7 +212,7 @@ private function dumpToPhpCode(array $array = array(), $level = 0): string * * @return ?array */ - private function generateInstalledVersions(InstallationManager $installationManager, array $installPaths, $devMode, $repoDir): ?array + private function generateInstalledVersions(InstallationManager $installationManager, array $installPaths, bool $devMode, string $repoDir): ?array { if (!$this->dumpVersions) { return null; @@ -241,7 +242,7 @@ private function generateInstalledVersions(InstallationManager $installationMana } if ($package instanceof RootPackageInterface) { - $to = $this->filesystem->normalizePath(realpath(getcwd())); + $to = $this->filesystem->normalizePath(realpath(Platform::getCwd())); $installPath = $this->filesystem->findShortestPath($repoDir, $to, true); } else { $installPath = $installPaths[$package->getName()]; diff --git a/src/Composer/Repository/FilterRepository.php b/src/Composer/Repository/FilterRepository.php index fc5acd776755..db678a3f3d73 100644 --- a/src/Composer/Repository/FilterRepository.php +++ b/src/Composer/Repository/FilterRepository.php @@ -135,7 +135,7 @@ public function loadPackages(array $packageMap, array $acceptableStabilities, ar /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null): array + public function search(string $query, int $mode = 0, ?string $type = null): array { $result = array(); @@ -195,7 +195,7 @@ public function count(): int * * @return bool */ - private function isAllowed($name): bool + private function isAllowed(string $name): bool { if (!$this->only && !$this->exclude) { return true; diff --git a/src/Composer/Repository/InstalledRepository.php b/src/Composer/Repository/InstalledRepository.php index e99ed95db7f3..c3157372164d 100644 --- a/src/Composer/Repository/InstalledRepository.php +++ b/src/Composer/Repository/InstalledRepository.php @@ -38,7 +38,7 @@ class InstalledRepository extends CompositeRepository * * @return BasePackage[] */ - public function findPackagesWithReplacersAndProviders($name, $constraint = null): array + public function findPackagesWithReplacersAndProviders(string $name, $constraint = null): array { $name = strtolower($name); @@ -87,7 +87,7 @@ public function findPackagesWithReplacersAndProviders($name, $constraint = null) * @return array[] An associative array of arrays as described above. * @phpstan-return array */ - public function getDependents($needle, $constraint = null, $invert = false, $recurse = true, $packagesFound = null): array + public function getDependents($needle, ?ConstraintInterface $constraint = null, bool $invert = false, bool $recurse = true, array $packagesFound = null): array { $needles = array_map('strtolower', (array) $needle); $results = array(); diff --git a/src/Composer/Repository/PlatformRepository.php b/src/Composer/Repository/PlatformRepository.php index 4722f9899743..461191e4a2ae 100644 --- a/src/Composer/Repository/PlatformRepository.php +++ b/src/Composer/Repository/PlatformRepository.php @@ -93,7 +93,7 @@ public function getRepoName(): string * @param string $name * @return bool */ - public function isPlatformPackageDisabled($name): bool + public function isPlatformPackageDisabled(string $name): bool { return isset($this->disabledPackages[$name]); } @@ -327,8 +327,8 @@ protected function initialize(): void } // ICU TZData version => 2019c - if (Preg::isMatch('/^ICU TZData version => (?.*)$/im', $info, $zoneinfoMatches)) { - $this->addLibrary('icu-zoneinfo', Version::parseZoneinfoVersion($zoneinfoMatches['version']), 'zoneinfo ("Olson") database for icu'); + if (Preg::isMatch('/^ICU TZData version => (?.*)$/im', $info, $zoneinfoMatches) && null !== ($version = Version::parseZoneinfoVersion($zoneinfoMatches['version']))) { + $this->addLibrary('icu-zoneinfo', $version, 'zoneinfo ("Olson") database for icu'); } // Add a separate version for the CLDR library version @@ -586,7 +586,7 @@ public function addPackage(PackageInterface $package): void * * @return CompletePackage */ - private function addOverriddenPackage(array $override, $name = null): CompletePackage + private function addOverriddenPackage(array $override, ?string $name = null): CompletePackage { $version = $this->versionParser->normalize($override['version']); $package = new CompletePackage($name ?: $override['name'], $version, $override['version']); @@ -620,7 +620,7 @@ private function addDisabledPackage(CompletePackage $package): void * * @return void */ - private function addExtension($name, $prettyVersion): void + private function addExtension(string $name, ?string $prettyVersion): void { $extraDescription = null; @@ -653,7 +653,7 @@ private function addExtension($name, $prettyVersion): void * @param string $name * @return string */ - private function buildPackageName($name): string + private function buildPackageName(string $name): string { return 'ext-' . str_replace(' ', '-', strtolower($name)); } @@ -667,7 +667,7 @@ private function buildPackageName($name): string * * @return void */ - private function addLibrary($name, $prettyVersion, $description = null, array $replaces = array(), array $provides = array()): void + private function addLibrary(string $name, string $prettyVersion, ?string $description = null, array $replaces = array(), array $provides = array()): void { try { $version = $this->versionParser->normalize($prettyVersion); @@ -704,7 +704,7 @@ private function addLibrary($name, $prettyVersion, $description = null, array $r * @param string $name * @return bool */ - public static function isPlatformPackage($name): bool + public static function isPlatformPackage(string $name): bool { static $cache = array(); @@ -730,7 +730,7 @@ public static function getPlatformPhpVersion(): ?string return self::$lastSeenPlatformPhp; } - public function search($query, $mode = 0, $type = null): array + public function search(string $query, int $mode = 0, ?string $type = null): array { // suppress vendor search as there are no vendors to match in platform packages if ($mode === self::SEARCH_VENDOR) { diff --git a/src/Composer/Repository/RepositoryFactory.php b/src/Composer/Repository/RepositoryFactory.php index 9dbfcb1bb867..80e03eff89c3 100644 --- a/src/Composer/Repository/RepositoryFactory.php +++ b/src/Composer/Repository/RepositoryFactory.php @@ -33,7 +33,7 @@ class RepositoryFactory * @param bool $allowFilesystem * @return array|mixed */ - public static function configFromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false) + public static function configFromString(IOInterface $io, Config $config, string $repository, bool $allowFilesystem = false) { if (0 === strpos($repository, 'http')) { $repoConfig = array('type' => 'composer', 'url' => $repository); @@ -64,7 +64,7 @@ public static function configFromString(IOInterface $io, Config $config, $reposi * @param bool $allowFilesystem * @return RepositoryInterface */ - public static function fromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false, RepositoryManager $rm = null): RepositoryInterface + public static function fromString(IOInterface $io, Config $config, string $repository, bool $allowFilesystem = false, RepositoryManager $rm = null): RepositoryInterface { $repoConfig = static::configFromString($io, $config, $repository, $allowFilesystem); diff --git a/src/Composer/Repository/RepositoryInterface.php b/src/Composer/Repository/RepositoryInterface.php index 9debf589dd82..0de31edd3d64 100644 --- a/src/Composer/Repository/RepositoryInterface.php +++ b/src/Composer/Repository/RepositoryInterface.php @@ -46,7 +46,7 @@ public function hasPackage(PackageInterface $package); * * @return BasePackage|null */ - public function findPackage($name, $constraint); + public function findPackage(string $name, $constraint); /** * Searches for all packages matching a name and optionally a version. @@ -56,7 +56,7 @@ public function findPackage($name, $constraint); * * @return BasePackage[] */ - public function findPackages($name, $constraint = null); + public function findPackages(string $name, $constraint = null); /** * Returns list of registered packages. @@ -86,14 +86,14 @@ public function loadPackages(array $packageNameMap, array $acceptableStabilities /** * Searches the repository for packages containing the query * - * @param string $query search query, for SEARCH_NAME and SEARCH_VENDOR regular expressions metacharacters are supported by implementations, and user input should be escaped through preg_quote by callers - * @param int $mode a set of SEARCH_* constants to search on, implementations should do a best effort only, default is SEARCH_FULLTEXT - * @param string $type The type of package to search for. Defaults to all types of packages + * @param string $query search query, for SEARCH_NAME and SEARCH_VENDOR regular expressions metacharacters are supported by implementations, and user input should be escaped through preg_quote by callers + * @param int $mode a set of SEARCH_* constants to search on, implementations should do a best effort only, default is SEARCH_FULLTEXT + * @param ?string $type The type of package to search for. Defaults to all types of packages * * @return array[] an array of array('name' => '...', 'description' => '...'|null, 'abandoned' => 'string'|true|unset) For SEARCH_VENDOR the name will be in "vendor" form * @phpstan-return list */ - public function search($query, $mode = 0, $type = null); + public function search(string $query, int $mode = 0, ?string $type = null); /** * Returns a list of packages providing a given package name @@ -105,7 +105,7 @@ public function search($query, $mode = 0, $type = null); * @return array[] an array with the provider name as key and value of array('name' => '...', 'description' => '...', 'type' => '...') * @phpstan-return array */ - public function getProviders($packageName); + public function getProviders(string $packageName); /** * Returns a name representing this repository to the user diff --git a/src/Composer/Repository/RepositoryManager.php b/src/Composer/Repository/RepositoryManager.php index a230c25e9e44..0f119931ee7b 100644 --- a/src/Composer/Repository/RepositoryManager.php +++ b/src/Composer/Repository/RepositoryManager.php @@ -62,7 +62,7 @@ public function __construct(IOInterface $io, Config $config, HttpDownloader $htt * * @return PackageInterface|null */ - public function findPackage($name, $constraint) + public function findPackage(string $name, $constraint): ?PackageInterface { foreach ($this->repositories as $repository) { /** @var RepositoryInterface $repository */ @@ -82,7 +82,7 @@ public function findPackage($name, $constraint) * * @return PackageInterface[] */ - public function findPackages($name, $constraint) + public function findPackages(string $name, $constraint): array { $packages = array(); @@ -100,7 +100,7 @@ public function findPackages($name, $constraint) * * @return void */ - public function addRepository(RepositoryInterface $repository) + public function addRepository(RepositoryInterface $repository): void { $this->repositories[] = $repository; } @@ -114,7 +114,7 @@ public function addRepository(RepositoryInterface $repository) * * @return void */ - public function prependRepository(RepositoryInterface $repository) + public function prependRepository(RepositoryInterface $repository): void { array_unshift($this->repositories, $repository); } @@ -128,7 +128,7 @@ public function prependRepository(RepositoryInterface $repository) * @throws \InvalidArgumentException if repository for provided type is not registered * @return RepositoryInterface */ - public function createRepository($type, $config, $name = null) + public function createRepository(string $type, array $config, string $name = null): RepositoryInterface { if (!isset($this->repositoryClasses[$type])) { throw new \InvalidArgumentException('Repository type is not registered: '.$type); @@ -162,7 +162,7 @@ public function createRepository($type, $config, $name = null) * * @return void */ - public function setRepositoryClass($type, $class) + public function setRepositoryClass(string $type, $class): void { $this->repositoryClasses[$type] = $class; } @@ -172,7 +172,7 @@ public function setRepositoryClass($type, $class) * * @return RepositoryInterface[] */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -184,7 +184,7 @@ public function getRepositories() * * @return void */ - public function setLocalRepository(InstalledRepositoryInterface $repository) + public function setLocalRepository(InstalledRepositoryInterface $repository): void { $this->localRepository = $repository; } @@ -194,7 +194,7 @@ public function setLocalRepository(InstalledRepositoryInterface $repository) * * @return InstalledRepositoryInterface */ - public function getLocalRepository() + public function getLocalRepository(): InstalledRepositoryInterface { return $this->localRepository; } diff --git a/src/Composer/Repository/RepositorySet.php b/src/Composer/Repository/RepositorySet.php index b01ce59f9c03..d13a423e03ca 100644 --- a/src/Composer/Repository/RepositorySet.php +++ b/src/Composer/Repository/RepositorySet.php @@ -93,7 +93,7 @@ class RepositorySet * @param ConstraintInterface[] $rootRequires an array of package name => constraint from the root package * @phpstan-param array $rootRequires */ - public function __construct($minimumStability = 'stable', array $stabilityFlags = array(), array $rootAliases = array(), array $rootReferences = array(), array $rootRequires = array()) + public function __construct(string $minimumStability = 'stable', array $stabilityFlags = array(), array $rootAliases = array(), array $rootReferences = array(), array $rootRequires = array()) { $this->rootAliases = self::getRootAliasesPerPackage($rootAliases); $this->rootReferences = $rootReferences; @@ -118,7 +118,7 @@ public function __construct($minimumStability = 'stable', array $stabilityFlags * * @return void */ - public function allowInstalledRepositories($allow = true): void + public function allowInstalledRepositories(bool $allow = true): void { $this->allowInstalledRepositories = $allow; } @@ -169,7 +169,7 @@ public function addRepository(RepositoryInterface $repo): void * @param int $flags any of the ALLOW_* constants from this class to tweak what is returned * @return BasePackage[] */ - public function findPackages($name, ConstraintInterface $constraint = null, $flags = 0): array + public function findPackages(string $name, ConstraintInterface $constraint = null, int $flags = 0): array { $ignoreStability = ($flags & self::ALLOW_UNACCEPTABLE_STABILITIES) !== 0; $loadFromAllRepos = ($flags & self::ALLOW_SHADOWED_REPOSITORIES) !== 0; @@ -216,7 +216,7 @@ public function findPackages($name, ConstraintInterface $constraint = null, $fla * @return array[] an array with the provider name as key and value of array('name' => '...', 'description' => '...', 'type' => '...') * @phpstan-return array */ - public function getProviders($packageName): array + public function getProviders(string $packageName): array { $providers = array(); foreach ($this->repositories as $repository) { @@ -235,7 +235,7 @@ public function getProviders($packageName): array * @param string $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev' * @return bool */ - public function isPackageAcceptable($names, $stability): bool + public function isPackageAcceptable(array $names, string $stability): bool { return StabilityFilter::isPackageAcceptable($this->acceptableStabilities, $this->stabilityFlags, $names, $stability); } @@ -304,7 +304,7 @@ public function createPoolWithAllPackages(): Pool * * @return Pool */ - public function createPoolForPackage($packageName, LockArrayRepository $lockedRepo = null): Pool + public function createPoolForPackage(string $packageName, LockArrayRepository $lockedRepo = null): Pool { // TODO unify this with above in some simpler version without "request"? return $this->createPoolForPackages(array($packageName), $lockedRepo); @@ -315,7 +315,7 @@ public function createPoolForPackage($packageName, LockArrayRepository $lockedRe * * @return Pool */ - public function createPoolForPackages($packageNames, LockArrayRepository $lockedRepo = null): Pool + public function createPoolForPackages(array $packageNames, LockArrayRepository $lockedRepo = null): Pool { $request = new Request($lockedRepo); diff --git a/src/Composer/Repository/Vcs/FossilDriver.php b/src/Composer/Repository/Vcs/FossilDriver.php index 8304c61c8cc8..1fb0fb36bec3 100644 --- a/src/Composer/Repository/Vcs/FossilDriver.php +++ b/src/Composer/Repository/Vcs/FossilDriver.php @@ -141,7 +141,7 @@ public function getUrl(): string /** * @inheritDoc */ - public function getSource($identifier): array + public function getSource(string $identifier): array { return array('type' => 'fossil', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -149,7 +149,7 @@ public function getSource($identifier): array /** * @inheritDoc */ - public function getDist($identifier): ?array + public function getDist(string $identifier): ?array { return null; } @@ -157,7 +157,7 @@ public function getDist($identifier): ?array /** * @inheritDoc */ - public function getFileContent($file, $identifier): ?string + public function getFileContent(string $file, string $identifier): ?string { $command = sprintf('fossil cat -r %s -- %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($command, $content, $this->checkoutDir); @@ -172,12 +172,12 @@ public function getFileContent($file, $identifier): ?string /** * @inheritDoc */ - public function getChangeDate($identifier): ?\DateTime + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $this->process->execute('fossil finfo -b -n 1 composer.json', $output, $this->checkoutDir); list(, $date) = explode(' ', trim($output), 3); - return new \DateTime($date, new \DateTimeZone('UTC')); + return new \DateTimeImmutable($date, new \DateTimeZone('UTC')); } /** @@ -222,7 +222,7 @@ public function getBranches(): array /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false): bool + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (Preg::isMatch('#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i', $url)) { return true; diff --git a/src/Composer/Repository/Vcs/GitBitbucketDriver.php b/src/Composer/Repository/Vcs/GitBitbucketDriver.php index dd4033991985..1e045c3e907e 100644 --- a/src/Composer/Repository/Vcs/GitBitbucketDriver.php +++ b/src/Composer/Repository/Vcs/GitBitbucketDriver.php @@ -59,7 +59,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { if (!Preg::isMatch('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i', $this->url, $match)) { throw new \InvalidArgumentException(sprintf('The Bitbucket repository URL %s is invalid. It must be the HTTPS URL of a Bitbucket repository.', $this->url)); @@ -83,7 +83,7 @@ public function initialize() /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { if ($this->fallbackDriver) { return $this->fallbackDriver->getUrl(); @@ -99,7 +99,7 @@ public function getUrl() * @return bool * @phpstan-impure */ - protected function getRepoData() + protected function getRepoData(): bool { $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s?%s', @@ -131,7 +131,7 @@ protected function getRepoData() /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier): ?array { if ($this->fallbackDriver) { return $this->fallbackDriver->getComposerInformation($identifier); @@ -148,7 +148,7 @@ public function getComposerInformation($identifier) } } - if ($composer) { + if ($composer !== null) { // specials for bitbucket if (!isset($composer['support']['source'])) { $label = array_search( @@ -205,7 +205,7 @@ public function getComposerInformation($identifier) /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { if ($this->fallbackDriver) { return $this->fallbackDriver->getFileContent($file, $identifier); @@ -232,7 +232,7 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->fallbackDriver) { return $this->fallbackDriver->getChangeDate($identifier); @@ -253,13 +253,13 @@ public function getChangeDate($identifier) ); $commit = $this->fetchWithOAuthCredentials($resource)->decodeJson(); - return new \DateTime($commit['date']); + return new \DateTimeImmutable($commit['date']); } /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getSource($identifier); @@ -271,7 +271,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { if ($this->fallbackDriver) { return $this->fallbackDriver->getDist($identifier); @@ -290,7 +290,7 @@ public function getDist($identifier) /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getTags(); @@ -333,7 +333,7 @@ public function getTags() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getBranches(); @@ -383,7 +383,7 @@ public function getBranches() * * @phpstan-impure */ - protected function fetchWithOAuthCredentials($url, $fetchingRepoData = false) + protected function fetchWithOAuthCredentials(string $url, bool $fetchingRepoData = false): Response { try { return parent::getContents($url); @@ -413,7 +413,7 @@ protected function fetchWithOAuthCredentials($url, $fetchingRepoData = false) * * @return string */ - protected function generateSshUrl() + protected function generateSshUrl(): string { return 'git@' . $this->originUrl . ':' . $this->owner.'/'.$this->repository.'.git'; } @@ -424,7 +424,7 @@ protected function generateSshUrl() * @return true * @throws \RuntimeException */ - protected function attemptCloneFallback() + protected function attemptCloneFallback(): bool { try { $this->setupFallbackDriver($this->generateSshUrl()); @@ -445,7 +445,7 @@ protected function attemptCloneFallback() * @param string $url * @return void */ - protected function setupFallbackDriver($url) + protected function setupFallbackDriver(string $url): void { $this->fallbackDriver = new GitDriver( array('url' => $url), @@ -461,7 +461,7 @@ protected function setupFallbackDriver($url) * @param array $cloneLinks * @return void */ - protected function parseCloneUrls(array $cloneLinks) + protected function parseCloneUrls(array $cloneLinks): void { foreach ($cloneLinks as $cloneLink) { if ($cloneLink['name'] === 'https') { @@ -475,7 +475,7 @@ protected function parseCloneUrls(array $cloneLinks) /** * @return (array{name: string}&mixed[])|null */ - protected function getMainBranchData() + protected function getMainBranchData(): ?array { $resource = sprintf( 'https://api.bitbucket.org/2.0/repositories/%s/%s?fields=mainbranch', @@ -494,7 +494,7 @@ protected function getMainBranchData() /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if ($this->fallbackDriver) { return $this->fallbackDriver->getRootIdentifier(); @@ -527,7 +527,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (!Preg::isMatch('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i', $url)) { return false; diff --git a/src/Composer/Repository/Vcs/GitDriver.php b/src/Composer/Repository/Vcs/GitDriver.php index cd69d5743d46..978db48ecf68 100644 --- a/src/Composer/Repository/Vcs/GitDriver.php +++ b/src/Composer/Repository/Vcs/GitDriver.php @@ -38,7 +38,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { if (Filesystem::isLocalPath($this->url)) { $this->url = Preg::replace('{[\\/]\.git/?$}', '', $this->url); @@ -88,7 +88,7 @@ public function initialize() /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'master'; @@ -112,7 +112,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -120,7 +120,7 @@ public function getUrl() /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -128,7 +128,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { return null; } @@ -136,7 +136,7 @@ public function getDist($identifier) /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { $resource = sprintf('%s:%s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute(sprintf('git show %s', $resource), $content, $this->repoDir); @@ -151,20 +151,20 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $this->process->execute(sprintf( 'git -c log.showSignature=false log -1 --format=%%at %s', ProcessExecutor::escape($identifier) ), $output, $this->repoDir); - return new \DateTime('@'.trim($output), new \DateTimeZone('UTC')); + return new \DateTimeImmutable('@'.trim($output), new \DateTimeZone('UTC')); } /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if (null === $this->tags) { $this->tags = array(); @@ -183,7 +183,7 @@ public function getTags() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -206,7 +206,7 @@ public function getBranches() /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (Preg::isMatch('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $url)) { return true; diff --git a/src/Composer/Repository/Vcs/GitHubDriver.php b/src/Composer/Repository/Vcs/GitHubDriver.php index 33d7e8cd37ce..548db6e265bf 100644 --- a/src/Composer/Repository/Vcs/GitHubDriver.php +++ b/src/Composer/Repository/Vcs/GitHubDriver.php @@ -57,7 +57,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { if (!Preg::isMatch('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $this->url, $match)) { throw new \InvalidArgumentException(sprintf('The GitHub repository URL %s is invalid.', $this->url)); @@ -84,7 +84,7 @@ public function initialize() /** * @return string */ - public function getRepositoryUrl() + public function getRepositoryUrl(): string { return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository; } @@ -92,7 +92,7 @@ public function getRepositoryUrl() /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); @@ -104,7 +104,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { if ($this->gitDriver) { return $this->gitDriver->getUrl(); @@ -116,7 +116,7 @@ public function getUrl() /** * @return string */ - protected function getApiUrl() + protected function getApiUrl(): string { if ('github.com' === $this->originUrl) { $apiUrl = 'api.github.com'; @@ -130,7 +130,7 @@ protected function getApiUrl() /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -149,7 +149,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier; @@ -159,7 +159,7 @@ public function getDist($identifier) /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -176,7 +176,7 @@ public function getComposerInformation($identifier) } } - if ($composer) { + if ($composer !== null) { // specials for github if (!isset($composer['support']['source'])) { $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier; @@ -287,7 +287,7 @@ private function getFundingInfo() /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); @@ -305,7 +305,7 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); @@ -314,13 +314,13 @@ public function getChangeDate($identifier) $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier); $commit = $this->getContents($resource)->decodeJson(); - return new \DateTime($commit['commit']['committer']['date']); + return new \DateTimeImmutable($commit['commit']['committer']['date']); } /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if ($this->gitDriver) { return $this->gitDriver->getTags(); @@ -348,7 +348,7 @@ public function getTags() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if ($this->gitDriver) { return $this->gitDriver->getBranches(); @@ -379,7 +379,7 @@ public function getBranches() /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (!Preg::isMatch('#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) { return false; @@ -404,7 +404,7 @@ public static function supports(IOInterface $io, Config $config, $url, $deep = f * * @return mixed[]|null */ - public function getRepoData() + public function getRepoData(): ?array { $this->fetchRootIdentifier(); @@ -416,7 +416,7 @@ public function getRepoData() * * @return string */ - protected function generateSshUrl() + protected function generateSshUrl(): string { if (false !== strpos($this->originUrl, ':')) { return 'ssh://git@' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git'; @@ -430,7 +430,7 @@ protected function generateSshUrl() * * @param bool $fetchingRepoData */ - protected function getContents($url, $fetchingRepoData = false) + protected function getContents(string $url, bool $fetchingRepoData = false): Response { try { return parent::getContents($url); @@ -521,7 +521,7 @@ protected function getContents($url, $fetchingRepoData = false) * @return void * @throws TransportException */ - protected function fetchRootIdentifier() + protected function fetchRootIdentifier(): void { if ($this->repoData) { return; @@ -563,7 +563,7 @@ protected function fetchRootIdentifier() * @return true * @throws \RuntimeException */ - protected function attemptCloneFallback() + protected function attemptCloneFallback(): bool { $this->isPrivate = true; @@ -588,7 +588,7 @@ protected function attemptCloneFallback() * * @return void */ - protected function setupGitDriver($url) + protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( array('url' => $url), @@ -603,7 +603,7 @@ protected function setupGitDriver($url) /** * @return string|null */ - protected function getNextPage(Response $response) + protected function getNextPage(Response $response): ?string { $header = $response->getHeader('link'); if (!$header) { diff --git a/src/Composer/Repository/Vcs/GitLabDriver.php b/src/Composer/Repository/Vcs/GitLabDriver.php index 85ac75049b7e..047cefa240a5 100644 --- a/src/Composer/Repository/Vcs/GitLabDriver.php +++ b/src/Composer/Repository/Vcs/GitLabDriver.php @@ -144,7 +144,7 @@ public function setHttpDownloader(HttpDownloader $httpDownloader): void /** * @inheritDoc */ - public function getComposerInformation($identifier): array + public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -161,7 +161,7 @@ public function getComposerInformation($identifier): array } } - if ($composer) { + if (null !== $composer) { // specials for gitlab (this data is only available if authentication is provided) if (!isset($composer['support']['source']) && isset($this->project['web_url'])) { $label = array_search($identifier, $this->getTags(), true) ?: array_search($identifier, $this->getBranches(), true) ?: $identifier; @@ -184,7 +184,7 @@ public function getComposerInformation($identifier): array /** * @inheritDoc */ - public function getFileContent($file, $identifier): ?string + public function getFileContent(string $file, string $identifier): ?string { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); @@ -216,17 +216,17 @@ public function getFileContent($file, $identifier): ?string /** * @inheritDoc */ - public function getChangeDate($identifier): ?\DateTime + public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); } if (isset($this->commits[$identifier])) { - return new \DateTime($this->commits[$identifier]['committed_date']); + return new \DateTimeImmutable($this->commits[$identifier]['committed_date']); } - return new \DateTime(); + return null; } /** @@ -256,7 +256,7 @@ public function getUrl(): string /** * @inheritDoc */ - public function getDist($identifier): ?array + public function getDist(string $identifier): ?array { $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier; @@ -266,7 +266,7 @@ public function getDist($identifier): ?array /** * @inheritDoc */ - public function getSource($identifier): array + public function getSource(string $identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -333,7 +333,7 @@ public function getApiUrl(): string * @param string $string * @return string */ - private function urlEncodeAll($string): string + private function urlEncodeAll(string $string): string { $encoded = ''; for ($i = 0; isset($string[$i]); $i++) { @@ -352,7 +352,7 @@ private function urlEncodeAll($string): string * * @return string[] where keys are named references like tags or branches and the value a sha */ - protected function getReferences($type): array + protected function getReferences(string $type): array { $perPage = 100; $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage; @@ -452,7 +452,7 @@ protected function generatePublicUrl(): string * * @return void */ - protected function setupGitDriver($url): void + protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( array('url' => $url), @@ -469,7 +469,7 @@ protected function setupGitDriver($url): void * * @param bool $fetchingRepoData */ - protected function getContents($url, $fetchingRepoData = false): Response + protected function getContents(string $url, bool $fetchingRepoData = false): Response { try { $response = parent::getContents($url); @@ -568,7 +568,7 @@ protected function getContents($url, $fetchingRepoData = false): Response * * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false): bool + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (!Preg::isMatch(self::URL_REGEX, $url, $match)) { return false; @@ -616,7 +616,7 @@ protected function getNextPage(Response $response): ?string * * @return string|false */ - private static function determineOrigin(array $configuredDomains, $guessedDomain, array &$urlParts, $portNumber) + private static function determineOrigin(array $configuredDomains, string $guessedDomain, array &$urlParts, string $portNumber) { $guessedDomain = strtolower($guessedDomain); diff --git a/src/Composer/Repository/Vcs/HgDriver.php b/src/Composer/Repository/Vcs/HgDriver.php index e9b83d6c547c..1faa3c3e3b55 100644 --- a/src/Composer/Repository/Vcs/HgDriver.php +++ b/src/Composer/Repository/Vcs/HgDriver.php @@ -37,7 +37,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { if (Filesystem::isLocalPath($this->url)) { $this->repoDir = $this->url; @@ -86,7 +86,7 @@ public function initialize() /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if (null === $this->rootIdentifier) { $this->process->execute(sprintf('hg tip --template "{node}"'), $output, $this->repoDir); @@ -100,7 +100,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -108,7 +108,7 @@ public function getUrl() /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -116,7 +116,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { return null; } @@ -124,7 +124,7 @@ public function getDist($identifier) /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($resource, $content, $this->repoDir); @@ -139,7 +139,7 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $this->process->execute( sprintf( @@ -150,13 +150,13 @@ public function getChangeDate($identifier) $this->repoDir ); - return new \DateTime(trim($output), new \DateTimeZone('UTC')); + return new \DateTimeImmutable(trim($output), new \DateTimeZone('UTC')); } /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if (null === $this->tags) { $tags = array(); @@ -178,7 +178,7 @@ public function getTags() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -208,7 +208,7 @@ public function getBranches() /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (Preg::isMatch('#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $url)) { return true; diff --git a/src/Composer/Repository/Vcs/PerforceDriver.php b/src/Composer/Repository/Vcs/PerforceDriver.php index b178257f2a7f..1caad14a7557 100644 --- a/src/Composer/Repository/Vcs/PerforceDriver.php +++ b/src/Composer/Repository/Vcs/PerforceDriver.php @@ -18,6 +18,7 @@ use Composer\Pcre\Preg; use Composer\Util\ProcessExecutor; use Composer\Util\Perforce; +use Composer\Util\Http\Response; /** * @author Matt Whittom @@ -34,7 +35,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { $this->depot = $this->repoConfig['depot']; $this->branch = ''; @@ -55,7 +56,7 @@ public function initialize() * * @return void */ - private function initPerforce($repoConfig): void + private function initPerforce(array $repoConfig): void { if (!empty($this->perforce)) { return; @@ -72,7 +73,7 @@ private function initPerforce($repoConfig): void /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { return $this->perforce->getFileContent($file, $identifier); } @@ -80,7 +81,7 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { return null; } @@ -88,7 +89,7 @@ public function getChangeDate($identifier) /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { return $this->branch; } @@ -96,7 +97,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { return $this->perforce->getBranches(); } @@ -104,7 +105,7 @@ public function getBranches() /** * @inheritDoc */ - public function getTags() + public function getTags(): array { return $this->perforce->getTags(); } @@ -112,7 +113,7 @@ public function getTags() /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { return null; } @@ -120,7 +121,7 @@ public function getDist($identifier) /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { return array( 'type' => 'perforce', @@ -133,7 +134,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -141,7 +142,7 @@ public function getUrl() /** * @inheritDoc */ - public function hasComposerFile($identifier) + public function hasComposerFile(string $identifier): bool { $composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier); @@ -151,7 +152,7 @@ public function hasComposerFile($identifier) /** * @inheritDoc */ - public function getContents($url) + public function getContents(string $url): Response { throw new \BadMethodCallException('Not implemented/used in PerforceDriver'); } @@ -159,7 +160,7 @@ public function getContents($url) /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if ($deep || Preg::isMatch('#\b(perforce|p4)\b#i', $url)) { return Perforce::checkServerExists($url, new ProcessExecutor($io)); @@ -171,7 +172,7 @@ public static function supports(IOInterface $io, Config $config, $url, $deep = f /** * @inheritDoc */ - public function cleanup() + public function cleanup(): void { $this->perforce->cleanupClientSpec(); $this->perforce = null; @@ -180,7 +181,7 @@ public function cleanup() /** * @return string */ - public function getDepot() + public function getDepot(): string { return $this->depot; } @@ -188,7 +189,7 @@ public function getDepot() /** * @return string */ - public function getBranch() + public function getBranch(): string { return $this->branch; } diff --git a/src/Composer/Repository/Vcs/SvnDriver.php b/src/Composer/Repository/Vcs/SvnDriver.php index c54b048382a4..0c028b369704 100644 --- a/src/Composer/Repository/Vcs/SvnDriver.php +++ b/src/Composer/Repository/Vcs/SvnDriver.php @@ -57,7 +57,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { $this->url = $this->baseUrl = rtrim(self::normalizeUrl($this->url), '/'); @@ -93,7 +93,7 @@ public function initialize() /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { return $this->rootIdentifier ?: $this->trunkPath; } @@ -101,7 +101,7 @@ public function getRootIdentifier() /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -109,7 +109,7 @@ public function getUrl() /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier): array { return array('type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier); } @@ -117,7 +117,7 @@ public function getSource($identifier) /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier): ?array { return null; } @@ -125,7 +125,7 @@ public function getDist($identifier) /** * @inheritDoc */ - protected function shouldCache($identifier) + protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{@\d+$}', $identifier); } @@ -133,7 +133,7 @@ protected function shouldCache($identifier) /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier): ?array { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier.'.json')) { @@ -165,7 +165,7 @@ public function getComposerInformation($identifier) * @param string $file * @param string $identifier */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { $identifier = '/' . trim($identifier, '/') . '/'; @@ -194,7 +194,7 @@ public function getFileContent($file, $identifier) /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $identifier = '/' . trim($identifier, '/') . '/'; @@ -210,7 +210,7 @@ public function getChangeDate($identifier) $output = $this->execute('svn info', $this->baseUrl . $path . $rev); foreach ($this->process->splitLines($output) as $line) { if ($line && Preg::isMatch('{^Last Changed Date: ([^(]+)}', $line, $match)) { - return new \DateTime($match[1], new \DateTimeZone('UTC')); + return new \DateTimeImmutable($match[1], new \DateTimeZone('UTC')); } } @@ -220,7 +220,7 @@ public function getChangeDate($identifier) /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if (null === $this->tags) { $tags = array(); @@ -251,7 +251,7 @@ public function getTags() /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -306,7 +306,7 @@ public function getBranches() /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { $url = self::normalizeUrl($url); if (Preg::isMatch('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) { @@ -353,7 +353,7 @@ public static function supports(IOInterface $io, Config $config, $url, $deep = f * * @return string */ - protected static function normalizeUrl($url) + protected static function normalizeUrl(string $url): string { $fs = new Filesystem(); if ($fs->isAbsolutePath($url)) { @@ -372,7 +372,7 @@ protected static function normalizeUrl($url) * @throws \RuntimeException * @return string */ - protected function execute($command, $url) + protected function execute(string $command, string $url): string { if (null === $this->util) { $this->util = new SvnUtil($this->baseUrl, $this->io, $this->config, $this->process); @@ -400,7 +400,7 @@ protected function execute($command, $url) * * @return string */ - protected function buildIdentifier($baseDir, $revision) + protected function buildIdentifier(string $baseDir, int $revision): string { return rtrim($baseDir, '/') . $this->packagePath . '/@' . $revision; } diff --git a/src/Composer/Repository/Vcs/VcsDriver.php b/src/Composer/Repository/Vcs/VcsDriver.php index b7f7fb97658f..8656aa69df19 100644 --- a/src/Composer/Repository/Vcs/VcsDriver.php +++ b/src/Composer/Repository/Vcs/VcsDriver.php @@ -79,7 +79,7 @@ final public function __construct(array $repoConfig, IOInterface $io, Config $co * @param string $identifier * @return bool */ - protected function shouldCache($identifier) + protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{^[a-f0-9]{40}$}iD', $identifier); } @@ -87,7 +87,7 @@ protected function shouldCache($identifier) /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier): ?array { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { @@ -111,7 +111,7 @@ public function getComposerInformation($identifier) * * @return array|null */ - protected function getBaseComposerInformation($identifier) + protected function getBaseComposerInformation(string $identifier): ?array { $composerFileContent = $this->getFileContent('composer.json', $identifier); @@ -121,7 +121,7 @@ protected function getBaseComposerInformation($identifier) $composer = JsonFile::parseJson($composerFileContent, $identifier . ':composer.json'); - if (empty($composer['time']) && $changeDate = $this->getChangeDate($identifier)) { + if (empty($composer['time']) && null !== ($changeDate = $this->getChangeDate($identifier))) { $composer['time'] = $changeDate->format(DATE_RFC3339); } @@ -131,7 +131,7 @@ protected function getBaseComposerInformation($identifier) /** * @inheritDoc */ - public function hasComposerFile($identifier) + public function hasComposerFile(string $identifier): bool { try { return (bool) $this->getComposerInformation($identifier); @@ -148,7 +148,7 @@ public function hasComposerFile($identifier) * * @return string The correct type of protocol */ - protected function getScheme() + protected function getScheme(): string { if (extension_loaded('openssl')) { return 'https'; @@ -165,7 +165,7 @@ protected function getScheme() * @return Response * @throws TransportException */ - protected function getContents($url) + protected function getContents(string $url): Response { $options = $this->repoConfig['options'] ?? array(); @@ -175,7 +175,7 @@ protected function getContents($url) /** * @inheritDoc */ - public function cleanup() + public function cleanup(): void { return; } diff --git a/src/Composer/Repository/Vcs/VcsDriverInterface.php b/src/Composer/Repository/Vcs/VcsDriverInterface.php index b8c5e842d297..9acf2e7023c6 100644 --- a/src/Composer/Repository/Vcs/VcsDriverInterface.php +++ b/src/Composer/Repository/Vcs/VcsDriverInterface.php @@ -17,6 +17,7 @@ /** * @author Jordi Boggiano + * @internal */ interface VcsDriverInterface { @@ -25,15 +26,15 @@ interface VcsDriverInterface * * @return void */ - public function initialize(); + public function initialize(): void; /** * Return the composer.json file information * * @param string $identifier Any identifier to a specific branch/tag/commit - * @return mixed[] containing all infos from the composer.json file + * @return mixed[]|null containing all infos from the composer.json file */ - public function getComposerInformation($identifier); + public function getComposerInformation(string $identifier): ?array; /** * Return the content of $file or null if the file does not exist. @@ -42,57 +43,56 @@ public function getComposerInformation($identifier); * @param string $identifier * @return string|null */ - public function getFileContent($file, $identifier); + public function getFileContent(string $file, string $identifier): ?string; /** * Get the changedate for $identifier. * * @param string $identifier - * @return \DateTime|null */ - public function getChangeDate($identifier); + public function getChangeDate(string $identifier): ?\DateTimeImmutable; /** * Return the root identifier (trunk, master, default/tip ..) * * @return string Identifier */ - public function getRootIdentifier(); + public function getRootIdentifier(): string; /** * Return list of branches in the repository * * @return array Branch names as keys, identifiers as values */ - public function getBranches(); + public function getBranches(): array; /** * Return list of tags in the repository * * @return array Tag names as keys, identifiers as values */ - public function getTags(); + public function getTags(): array; /** * @param string $identifier Any identifier to a specific branch/tag/commit * * @return array{type: string, url: string, reference: string, shasum: string}|null */ - public function getDist($identifier); + public function getDist(string $identifier): ?array; /** * @param string $identifier Any identifier to a specific branch/tag/commit * * @return array{type: string, url: string, reference: string} */ - public function getSource($identifier); + public function getSource(string $identifier): array; /** * Return the URL of the repository * * @return string */ - public function getUrl(); + public function getUrl(): string; /** * Return true if the repository has a composer file for a given identifier, @@ -101,14 +101,14 @@ public function getUrl(); * @param string $identifier Any identifier to a specific branch/tag/commit * @return bool Whether the repository has a composer file for a given identifier. */ - public function hasComposerFile($identifier); + public function hasComposerFile(string $identifier): bool; /** * Performs any cleanup necessary as the driver is not longer needed * * @return void */ - public function cleanup(); + public function cleanup(): void; /** * Checks if this driver can handle a given url @@ -119,5 +119,5 @@ public function cleanup(); * @param bool $deep unless true, only shallow checks (url matching typically) should be done * @return bool */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false); + public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool; } diff --git a/src/Composer/Repository/VcsRepository.php b/src/Composer/Repository/VcsRepository.php index 11d8df0e9a06..9978413c748d 100644 --- a/src/Composer/Repository/VcsRepository.php +++ b/src/Composer/Repository/VcsRepository.php @@ -121,7 +121,7 @@ public function getRepoConfig() /** * @return void */ - public function setLoader(LoaderInterface $loader) + public function setLoader(LoaderInterface $loader): void { $this->loader = $loader; } @@ -129,7 +129,7 @@ public function setLoader(LoaderInterface $loader) /** * @return VcsDriverInterface|null */ - public function getDriver() + public function getDriver(): ?VcsDriverInterface { if ($this->driver) { return $this->driver; @@ -167,7 +167,7 @@ public function getDriver() /** * @return bool */ - public function hadInvalidBranches() + public function hadInvalidBranches(): bool { return $this->branchErrorOccurred; } @@ -175,7 +175,7 @@ public function hadInvalidBranches() /** * @return string[] */ - public function getEmptyReferences() + public function getEmptyReferences(): array { return $this->emptyReferences; } @@ -183,7 +183,7 @@ public function getEmptyReferences() /** * @return array<'tags'|'branches', array> */ - public function getVersionTransportExceptions() + public function getVersionTransportExceptions(): array { return $this->versionTransportExceptions; } @@ -254,7 +254,8 @@ protected function initialize() } try { - if (!$data = $driver->getComposerInformation($identifier)) { + $data = $driver->getComposerInformation($identifier); + if (null === $data) { if ($isVeryVerbose) { $this->io->writeError('Skipped tag '.$tag.', no composer file'); } @@ -367,7 +368,8 @@ protected function initialize() } try { - if (!$data = $driver->getComposerInformation($identifier)) { + $data = $driver->getComposerInformation($identifier); + if (null === $data) { if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file'); } @@ -434,7 +436,7 @@ protected function initialize() * * @return array{name: string|null, dist: array{type: string, url: string, reference: string, shasum: string}|null, source: array{type: string, url: string, reference: string}} */ - protected function preProcess(VcsDriverInterface $driver, array $data, $identifier) + protected function preProcess(VcsDriverInterface $driver, array $data, string $identifier): array { // keep the name of the main identifier for all packages // this ensures that a package can be renamed in one place and that all old tags @@ -457,7 +459,7 @@ protected function preProcess(VcsDriverInterface $driver, array $data, $identifi * * @return string|false */ - private function validateBranch($branch) + private function validateBranch(string $branch) { try { $normalizedBranch = $this->versionParser->normalizeBranch($branch); @@ -477,7 +479,7 @@ private function validateBranch($branch) * * @return string|false */ - private function validateTag($version) + private function validateTag(string $version) { try { return $this->versionParser->normalize($version); @@ -496,7 +498,7 @@ private function validateTag($version) * * @return \Composer\Package\CompletePackage|\Composer\Package\CompleteAliasPackage|null|false null if no cache present, false if the absence of a version was cached */ - private function getCachedPackageVersion($version, $identifier, $isVerbose, $isVeryVerbose, $isDefaultBranch = false) + private function getCachedPackageVersion(string $version, string $identifier, bool $isVerbose, bool $isVeryVerbose, bool $isDefaultBranch = false) { if (!$this->versionCache) { return null; diff --git a/src/Composer/Repository/VersionCacheInterface.php b/src/Composer/Repository/VersionCacheInterface.php index 80de9833c614..93572c10a60d 100644 --- a/src/Composer/Repository/VersionCacheInterface.php +++ b/src/Composer/Repository/VersionCacheInterface.php @@ -19,5 +19,5 @@ interface VersionCacheInterface * @param string $identifier * @return mixed[]|null|false Package version data if found, false to indicate the identifier is known but has no package, null for an unknown identifier */ - public function getVersionPackage($version, $identifier); + public function getVersionPackage(string $version, string $identifier); } diff --git a/src/Composer/Repository/WritableArrayRepository.php b/src/Composer/Repository/WritableArrayRepository.php index eb6b595dbb04..6f98ad18dde6 100644 --- a/src/Composer/Repository/WritableArrayRepository.php +++ b/src/Composer/Repository/WritableArrayRepository.php @@ -12,7 +12,6 @@ namespace Composer\Repository; -use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Installer\InstallationManager; @@ -58,7 +57,7 @@ public function getDevPackageNames() /** * @inheritDoc */ - public function write($devMode, InstallationManager $installationManager) + public function write(bool $devMode, InstallationManager $installationManager) { $this->devMode = $devMode; } diff --git a/src/Composer/Repository/WritableRepositoryInterface.php b/src/Composer/Repository/WritableRepositoryInterface.php index 376af210897b..8e7eac21efcb 100644 --- a/src/Composer/Repository/WritableRepositoryInterface.php +++ b/src/Composer/Repository/WritableRepositoryInterface.php @@ -28,7 +28,7 @@ interface WritableRepositoryInterface extends RepositoryInterface * @param bool $devMode Whether dev requirements were included or not in this installation * @return void */ - public function write($devMode, InstallationManager $installationManager); + public function write(bool $devMode, InstallationManager $installationManager); /** * Adds package to the repository. diff --git a/src/Composer/Script/Event.php b/src/Composer/Script/Event.php index 3ddf2eae0000..0f05a72912f1 100644 --- a/src/Composer/Script/Event.php +++ b/src/Composer/Script/Event.php @@ -40,7 +40,7 @@ class Event extends BaseEvent private $devMode; /** - * @var BaseEvent + * @var BaseEvent|null */ private $originatingEvent; @@ -54,7 +54,7 @@ class Event extends BaseEvent * @param array $args Arguments passed by the user * @param mixed[] $flags Optional flags to pass data not as argument */ - public function __construct($name, Composer $composer, IOInterface $io, $devMode = false, array $args = array(), array $flags = array()) + public function __construct(string $name, Composer $composer, IOInterface $io, bool $devMode = false, array $args = array(), array $flags = array()) { parent::__construct($name, $args, $flags); $this->composer = $composer; @@ -67,7 +67,7 @@ public function __construct($name, Composer $composer, IOInterface $io, $devMode * * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -77,7 +77,7 @@ public function getComposer() * * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -87,7 +87,7 @@ public function getIO() * * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } @@ -97,7 +97,7 @@ public function isDevMode() * * @return ?BaseEvent */ - public function getOriginatingEvent() + public function getOriginatingEvent(): ?BaseEvent { return $this->originatingEvent; } @@ -108,7 +108,7 @@ public function getOriginatingEvent() * @param BaseEvent $event * @return $this */ - public function setOriginatingEvent(BaseEvent $event) + public function setOriginatingEvent(BaseEvent $event): self { $this->originatingEvent = $this->calculateOriginatingEvent($event); diff --git a/src/Composer/SelfUpdate/Keys.php b/src/Composer/SelfUpdate/Keys.php index 8c33a436ffe8..e8ce93045aa5 100644 --- a/src/Composer/SelfUpdate/Keys.php +++ b/src/Composer/SelfUpdate/Keys.php @@ -24,7 +24,7 @@ class Keys * * @return string */ - public static function fingerprint($path): string + public static function fingerprint(string $path): string { $hash = strtoupper(hash('sha256', Preg::replace('{\s}', '', file_get_contents($path)))); diff --git a/src/Composer/SelfUpdate/Versions.php b/src/Composer/SelfUpdate/Versions.php index ce959479d83c..ea51319f7089 100644 --- a/src/Composer/SelfUpdate/Versions.php +++ b/src/Composer/SelfUpdate/Versions.php @@ -63,7 +63,7 @@ public function getChannel(): string * * @return void */ - public function setChannel($channel): void + public function setChannel(string $channel): void { if (!in_array($channel, self::$channels, true)) { throw new \InvalidArgumentException('Invalid channel '.$channel.', must be one of: ' . implode(', ', self::$channels)); @@ -79,7 +79,7 @@ public function setChannel($channel): void * * @return array{path: string, version: string, min-php: int} */ - public function getLatest($channel = null): array + public function getLatest(?string $channel = null): array { $versions = $this->getVersionsData(); diff --git a/src/Composer/Util/AuthHelper.php b/src/Composer/Util/AuthHelper.php index 26eab08b2fb9..54cb83f581ff 100644 --- a/src/Composer/Util/AuthHelper.php +++ b/src/Composer/Util/AuthHelper.php @@ -41,7 +41,7 @@ public function __construct(IOInterface $io, Config $config) * * @return void */ - public function storeAuth($origin, $storeAuth): void + public function storeAuth(string $origin, $storeAuth): void { $store = false; $configSource = $this->config->getAuthConfigSource(); @@ -83,7 +83,7 @@ function ($value): string { * retried, if storeAuth is true then on a successful retry the authentication should be persisted to auth.json * @phpstan-return ?array{retry: bool, storeAuth: string|bool} */ - public function promptAuthIfNeeded($url, $origin, $statusCode, $reason = null, $headers = array()): ?array + public function promptAuthIfNeeded(string $url, string $origin, int $statusCode, ?string $reason = null, array $headers = array()): ?array { $storeAuth = false; @@ -215,7 +215,7 @@ public function promptAuthIfNeeded($url, $origin, $statusCode, $reason = null, $ * * @return string[] updated headers array */ - public function addAuthenticationHeader(array $headers, $origin, $url): array + public function addAuthenticationHeader(array $headers, string $origin, string $url): array { if ($this->io->hasAuthentication($origin)) { $authenticationDisplayMessage = null; @@ -272,7 +272,7 @@ public function addAuthenticationHeader(array $headers, $origin, $url): array * * @return bool Whether the given URL is a public BitBucket download which requires no authentication. */ - public function isPublicBitBucketDownload($urlToBitBucketFile): bool + public function isPublicBitBucketDownload(string $urlToBitBucketFile): bool { $domain = parse_url($urlToBitBucketFile, PHP_URL_HOST); if (strpos($domain, 'bitbucket.org') === false) { diff --git a/src/Composer/Util/Bitbucket.php b/src/Composer/Util/Bitbucket.php index 5eb6b8fe63af..4ce3b7599ddb 100644 --- a/src/Composer/Util/Bitbucket.php +++ b/src/Composer/Util/Bitbucket.php @@ -46,7 +46,7 @@ class Bitbucket * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking * @param int $time Timestamp, injectable for mocking */ - public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, HttpDownloader $httpDownloader = null, $time = null) + public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, HttpDownloader $httpDownloader = null, int $time = null) { $this->io = $io; $this->config = $config; @@ -73,7 +73,7 @@ public function getToken(): string * @param string $originUrl The host this Bitbucket instance is located at * @return bool true on success */ - public function authorizeOAuth($originUrl): bool + public function authorizeOAuth(string $originUrl): bool { if ($originUrl !== 'bitbucket.org') { return false; @@ -140,7 +140,7 @@ private function requestAccessToken(): bool * @throws TransportException|\Exception * @return bool true on success */ - public function authorizeOAuthInteractively($originUrl, $message = null): bool + public function authorizeOAuthInteractively(string $originUrl, string $message = null): bool { if ($message) { $this->io->writeError($message); @@ -194,7 +194,7 @@ public function authorizeOAuthInteractively($originUrl, $message = null): bool * @param string $consumerSecret * @return string */ - public function requestToken($originUrl, $consumerKey, $consumerSecret): string + public function requestToken(string $originUrl, string $consumerKey, string $consumerSecret): string { if ($this->token !== null || $this->getTokenFromConfig($originUrl)) { return $this->token['access_token']; @@ -223,7 +223,7 @@ public function requestToken($originUrl, $consumerKey, $consumerSecret): string * * @return void */ - private function storeInAuthConfig($originUrl, $consumerKey, $consumerSecret): void + private function storeInAuthConfig(string $originUrl, string $consumerKey, string $consumerSecret): void { $this->config->getConfigSource()->removeConfigSetting('bitbucket-oauth.'.$originUrl); @@ -246,7 +246,7 @@ private function storeInAuthConfig($originUrl, $consumerKey, $consumerSecret): v * @param string $originUrl * @return bool */ - private function getTokenFromConfig($originUrl): bool + private function getTokenFromConfig(string $originUrl): bool { $authConfig = $this->config->get('bitbucket-oauth'); diff --git a/src/Composer/Util/ComposerMirror.php b/src/Composer/Util/ComposerMirror.php index 948bccee3e8d..26afb80e5428 100644 --- a/src/Composer/Util/ComposerMirror.php +++ b/src/Composer/Util/ComposerMirror.php @@ -31,7 +31,7 @@ class ComposerMirror * * @return string */ - public static function processUrl($mirrorUrl, $packageName, $version, $reference, $type, $prettyVersion = null): string + public static function processUrl(string $mirrorUrl, string $packageName, string $version, ?string $reference, ?string $type, ?string $prettyVersion = null): string { if ($reference) { $reference = Preg::isMatch('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : md5($reference); @@ -56,7 +56,7 @@ public static function processUrl($mirrorUrl, $packageName, $version, $reference * * @return string */ - public static function processGitUrl($mirrorUrl, $packageName, $url, $type): string + public static function processGitUrl(string $mirrorUrl, string $packageName, string $url, ?string $type): string { if (Preg::isMatch('#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#', $url, $match)) { $url = 'gh-'.$match[1].'/'.$match[2]; @@ -81,7 +81,7 @@ public static function processGitUrl($mirrorUrl, $packageName, $url, $type): str * * @return string */ - public static function processHgUrl($mirrorUrl, $packageName, $url, $type): string + public static function processHgUrl(string $mirrorUrl, string $packageName, string $url, string $type): string { return self::processGitUrl($mirrorUrl, $packageName, $url, $type); } diff --git a/src/Composer/Util/ConfigValidator.php b/src/Composer/Util/ConfigValidator.php index b0dd79fad321..4d2f50d2dd09 100644 --- a/src/Composer/Util/ConfigValidator.php +++ b/src/Composer/Util/ConfigValidator.php @@ -48,7 +48,7 @@ public function __construct(IOInterface $io) * * @return array{list, list, list} a triple containing the errors, publishable errors, and warnings */ - public function validate($file, $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL, $flags = self::CHECK_VERSION): array + public function validate(string $file, int $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL, int $flags = self::CHECK_VERSION): array { $errors = array(); $publishErrors = array(); diff --git a/src/Composer/Util/ErrorHandler.php b/src/Composer/Util/ErrorHandler.php index 257f7ce29117..fa2459e2cad0 100644 --- a/src/Composer/Util/ErrorHandler.php +++ b/src/Composer/Util/ErrorHandler.php @@ -36,7 +36,7 @@ class ErrorHandler * @throws \ErrorException * @return bool */ - public static function handle($level, $message, $file, $line): bool + public static function handle(int $level, string $message, string $file, int $line): bool { // error code is not included in error_reporting if (!(error_reporting() & $level)) { diff --git a/src/Composer/Util/Filesystem.php b/src/Composer/Util/Filesystem.php index 99aa803c927d..c60dd80ec941 100644 --- a/src/Composer/Util/Filesystem.php +++ b/src/Composer/Util/Filesystem.php @@ -38,7 +38,7 @@ public function __construct(ProcessExecutor $executor = null) * * @return bool */ - public function remove($file) + public function remove(string $file) { if (is_dir($file)) { return $this->removeDirectory($file); @@ -57,7 +57,7 @@ public function remove($file) * @param string $dir * @return bool */ - public function isDirEmpty($dir) + public function isDirEmpty(string $dir) { $finder = Finder::create() ->ignoreVCS(false) @@ -74,7 +74,7 @@ public function isDirEmpty($dir) * * @return void */ - public function emptyDirectory($dir, $ensureDirectoryExists = true) + public function emptyDirectory(string $dir, bool $ensureDirectoryExists = true) { if (is_link($dir) && file_exists($dir)) { $this->unlink($dir); @@ -107,7 +107,7 @@ public function emptyDirectory($dir, $ensureDirectoryExists = true) * @throws \RuntimeException * @return bool */ - public function removeDirectory($directory) + public function removeDirectory(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { @@ -142,7 +142,7 @@ public function removeDirectory($directory) * @throws \RuntimeException * @return PromiseInterface */ - public function removeDirectoryAsync($directory) + public function removeDirectoryAsync(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { @@ -177,7 +177,7 @@ public function removeDirectoryAsync($directory) * * @return bool|null Returns null, when no edge case was hit. Otherwise a bool whether removal was successful */ - private function removeEdgeCases($directory, $fallbackToPhp = true): ?bool + private function removeEdgeCases(string $directory, bool $fallbackToPhp = true): ?bool { if ($this->isSymlinkedDirectory($directory)) { return $this->unlinkSymlinkedDirectory($directory); @@ -216,7 +216,7 @@ private function removeEdgeCases($directory, $fallbackToPhp = true): ?bool * @param string $directory * @return bool */ - public function removeDirectoryPhp($directory) + public function removeDirectoryPhp(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory, false); if ($edgeCaseResult !== null) { @@ -256,7 +256,7 @@ public function removeDirectoryPhp($directory) * * @return void */ - public function ensureDirectoryExists($directory) + public function ensureDirectoryExists(string $directory) { if (!is_dir($directory)) { if (file_exists($directory)) { @@ -279,7 +279,7 @@ public function ensureDirectoryExists($directory) * @throws \RuntimeException * @return bool */ - public function unlink($path) + public function unlink(string $path) { $unlinked = @$this->unlinkImplementation($path); if (!$unlinked) { @@ -310,7 +310,7 @@ public function unlink($path) * @throws \RuntimeException * @return bool */ - public function rmdir($path) + public function rmdir(string $path) { $deleted = @rmdir($path); if (!$deleted) { @@ -345,7 +345,7 @@ public function rmdir($path) * * @return void */ - public function copyThenRemove($source, $target) + public function copyThenRemove(string $source, string $target) { $this->copy($source, $target); if (!is_dir($source)) { @@ -364,7 +364,7 @@ public function copyThenRemove($source, $target) * @param string $target * @return bool */ - public function copy($source, $target) + public function copy(string $source, string $target) { if (!is_dir($source)) { return copy($source, $target); @@ -394,7 +394,7 @@ public function copy($source, $target) * * @return void */ - public function rename($source, $target) + public function rename(string $source, string $target) { if (true === @rename($source, $target)) { return; @@ -445,7 +445,7 @@ public function rename($source, $target) * @throws \InvalidArgumentException * @return string */ - public function findShortestPath($from, $to, $directories = false) + public function findShortestPath(string $from, string $to, bool $directories = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); @@ -488,7 +488,7 @@ public function findShortestPath($from, $to, $directories = false) * @throws \InvalidArgumentException * @return string */ - public function findShortestPathCode($from, $to, $directories = false, $staticCode = false) + public function findShortestPathCode(string $from, string $to, bool $directories = false, bool $staticCode = false) { if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) { throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to)); @@ -531,7 +531,7 @@ public function findShortestPathCode($from, $to, $directories = false, $staticCo * @param string $path * @return bool */ - public function isAbsolutePath($path) + public function isAbsolutePath(string $path) { return strpos($path, '/') === 0 || substr($path, 1, 1) === ':' || strpos($path, '\\\\') === 0; } @@ -544,7 +544,7 @@ public function isAbsolutePath($path) * @throws \RuntimeException * @return int */ - public function size($path) + public function size(string $path) { if (!file_exists($path)) { throw new \RuntimeException("$path does not exist."); @@ -563,7 +563,7 @@ public function size($path) * @param string $path Path to the file or directory * @return string */ - public function normalizePath($path) + public function normalizePath(string $path) { $parts = array(); $path = strtr($path, '\\', '/'); @@ -609,7 +609,7 @@ public function normalizePath($path) * @param string $path * @return string */ - public static function trimTrailingSlash($path) + public static function trimTrailingSlash(string $path) { if (!Preg::isMatch('{^[/\\\\]+$}', $path)) { $path = rtrim($path, '/\\'); @@ -624,7 +624,7 @@ public static function trimTrailingSlash($path) * @param string $path * @return bool */ - public static function isLocalPath($path) + public static function isLocalPath(string $path) { return Preg::isMatch('{^(file://(?!//)|/(?!/)|/?[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path); } @@ -634,7 +634,7 @@ public static function isLocalPath($path) * * @return string */ - public static function getPlatformPath($path) + public static function getPlatformPath(string $path) { if (Platform::isWindows()) { $path = Preg::replace('{^(?:file:///([a-z]):?/)}i', 'file://$1:/', $path); @@ -652,7 +652,7 @@ public static function getPlatformPath($path) * @param string $path * @return bool */ - public static function isReadable($path) + public static function isReadable(string $path) { if (is_readable($path)) { return true; @@ -675,7 +675,7 @@ public static function isReadable($path) * * @return int */ - protected function directorySize($directory) + protected function directorySize(string $directory) { $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST); @@ -711,7 +711,7 @@ protected function getProcess() * * @return bool */ - private function unlinkImplementation($path): bool + private function unlinkImplementation(string $path): bool { if (Platform::isWindows() && is_dir($path) && is_link($path)) { return rmdir($path); @@ -727,13 +727,13 @@ private function unlinkImplementation($path): bool * @param string $link The path where the symlink should be created * @return bool */ - public function relativeSymlink($target, $link) + public function relativeSymlink(string $target, string $link) { if (!function_exists('symlink')) { return false; } - $cwd = getcwd(); + $cwd = Platform::getCwd(); $relativePath = $this->findShortestPath($link, $target); chdir(\dirname($link)); @@ -751,7 +751,7 @@ public function relativeSymlink($target, $link) * * @return bool */ - public function isSymlinkedDirectory($directory) + public function isSymlinkedDirectory(string $directory) { if (!is_dir($directory)) { return false; @@ -767,7 +767,7 @@ public function isSymlinkedDirectory($directory) * * @return bool */ - private function unlinkSymlinkedDirectory($directory): bool + private function unlinkSymlinkedDirectory(string $directory): bool { $resolved = $this->resolveSymlinkedDirectorySymlink($directory); @@ -781,7 +781,7 @@ private function unlinkSymlinkedDirectory($directory): bool * * @return string resolved path to symbolic link or original pathname (unresolved) */ - private function resolveSymlinkedDirectorySymlink($pathname): string + private function resolveSymlinkedDirectorySymlink(string $pathname): string { if (!is_dir($pathname)) { return $pathname; @@ -804,7 +804,7 @@ private function resolveSymlinkedDirectorySymlink($pathname): string * * @return void */ - public function junction($target, $junction) + public function junction(string $target, string $junction) { if (!Platform::isWindows()) { throw new \LogicException(sprintf('Function %s is not available on non-Windows platform', __CLASS__)); @@ -843,7 +843,7 @@ public function junction($target, $junction) * @param string $junction Path to check. * @return bool */ - public function isJunction($junction) + public function isJunction(string $junction) { if (!Platform::isWindows()) { return false; @@ -868,7 +868,7 @@ public function isJunction($junction) * @param string $junction * @return bool */ - public function removeJunction($junction) + public function removeJunction(string $junction) { if (!Platform::isWindows()) { return false; @@ -887,7 +887,7 @@ public function removeJunction($junction) * * @return int|false */ - public function filePutContentsIfModified($path, $content) + public function filePutContentsIfModified(string $path, string $content) { $currentContent = @file_get_contents($path); if (!$currentContent || ($currentContent != $content)) { @@ -905,7 +905,7 @@ public function filePutContentsIfModified($path, $content) * * @return void */ - public function safeCopy($source, $target) + public function safeCopy(string $source, string $target) { if (!file_exists($target) || !file_exists($source) || !$this->filesAreEqual($source, $target)) { $source = fopen($source, 'r'); @@ -926,7 +926,7 @@ public function safeCopy($source, $target) * * @return bool */ - private function filesAreEqual($a, $b): bool + private function filesAreEqual(string $a, string $b): bool { // Check if filesize is different if (filesize($a) !== filesize($b)) { diff --git a/src/Composer/Util/Git.php b/src/Composer/Util/Git.php index 27dc75a0dd9e..f28271c74e10 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -49,7 +49,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr * * @return void */ - public function runCommand($commandCallable, $url, $cwd, $initialClone = false) + public function runCommand(callable $commandCallable, string $url, ?string $cwd, bool $initialClone = false): void { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -272,7 +272,7 @@ public function runCommand($commandCallable, $url, $cwd, $initialClone = false) * * @return bool */ - public function syncMirror($url, $dir) + public function syncMirror(string $url, string $dir): bool { if (Platform::getEnv('COMPOSER_DISABLE_NETWORK') && Platform::getEnv('COMPOSER_DISABLE_NETWORK') !== 'prime') { $this->io->writeError('Aborting git mirror sync of '.$url.' as network is disabled'); @@ -317,7 +317,7 @@ public function syncMirror($url, $dir) * * @return bool */ - public function fetchRefOrSyncMirror($url, $dir, $ref) + public function fetchRefOrSyncMirror(string $url, string $dir, string $ref): bool { if ($this->checkRefIsInMirror($dir, $ref)) { return true; @@ -333,7 +333,7 @@ public function fetchRefOrSyncMirror($url, $dir, $ref) /** * @return string */ - public static function getNoShowSignatureFlag(ProcessExecutor $process) + public static function getNoShowSignatureFlag(ProcessExecutor $process): string { $gitVersion = self::getVersion($process); if ($gitVersion && version_compare($gitVersion, '2.10.0-rc0', '>=')) { @@ -349,7 +349,7 @@ public static function getNoShowSignatureFlag(ProcessExecutor $process) * * @return bool */ - private function checkRefIsInMirror($dir, $ref): bool + private function checkRefIsInMirror(string $dir, string $ref): bool { if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { $escapedRef = ProcessExecutor::escape($ref.'^{commit}'); @@ -368,7 +368,7 @@ private function checkRefIsInMirror($dir, $ref): bool * * @return bool */ - private function isAuthenticationFailure($url, &$match): bool + private function isAuthenticationFailure(string $url, array &$match): bool { if (!Preg::isMatch('{^(https?://)([^/]+)(.*)$}i', $url, $match)) { return false; @@ -395,7 +395,7 @@ private function isAuthenticationFailure($url, &$match): bool /** * @return void */ - public static function cleanEnv() + public static function cleanEnv(): void { // added in git 1.7.1, prevents prompting the user for username/password if (Platform::getEnv('GIT_ASKPASS') !== 'echo') { @@ -422,7 +422,7 @@ public static function cleanEnv() /** * @return non-empty-string */ - public static function getGitHubDomainsRegex(Config $config) + public static function getGitHubDomainsRegex(Config $config): string { return '(' . implode('|', array_map('preg_quote', $config->get('github-domains'))) . ')'; } @@ -430,7 +430,7 @@ public static function getGitHubDomainsRegex(Config $config) /** * @return non-empty-string */ - public static function getGitLabDomainsRegex(Config $config) + public static function getGitLabDomainsRegex(Config $config): string { return '(' . implode('|', array_map('preg_quote', $config->get('gitlab-domains'))) . ')'; } @@ -441,7 +441,7 @@ public static function getGitLabDomainsRegex(Config $config) * * @return never */ - private function throwException($message, $url): void + private function throwException($message, string $url): void { // git might delete a directory when it fails and php will not know clearstatcache(); @@ -458,7 +458,7 @@ private function throwException($message, $url): void * * @return string|null The git version number, if present. */ - public static function getVersion(ProcessExecutor $process) + public static function getVersion(ProcessExecutor $process): ?string { if (false === self::$version) { self::$version = null; @@ -476,7 +476,7 @@ public static function getVersion(ProcessExecutor $process) * * @return string */ - private function maskCredentials($error, array $credentials): string + private function maskCredentials(string $error, array $credentials): string { $maskedCredentials = array(); diff --git a/src/Composer/Util/GitHub.php b/src/Composer/Util/GitHub.php index f20cb237678c..4390bb8ac7bc 100644 --- a/src/Composer/Util/GitHub.php +++ b/src/Composer/Util/GitHub.php @@ -54,7 +54,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr * @param string $originUrl The host this GitHub instance is located at * @return bool true on success */ - public function authorizeOAuth($originUrl): bool + public function authorizeOAuth(string $originUrl): bool { if (!in_array($originUrl, $this->config->get('github-domains'))) { return false; @@ -79,7 +79,7 @@ public function authorizeOAuth($originUrl): bool * @throws TransportException|\Exception * @return bool true on success */ - public function authorizeOAuthInteractively($originUrl, $message = null): bool + public function authorizeOAuthInteractively(string $originUrl, string $message = null): bool { if ($message) { $this->io->writeError($message); diff --git a/src/Composer/Util/GitLab.php b/src/Composer/Util/GitLab.php index 4bd61d792bf0..97c920ddec66 100644 --- a/src/Composer/Util/GitLab.php +++ b/src/Composer/Util/GitLab.php @@ -55,7 +55,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr * * @return bool true on success */ - public function authorizeOAuth($originUrl): bool + public function authorizeOAuth(string $originUrl): bool { // before composer 1.9, origin URLs had no port number in them $bcOriginUrl = Preg::replace('{:\d+}', '', $originUrl); @@ -112,7 +112,7 @@ public function authorizeOAuth($originUrl): bool * * @return bool true on success */ - public function authorizeOAuthInteractively($scheme, $originUrl, $message = null): bool + public function authorizeOAuthInteractively(string $scheme, string $originUrl, string $message = null): bool { if ($message) { $this->io->writeError($message); @@ -169,7 +169,7 @@ public function authorizeOAuthInteractively($scheme, $originUrl, $message = null * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ - private function createToken($scheme, $originUrl): array + private function createToken(string $scheme, string $originUrl): array { $username = $this->io->ask('Username: '); $password = $this->io->askAndHideAnswer('Password: '); diff --git a/src/Composer/Util/Hg.php b/src/Composer/Util/Hg.php index da8c3329a57a..7797fe1a4083 100644 --- a/src/Composer/Util/Hg.php +++ b/src/Composer/Util/Hg.php @@ -53,7 +53,7 @@ public function __construct(IOInterface $io, Config $config, ProcessExecutor $pr * * @return void */ - public function runCommand($commandCallable, $url, $cwd): void + public function runCommand(callable $commandCallable, string $url, ?string $cwd): void { $this->config->prohibitUrlByConfig($url, $this->io); @@ -89,7 +89,7 @@ public function runCommand($commandCallable, $url, $cwd): void * * @return never */ - private function throwException($message, $url): void + private function throwException($message, string $url): void { if (null === self::getVersion($this->process)) { throw new \RuntimeException(Url::sanitize('Failed to clone ' . $url . ', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput())); diff --git a/src/Composer/Util/Http/CurlDownloader.php b/src/Composer/Util/Http/CurlDownloader.php index eeff04e1f228..327c09976b99 100644 --- a/src/Composer/Util/Http/CurlDownloader.php +++ b/src/Composer/Util/Http/CurlDownloader.php @@ -95,7 +95,7 @@ class CurlDownloader * @param mixed[] $options * @param bool $disableTls */ - public function __construct(IOInterface $io, Config $config, array $options = array(), $disableTls = false) + public function __construct(IOInterface $io, Config $config, array $options = array(), bool $disableTls = false) { $this->io = $io; $this->config = $config; @@ -129,11 +129,11 @@ public function __construct(IOInterface $io, Config $config, array $options = ar * @param string $origin * @param string $url * @param mixed[] $options - * @param ?string $copyTo + * @param null|string $copyTo * * @return int internal job id */ - public function download($resolve, $reject, $origin, $url, $options, $copyTo = null): int + public function download(callable $resolve, callable $reject, string $origin, string $url, array $options, ?string $copyTo = null): int { $attributes = array(); if (isset($options['retry-auth-failure'])) { @@ -150,13 +150,13 @@ public function download($resolve, $reject, $origin, $url, $options, $copyTo = n * @param string $origin * @param string $url * @param mixed[] $options - * @param ?string $copyTo + * @param null|string $copyTo * * @param array{retryAuthFailure?: bool, redirects?: int, retries?: int, storeAuth?: bool} $attributes * * @return int internal job id */ - private function initDownload($resolve, $reject, $origin, $url, $options, $copyTo = null, array $attributes = array()): int + private function initDownload(callable $resolve, callable $reject, string $origin, string $url, array $options, ?string $copyTo = null, array $attributes = array()): int { // set defaults in a PHPStan-happy way (array_merge is not well supported) $attributes['retryAuthFailure'] = $attributes['retryAuthFailure'] ?? true; @@ -287,7 +287,7 @@ private function initDownload($resolve, $reject, $origin, $url, $options, $copyT * @param int $id * @return void */ - public function abortRequest($id): void + public function abortRequest(int $id): void { if (isset($this->jobs[$id], $this->jobs[$id]['curlHandle'])) { $job = $this->jobs[$id]; @@ -579,7 +579,7 @@ private function isAuthenticatedRetryNeeded(array $job, Response $response): arr * * @return void */ - private function restartJob(array $job, $url, array $attributes = array()): void + private function restartJob(array $job, string $url, array $attributes = array()): void { if (null !== $job['filename']) { @unlink($job['filename'].'~'); @@ -596,7 +596,7 @@ private function restartJob(array $job, $url, array $attributes = array()): void * @param string $errorMessage * @return TransportException */ - private function failResponse(array $job, Response $response, $errorMessage): TransportException + private function failResponse(array $job, Response $response, string $errorMessage): TransportException { if (null !== $job['filename']) { @unlink($job['filename'].'~'); @@ -632,7 +632,7 @@ private function rejectJob(array $job, \Exception $e): void * @param int $code * @return void */ - private function checkCurlResult($code): void + private function checkCurlResult(int $code): void { if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) { throw new \RuntimeException( diff --git a/src/Composer/Util/Http/ProxyHelper.php b/src/Composer/Util/Http/ProxyHelper.php index db19db62d646..49c89c215fd5 100644 --- a/src/Composer/Util/Http/ProxyHelper.php +++ b/src/Composer/Util/Http/ProxyHelper.php @@ -64,7 +64,7 @@ public static function getProxyData(): array * * @return array{http: array{proxy: string, header?: string}} */ - public static function getContextOptions($proxyUrl): array + public static function getContextOptions(string $proxyUrl): array { $proxy = parse_url($proxyUrl); @@ -97,7 +97,7 @@ public static function getContextOptions($proxyUrl): array * * @return void */ - public static function setRequestFullUri($requestUrl, array &$options): void + public static function setRequestFullUri(string $requestUrl, array &$options): void { if ('http' === parse_url($requestUrl, PHP_URL_SCHEME)) { $options['http']['request_fulluri'] = true; @@ -114,7 +114,7 @@ public static function setRequestFullUri($requestUrl, array &$options): void * * @return string|null The found value */ - private static function getProxyEnv(array $names, &$name): ?string + private static function getProxyEnv(array $names, ?string &$name): ?string { foreach ($names as $name) { if (!empty($_SERVER[$name])) { @@ -133,7 +133,7 @@ private static function getProxyEnv(array $names, &$name): ?string * @throws \RuntimeException on malformed url * @return string The formatted proxy url */ - private static function checkProxy($proxyUrl, $envName): string + private static function checkProxy(string $proxyUrl, string $envName): string { $error = sprintf('malformed %s url', $envName); $proxy = parse_url($proxyUrl); @@ -161,7 +161,7 @@ private static function checkProxy($proxyUrl, $envName): string * * @return string The formatted value */ - private static function formatParsedUrl(array $proxy, $includeAuth): string + private static function formatParsedUrl(array $proxy, bool $includeAuth): string { $proxyUrl = isset($proxy['scheme']) ? strtolower($proxy['scheme']) . '://' : ''; diff --git a/src/Composer/Util/Http/ProxyManager.php b/src/Composer/Util/Http/ProxyManager.php index 5f11c82424d6..df7db9f5f68c 100644 --- a/src/Composer/Util/Http/ProxyManager.php +++ b/src/Composer/Util/Http/ProxyManager.php @@ -83,7 +83,7 @@ public static function reset(): void * @param string $requestUrl * @return RequestProxy */ - public function getProxyForRequest($requestUrl): RequestProxy + public function getProxyForRequest(string $requestUrl): RequestProxy { if ($this->error) { throw new TransportException('Unable to use a proxy: '.$this->error); @@ -184,7 +184,7 @@ private function setData($url, $scheme): string * @param string $requestUrl * @return bool */ - private function noProxy($requestUrl): bool + private function noProxy(string $requestUrl): bool { return $this->noProxyHandler && $this->noProxyHandler->test($requestUrl); } diff --git a/src/Composer/Util/Http/RequestProxy.php b/src/Composer/Util/Http/RequestProxy.php index e60c1a19cbbb..eaf3f9452bd5 100644 --- a/src/Composer/Util/Http/RequestProxy.php +++ b/src/Composer/Util/Http/RequestProxy.php @@ -34,7 +34,7 @@ class RequestProxy * @param mixed[] $contextOptions * @param string $formattedUrl */ - public function __construct($url, array $contextOptions, $formattedUrl) + public function __construct(string $url, array $contextOptions, string $formattedUrl) { $this->url = $url; $this->contextOptions = $contextOptions; @@ -58,7 +58,7 @@ public function getContextOptions(): array * @param string|null $format Output format specifier * @return string Safe proxy, no proxy or empty */ - public function getFormattedUrl($format = ''): string + public function getFormattedUrl(?string $format = ''): string { $result = ''; if ($this->formattedUrl) { diff --git a/src/Composer/Util/Http/Response.php b/src/Composer/Util/Http/Response.php index 4c9072facd5a..5556b6754cf5 100644 --- a/src/Composer/Util/Http/Response.php +++ b/src/Composer/Util/Http/Response.php @@ -34,9 +34,9 @@ class Response * @param Request $request * @param int $code * @param list $headers - * @param ?string $body + * @param null|string $body */ - public function __construct(array $request, $code, array $headers, $body) + public function __construct(array $request, ?int $code, array $headers, ?string $body) { if (!isset($request['url'])) { // @phpstan-ignore-line throw new \LogicException('url key missing from request array'); @@ -84,7 +84,7 @@ public function getHeaders(): array * @param string $name * @return ?string */ - public function getHeader($name): ?string + public function getHeader(string $name): ?string { return self::findHeaderValue($this->headers, $name); } @@ -120,7 +120,7 @@ public function collect(): void * @param string $name header name (case insensitive) * @return string|null */ - public static function findHeaderValue(array $headers, $name): ?string + public static function findHeaderValue(array $headers, string $name): ?string { $value = null; foreach ($headers as $header) { diff --git a/src/Composer/Util/HttpDownloader.php b/src/Composer/Util/HttpDownloader.php index b919680f2937..80d1385c0923 100644 --- a/src/Composer/Util/HttpDownloader.php +++ b/src/Composer/Util/HttpDownloader.php @@ -67,7 +67,7 @@ class HttpDownloader * @param mixed[] $options The options * @param bool $disableTls */ - public function __construct(IOInterface $io, Config $config, array $options = array(), $disableTls = false) + public function __construct(IOInterface $io, Config $config, array $options = array(), bool $disableTls = false) { $this->io = $io; @@ -103,7 +103,7 @@ public function __construct(IOInterface $io, Config $config, array $options = ar * @throws TransportException * @return Response */ - public function get($url, $options = array()) + public function get(string $url, array $options = array()) { list($job) = $this->addJob(array('url' => $url, 'options' => $options, 'copyTo' => null), true); $this->wait($job['id']); @@ -122,7 +122,7 @@ public function get($url, $options = array()) * @throws TransportException * @return PromiseInterface */ - public function add($url, $options = array()) + public function add(string $url, array $options = array()) { list(, $promise) = $this->addJob(array('url' => $url, 'options' => $options, 'copyTo' => null)); @@ -139,7 +139,7 @@ public function add($url, $options = array()) * @throws TransportException * @return Response */ - public function copy($url, $to, $options = array()) + public function copy(string $url, string $to, array $options = array()) { list($job) = $this->addJob(array('url' => $url, 'options' => $options, 'copyTo' => $to), true); $this->wait($job['id']); @@ -157,7 +157,7 @@ public function copy($url, $to, $options = array()) * @throws TransportException * @return PromiseInterface */ - public function addCopy($url, $to, $options = array()) + public function addCopy(string $url, string $to, array $options = array()) { list(, $promise) = $this->addJob(array('url' => $url, 'options' => $options, 'copyTo' => $to)); @@ -186,12 +186,10 @@ public function setOptions(array $options) } /** - * @param Request $request - * @param bool $sync - * + * @phpstan-param Request $request * @return array{Job, PromiseInterface} */ - private function addJob($request, $sync = false): array + private function addJob(array $request, bool $sync = false): array { $request['options'] = array_replace_recursive($this->options, $request['options']); @@ -291,7 +289,7 @@ private function addJob($request, $sync = false): array * @param int $id * @return void */ - private function startJob($id): void + private function startJob(int $id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { @@ -343,7 +341,7 @@ private function markJobDone(): void * * @return void */ - public function wait($index = null) + public function wait(?int $index = null) { do { $jobCount = $this->countActiveJobs($index); @@ -366,7 +364,7 @@ public function enableAsync(): void * @param int|null $index For internal use only, the job id * @return int number of active (queued or started) jobs */ - public function countActiveJobs($index = null): int + public function countActiveJobs(?int $index = null): int { if ($this->runningJobs < $this->maxJobs) { foreach ($this->jobs as $job) { @@ -400,7 +398,7 @@ public function countActiveJobs($index = null): int * @param int $index Job id * @return Response */ - private function getResponse($index): Response + private function getResponse(int $index): Response { if (!isset($this->jobs[$index])) { throw new \LogicException('Invalid request id'); @@ -428,7 +426,7 @@ private function getResponse($index): Response * @param array{warning?: string, info?: string, warning-versions?: string, info-versions?: string, warnings?: array, infos?: array} $data * @return void */ - public static function outputWarnings(IOInterface $io, $url, $data): void + public static function outputWarnings(IOInterface $io, string $url, $data): void { // legacy warning/info keys foreach (array('warning', 'info') as $type) { diff --git a/src/Composer/Util/NoProxyPattern.php b/src/Composer/Util/NoProxyPattern.php index a81a88a5beae..2ae47556105e 100644 --- a/src/Composer/Util/NoProxyPattern.php +++ b/src/Composer/Util/NoProxyPattern.php @@ -38,7 +38,7 @@ class NoProxyPattern /** * @param string $pattern NO_PROXY pattern */ - public function __construct($pattern) + public function __construct(string $pattern) { $this->hostNames = Preg::split('{[\s,]+}', $pattern, -1, PREG_SPLIT_NO_EMPTY); $this->noproxy = empty($this->hostNames) || '*' === $this->hostNames[0]; @@ -51,7 +51,7 @@ public function __construct($pattern) * * @return bool */ - public function test($url): bool + public function test(string $url): bool { if ($this->noproxy) { return true; @@ -77,7 +77,7 @@ public function test($url): bool * * @return bool|stdClass */ - protected function getUrlData($url) + protected function getUrlData(string $url) { if (!$host = parse_url($url, PHP_URL_HOST)) { return false; @@ -115,7 +115,7 @@ protected function getUrlData($url) * * @return bool */ - protected function match($index, $hostName, $url): bool + protected function match(int $index, string $hostName, stdClass $url): bool { if (!$rule = $this->getRule($index, $hostName)) { // Data must have been misformatted @@ -186,7 +186,7 @@ protected function matchRange(stdClass $network, stdClass $target): bool * * @return null|stdClass Null if the hostname is invalid */ - private function getRule($index, $hostName): ?stdClass + private function getRule(int $index, string $hostName): ?stdClass { if (array_key_exists($index, $this->rules)) { return $this->rules[$index]; @@ -213,7 +213,7 @@ private function getRule($index, $hostName): ?stdClass * * @return bool False if the host contains invalid data */ - private function ipCheckData($host, &$ipdata, $allowPrefix = false): bool + private function ipCheckData(string $host, ?stdClass &$ipdata, bool $allowPrefix = false): bool { $ipdata = null; $netmask = null; @@ -262,7 +262,7 @@ private function ipCheckData($host, &$ipdata, $allowPrefix = false): bool * * @return mixed[] in_addr, size */ - private function ipGetAddr($host): array + private function ipGetAddr(string $host): array { $ip = inet_pton($host); $size = strlen($ip); @@ -279,7 +279,7 @@ private function ipGetAddr($host): array * * @return string */ - private function ipGetMask($prefix, $size): string + private function ipGetMask(int $prefix, int $size): string { $mask = ''; @@ -305,7 +305,7 @@ private function ipGetMask($prefix, $size): string * * @return string[] network in_addr, binary mask */ - private function ipGetNetwork($rangeIp, $size, $prefix): array + private function ipGetNetwork(string $rangeIp, int $size, int $prefix): array { $netmask = $this->ipGetMask($prefix, $size); @@ -335,7 +335,7 @@ private function ipGetNetwork($rangeIp, $size, $prefix): array * * @return string Mapped or existing in_addr */ - private function ipMapTo6($binary, $size): string + private function ipMapTo6(string $binary, int $size): string { if ($size === 4) { $prefix = str_repeat(chr(0), 10) . str_repeat(chr(255), 2); @@ -354,7 +354,7 @@ private function ipMapTo6($binary, $size): string * * @return stdClass */ - private function makeData($host, $port, $ipdata): stdClass + private function makeData(string $host, int $port, ?stdClass $ipdata): stdClass { return (object) array( 'host' => $host, @@ -373,7 +373,7 @@ private function makeData($host, $port, $ipdata): stdClass * * @return stdClass */ - private function makeIpData($ip, $size, $netmask): stdClass + private function makeIpData(string $ip, int $size, ?string $netmask): stdClass { return (object) array( 'ip' => $ip, @@ -389,7 +389,7 @@ private function makeIpData($ip, $size, $netmask): stdClass * * @return mixed[] host, port, if there was error */ - private function splitHostPort($hostName): array + private function splitHostPort(string $hostName): array { // host, port, err $error = array('', '', true); @@ -439,7 +439,7 @@ private function splitHostPort($hostName): array * * @return bool */ - private function validateInt($int, $min, $max): bool + private function validateInt(string $int, int $min, int $max): bool { $options = array( 'options' => array( diff --git a/src/Composer/Util/Perforce.php b/src/Composer/Util/Perforce.php index 559e8c31130f..ee21169e107c 100644 --- a/src/Composer/Util/Perforce.php +++ b/src/Composer/Util/Perforce.php @@ -66,7 +66,7 @@ class Perforce * @param bool $isWindows * @param IOInterface $io */ - public function __construct($repoConfig, $port, $path, ProcessExecutor $process, $isWindows, IOInterface $io) + public function __construct($repoConfig, string $port, string $path, ProcessExecutor $process, bool $isWindows, IOInterface $io) { $this->windowsFlag = $isWindows; $this->p4Port = $port; @@ -85,7 +85,7 @@ public function __construct($repoConfig, $port, $path, ProcessExecutor $process, * * @return self */ - public static function create($repoConfig, $port, $path, ProcessExecutor $process, IOInterface $io) + public static function create($repoConfig, string $port, string $path, ProcessExecutor $process, IOInterface $io): self { return new Perforce($repoConfig, $port, $path, $process, Platform::isWindows(), $io); } @@ -96,7 +96,7 @@ public static function create($repoConfig, $port, $path, ProcessExecutor $proces * * @return bool */ - public static function checkServerExists($url, ProcessExecutor $processExecutor) + public static function checkServerExists(string $url, ProcessExecutor $processExecutor): bool { return 0 === $processExecutor->execute('p4 -p ' . ProcessExecutor::escape($url) . ' info -s', $ignoredOutput); } @@ -106,7 +106,7 @@ public static function checkServerExists($url, ProcessExecutor $processExecutor) * * @return void */ - public function initialize($repoConfig) + public function initialize($repoConfig): void { $this->uniquePerforceClientName = $this->generateUniquePerforceClientName(); if (!$repoConfig) { @@ -138,7 +138,7 @@ public function initialize($repoConfig) * * @return void */ - public function initializeDepotAndBranch($depot, $branch) + public function initializeDepotAndBranch(?string $depot, ?string $branch): void { if (isset($depot)) { $this->p4Depot = $depot; @@ -151,7 +151,7 @@ public function initializeDepotAndBranch($depot, $branch) /** * @return non-empty-string */ - public function generateUniquePerforceClientName() + public function generateUniquePerforceClientName(): string { return gethostname() . "_" . time(); } @@ -159,7 +159,7 @@ public function generateUniquePerforceClientName() /** * @return void */ - public function cleanupClientSpec() + public function cleanupClientSpec(): void { $client = $this->getClient(); $task = 'client -d ' . ProcessExecutor::escape($client); @@ -176,7 +176,7 @@ public function cleanupClientSpec() * * @return int */ - protected function executeCommand($command) + protected function executeCommand($command): int { $this->commandResult = ''; @@ -186,7 +186,7 @@ protected function executeCommand($command) /** * @return string */ - public function getClient() + public function getClient(): string { if (!isset($this->p4Client)) { $cleanStreamName = str_replace(array('//', '/', '@'), array('', '_', ''), $this->getStream()); @@ -199,7 +199,7 @@ public function getClient() /** * @return string */ - protected function getPath() + protected function getPath(): string { return $this->path; } @@ -209,7 +209,7 @@ protected function getPath() * * @return void */ - public function initializePath($path) + public function initializePath(string $path): void { $this->path = $path; $fs = $this->getFilesystem(); @@ -219,7 +219,7 @@ public function initializePath($path) /** * @return string */ - protected function getPort() + protected function getPort(): string { return $this->p4Port; } @@ -229,7 +229,7 @@ protected function getPort() * * @return void */ - public function setStream($stream) + public function setStream(string $stream): void { $this->p4Stream = $stream; $index = strrpos($stream, '/'); @@ -242,7 +242,7 @@ public function setStream($stream) /** * @return bool */ - public function isStream() + public function isStream(): bool { return is_string($this->p4DepotType) && (strcmp($this->p4DepotType, 'stream') === 0); } @@ -250,7 +250,7 @@ public function isStream() /** * @return string */ - public function getStream() + public function getStream(): string { if (!isset($this->p4Stream)) { if ($this->isStream()) { @@ -268,7 +268,7 @@ public function getStream() * * @return string */ - public function getStreamWithoutLabel($stream) + public function getStreamWithoutLabel(string $stream): string { $index = strpos($stream, '@'); if ($index === false) { @@ -281,7 +281,7 @@ public function getStreamWithoutLabel($stream) /** * @return non-empty-string */ - public function getP4ClientSpec() + public function getP4ClientSpec(): string { return $this->path . '/' . $this->getClient() . '.p4.spec'; } @@ -289,7 +289,7 @@ public function getP4ClientSpec() /** * @return string|null */ - public function getUser() + public function getUser(): ?string { return $this->p4User; } @@ -299,7 +299,7 @@ public function getUser() * * @return void */ - public function setUser($user) + public function setUser(?string $user): void { $this->p4User = $user; } @@ -307,7 +307,7 @@ public function setUser($user) /** * @return void */ - public function queryP4User() + public function queryP4User(): void { $this->getUser(); if (strlen((string) $this->p4User) > 0) { @@ -330,7 +330,7 @@ public function queryP4User() * @param string $name * @return ?string */ - protected function getP4variable($name) + protected function getP4variable(string $name): ?string { if ($this->windowsFlag) { $command = 'p4 set'; @@ -365,7 +365,7 @@ protected function getP4variable($name) /** * @return string|null */ - public function queryP4Password() + public function queryP4Password(): ?string { if (isset($this->p4Password)) { return $this->p4Password; @@ -385,7 +385,7 @@ public function queryP4Password() * * @return non-empty-string */ - public function generateP4Command($command, $useClient = true) + public function generateP4Command(string $command, bool $useClient = true): string { $p4Command = 'p4 '; $p4Command .= '-u ' . $this->getUser() . ' '; @@ -400,7 +400,7 @@ public function generateP4Command($command, $useClient = true) /** * @return bool */ - public function isLoggedIn() + public function isLoggedIn(): bool { $command = $this->generateP4Command('login -s', false); $exitCode = $this->executeCommand($command); @@ -423,7 +423,7 @@ public function isLoggedIn() /** * @return void */ - public function connectClient() + public function connectClient(): void { $p4CreateClientCommand = $this->generateP4Command( 'client -i < ' . str_replace(" ", "\\ ", $this->getP4ClientSpec()) @@ -436,9 +436,9 @@ public function connectClient() * * @return void */ - public function syncCodeBase($sourceReference) + public function syncCodeBase(?string $sourceReference): void { - $prevDir = getcwd(); + $prevDir = Platform::getCwd(); chdir($this->path); $p4SyncCommand = $this->generateP4Command('sync -f '); if (null !== $sourceReference) { @@ -453,7 +453,7 @@ public function syncCodeBase($sourceReference) * * @return void */ - public function writeClientSpecToFile($spec) + public function writeClientSpecToFile($spec): void { fwrite($spec, 'Client: ' . $this->getClient() . PHP_EOL . PHP_EOL); fwrite($spec, 'Update: ' . date('Y/m/d H:i:s') . PHP_EOL . PHP_EOL); @@ -479,7 +479,7 @@ public function writeClientSpecToFile($spec) /** * @return void */ - public function writeP4ClientSpec() + public function writeP4ClientSpec(): void { $clientSpec = $this->getP4ClientSpec(); $spec = fopen($clientSpec, 'w'); @@ -498,7 +498,7 @@ public function writeP4ClientSpec() * * @return void */ - protected function read($pipe, $name) + protected function read($pipe, $name): void { if (feof($pipe)) { return; @@ -514,7 +514,7 @@ protected function read($pipe, $name) * * @return int */ - public function windowsLogin($password) + public function windowsLogin(?string $password): int { $command = $this->generateP4Command(' login -a'); @@ -526,7 +526,7 @@ public function windowsLogin($password) /** * @return void */ - public function p4Login() + public function p4Login(): void { $this->queryP4User(); if (!$this->isLoggedIn()) { @@ -546,14 +546,14 @@ public function p4Login() /** * @param string $identifier * - * @return mixed|void + * @return mixed[]|null */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier): ?array { $composerFileContent = $this->getFileContent('composer.json', $identifier); if (!$composerFileContent) { - return; + return null; } return json_decode($composerFileContent, true); @@ -565,7 +565,7 @@ public function getComposerInformation($identifier) * * @return string|null */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier): ?string { $path = $this->getFilePath($file, $identifier); @@ -586,7 +586,7 @@ public function getFileContent($file, $identifier) * * @return string|null */ - public function getFilePath($file, $identifier) + public function getFilePath(string $file, string $identifier): ?string { $index = strpos($identifier, '@'); if ($index === false) { @@ -614,7 +614,7 @@ public function getFilePath($file, $identifier) /** * @return array{master: string} */ - public function getBranches() + public function getBranches(): array { $possibleBranches = array(); if (!$this->isStream()) { @@ -646,7 +646,7 @@ public function getBranches() /** * @return array */ - public function getTags() + public function getTags(): array { $command = $this->generateP4Command('labels'); $this->executeCommand($command); @@ -666,7 +666,7 @@ public function getTags() /** * @return bool */ - public function checkStream() + public function checkStream(): bool { $command = $this->generateP4Command('depots', false); $this->executeCommand($command); @@ -690,7 +690,7 @@ public function checkStream() * @param string $reference * @return mixed|null */ - protected function getChangeList($reference) + protected function getChangeList(string $reference): mixed { $index = strpos($reference, '@'); if ($index === false) { @@ -713,7 +713,7 @@ protected function getChangeList($reference) * @param string $toReference * @return mixed|null */ - public function getCommitLogs($fromReference, $toReference) + public function getCommitLogs(string $fromReference, string $toReference): mixed { $fromChangeList = $this->getChangeList($fromReference); if ($fromChangeList === null) { @@ -734,7 +734,7 @@ public function getCommitLogs($fromReference, $toReference) /** * @return Filesystem */ - public function getFilesystem() + public function getFilesystem(): Filesystem { if (null === $this->filesystem) { $this->filesystem = new Filesystem($this->process); @@ -746,7 +746,7 @@ public function getFilesystem() /** * @return void */ - public function setFilesystem(Filesystem $fs) + public function setFilesystem(Filesystem $fs): void { $this->filesystem = $fs; } diff --git a/src/Composer/Util/Platform.php b/src/Composer/Util/Platform.php index d237f8ea10b3..4e58cecbb62c 100644 --- a/src/Composer/Util/Platform.php +++ b/src/Composer/Util/Platform.php @@ -26,13 +26,39 @@ class Platform /** @var ?bool */ private static $isWindowsSubsystemForLinux = null; + /** + * getcwd() equivalent which always returns a string + * + * @throws \RuntimeException + */ + public static function getCwd(bool $allowEmpty = false): string + { + $cwd = getcwd(); + + // fallback to realpath('') just in case this works but odds are it would break as well if we are in a case where getcwd fails + if (false === $cwd) { + $cwd = realpath(''); + } + + // crappy state, assume '' and hopefully relative paths allow things to continue + if (false === $cwd) { + if ($allowEmpty) { + return ''; + } + + throw new \RuntimeException('Could not determine the current working directory'); + } + + return $cwd; + } + /** * getenv() equivalent but reads from the runtime global variables first * * @param string $name * @return string|false */ - public static function getEnv($name) + public static function getEnv(string $name) { if (array_key_exists($name, $_SERVER)) { return (string) $_SERVER[$name]; @@ -51,7 +77,7 @@ public static function getEnv($name) * @param string $value * @return void */ - public static function putEnv($name, $value): void + public static function putEnv(string $name, string $value): void { $value = (string) $value; putenv($name . '=' . $value); @@ -64,7 +90,7 @@ public static function putEnv($name, $value): void * @param string $name * @return void */ - public static function clearEnv($name): void + public static function clearEnv(string $name): void { putenv($name); unset($_SERVER[$name], $_ENV[$name]); @@ -76,7 +102,7 @@ public static function clearEnv($name): void * @param string $path * @return string */ - public static function expandPath($path): string + public static function expandPath(string $path): string { if (Preg::isMatch('#^~[\\/]#', $path)) { return self::getUserDirectory() . substr($path, 1); @@ -153,7 +179,7 @@ public static function isWindows(): bool * @param string $str * @return int return a guaranteed binary length of the string, regardless of silly mbstring configs */ - public static function strlen($str): int + public static function strlen(string $str): int { static $useMbString = null; if (null === $useMbString) { diff --git a/src/Composer/Util/ProcessExecutor.php b/src/Composer/Util/ProcessExecutor.php index fb661bac4d7f..429337708c0a 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -65,10 +65,10 @@ public function __construct(IOInterface $io = null) * @param string|list $command the command to execute * @param mixed $output the output will be written into this var if passed by ref * if a callable is passed it will be used as output handler - * @param ?string $cwd the working directory + * @param null|string $cwd the working directory * @return int statuscode */ - public function execute($command, &$output = null, $cwd = null) + public function execute($command, &$output = null, ?string $cwd = null): int { if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); @@ -81,10 +81,10 @@ public function execute($command, &$output = null, $cwd = null) * runs a process on the commandline in TTY mode * * @param string|list $command the command to execute - * @param ?string $cwd the working directory + * @param null|string $cwd the working directory * @return int statuscode */ - public function executeTty($command, $cwd = null) + public function executeTty($command, ?string $cwd = null): int { if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); @@ -95,12 +95,12 @@ public function executeTty($command, $cwd = null) /** * @param string|list $command - * @param ?string $cwd + * @param null|string $cwd * @param bool $tty * @param mixed $output * @return int */ - private function doExecute($command, $cwd, $tty, &$output = null): int + private function doExecute($command, ?string $cwd, bool $tty, &$output = null): int { $this->outputCommandRun($command, $cwd, false); @@ -121,7 +121,10 @@ private function doExecute($command, $cwd, $tty, &$output = null): int } } - $callback = is_callable($output) ? $output : array($this, 'outputHandler'); + $callback = is_callable($output) ? $output : function (string $type, string $buffer): void { + $this->outputHandler($type, $buffer); + }; + $process->run($callback); if ($this->captureOutput && !is_callable($output)) { @@ -140,7 +143,7 @@ private function doExecute($command, $cwd, $tty, &$output = null): int * @param string $cwd the working directory * @return PromiseInterface */ - public function executeAsync($command, $cwd = null) + public function executeAsync($command, ?string $cwd = null): PromiseInterface { if (!$this->allowAsync) { throw new \LogicException('You must use the ProcessExecutor instance which is part of a Composer\Loop instance to be able to run async processes'); @@ -206,11 +209,30 @@ public function executeAsync($command, $cwd = null) return $promise; } + protected function outputHandler(string $type, string $buffer): void + { + if ($this->captureOutput) { + return; + } + + if (null === $this->io) { + echo $buffer; + + return; + } + + if (Process::ERR === $type) { + $this->io->writeErrorRaw($buffer, false); + } else { + $this->io->writeRaw($buffer, false); + } + } + /** * @param int $id * @return void */ - private function startJob($id): void + private function startJob(int $id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { @@ -253,7 +275,7 @@ private function startJob($id): void * @param ?int $index job id * @return void */ - public function wait($index = null) + public function wait($index = null): void { while (true) { if (!$this->countActiveJobs($index)) { @@ -321,10 +343,10 @@ private function markJobDone(): void } /** - * @param ?string $output + * @param null|string $output * @return string[] */ - public function splitLines($output) + public function splitLines(?string $output): array { $output = trim((string) $output); @@ -336,42 +358,15 @@ public function splitLines($output) * * @return string */ - public function getErrorOutput() + public function getErrorOutput(): string { return $this->errorOutput; } - /** - * @private - * - * @param Process::ERR|Process::OUT $type - * @param string $buffer - * - * @return void - */ - public function outputHandler($type, $buffer) - { - if ($this->captureOutput) { - return; - } - - if (null === $this->io) { - echo $buffer; - - return; - } - - if (Process::ERR === $type) { - $this->io->writeErrorRaw($buffer, false); - } else { - $this->io->writeRaw($buffer, false); - } - } - /** * @return int the timeout in seconds */ - public static function getTimeout() + public static function getTimeout(): int { return static::$timeout; } @@ -380,7 +375,7 @@ public static function getTimeout() * @param int $timeout the timeout in seconds * @return void */ - public static function setTimeout($timeout) + public static function setTimeout(int $timeout): void { static::$timeout = $timeout; } @@ -392,7 +387,7 @@ public static function setTimeout($timeout) * * @return string The escaped argument */ - public static function escape($argument) + public static function escape($argument): string { return self::escapeArgument($argument); } diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 1d6866f7a583..4d666fc30e34 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -76,7 +76,7 @@ class RemoteFilesystem * @param bool $disableTls * @param AuthHelper $authHelper */ - public function __construct(IOInterface $io, Config $config, array $options = array(), $disableTls = false, AuthHelper $authHelper = null) + public function __construct(IOInterface $io, Config $config, array $options = array(), bool $disableTls = false, AuthHelper $authHelper = null) { $this->io = $io; @@ -106,7 +106,7 @@ public function __construct(IOInterface $io, Config $config, array $options = ar * * @return bool true */ - public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array()): bool + public function copy(string $originUrl, string $fileUrl, string $fileName, bool $progress = true, array $options = array()) { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); } @@ -121,7 +121,7 @@ public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options * * @return bool|string The content */ - public function getContents($originUrl, $fileUrl, $progress = true, $options = array()) + public function getContents(string $originUrl, string $fileUrl, bool $progress = true, array $options = array()) { return $this->get($originUrl, $fileUrl, $options, null, $progress); } @@ -131,7 +131,7 @@ public function getContents($originUrl, $fileUrl, $progress = true, $options = a * * @return mixed[] Options */ - public function getOptions(): array + public function getOptions() { return $this->options; } @@ -142,7 +142,7 @@ public function getOptions(): array * @param mixed[] $options * @return void */ - public function setOptions(array $options): void + public function setOptions(array $options) { $this->options = array_replace_recursive($this->options, $options); } @@ -152,7 +152,7 @@ public function setOptions(array $options): void * * @return bool */ - public function isTlsDisabled(): bool + public function isTlsDisabled() { return $this->disableTls === true; } @@ -162,7 +162,7 @@ public function isTlsDisabled(): bool * * @return string[] */ - public function getLastHeaders(): array + public function getLastHeaders() { return $this->lastHeaders; } @@ -171,7 +171,7 @@ public function getLastHeaders(): array * @param string[] $headers array of returned headers like from getLastHeaders() * @return int|null */ - public static function findStatusCode(array $headers): ?int + public static function findStatusCode(array $headers) { $value = null; foreach ($headers as $header) { @@ -189,7 +189,7 @@ public static function findStatusCode(array $headers): ?int * @param string[] $headers array of returned headers like from getLastHeaders() * @return string|null */ - public function findStatusMessage(array $headers): ?string + public function findStatusMessage(array $headers) { $value = null; foreach ($headers as $header) { @@ -217,7 +217,7 @@ public function findStatusMessage(array $headers): ?string * * @return bool|string */ - protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true) + protected function get(string $originUrl, string $fileUrl, array $additionalOptions = array(), string $fileName = null, bool $progress = true) { $this->scheme = parse_url($fileUrl, PHP_URL_SCHEME); $this->bytesMax = 0; @@ -511,7 +511,7 @@ protected function get($originUrl, $fileUrl, $additionalOptions = array(), $file * * @return string|false The response contents or false on failure */ - protected function getRemoteContents($originUrl, $fileUrl, $context, array &$responseHeaders = null, $maxFileSize = null) + protected function getRemoteContents(string $originUrl, string $fileUrl, $context, array &$responseHeaders = null, int $maxFileSize = null) { $result = false; @@ -554,7 +554,7 @@ protected function getRemoteContents($originUrl, $fileUrl, $context, array &$res * * @throws TransportException */ - protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax): void + protected function callbackGet(int $notificationCode, int $severity, ?string $message, int $messageCode, int $bytesTransferred, int $bytesMax) { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: @@ -592,7 +592,7 @@ protected function callbackGet($notificationCode, $severity, $message, $messageC * * @return void */ - protected function promptAuthAndRetry($httpStatus, $reason = null, $headers = array()): void + protected function promptAuthAndRetry($httpStatus, ?string $reason = null, array $headers = array()) { $result = $this->authHelper->promptAuthIfNeeded($this->fileUrl, $this->originUrl, $httpStatus, $reason, $headers); @@ -610,7 +610,7 @@ protected function promptAuthAndRetry($httpStatus, $reason = null, $headers = ar * * @return mixed[] */ - protected function getOptionsForUrl($originUrl, $additionalOptions): array + protected function getOptionsForUrl(string $originUrl, array $additionalOptions) { $tlsOptions = array(); $headers = array(); @@ -698,7 +698,7 @@ private function handleRedirect(array $http_response_header, array $additionalOp * * @return string|null */ - private function decodeResult($result, $http_response_header): ?string + private function decodeResult($result, array $http_response_header): ?string { // decode gzip if ($result && extension_loaded('zlib')) { diff --git a/src/Composer/Util/Silencer.php b/src/Composer/Util/Silencer.php index 75a97575b7fe..484b5a5c7a6c 100644 --- a/src/Composer/Util/Silencer.php +++ b/src/Composer/Util/Silencer.php @@ -30,7 +30,7 @@ class Silencer * @param int|null $mask Error levels to suppress, default value NULL indicates all warnings and below. * @return int The old error reporting level. */ - public static function suppress($mask = null): int + public static function suppress(?int $mask = null): int { if (!isset($mask)) { $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT; @@ -57,17 +57,16 @@ public static function restore(): void /** * Calls a specified function while silencing warnings and below. * - * Future improvement: when PHP requirements are raised add Callable type hint (5.4) and variadic parameters (5.6) - * * @param callable $callable Function to execute. + * @param mixed $parameters Function to execute. * @throws \Exception Any exceptions from the callback are rethrown. * @return mixed Return value of the callback. */ - public static function call($callable /*, ...$parameters */) + public static function call(callable $callable, ...$parameters) { try { self::suppress(); - $result = call_user_func_array($callable, array_slice(func_get_args(), 1)); + $result = $callable(...$parameters); self::restore(); return $result; diff --git a/src/Composer/Util/StreamContextFactory.php b/src/Composer/Util/StreamContextFactory.php index 7448990d3df9..a4b1dbd4a619 100644 --- a/src/Composer/Util/StreamContextFactory.php +++ b/src/Composer/Util/StreamContextFactory.php @@ -37,7 +37,7 @@ final class StreamContextFactory * @throws \RuntimeException if https proxy required and OpenSSL uninstalled * @return resource Default context */ - public static function getContext($url, array $defaultOptions = array(), array $defaultParams = array()) + public static function getContext(string $url, array $defaultOptions = array(), array $defaultParams = array()) { $options = array('http' => array( // specify defaults again to try and work better with curlwrappers enabled @@ -63,7 +63,7 @@ public static function getContext($url, array $defaultOptions = array(), array $ * @phpstan-return array{http: array{header: string[], proxy?: string, request_fulluri: bool}, ssl?: mixed[]} * @return array formatted as a stream context array */ - public static function initOptions($url, array $options, $forCurl = false): array + public static function initOptions(string $url, array $options, bool $forCurl = false): array { // Make sure the headers are in an array form if (!isset($options['http']['header'])) { diff --git a/src/Composer/Util/Svn.php b/src/Composer/Util/Svn.php index 5c47d408c6e1..86416e56d508 100644 --- a/src/Composer/Util/Svn.php +++ b/src/Composer/Util/Svn.php @@ -75,7 +75,7 @@ class Svn * @param Config $config * @param ProcessExecutor $process */ - public function __construct($url, IOInterface $io, Config $config, ProcessExecutor $process = null) + public function __construct(string $url, IOInterface $io, Config $config, ProcessExecutor $process = null) { $this->url = $url; $this->io = $io; @@ -96,16 +96,16 @@ public static function cleanEnv(): void * Execute an SVN remote command and try to fix up the process with credentials * if necessary. * - * @param string $command SVN command to run - * @param string $url SVN url - * @param string $cwd Working directory - * @param string $path Target for a checkout - * @param bool $verbose Output all output to the user + * @param string $command SVN command to run + * @param string $url SVN url + * @param ?string $cwd Working directory + * @param ?string $path Target for a checkout + * @param bool $verbose Output all output to the user * * @throws \RuntimeException * @return string */ - public function execute($command, $url, $cwd = null, $path = null, $verbose = false): string + public function execute(string $command, string $url, ?string $cwd = null, ?string $path = null, bool $verbose = false): string { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -125,22 +125,13 @@ public function execute($command, $url, $cwd = null, $path = null, $verbose = fa * @throws \RuntimeException * @return string */ - public function executeLocal($command, $path, $cwd = null, $verbose = false): string + public function executeLocal(string $command, string $path, string $cwd = null, bool $verbose = false): string { // A local command has no remote url return $this->executeWithAuthRetry($command, $cwd, '', $path, $verbose); } - /** - * @param string $svnCommand - * @param string $cwd - * @param string $url - * @param string $path - * @param bool $verbose - * - * @return ?string - */ - private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose): ?string + private function executeWithAuthRetry(string $svnCommand, ?string $cwd, string $url, ?string $path, bool $verbose): ?string { // Regenerate the command at each try, to use the newly user-provided credentials $command = $this->getCommand($svnCommand, $url, $path); @@ -194,7 +185,7 @@ private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose): * @param bool $cacheCredentials * @return void */ - public function setCacheCredentials($cacheCredentials): void + public function setCacheCredentials(bool $cacheCredentials): void { $this->cacheCredentials = $cacheCredentials; } @@ -205,7 +196,7 @@ public function setCacheCredentials($cacheCredentials): void * @throws \RuntimeException * @return \Composer\Util\Svn */ - protected function doAuthDance(): \Composer\Util\Svn + protected function doAuthDance(): Svn { // cannot ask for credentials in non interactive mode if (!$this->io->isInteractive()) { @@ -236,7 +227,7 @@ protected function doAuthDance(): \Composer\Util\Svn * * @return string */ - protected function getCommand($cmd, $url, $path = null): string + protected function getCommand(string $cmd, string $url, ?string $path = null): string { $cmd = sprintf( '%s %s%s -- %s', diff --git a/src/Composer/Util/SyncHelper.php b/src/Composer/Util/SyncHelper.php index f61d02dbe58c..c245d2132e70 100644 --- a/src/Composer/Util/SyncHelper.php +++ b/src/Composer/Util/SyncHelper.php @@ -31,7 +31,7 @@ class SyncHelper * * @return void */ - public static function downloadAndInstallPackageSync(Loop $loop, DownloaderInterface $downloader, $path, PackageInterface $package, PackageInterface $prevPackage = null): void + public static function downloadAndInstallPackageSync(Loop $loop, DownloaderInterface $downloader, string $path, PackageInterface $package, PackageInterface $prevPackage = null): void { $type = $prevPackage ? 'update' : 'install'; diff --git a/src/Composer/Util/Tar.php b/src/Composer/Util/Tar.php index 9d4f7f112427..05f2229f03b2 100644 --- a/src/Composer/Util/Tar.php +++ b/src/Composer/Util/Tar.php @@ -22,7 +22,7 @@ class Tar * * @return string|null */ - public static function getComposerJson($pathToArchive): ?string + public static function getComposerJson(string $pathToArchive): ?string { $phar = new \PharData($pathToArchive); diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php index 697a66b17552..78829e60e47a 100644 --- a/src/Composer/Util/TlsHelper.php +++ b/src/Composer/Util/TlsHelper.php @@ -30,7 +30,7 @@ final class TlsHelper * * @return bool */ - public static function checkCertificateHost($certificate, $hostname, &$cn = null): bool + public static function checkCertificateHost($certificate, string $hostname, string &$cn = null): bool { $names = self::getCertificateNames($certificate); @@ -136,7 +136,7 @@ public static function getCertificateNames($certificate): ?array * @param string $certificate * @return string */ - public static function getCertificateFingerprint($certificate): string + public static function getCertificateFingerprint(string $certificate): string { $pubkey = openssl_get_publickey($certificate); if ($pubkey === false) { @@ -173,7 +173,7 @@ public static function isOpensslParseSafe(): bool * * @return callable|null */ - private static function certNameMatcher($certName): ?callable + private static function certNameMatcher(string $certName): ?callable { $wildcards = substr_count($certName, '*'); diff --git a/src/Composer/Util/Url.php b/src/Composer/Util/Url.php index d118054d24b6..6089da925d7e 100644 --- a/src/Composer/Util/Url.php +++ b/src/Composer/Util/Url.php @@ -26,7 +26,7 @@ class Url * @param string $ref * @return string the updated URL */ - public static function updateDistReference(Config $config, $url, $ref): string + public static function updateDistReference(Config $config, string $url, string $ref): string { $host = parse_url($url, PHP_URL_HOST); @@ -64,7 +64,7 @@ public static function updateDistReference(Config $config, $url, $ref): string * @param string $url * @return string */ - public static function getOrigin(Config $config, $url): string + public static function getOrigin(Config $config, string $url): string { if (0 === strpos($url, 'file://')) { return $url; @@ -108,7 +108,7 @@ public static function getOrigin(Config $config, $url): string * @param string $url * @return string */ - public static function sanitize($url): string + public static function sanitize(string $url): string { // GitHub repository rename result in redirect locations containing the access_token as GET parameter // e.g. https://api.github.com/repositories/9999999999?access_token=github_token diff --git a/src/Composer/Util/Zip.php b/src/Composer/Util/Zip.php index 3e448048da2f..342c1d3b724f 100644 --- a/src/Composer/Util/Zip.php +++ b/src/Composer/Util/Zip.php @@ -24,7 +24,7 @@ class Zip * * @return string|null */ - public static function getComposerJson($pathToZip): ?string + public static function getComposerJson(string $pathToZip): ?string { if (!extension_loaded('zip')) { throw new \RuntimeException('The Zip Util requires PHP\'s zip extension'); @@ -65,7 +65,7 @@ public static function getComposerJson($pathToZip): ?string * * @return int */ - private static function locateFile(\ZipArchive $zip, $filename): int + private static function locateFile(\ZipArchive $zip, string $filename): int { // return root composer.json if it is there and is a file if (false !== ($index = $zip->locateName($filename)) && $zip->getFromIndex($index) !== false) { diff --git a/src/bootstrap.php b/src/bootstrap.php index 9b33ec1b01b9..f61063a4a0f8 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -10,11 +10,7 @@ * file that was distributed with this source code. */ -/** - * @param string $file - * @return ?\Composer\Autoload\ClassLoader - */ -function includeIfExists($file) +function includeIfExists(string $file): ?\Composer\Autoload\ClassLoader { return file_exists($file) ? include $file : null; } diff --git a/tests/Composer/Test/AllFunctionalTest.php b/tests/Composer/Test/AllFunctionalTest.php index 12bd95e3dc46..2bebf801c758 100644 --- a/tests/Composer/Test/AllFunctionalTest.php +++ b/tests/Composer/Test/AllFunctionalTest.php @@ -14,6 +14,7 @@ use Composer\Pcre\Preg; use Composer\Util\Filesystem; +use Composer\Util\Platform; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; @@ -33,7 +34,7 @@ class AllFunctionalTest extends TestCase public function setUp(): void { - $this->oldcwd = getcwd(); + $this->oldcwd = Platform::getCwd(); chdir(__DIR__.'/Fixtures/functional'); } @@ -100,7 +101,7 @@ public function testBuildPhar(): void * @depends testBuildPhar * @param string $testFile */ - public function testIntegration($testFile): void + public function testIntegration(string $testFile): void { $testData = $this->parseTestFile($testFile); $this->testDir = self::getUniqueTmpDirectory(); @@ -193,7 +194,7 @@ public function getTestFiles(): array * @param string $file * @return array{RUN: string, EXPECT?: string, EXPECT-EXIT-CODE?: int, EXPECT-REGEX?: string, EXPECT-REGEXES?: string, TEST?: string} */ - private function parseTestFile($file): array + private function parseTestFile(string $file): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); $data = array(); @@ -255,7 +256,7 @@ private function parseTestFile($file): array * @param string $output * @return string */ - private function cleanOutput($output): string + private function cleanOutput(string $output): string { $processed = ''; diff --git a/tests/Composer/Test/ApplicationTest.php b/tests/Composer/Test/ApplicationTest.php index 30aab498883e..e0674c4faad5 100644 --- a/tests/Composer/Test/ApplicationTest.php +++ b/tests/Composer/Test/ApplicationTest.php @@ -84,7 +84,7 @@ public function testDevWarning(): void * @param string $command * @return void */ - public function ensureNoDevWarning($command): void + public function ensureNoDevWarning(string $command): void { $application = new Application; diff --git a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php index 06c12cfb50db..507d161b1f74 100644 --- a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php +++ b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php @@ -122,7 +122,7 @@ protected function setUp(): void return $ret; })); - $this->origDir = getcwd(); + $this->origDir = Platform::getCwd(); chdir($this->workingDir); $this->im = $this->getMockBuilder('Composer\Installer\InstallationManager') @@ -1705,11 +1705,11 @@ public function testExcludeFromClassmap(): void * @param string|null $expectedFixture * @param array $provides * @param array $replaces - * @param bool $ignorePlatformReqs + * @param bool|array $ignorePlatformReqs * * @dataProvider platformCheckProvider */ - public function testGeneratesPlatformCheck(array $requires, $expectedFixture, array $provides = array(), array $replaces = array(), $ignorePlatformReqs = false): void + public function testGeneratesPlatformCheck(array $requires, ?string $expectedFixture, array $provides = array(), array $replaces = array(), $ignorePlatformReqs = false): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires($requires); @@ -1850,7 +1850,7 @@ public function platformCheckProvider(): array * * @return void */ - private function assertAutoloadFiles($name, $dir, $type = 'namespaces'): void + private function assertAutoloadFiles(string $name, string $dir, string $type = 'namespaces'): void { $a = __DIR__.'/Fixtures/autoload_'.$name.'.php'; $b = $dir.'/autoload_'.$type.'.php'; diff --git a/tests/Composer/Test/Autoload/ClassLoaderTest.php b/tests/Composer/Test/Autoload/ClassLoaderTest.php index d11c522a9614..27f96d6b7a6b 100644 --- a/tests/Composer/Test/Autoload/ClassLoaderTest.php +++ b/tests/Composer/Test/Autoload/ClassLoaderTest.php @@ -27,7 +27,7 @@ class ClassLoaderTest extends TestCase * * @param string $class The fully-qualified class name to test, without preceding namespace separator. */ - public function testLoadClass($class): void + public function testLoadClass(string $class): void { $loader = new ClassLoader(); $loader->add('Namespaced\\', __DIR__ . '/Fixtures'); diff --git a/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php b/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php index 5315c4b33bc4..302ab6094a48 100644 --- a/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php +++ b/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php @@ -30,7 +30,7 @@ class ClassMapGeneratorTest extends TestCase * @param string $directory * @param array $expected */ - public function testCreateMap($directory, $expected): void + public function testCreateMap(string $directory, array $expected): void { $this->assertEqualsNormalized($expected, ClassMapGenerator::createMap($directory)); } @@ -274,7 +274,7 @@ public function testCreateMapDoesNotHitRegexBacktraceLimit(): void * @param string $message * @return void */ - protected function assertEqualsNormalized($expected, $actual, $message = ''): void + protected function assertEqualsNormalized(array $expected, array $actual, string $message = ''): void { foreach ($expected as $ns => $path) { $expected[$ns] = strtr($path, '\\', '/'); diff --git a/tests/Composer/Test/Command/ArchiveCommandTest.php b/tests/Composer/Test/Command/ArchiveCommandTest.php index 88cc15fe10d1..9ad7bf73f320 100644 --- a/tests/Composer/Test/Command/ArchiveCommandTest.php +++ b/tests/Composer/Test/Command/ArchiveCommandTest.php @@ -16,6 +16,7 @@ use Composer\Config; use Composer\Factory; use Composer\Test\TestCase; +use Composer\Util\Platform; use Symfony\Component\Console\Input\ArrayInput; class ArchiveCommandTest extends TestCase @@ -42,7 +43,7 @@ public function testUsesConfigFromComposerObject(): void ->getMock(); $manager->expects($this->once())->method('archive') - ->with($package, 'zip', '.', null, false)->willReturn(getcwd()); + ->with($package, 'zip', '.', null, false)->willReturn(Platform::getCwd()); $composer->setArchiveManager($manager); $composer->setEventDispatcher($ed); diff --git a/tests/Composer/Test/Command/InitCommandTest.php b/tests/Composer/Test/Command/InitCommandTest.php index 69af6cfbc367..25af49ed503c 100644 --- a/tests/Composer/Test/Command/InitCommandTest.php +++ b/tests/Composer/Test/Command/InitCommandTest.php @@ -20,7 +20,7 @@ class InitCommandTest extends TestCase public function testParseValidAuthorString(): void { $command = new InitCommand; - $author = $command->parseAuthorString('John Smith '); + $author = $this->callParseAuthorString($command, 'John Smith '); $this->assertEquals('John Smith', $author['name']); $this->assertEquals('john@example.com', $author['email']); } @@ -28,7 +28,7 @@ public function testParseValidAuthorString(): void public function testParseValidAuthorStringWithoutEmail(): void { $command = new InitCommand; - $author = $command->parseAuthorString('John Smith'); + $author = $this->callParseAuthorString($command, 'John Smith'); $this->assertEquals('John Smith', $author['name']); $this->assertNull($author['email']); } @@ -36,7 +36,7 @@ public function testParseValidAuthorStringWithoutEmail(): void public function testParseValidUtf8AuthorString(): void { $command = new InitCommand; - $author = $command->parseAuthorString('Matti Meikäläinen '); + $author = $this->callParseAuthorString($command, 'Matti Meikäläinen '); $this->assertEquals('Matti Meikäläinen', $author['name']); $this->assertEquals('matti@example.com', $author['email']); } @@ -46,7 +46,7 @@ public function testParseValidUtf8AuthorStringWithNonSpacingMarks(): void // \xCC\x88 is UTF-8 for U+0308 diaeresis (umlaut) combining mark $utf8_expected = "Matti Meika\xCC\x88la\xCC\x88inen"; $command = new InitCommand; - $author = $command->parseAuthorString($utf8_expected." "); + $author = $this->callParseAuthorString($command, $utf8_expected." "); $this->assertEquals($utf8_expected, $author['name']); $this->assertEquals('matti@example.com', $author['email']); } @@ -54,7 +54,7 @@ public function testParseValidUtf8AuthorStringWithNonSpacingMarks(): void public function testParseNumericAuthorString(): void { $command = new InitCommand; - $author = $command->parseAuthorString('h4x0r '); + $author = $this->callParseAuthorString($command, 'h4x0r '); $this->assertEquals('h4x0r', $author['name']); $this->assertEquals('h4x@example.com', $author['email']); } @@ -66,7 +66,7 @@ public function testParseNumericAuthorString(): void public function testParseValidAlias1AuthorString(): void { $command = new InitCommand; - $author = $command->parseAuthorString( + $author = $this->callParseAuthorString($command, 'Johnathon "Johnny" Smith ' ); $this->assertEquals('Johnathon "Johnny" Smith', $author['name']); @@ -80,7 +80,7 @@ public function testParseValidAlias1AuthorString(): void public function testParseValidAlias2AuthorString(): void { $command = new InitCommand; - $author = $command->parseAuthorString( + $author = $this->callParseAuthorString($command, 'Johnathon (Johnny) Smith ' ); $this->assertEquals('Johnathon (Johnny) Smith', $author['name']); @@ -91,14 +91,14 @@ public function testParseEmptyAuthorString(): void { $command = new InitCommand; self::expectException('InvalidArgumentException'); - $command->parseAuthorString(''); + $this->callParseAuthorString($command, ''); } public function testParseAuthorStringWithInvalidEmail(): void { $command = new InitCommand; self::expectException('InvalidArgumentException'); - $command->parseAuthorString('John Smith '); + $this->callParseAuthorString($command, 'John Smith '); } public function testNamespaceFromValidPackageName(): void @@ -121,4 +121,15 @@ public function testNamespaceFromMissingPackageName(): void $namespace = $command->namespaceFromPackageName(''); $this->assertNull($namespace); } + + /** + * @return array{name: string, email: string|null} + */ + private function callParseAuthorString(InitCommand $command, string $string): array + { + $reflMethod = new \ReflectionMethod($command, 'parseAuthorString'); + $reflMethod->setAccessible(true); + + return $reflMethod->invoke($command, $string); + } } diff --git a/tests/Composer/Test/Command/RunScriptCommandTest.php b/tests/Composer/Test/Command/RunScriptCommandTest.php index 7a9d7aef85ef..200ae7c9a1eb 100644 --- a/tests/Composer/Test/Command/RunScriptCommandTest.php +++ b/tests/Composer/Test/Command/RunScriptCommandTest.php @@ -24,7 +24,7 @@ class RunScriptCommandTest extends TestCase * @param bool $dev * @param bool $noDev */ - public function testDetectAndPassDevModeToEventAndToDispatching($dev, $noDev): void + public function testDetectAndPassDevModeToEventAndToDispatching(bool $dev, bool $noDev): void { $scriptName = 'testScript'; diff --git a/tests/Composer/Test/Config/JsonConfigSourceTest.php b/tests/Composer/Test/Config/JsonConfigSourceTest.php index fd0e1f3e4494..818e22db365c 100644 --- a/tests/Composer/Test/Config/JsonConfigSourceTest.php +++ b/tests/Composer/Test/Config/JsonConfigSourceTest.php @@ -29,7 +29,7 @@ class JsonConfigSourceTest extends TestCase * * @return string */ - protected function fixturePath($name): string + protected function fixturePath(string $name): string { return __DIR__.'/Fixtures/'.$name; } @@ -117,7 +117,7 @@ public function testRemovePackagist(): void * * @dataProvider provideAddLinkData */ - public function testAddLink($sourceFile, $type, $name, $value, $compareAgainst): void + public function testAddLink(string $sourceFile, string $type, string $name, string $value, string $compareAgainst): void { $composerJson = $this->workingDir.'/composer.json'; copy($sourceFile, $composerJson); @@ -138,7 +138,7 @@ public function testAddLink($sourceFile, $type, $name, $value, $compareAgainst): * * @dataProvider provideRemoveLinkData */ - public function testRemoveLink($sourceFile, $type, $name, $compareAgainst): void + public function testRemoveLink(string $sourceFile, string $type, string $name, string $compareAgainst): void { $composerJson = $this->workingDir.'/composer.json'; copy($sourceFile, $composerJson); @@ -160,7 +160,7 @@ public function testRemoveLink($sourceFile, $type, $name, $compareAgainst): void * * @phpstan-return array{string, string, string, string, string} */ - protected function addLinkDataArguments($type, $name, $value, $fixtureBasename, $before): array + protected function addLinkDataArguments(string $type, string $name, string $value, string $fixtureBasename, string $before): array { return array( $before, @@ -217,7 +217,7 @@ public function provideAddLinkData(): array * * @phpstan-return array{string, string, string, string} */ - protected function removeLinkDataArguments($type, $name, $fixtureBasename, $after = null): array + protected function removeLinkDataArguments(string $type, string $name, string $fixtureBasename, ?string $after = null): array { return array( $this->fixturePath('removeLink/'.$fixtureBasename.'.json'), diff --git a/tests/Composer/Test/ConfigTest.php b/tests/Composer/Test/ConfigTest.php index 17f4384c288f..924806e606e4 100644 --- a/tests/Composer/Test/ConfigTest.php +++ b/tests/Composer/Test/ConfigTest.php @@ -21,9 +21,9 @@ class ConfigTest extends TestCase * @dataProvider dataAddPackagistRepository * @param mixed[] $expected * @param mixed[] $localConfig - * @param ?mixed[] $systemConfig + * @param ?array $systemConfig */ - public function testAddPackagistRepository($expected, $localConfig, $systemConfig = null): void + public function testAddPackagistRepository(array $expected, array $localConfig, ?array $systemConfig = null): void { $config = new Config(false); if ($systemConfig) { @@ -247,7 +247,7 @@ public function testGitDisabledByDefaultInGithubProtocols(): void * * @param string $url */ - public function testAllowedUrlsPass($url): void + public function testAllowedUrlsPass(string $url): void { $config = new Config(false); $config->prohibitUrlByConfig($url); @@ -258,7 +258,7 @@ public function testAllowedUrlsPass($url): void * * @param string $url */ - public function testProhibitedUrlsThrowException($url): void + public function testProhibitedUrlsThrowException(string $url): void { self::expectException('Composer\Downloader\TransportException'); self::expectExceptionMessage('Your configuration does not allow connections to ' . $url); diff --git a/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php b/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php index 92b9840a822e..913fa5470f49 100644 --- a/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php @@ -30,6 +30,7 @@ use Composer\Repository\RepositoryFactory; use Composer\Repository\RepositorySet; use Composer\Test\TestCase; +use Composer\Util\Platform; class PoolBuilderTest extends TestCase { @@ -44,7 +45,7 @@ class PoolBuilderTest extends TestCase * @param mixed[] $packageRepos * @param mixed[] $fixed */ - public function testPoolBuilder($file, $message, $expect, $expectOptimized, $root, $requestData, $packageRepos, $fixed): void + public function testPoolBuilder(string $file, string $message, array $expect, array $expectOptimized, array $root, array $requestData, array $packageRepos, array $fixed): void { $rootAliases = !empty($root['aliases']) ? $root['aliases'] : array(); $minimumStability = !empty($root['minimum-stability']) ? $root['minimum-stability'] : 'stable'; @@ -82,7 +83,7 @@ public function testPoolBuilder($file, $message, $expect, $expectOptimized, $roo return $pkg; }; - $oldCwd = getcwd(); + $oldCwd = Platform::getCwd(); chdir(__DIR__.'/Fixtures/poolbuilder/'); $repositorySet = new RepositorySet($minimumStability, $stabilityFlags, $rootAliases, $rootReferences); @@ -149,7 +150,7 @@ public function testPoolBuilder($file, $message, $expect, $expectOptimized, $roo * @param array $packageIds * @return string[] */ - private function getPackageResultSet(Pool $pool, $packageIds): array + private function getPackageResultSet(Pool $pool, array $packageIds): array { $result = array(); for ($i = 1, $count = count($pool); $i <= $count; $i++) { @@ -223,7 +224,7 @@ public function getIntegrationTests(): array * @param string $fixturesDir * @return array */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir): array + protected function readTestFile(\SplFileInfo $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); diff --git a/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php b/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php index 1f78a4013726..a9f87feaadb1 100644 --- a/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php @@ -34,7 +34,7 @@ class PoolOptimizerTest extends TestCase * @param BasePackage[] $expectedPackages * @param string $message */ - public function testPoolOptimizer(array $requestData, array $packagesBefore, array $expectedPackages, $message): void + public function testPoolOptimizer(array $requestData, array $packagesBefore, array $expectedPackages, string $message): void { $lockedRepo = new LockArrayRepository(); @@ -100,7 +100,7 @@ public function provideIntegrationTests(): array * @param string $fixturesDir * @return mixed[] */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir): array + protected function readTestFile(\SplFileInfo $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); diff --git a/tests/Composer/Test/DependencyResolver/PoolTest.php b/tests/Composer/Test/DependencyResolver/PoolTest.php index c4c5185aec8e..3d24f9fdfb14 100644 --- a/tests/Composer/Test/DependencyResolver/PoolTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolTest.php @@ -61,7 +61,7 @@ public function testWhatProvidesWhenPackageCannotBeFound(): void * @param array<\Composer\Package\BasePackage>|null $packages * @return \Composer\DependencyResolver\Pool */ - protected function createPool($packages = array()): \Composer\DependencyResolver\Pool + protected function createPool(?array $packages = array()): Pool { return new Pool($packages); } diff --git a/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php b/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php index 00e31a3cb936..4b95b2bd919e 100644 --- a/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php @@ -93,7 +93,7 @@ public function testProcessUrl3(): void * @dataProvider provideUrls * @param string $url */ - public function testProcessUrlRewriteDist($url): void + public function testProcessUrlRewriteDist(string $url): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -132,7 +132,7 @@ public function provideUrls(): array * @param string $url * @param string $extension */ - public function testProcessUrlRewriteBitbucketDist($url, $extension): void + public function testProcessUrlRewriteBitbucketDist(string $url, string $extension): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); diff --git a/tests/Composer/Test/Downloader/DownloadManagerTest.php b/tests/Composer/Test/Downloader/DownloadManagerTest.php index b3eb77c2643f..8ff051927061 100644 --- a/tests/Composer/Test/Downloader/DownloadManagerTest.php +++ b/tests/Composer/Test/Downloader/DownloadManagerTest.php @@ -223,7 +223,8 @@ public function testFullPackageDownload(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -273,7 +274,8 @@ public function testFullPackageDownloadFailover(): void $downloaderSuccess ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -330,7 +332,8 @@ public function testDistOnlyPackageDownload(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -366,7 +369,8 @@ public function testSourceOnlyPackageDownload(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -432,7 +436,8 @@ public function testFullPackageDownloadWithSourcePreferred(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -469,7 +474,8 @@ public function testDistOnlyPackageDownloadWithSourcePreferred(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -506,7 +512,8 @@ public function testSourceOnlyPackageDownloadWithSourcePreferred(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -567,7 +574,8 @@ public function testUpdateDistWithEqualTypes(): void $zipDownloader ->expects($this->once()) ->method('update') - ->with($initial, $target, 'vendor/bundles/FOS/UserBundle'); + ->with($initial, $target, 'vendor/bundles/FOS/UserBundle') + ->will($this->returnValue(\React\Promise\resolve())); $zipDownloader ->expects($this->any()) ->method('getInstallationSource') @@ -605,7 +613,8 @@ public function testUpdateDistWithNotEqualTypes(): void $xzDownloader ->expects($this->once()) ->method('remove') - ->with($initial, 'vendor/bundles/FOS/UserBundle'); + ->with($initial, 'vendor/bundles/FOS/UserBundle') + ->will($this->returnValue(\React\Promise\resolve())); $xzDownloader ->expects($this->any()) ->method('getInstallationSource') @@ -615,7 +624,8 @@ public function testUpdateDistWithNotEqualTypes(): void $zipDownloader ->expects($this->once()) ->method('install') - ->with($target, 'vendor/bundles/FOS/UserBundle'); + ->with($target, 'vendor/bundles/FOS/UserBundle') + ->will($this->returnValue(\React\Promise\resolve())); $zipDownloader ->expects($this->any()) ->method('getInstallationSource') @@ -630,13 +640,13 @@ public function testUpdateDistWithNotEqualTypes(): void /** * @dataProvider updatesProvider - * @param ?string $prevPkgSource - * @param ?bool $prevPkgIsDev + * @param null|string $prevPkgSource + * @param null|bool $prevPkgIsDev * @param string[] $targetAvailable * @param bool $targetIsDev * @param string[] $expected */ - public function testGetAvailableSourcesUpdateSticksToSameSource($prevPkgSource, $prevPkgIsDev, $targetAvailable, $targetIsDev, $expected): void + public function testGetAvailableSourcesUpdateSticksToSameSource(?string $prevPkgSource, ?bool $prevPkgIsDev, array $targetAvailable, bool $targetIsDev, array $expected): void { $initial = null; if ($prevPkgSource) { @@ -775,7 +785,8 @@ public function testInstallPreferenceWithoutPreferenceDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -818,7 +829,8 @@ public function testInstallPreferenceWithoutPreferenceNoDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -864,7 +876,8 @@ public function testInstallPreferenceWithoutMatchDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -911,7 +924,8 @@ public function testInstallPreferenceWithoutMatchNoDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -958,7 +972,8 @@ public function testInstallPreferenceWithMatchAutoDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -1005,7 +1020,8 @@ public function testInstallPreferenceWithMatchAutoNoDev(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -1048,7 +1064,8 @@ public function testInstallPreferenceWithMatchSource(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) @@ -1091,7 +1108,8 @@ public function testInstallPreferenceWithMatchDist(): void $downloader ->expects($this->once()) ->method('download') - ->with($package, 'target_dir'); + ->with($package, 'target_dir') + ->will($this->returnValue(\React\Promise\resolve())); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs(array($this->io, false, $this->filesystem)) diff --git a/tests/Composer/Test/Downloader/FileDownloaderTest.php b/tests/Composer/Test/Downloader/FileDownloaderTest.php index d3f9c0056383..c147351626cf 100644 --- a/tests/Composer/Test/Downloader/FileDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FileDownloaderTest.php @@ -20,33 +20,30 @@ use Composer\Util\Filesystem; use Composer\Util\Http\Response; use Composer\Util\Loop; +use Composer\Config; +use Composer\Composer; class FileDownloaderTest extends TestCase { /** @var \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject */ private $httpDownloader; - /** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */ - private $config; public function setUp(): void { $this->httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(); - $this->config = $this->getMockBuilder('Composer\Config')->getMock(); } /** - * @param \Composer\IO\IOInterface $io - * @param \Composer\Config&\PHPUnit\Framework\MockObject\MockObject $config * @param \Composer\EventDispatcher\EventDispatcher $eventDispatcher * @param \Composer\Cache $cache * @param \Composer\Util\HttpDownloader&\PHPUnit\Framework\MockObject\MockObject $httpDownloader * @param \Composer\Util\Filesystem $filesystem * @return \Composer\Downloader\FileDownloader */ - protected function getDownloader($io = null, $config = null, $eventDispatcher = null, $cache = null, $httpDownloader = null, $filesystem = null): \Composer\Downloader\FileDownloader + protected function getDownloader(\Composer\IO\IOInterface $io = null, ?Config $config = null, EventDispatcher $eventDispatcher = null, \Composer\Cache $cache = null, $httpDownloader = null, Filesystem $filesystem = null): FileDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $config = $config ?: $this->config; + $config = $config ?: $this->getConfig(); $httpDownloader = $httpDownloader ?: $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(); $httpDownloader ->expects($this->any()) @@ -54,40 +51,29 @@ protected function getDownloader($io = null, $config = null, $eventDispatcher = ->will($this->returnValue(\React\Promise\resolve(new Response(array('url' => 'http://example.org/'), 200, array(), 'file~')))); $this->httpDownloader = $httpDownloader; - return new FileDownloader($io, $this->config, $httpDownloader, $eventDispatcher, $cache, $filesystem); + return new FileDownloader($io, $config, $httpDownloader, $eventDispatcher, $cache, $filesystem); } public function testDownloadForPackageWithoutDistReference(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->once()) - ->method('getDistUrl') - ->will($this->returnValue(null)) - ; + $package = $this->getPackage(); self::expectException('InvalidArgumentException'); $downloader = $this->getDownloader(); - $downloader->download($packageMock, '/path'); + $downloader->download($package, '/path'); } public function testDownloadToExistingFile(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue('url')) - ; - $packageMock->expects($this->any()) - ->method('getDistUrls') - ->will($this->returnValue(array('url'))) - ; + $package = $this->getPackage(); + $package->setDistUrl('url'); $path = $this->createTempFile($this->getUniqueTmpDirectory()); $downloader = $this->getDownloader(); try { - $downloader->download($packageMock, $path); + $downloader->download($package, $path); $this->fail(); } catch (\Exception $e) { if (is_dir($path)) { @@ -103,39 +89,21 @@ public function testDownloadToExistingFile(): void public function testGetFileName(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->once()) - ->method('getDistUrl') - ->will($this->returnValue('http://example.com/script.js')) - ; + $package = $this->getPackage(); + $package->setDistUrl('http://example.com/script.js'); - $downloader = $this->getDownloader(); + $config = $this->getConfig(['vendor-dir' => '/vendor']); + $downloader = $this->getDownloader(null, $config); $method = new \ReflectionMethod($downloader, 'getFileName'); $method->setAccessible(true); - $this->config->expects($this->once()) - ->method('get') - ->with('vendor-dir') - ->will($this->returnValue('/vendor')); - - $this->assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $method->invoke($downloader, $packageMock, '/path')); + $this->assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $method->invoke($downloader, $package, '/path')); } public function testDownloadButFileIsUnsaved(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue($distUrl = 'http://example.com/script.js')) - ; - $packageMock->expects($this->once()) - ->method('getDistUrls') - ->will($this->returnValue(array($distUrl))) - ; - $packageMock->expects($this->atLeastOnce()) - ->method('getTransportOptions') - ->will($this->returnValue(array())) - ; + $package = $this->getPackage(); + $package->setDistUrl('http://example.com/script.js'); $path = $this->getUniqueTmpDirectory(); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); @@ -150,16 +118,12 @@ public function testDownloadButFileIsUnsaved(): void })) ; - $downloader = $this->getDownloader($ioMock); - - $this->config->expects($this->once()) - ->method('get') - ->with('vendor-dir') - ->will($this->returnValue($path.'/vendor')); + $config = $this->getConfig(['vendor-dir' => $path.'/vendor']); + $downloader = $this->getDownloader($ioMock, $config); try { $loop = new Loop($this->httpDownloader); - $promise = $downloader->download($packageMock, $path); + $promise = $downloader->download($package, $path); $loop->wait(array($promise)); $this->fail('Download was expected to throw'); @@ -180,41 +144,25 @@ public function testDownloadWithCustomProcessedUrl(): void { $path = $this->getUniqueTmpDirectory(); - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue('url')); - $packageMock->expects($this->any()) - ->method('getDistUrls') - ->will($this->returnValue(array('url'))); - - $rootPackageMock = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - $rootPackageMock->expects($this->any()) - ->method('getScripts') - ->will($this->returnValue(array())); - - $composerMock = $this->getMockBuilder('Composer\Composer')->getMock(); - $composerMock->expects($this->any()) - ->method('getPackage') - ->will($this->returnValue($rootPackageMock)); - $composerMock->expects($this->any()) - ->method('getConfig') - ->will($this->returnValue($this->config)); - $this->config->expects($this->any()) - ->method('get') - ->will($this->returnCallback(function ($key) use ($path) { - if ($key === 'vendor-dir') { - return $path.'/vendor'; - } elseif ($key === 'bin-dir') { - return $path.'/vendor/bin'; - } - })); + $package = $this->getPackage(); + $package->setDistUrl('url'); + + $rootPackage = $this->getRootPackage(); + + $config = $this->getConfig([ + 'vendor-dir' => $path.'/vendor', + 'bin-dir' => $path.'/vendor/bin', + ]); + + $composer = new Composer; + $composer->setPackage($rootPackage); + $composer->setConfig($config); $expectedUrl = 'foobar'; - $expectedCacheKey = '/'.sha1($expectedUrl).'.'; + $expectedCacheKey = 'dummy/pkg/'.sha1($expectedUrl).'.'; $dispatcher = new EventDispatcher( - $composerMock, + $composer, $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getProcessExecutorMock() ); @@ -254,11 +202,11 @@ public function testDownloadWithCustomProcessedUrl(): void ); })); - $downloader = $this->getDownloader(null, $this->config, $dispatcher, $cacheMock, $httpDownloaderMock); + $downloader = $this->getDownloader(null, $config, $dispatcher, $cacheMock, $httpDownloaderMock); try { $loop = new Loop($this->httpDownloader); - $promise = $downloader->download($packageMock, $path); + $promise = $downloader->download($package, $path); $loop->wait(array($promise)); $this->fail('Download was expected to throw'); @@ -279,42 +227,26 @@ public function testDownloadWithCustomCacheKey(): void { $path = $this->getUniqueTmpDirectory(); - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue('url')); - $packageMock->expects($this->any()) - ->method('getDistUrls') - ->will($this->returnValue(array('url'))); - - $rootPackageMock = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - $rootPackageMock->expects($this->any()) - ->method('getScripts') - ->will($this->returnValue(array())); - - $composerMock = $this->getMockBuilder('Composer\Composer')->getMock(); - $composerMock->expects($this->any()) - ->method('getPackage') - ->will($this->returnValue($rootPackageMock)); - $composerMock->expects($this->any()) - ->method('getConfig') - ->will($this->returnValue($this->config)); - $this->config->expects($this->any()) - ->method('get') - ->will($this->returnCallback(function ($key) use ($path) { - if ($key === 'vendor-dir') { - return $path.'/vendor'; - } elseif ($key === 'bin-dir') { - return $path.'/vendor/bin'; - } - })); + $package = $this->getPackage(); + $package->setDistUrl('url'); + + $rootPackage = $this->getRootPackage(); + + $config = $this->getConfig([ + 'vendor-dir' => $path.'/vendor', + 'bin-dir' => $path.'/vendor/bin', + ]); + + $composer = new Composer; + $composer->setPackage($rootPackage); + $composer->setConfig($config); $expectedUrl = 'url'; $customCacheKey = 'xyzzy'; - $expectedCacheKey = '/'.sha1($customCacheKey).'.'; + $expectedCacheKey = 'dummy/pkg/'.sha1($customCacheKey).'.'; $dispatcher = new EventDispatcher( - $composerMock, + $composer, $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getProcessExecutorMock() ); @@ -354,11 +286,11 @@ public function testDownloadWithCustomCacheKey(): void ); })); - $downloader = $this->getDownloader(null, $this->config, $dispatcher, $cacheMock, $httpDownloaderMock); + $downloader = $this->getDownloader(null, $config, $dispatcher, $cacheMock, $httpDownloaderMock); try { $loop = new Loop($this->httpDownloader); - $promise = $downloader->download($packageMock, $path); + $promise = $downloader->download($package, $path); $loop->wait(array($promise)); $this->fail('Download was expected to throw'); @@ -379,14 +311,10 @@ public function testCacheGarbageCollectionIsCalled(): void { $expectedTtl = '99999999'; - $this->config = $this->getMockBuilder('Composer\Config')->getMock(); - $this->config - ->expects($this->atLeast(2)) - ->method('get') - ->willReturnMap([ - ['cache-files-ttl', 0, $expectedTtl], - ['cache-files-maxsize', 0, '500M'], - ]); + $config = $this->getConfig([ + 'cache-files-ttl' => $expectedTtl, + 'cache-files-maxsize' => '500M', + ]); $cacheMock = $this->getMockBuilder('Composer\Cache') ->disableOriginalConstructor() @@ -400,48 +328,32 @@ public function testCacheGarbageCollectionIsCalled(): void ->method('gc') ->with($expectedTtl, $this->anything()); - $downloader = $this->getDownloader(null, $this->config, null, $cacheMock, null, null); + $downloader = $this->getDownloader(null, $config, null, $cacheMock, null, null); } public function testDownloadFileWithInvalidChecksum(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue($distUrl = 'http://example.com/script.js')) - ; - $packageMock->expects($this->atLeastOnce()) - ->method('getTransportOptions') - ->will($this->returnValue(array())) - ; - $packageMock->expects($this->any()) - ->method('getDistSha1Checksum') - ->will($this->returnValue('invalid')) - ; - $packageMock->expects($this->once()) - ->method('getDistUrls') - ->will($this->returnValue(array($distUrl))) - ; + $package = $this->getPackage(); + $package->setDistUrl($distUrl = 'http://example.com/script.js'); + $package->setDistSha1Checksum('invalid'); + $filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $path = $this->getUniqueTmpDirectory(); - $downloader = $this->getDownloader(null, null, null, null, null, $filesystem); + $config = $this->getConfig(['vendor-dir' => $path.'/vendor']); - // make sure the file expected to be downloaded is on disk already - $this->config->expects($this->any()) - ->method('get') - ->with('vendor-dir') - ->will($this->returnValue($path.'/vendor')); + $downloader = $this->getDownloader(null, $config, null, null, null, $filesystem); + // make sure the file expected to be downloaded is on disk already $method = new \ReflectionMethod($downloader, 'getFileName'); $method->setAccessible(true); - $dlFile = $method->invoke($downloader, $packageMock, $path); + $dlFile = $method->invoke($downloader, $package, $path); mkdir(dirname($dlFile), 0777, true); touch($dlFile); try { $loop = new Loop($this->httpDownloader); - $promise = $downloader->download($packageMock, $path); + $promise = $downloader->download($package, $path); $loop->wait(array($promise)); $this->fail('Download was expected to throw'); @@ -460,27 +372,9 @@ public function testDownloadFileWithInvalidChecksum(): void public function testDowngradeShowsAppropriateMessage(): void { - $oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $oldPackage->expects($this->once()) - ->method('getFullPrettyVersion') - ->will($this->returnValue('1.2.0')); - $oldPackage->expects($this->once()) - ->method('getVersion') - ->will($this->returnValue('1.2.0.0')); - - $newPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $newPackage->expects($this->any()) - ->method('getFullPrettyVersion') - ->will($this->returnValue('1.0.0')); - $newPackage->expects($this->once()) - ->method('getVersion') - ->will($this->returnValue('1.0.0.0')); - $newPackage->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue($distUrl = 'http://example.com/script.js')); - $newPackage->expects($this->once()) - ->method('getDistUrls') - ->will($this->returnValue(array($distUrl))); + $oldPackage = $this->getPackage('dummy/pkg', '1.2.0'); + $newPackage = $this->getPackage('dummy/pkg', '1.0.0'); + $newPackage->setDistUrl($distUrl = 'http://example.com/script.js'); $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $ioMock->expects($this->atLeast(2)) @@ -491,19 +385,16 @@ public function testDowngradeShowsAppropriateMessage(): void ); $path = $this->getUniqueTmpDirectory(); + $config = $this->getConfig(['vendor-dir' => $path.'/vendor']); + $filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $filesystem->expects($this->once()) ->method('removeDirectoryAsync') ->will($this->returnValue(\React\Promise\resolve(true))); - $downloader = $this->getDownloader($ioMock, null, null, null, null, $filesystem); + $downloader = $this->getDownloader($ioMock, $config, null, null, null, $filesystem); // make sure the file expected to be downloaded is on disk already - $this->config->expects($this->any()) - ->method('get') - ->with('vendor-dir') - ->will($this->returnValue($path.'/vendor')); - $method = new \ReflectionMethod($downloader, 'getFileName'); $method->setAccessible(true); $dlFile = $method->invoke($downloader, $newPackage, $path); diff --git a/tests/Composer/Test/Downloader/FossilDownloaderTest.php b/tests/Composer/Test/Downloader/FossilDownloaderTest.php index 2ba0e33f00a6..932fa5a36bb5 100644 --- a/tests/Composer/Test/Downloader/FossilDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FossilDownloaderTest.php @@ -42,10 +42,10 @@ protected function tearDown(): void * @param \Composer\Util\Filesystem $filesystem * @return FossilDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): FossilDownloader + protected function getDownloaderMock(\Composer\IO\IOInterface $io = null, \Composer\Config $config = null, \Composer\Test\Mock\ProcessExecutorMock $executor = null, Filesystem $filesystem = null): FossilDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); + $config = $config ?: $this->getConfig(['secure-http' => false]); $executor = $executor ?: $this->getProcessExecutorMock(); $filesystem = $filesystem ?: $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); diff --git a/tests/Composer/Test/Downloader/GitDownloaderTest.php b/tests/Composer/Test/Downloader/GitDownloaderTest.php index fce2ba033e40..91b90b369e42 100644 --- a/tests/Composer/Test/Downloader/GitDownloaderTest.php +++ b/tests/Composer/Test/Downloader/GitDownloaderTest.php @@ -62,7 +62,7 @@ private function initGitVersion($version): void * @param ?\Composer\Config $config * @return \Composer\Config */ - protected function setupConfig($config = null): \Composer\Config + protected function setupConfig($config = null): Config { if (!$config) { $config = new Config(); @@ -82,7 +82,7 @@ protected function setupConfig($config = null): \Composer\Config * @param \Composer\Util\Filesystem $filesystem * @return GitDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): GitDownloader + protected function getDownloaderMock(\Composer\IO\IOInterface $io = null, Config $config = null, \Composer\Test\Mock\ProcessExecutorMock $executor = null, Filesystem $filesystem = null): GitDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $executor = $executor ?: $this->getProcessExecutorMock(); @@ -238,7 +238,7 @@ public function pushUrlProvider(): array * @param string $url * @param string $pushUrl */ - public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub($protocols, $url, $pushUrl): void + public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub(array $protocols, string $url, string $pushUrl): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -647,11 +647,11 @@ public function testGetInstallationSource(): void * @param string $cmd * @return string */ - private function winCompat($cmd): string + private function winCompat(string $cmd): string { if (Platform::isWindows()) { $cmd = str_replace('cd ', 'cd /D ', $cmd); - $cmd = str_replace('composerPath', getcwd().'/composerPath', $cmd); + $cmd = str_replace('composerPath', Platform::getCwd().'/composerPath', $cmd); return $this->getCmd($cmd); } diff --git a/tests/Composer/Test/Downloader/HgDownloaderTest.php b/tests/Composer/Test/Downloader/HgDownloaderTest.php index 81a039a24976..135194263085 100644 --- a/tests/Composer/Test/Downloader/HgDownloaderTest.php +++ b/tests/Composer/Test/Downloader/HgDownloaderTest.php @@ -42,7 +42,7 @@ protected function tearDown(): void * @param \Composer\Util\Filesystem $filesystem * @return HgDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): HgDownloader + protected function getDownloaderMock(\Composer\IO\IOInterface $io = null, \Composer\Config $config = null, \Composer\Test\Mock\ProcessExecutorMock $executor = null, Filesystem $filesystem = null): HgDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); diff --git a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php index 16bd4d1281b7..f8a8e16c6323 100644 --- a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php +++ b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php @@ -53,16 +53,9 @@ protected function setUp(): void $this->downloader = new PerforceDownloader($this->io, $this->config, $this->processExecutor); } - /** - * @return \Composer\Config - */ - protected function getConfig(): \Composer\Config + protected function getConfig(array $configOptions = [], bool $useEnvironment = false): Config { - $config = new Config(); - $settings = array('config' => array('home' => $this->testPath)); - $config->merge($settings); - - return $config; + return parent::getConfig(array_merge(['home' => $this->testPath], $configOptions), $useEnvironment); } /** diff --git a/tests/Composer/Test/Downloader/XzDownloaderTest.php b/tests/Composer/Test/Downloader/XzDownloaderTest.php index 1f2501d379a3..f20129bfbd0e 100644 --- a/tests/Composer/Test/Downloader/XzDownloaderTest.php +++ b/tests/Composer/Test/Downloader/XzDownloaderTest.php @@ -51,33 +51,18 @@ protected function tearDown(): void public function testErrorMessages(): void { - $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); - $packageMock->expects($this->any()) - ->method('getDistUrl') - ->will($this->returnValue($distUrl = 'file://'.__FILE__)) - ; - $packageMock->expects($this->any()) - ->method('getDistUrls') - ->will($this->returnValue(array($distUrl))) - ; - $packageMock->expects($this->atLeastOnce()) - ->method('getTransportOptions') - ->will($this->returnValue(array())) - ; + $package = $this->getPackage(); + $package->setDistUrl($distUrl = 'file://'.__FILE__); $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); - $config = $this->getMockBuilder('Composer\Config')->getMock(); - $config->expects($this->any()) - ->method('get') - ->with('vendor-dir') - ->will($this->returnValue($this->testDir)); - $downloader = new XzDownloader($io, $config, $httpDownloader = new HttpDownloader($io, $this->getMockBuilder('Composer\Config')->getMock()), null, null, null); + $config = $this->getConfig(['vendor-dir' => $this->testDir]); + $downloader = new XzDownloader($io, $config, $httpDownloader = new HttpDownloader($io, $config), null, null, null); try { $loop = new Loop($httpDownloader); - $promise = $downloader->download($packageMock, $this->testDir.'/install-path'); + $promise = $downloader->download($package, $this->testDir.'/install-path'); $loop->wait(array($promise)); - $downloader->install($packageMock, $this->testDir.'/install-path'); + $downloader->install($package, $this->testDir.'/install-path'); $this->fail('Download of invalid tarball should throw an exception'); } catch (\RuntimeException $e) { diff --git a/tests/Composer/Test/Downloader/ZipDownloaderTest.php b/tests/Composer/Test/Downloader/ZipDownloaderTest.php index 49e9dcda4b95..f7a44441298c 100644 --- a/tests/Composer/Test/Downloader/ZipDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ZipDownloaderTest.php @@ -57,7 +57,7 @@ protected function tearDown(): void * @param ?\Composer\Test\Downloader\MockedZipDownloader $obj * @return void */ - public function setPrivateProperty($name, $value, $obj = null): void + public function setPrivateProperty(string $name, $value, $obj = null): void { $reflectionClass = new \ReflectionClass('Composer\Downloader\ZipDownloader'); $reflectedProperty = $reflectionClass->getProperty($name); @@ -335,7 +335,7 @@ private function wait($promise): void class MockedZipDownloader extends ZipDownloader { - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true): ?PromiseInterface + public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true): PromiseInterface { return \React\Promise\resolve(); } @@ -345,7 +345,7 @@ public function install(PackageInterface $package, $path, $output = true): Promi return \React\Promise\resolve(); } - public function extract(PackageInterface $package, $file, $path): ?PromiseInterface + public function extract(PackageInterface $package, $file, $path): PromiseInterface { return parent::extract($package, $file, $path); } diff --git a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php index 57b8efb5c142..fc57a12413f6 100644 --- a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php +++ b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php @@ -56,7 +56,7 @@ public function testListenerExceptionsAreCaught(): void * * @param string $command */ - public function testDispatcherCanExecuteSingleCommandLineScript($command): void + public function testDispatcherCanExecuteSingleCommandLineScript(string $command): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -85,7 +85,7 @@ public function testDispatcherCanExecuteSingleCommandLineScript($command): void * * @param bool $devMode */ - public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($devMode): void + public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents(bool $devMode): void { $composer = $this->createComposerInstance(); @@ -288,7 +288,7 @@ public function testDispatcherCanPutEnv(): void public function testDispatcherAppendsDirBinOnPathForEveryListener(): void { - $currentDirectoryBkp = getcwd(); + $currentDirectoryBkp = Platform::getCwd(); $composerBinDirBkp = Platform::getEnv('COMPOSER_BIN_DIR'); chdir(__DIR__); Platform::putEnv('COMPOSER_BIN_DIR', __DIR__ . '/vendor/bin'); @@ -483,7 +483,7 @@ public function testDispatcherDetectInfiniteRecursion(): void * * @return \PHPUnit\Framework\MockObject\MockObject&\Composer\EventDispatcher\EventDispatcher */ - private function getDispatcherStubForListenersTest($listeners, IOInterface $io) + private function getDispatcherStubForListenersTest(array $listeners, IOInterface $io) { $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->setConstructorArgs(array( diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php index d7dcd9b334af..1c3b79a6e0ec 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php @@ -23,7 +23,7 @@ final class IgnoreAllPlatformRequirementFilterTest extends TestCase * @param string $req * @param bool $expectIgnored */ - public function testIsIgnored($req, $expectIgnored): void + public function testIsIgnored(string $req, bool $expectIgnored): void { $platformRequirementFilter = new IgnoreAllPlatformRequirementFilter(); diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php index 47af67fd2bec..dd1f71d85f8e 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php @@ -24,7 +24,7 @@ final class IgnoreListPlatformRequirementFilterTest extends TestCase * @param string $req * @param bool $expectIgnored */ - public function testIsIgnored(array $reqList, $req, $expectIgnored): void + public function testIsIgnored(array $reqList, string $req, bool $expectIgnored): void { $platformRequirementFilter = new IgnoreListPlatformRequirementFilter($reqList); diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php index 8b5b1f897930..02b6ad50ce6c 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php @@ -22,7 +22,7 @@ final class IgnoreNothingPlatformRequirementFilterTest extends TestCase * * @param string $req */ - public function testIsIgnored($req): void + public function testIsIgnored(string $req): void { $platformRequirementFilter = new IgnoreNothingPlatformRequirementFilter(); diff --git a/tests/Composer/Test/InstalledVersionsTest.php b/tests/Composer/Test/InstalledVersionsTest.php index 9cfb96faff36..e23e90eceae0 100644 --- a/tests/Composer/Test/InstalledVersionsTest.php +++ b/tests/Composer/Test/InstalledVersionsTest.php @@ -74,7 +74,7 @@ public function testGetInstalledPackages(): void * @param string $name * @param bool $includeDevRequirements */ - public function testIsInstalled($expected, $name, $includeDevRequirements = true): void + public function testIsInstalled(bool $expected, string $name, bool $includeDevRequirements = true): void { $this->assertSame($expected, InstalledVersions::isInstalled($name, $includeDevRequirements)); } @@ -99,7 +99,7 @@ public static function isInstalledProvider(): array * @param string $name * @param string $constraint */ - public function testSatisfies($expected, $name, $constraint): void + public function testSatisfies(bool $expected, string $name, string $constraint): void { $this->assertSame($expected, InstalledVersions::satisfies(new VersionParser, $name, $constraint)); } @@ -139,7 +139,7 @@ public static function satisfiesProvider(): array * @param string $expected * @param string $name */ - public function testGetVersionRanges($expected, $name): void + public function testGetVersionRanges(string $expected, string $name): void { $this->assertSame($expected, InstalledVersions::getVersionRanges($name)); } @@ -160,10 +160,10 @@ public static function getVersionRangesProvider(): array /** * @dataProvider getVersionProvider - * @param ?string $expected + * @param null|string $expected * @param string $name */ - public function testGetVersion($expected, $name): void + public function testGetVersion(?string $expected, string $name): void { $this->assertSame($expected, InstalledVersions::getVersion($name)); } @@ -184,10 +184,10 @@ public static function getVersionProvider(): array /** * @dataProvider getPrettyVersionProvider - * @param ?string $expected + * @param null|string $expected * @param string $name */ - public function testGetPrettyVersion($expected, $name): void + public function testGetPrettyVersion(?string $expected, string $name): void { $this->assertSame($expected, InstalledVersions::getPrettyVersion($name)); } @@ -239,10 +239,10 @@ public function testGetRawData(): void /** * @dataProvider getReferenceProvider - * @param ?string $expected + * @param null|string $expected * @param string $name */ - public function testGetReference($expected, $name): void + public function testGetReference(?string $expected, string $name): void { $this->assertSame($expected, InstalledVersions::getReference($name)); } diff --git a/tests/Composer/Test/Installer/BinaryInstallerTest.php b/tests/Composer/Test/Installer/BinaryInstallerTest.php index 821bc3ce4535..28b1f0fc0606 100644 --- a/tests/Composer/Test/Installer/BinaryInstallerTest.php +++ b/tests/Composer/Test/Installer/BinaryInstallerTest.php @@ -68,7 +68,7 @@ protected function tearDown(): void * @dataProvider executableBinaryProvider * @param string $contents */ - public function testInstallAndExecBinaryWithFullCompat($contents): void + public function testInstallAndExecBinaryWithFullCompat(string $contents): void { $package = $this->createPackageMock(); $package->expects($this->any()) diff --git a/tests/Composer/Test/Installer/LibraryInstallerTest.php b/tests/Composer/Test/Installer/LibraryInstallerTest.php index 5f2cc55f8267..e14a830df83a 100644 --- a/tests/Composer/Test/Installer/LibraryInstallerTest.php +++ b/tests/Composer/Test/Installer/LibraryInstallerTest.php @@ -151,7 +151,8 @@ public function testInstall(): void $this->dm ->expects($this->once()) ->method('install') - ->with($package, $this->vendorDir.'/some/package'); + ->with($package, $this->vendorDir.'/some/package') + ->will($this->returnValue(\React\Promise\resolve())); $this->repository ->expects($this->once()) @@ -190,7 +191,8 @@ public function testUpdate(): void $this->dm ->expects($this->once()) ->method('update') - ->with($initial, $target, $this->vendorDir.'/vendor/package1/newtarget'); + ->with($initial, $target, $this->vendorDir.'/vendor/package1/newtarget') + ->will($this->returnValue(\React\Promise\resolve())); $this->repository ->expects($this->once()) @@ -226,7 +228,8 @@ public function testUninstall(): void $this->dm ->expects($this->once()) ->method('remove') - ->with($package, $this->vendorDir.'/vendor/pkg'); + ->with($package, $this->vendorDir.'/vendor/pkg') + ->will($this->returnValue(\React\Promise\resolve())); $this->repository ->expects($this->once()) diff --git a/tests/Composer/Test/InstallerTest.php b/tests/Composer/Test/InstallerTest.php index a38d02424bfa..04e4346c062b 100644 --- a/tests/Composer/Test/InstallerTest.php +++ b/tests/Composer/Test/InstallerTest.php @@ -21,7 +21,6 @@ use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Composer\IO\BufferIO; -use Composer\Config; use Composer\Json\JsonFile; use Composer\Package\Dumper\ArrayDumper; use Composer\Util\Filesystem; @@ -52,7 +51,7 @@ class InstallerTest extends TestCase public function setUp(): void { - $this->prevCwd = getcwd(); + $this->prevCwd = Platform::getCwd(); chdir(__DIR__); } @@ -74,7 +73,7 @@ protected function tearDown(): void * @param RepositoryInterface[] $repositories * @param mixed[] $options */ - public function testInstaller(RootPackageInterface $rootPackage, $repositories, array $options): void + public function testInstaller(RootPackageInterface $rootPackage, array $repositories, array $options): void { $io = new BufferIO('', OutputInterface::VERBOSITY_NORMAL, new OutputFormatter(false)); @@ -160,7 +159,7 @@ public function testInstaller(RootPackageInterface $rootPackage, $repositories, * @param PackageInterface[] $packages * @return mixed[] */ - protected function makePackagesComparable($packages): array + protected function makePackagesComparable(array $packages): array { $dumper = new ArrayDumper(); @@ -190,7 +189,7 @@ public function provideInstaller(): array $cases[] = array( $a, - new ArrayRepository(array($b)), + [new ArrayRepository(array($b))], array( 'install' => array($b), ), @@ -210,7 +209,7 @@ public function provideInstaller(): array $cases[] = array( $a, - new ArrayRepository(array($a, $b)), + [new ArrayRepository(array($a, $b))], array( 'install' => array($b), ), @@ -225,19 +224,19 @@ public function provideInstaller(): array * @dataProvider provideSlowIntegrationTests * @param string $file * @param string $message - * @param ?string $condition - * @param Config $composerConfig - * @param ?mixed[] $lock - * @param ?mixed[] $installed + * @param null|string $condition + * @param mixed[] $composerConfig + * @param ?array $lock + * @param ?array $installed * @param string $run * @param mixed[]|false $expectLock - * @param ?mixed[] $expectInstalled - * @param ?string $expectOutput - * @param ?string $expectOutputOptimized + * @param ?array $expectInstalled + * @param null|string $expectOutput + * @param null|string $expectOutputOptimized * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testSlowIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void + public function testSlowIntegration(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); @@ -248,19 +247,19 @@ public function testSlowIntegration($file, $message, $condition, $composerConfig * @dataProvider provideIntegrationTests * @param string $file * @param string $message - * @param ?string $condition - * @param Config $composerConfig - * @param ?mixed[] $lock - * @param ?mixed[] $installed + * @param null|string $condition + * @param mixed[] $composerConfig + * @param ?array $lock + * @param ?array $installed * @param string $run * @param mixed[]|false $expectLock - * @param ?mixed[] $expectInstalled - * @param ?string $expectOutput - * @param ?string $expectOutputOptimized + * @param ?array $expectInstalled + * @param null|string $expectOutput + * @param null|string $expectOutputOptimized * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testIntegrationWithPoolOptimizer($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void + public function testIntegrationWithPoolOptimizer(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '1'); @@ -271,19 +270,19 @@ public function testIntegrationWithPoolOptimizer($file, $message, $condition, $c * @dataProvider provideIntegrationTests * @param string $file * @param string $message - * @param ?string $condition - * @param Config $composerConfig - * @param ?mixed[] $lock - * @param ?mixed[] $installed + * @param null|string $condition + * @param mixed[] $composerConfig + * @param ?array $lock + * @param ?array $installed * @param string $run * @param mixed[]|false $expectLock - * @param ?mixed[] $expectInstalled - * @param ?string $expectOutput - * @param ?string $expectOutputOptimized + * @param ?array $expectInstalled + * @param null|string $expectOutput + * @param null|string $expectOutputOptimized * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testIntegrationWithRawPool($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void + public function testIntegrationWithRawPool(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); @@ -293,19 +292,19 @@ public function testIntegrationWithRawPool($file, $message, $condition, $compose /** * @param string $file * @param string $message - * @param ?string $condition - * @param Config $composerConfig - * @param ?mixed[] $lock - * @param ?mixed[] $installed + * @param null|string $condition + * @param mixed[] $composerConfig + * @param ?array $lock + * @param ?array $installed * @param string $run * @param mixed[]|false $expectLock - * @param ?mixed[] $expectInstalled - * @param ?string $expectOutput + * @param ?array $expectInstalled + * @param null|string $expectOutput * @param string $expect * @param int|class-string<\Throwable> $expectResult * @return void */ - private function doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult): void + private function doTestIntegration(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, string $expect, $expectResult): void { if ($condition) { eval('$res = '.$condition.';'); @@ -516,7 +515,7 @@ public function provideIntegrationTests(): array * @param string $path * @return mixed[] */ - public function loadIntegrationTests($path): array + public function loadIntegrationTests(string $path): array { $fixturesDir = realpath(__DIR__.'/Fixtures/'.$path); $tests = array(); @@ -602,7 +601,7 @@ public function loadIntegrationTests($path): array * @param string $fixturesDir * @return mixed[] */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir): array + protected function readTestFile(\SplFileInfo $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); diff --git a/tests/Composer/Test/Json/ComposerSchemaTest.php b/tests/Composer/Test/Json/ComposerSchemaTest.php index 474523b464f9..e6aea2271b7b 100644 --- a/tests/Composer/Test/Json/ComposerSchemaTest.php +++ b/tests/Composer/Test/Json/ComposerSchemaTest.php @@ -94,7 +94,7 @@ public function testMinimumStabilityValues(): void * @param string $json * @return mixed */ - private function check($json) + private function check(string $json) { $validator = new Validator(); $validator->check(json_decode($json), (object) array('$ref' => 'file://' . __DIR__ . '/../../../../res/composer-schema.json')); diff --git a/tests/Composer/Test/Json/JsonFileTest.php b/tests/Composer/Test/Json/JsonFileTest.php index 131730c9d08c..02ede63dc074 100644 --- a/tests/Composer/Test/Json/JsonFileTest.php +++ b/tests/Composer/Test/Json/JsonFileTest.php @@ -351,7 +351,7 @@ public function testDoubleEscapedUnicode(): void * @param string $json * @return void */ - private function expectParseException($text, $json): void + private function expectParseException(string $text, string $json): void { try { $result = JsonFile::parseJson($json); @@ -367,7 +367,7 @@ private function expectParseException($text, $json): void * @param int|null $options * @return void */ - private function assertJsonFormat($json, $data, $options = null): void + private function assertJsonFormat(string $json, $data, ?int $options = null): void { $file = new JsonFile('composer.json'); diff --git a/tests/Composer/Test/Json/JsonManipulatorTest.php b/tests/Composer/Test/Json/JsonManipulatorTest.php index 6d0900b9102e..5337511322df 100644 --- a/tests/Composer/Test/Json/JsonManipulatorTest.php +++ b/tests/Composer/Test/Json/JsonManipulatorTest.php @@ -25,7 +25,7 @@ class JsonManipulatorTest extends TestCase * @param string $constraint * @param string $expected */ - public function testAddLink($json, $type, $package, $constraint, $expected): void + public function testAddLink(string $json, string $type, string $package, string $constraint, string $expected): void { $manipulator = new JsonManipulator($json); $this->assertTrue($manipulator->addLink($type, $package, $constraint)); @@ -1301,7 +1301,7 @@ public function linkProvider(): array * @param bool $sortPackages * @param string $expected */ - public function testAddLinkAndSortPackages($json, $type, $package, $constraint, $sortPackages, $expected): void + public function testAddLinkAndSortPackages(string $json, string $type, string $package, string $constraint, bool $sortPackages, string $expected): void { $manipulator = new JsonManipulator($json); $this->assertTrue($manipulator->addLink($type, $package, $constraint, $sortPackages)); @@ -1382,10 +1382,10 @@ public function providerAddLinkAndSortPackages(): array * @dataProvider removeSubNodeProvider * @param string $json * @param string $name - * @param string $expected - * @param ?string $expectedContent + * @param bool $expected + * @param null|string $expectedContent */ - public function testRemoveSubNode($json, $name, $expected, $expectedContent = null): void + public function testRemoveSubNode(string $json, string $name, bool $expected, ?string $expectedContent = null): void { $manipulator = new JsonManipulator($json); diff --git a/tests/Composer/Test/Json/JsonValidationExceptionTest.php b/tests/Composer/Test/Json/JsonValidationExceptionTest.php index 79c43683304e..863368303b61 100644 --- a/tests/Composer/Test/Json/JsonValidationExceptionTest.php +++ b/tests/Composer/Test/Json/JsonValidationExceptionTest.php @@ -22,7 +22,7 @@ class JsonValidationExceptionTest extends TestCase * @param string[] $errors * @param string[] $expectedErrors */ - public function testGetErrors(?string $message, array $errors, string $expectedMessage, array $expectedErrors): void + public function testGetErrors(string $message, array $errors, string $expectedMessage, array $expectedErrors): void { $object = new JsonValidationException($message, $errors); $this->assertSame($expectedMessage, $object->getMessage()); @@ -39,7 +39,7 @@ public function errorProvider(): array { return array( array('test message', array(), 'test message', []), - array(null, ['foo'], '', ['foo']), + array('', ['foo'], '', ['foo']), ); } } diff --git a/tests/Composer/Test/Mock/FactoryMock.php b/tests/Composer/Test/Mock/FactoryMock.php index 8db24fe1168f..17e21c83be97 100644 --- a/tests/Composer/Test/Mock/FactoryMock.php +++ b/tests/Composer/Test/Mock/FactoryMock.php @@ -14,7 +14,6 @@ use Composer\Installer\InstallationManager; use Composer\Package\Loader\RootPackageLoader; -use Composer\Composer; use Composer\Config; use Composer\Factory; use Composer\PartialComposer; @@ -22,7 +21,6 @@ use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Package\RootPackageInterface; -use Composer\Installer; use Composer\EventDispatcher\EventDispatcher; use Composer\IO\IOInterface; use Composer\Repository\InstalledArrayRepository; diff --git a/tests/Composer/Test/Mock/ProcessExecutorMock.php b/tests/Composer/Test/Mock/ProcessExecutorMock.php index 277ead749890..897d889ce4fb 100644 --- a/tests/Composer/Test/Mock/ProcessExecutorMock.php +++ b/tests/Composer/Test/Mock/ProcessExecutorMock.php @@ -49,7 +49,7 @@ class ProcessExecutorMock extends ProcessExecutor * * @return void */ - public function expects(array $expectations, $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')): void + public function expects(array $expectations, bool $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')): void { /** @var array{cmd: string|list, return?: int, stdout?: string, stderr?: string, callback?: callable} $default */ $default = array('cmd' => '', 'return' => 0, 'stdout' => '', 'stderr' => '', 'callback' => null); @@ -105,6 +105,7 @@ public function assertComplete(): void public function execute($command, &$output = null, $cwd = null): int { + $cwd = $cwd ?? Platform::getCwd(); if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); } @@ -114,6 +115,7 @@ public function execute($command, &$output = null, $cwd = null): int public function executeTty($command, $cwd = null): int { + $cwd = $cwd ?? Platform::getCwd(); if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); } @@ -125,15 +127,17 @@ public function executeTty($command, $cwd = null): int * @param string|list $command * @param string $cwd * @param bool $tty - * @param callable $output + * @param callable|string|null $output * @return mixed */ - private function doExecute($command, $cwd, $tty, &$output = null) + private function doExecute($command, string $cwd, bool $tty, &$output = null) { $this->captureOutput = func_num_args() > 3; $this->errorOutput = ''; - $callback = is_callable($output) ? $output : array($this, 'outputHandler'); + $callback = is_callable($output) ? $output : function (string $type, string $buffer): void { + $this->outputHandler($type, $buffer); + }; $commandString = is_array($command) ? implode(' ', $command) : $command; $this->log[] = $commandString; @@ -174,7 +178,7 @@ private function doExecute($command, $cwd, $tty, &$output = null) return $return; } - public function executeAsync($command, $cwd = null): PromiseInterface + public function executeAsync($command, ?string $cwd = null): PromiseInterface { $resolver = function ($resolve, $reject): void { // TODO strictly speaking this should resolve with a mock Process instance here diff --git a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php index ad9bce604b62..8ef013b278d8 100644 --- a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php @@ -279,7 +279,7 @@ protected function getArchivableFiles(): array * * @return string[] */ - protected function getArchivedFiles($command): array + protected function getArchivedFiles(string $command): array { $process = Process::fromShellCommandline($command, $this->sources); $process->run(); @@ -303,7 +303,7 @@ protected function getArchivedFiles($command): array * * @return void */ - protected function assertArchivableFiles($expectedFiles): void + protected function assertArchivableFiles(array $expectedFiles): void { $actualFiles = $this->getArchivableFiles(); diff --git a/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php b/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php index 8d620fbc9302..04f098355bdf 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php @@ -18,6 +18,7 @@ use Composer\Package\CompletePackage; use Composer\Util\Loop; use Composer\Test\Mock\FactoryMock; +use Composer\Util\Platform; use Composer\Util\ProcessExecutor; class ArchiveManagerTest extends ArchiverTest @@ -104,7 +105,7 @@ public function testArchiveCustomFileName(): void * * @return string */ - protected function getTargetName(CompletePackage $package, $format, $fileName = null): string + protected function getTargetName(CompletePackage $package, string $format, ?string $fileName = null): string { if (null === $fileName) { $packageName = $this->manager->getPackageFilename($package); @@ -122,7 +123,7 @@ protected function getTargetName(CompletePackage $package, $format, $fileName = */ protected function setupGitRepo(): void { - $currentWorkDir = getcwd(); + $currentWorkDir = Platform::getCwd(); chdir($this->testDir); $output = null; diff --git a/tests/Composer/Test/Package/Archiver/ArchiverTest.php b/tests/Composer/Test/Package/Archiver/ArchiverTest.php index 5ac901d1b9bb..eecd8dff2a09 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiverTest.php @@ -55,7 +55,7 @@ protected function tearDown(): void protected function setupPackage(): CompletePackage { $package = new CompletePackage('archivertest/archivertest', 'master', 'master'); - $package->setSourceUrl(realpath($this->testDir)); + $package->setSourceUrl((string) realpath($this->testDir)); $package->setSourceReference('master'); $package->setSourceType('git'); diff --git a/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php b/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php index 2c8f96a2ef8a..32c255cfc544 100644 --- a/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php +++ b/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php @@ -23,7 +23,7 @@ class GitExcludeFilterTest extends TestCase * @param string $ignore * @param mixed[] $expected */ - public function testPatternEscape($ignore, $expected): void + public function testPatternEscape(string $ignore, array $expected): void { $filter = new GitExcludeFilter('/'); diff --git a/tests/Composer/Test/Package/Archiver/PharArchiverTest.php b/tests/Composer/Test/Package/Archiver/PharArchiverTest.php index 5c571316a616..22ebb83d5e35 100644 --- a/tests/Composer/Test/Package/Archiver/PharArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/PharArchiverTest.php @@ -13,6 +13,7 @@ namespace Composer\Test\Package\Archiver; use Composer\Package\Archiver\PharArchiver; +use Composer\Util\Platform; class PharArchiverTest extends ArchiverTest { @@ -53,7 +54,7 @@ public function testZipArchive(): void */ protected function setupDummyRepo(): void { - $currentWorkDir = getcwd(); + $currentWorkDir = Platform::getCwd(); chdir($this->testDir); $this->writeFile('file.txt', 'content', $currentWorkDir); @@ -72,7 +73,7 @@ protected function setupDummyRepo(): void * * @return void */ - protected function writeFile($path, $content, $currentWorkDir): void + protected function writeFile(string $path, string $content, string $currentWorkDir): void { if (!file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); diff --git a/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php b/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php index e88711a4cdd6..7e4fb7f896d9 100644 --- a/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php @@ -23,7 +23,7 @@ class ZipArchiverTest extends ArchiverTest * * @dataProvider provideGitignoreExcludeNegationTestCases */ - public function testGitignoreExcludeNegation($include): void + public function testGitignoreExcludeNegation(string $include): void { $this->testZipArchive(array( 'docs/README.md' => '# The doc', @@ -57,7 +57,7 @@ public function testZipArchive(array $files = array()): void ); if (!Platform::isWindows()) { - $files['foo' . getcwd() . '/file.txt'] = null; + $files['foo' . Platform::getCwd() . '/file.txt'] = null; } } // Set up repository @@ -89,7 +89,7 @@ public function testZipArchive(array $files = array()): void */ protected function setupDummyRepo(array &$files): void { - $currentWorkDir = getcwd(); + $currentWorkDir = Platform::getCwd(); chdir($this->testDir); foreach ($files as $path => $content) { if ($files[$path] === null) { @@ -108,7 +108,7 @@ protected function setupDummyRepo(array &$files): void * * @return void */ - protected function writeFile($path, $content, $currentWorkDir): void + protected function writeFile(string $path, string $content, string $currentWorkDir): void { if (!file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); diff --git a/tests/Composer/Test/Package/BasePackageTest.php b/tests/Composer/Test/Package/BasePackageTest.php index 3b92316b2e86..90921bc7cfdf 100644 --- a/tests/Composer/Test/Package/BasePackageTest.php +++ b/tests/Composer/Test/Package/BasePackageTest.php @@ -49,7 +49,7 @@ public function testSetAnotherRepository(): void * @param bool $truncate * @param string $expected */ - public function testFormatVersionForDevPackage(BasePackage $package, $truncate, $expected): void + public function testFormatVersionForDevPackage(BasePackage $package, bool $truncate, string $expected): void { $this->assertSame($expected, $package->getFullPrettyVersion($truncate)); } @@ -99,7 +99,7 @@ public function provideFormattedVersions(): array * * @dataProvider dataPackageNamesToRegexp */ - public function testPackageNamesToRegexp(array $packageNames, $wrap, $expectedRegexp): void + public function testPackageNamesToRegexp(array $packageNames, $wrap, string $expectedRegexp): void { $regexp = BasePackage::packageNamesToRegexp($packageNames, $wrap); diff --git a/tests/Composer/Test/Package/CompletePackageTest.php b/tests/Composer/Test/Package/CompletePackageTest.php index 2f8de80d1148..4f57dff145e4 100644 --- a/tests/Composer/Test/Package/CompletePackageTest.php +++ b/tests/Composer/Test/Package/CompletePackageTest.php @@ -40,7 +40,7 @@ public function providerVersioningSchemes(): array * @param string $name * @param string $version */ - public function testPackageHasExpectedNamingSemantics($name, $version): void + public function testPackageHasExpectedNamingSemantics(string $name, string $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); @@ -54,7 +54,7 @@ public function testPackageHasExpectedNamingSemantics($name, $version): void * @param string $name * @param string $version */ - public function testPackageHasExpectedVersioningSemantics($name, $version): void + public function testPackageHasExpectedVersioningSemantics(string $name, string $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); @@ -69,7 +69,7 @@ public function testPackageHasExpectedVersioningSemantics($name, $version): void * @param string $name * @param string $version */ - public function testPackageHasExpectedMarshallingSemantics($name, $version): void + public function testPackageHasExpectedMarshallingSemantics(string $name, string $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); diff --git a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php index b5ee6d07390a..8b1d5af0cd80 100644 --- a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php +++ b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php @@ -23,32 +23,21 @@ class ArrayDumperTest extends TestCase * @var ArrayDumper */ private $dumper; - /** - * @var \Composer\Package\CompletePackageInterface|\PHPUnit\Framework\MockObject\MockObject - */ - private $package; public function setUp(): void { $this->dumper = new ArrayDumper(); - $this->package = $this->getMockBuilder('Composer\Package\CompletePackageInterface')->getMock(); - $this->packageExpects('getTransportOptions', array()); } public function testRequiredInformation(): void { - $this - ->packageExpects('getPrettyName', 'foo') - ->packageExpects('getPrettyVersion', '1.0') - ->packageExpects('getVersion', '1.0.0.0') - ; - - $config = $this->dumper->dump($this->package); + $config = $this->dumper->dump($this->getPackage()); $this->assertEquals( array( - 'name' => 'foo', - 'version' => '1.0', + 'name' => 'dummy/pkg', + 'version' => '1.0.0', 'version_normalized' => '1.0.0.0', + 'type' => 'library', ), $config ); @@ -56,33 +45,27 @@ public function testRequiredInformation(): void public function testRootPackage(): void { - $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - - $this - ->packageExpects('getMinimumStability', 'dev') - ->packageExpects('getTransportOptions', array()) - ; + $package = $this->getRootPackage(); + $package->setMinimumStability('dev'); - $config = $this->dumper->dump($this->package); + $config = $this->dumper->dump($package); $this->assertSame('dev', $config['minimum-stability']); } public function testDumpAbandoned(): void { - $this->packageExpects('isAbandoned', true); - $this->packageExpects('getReplacementPackage', true); - - $config = $this->dumper->dump($this->package); + $package = $this->getPackage(); + $package->setAbandoned(true); + $config = $this->dumper->dump($package); $this->assertTrue($config['abandoned']); } public function testDumpAbandonedReplacement(): void { - $this->packageExpects('isAbandoned', true); - $this->packageExpects('getReplacementPackage', 'foo/bar'); - - $config = $this->dumper->dump($this->package); + $package = $this->getPackage(); + $package->setAbandoned('foo/bar'); + $config = $this->dumper->dump($package); $this->assertSame('foo/bar', $config['abandoned']); } @@ -95,18 +78,14 @@ public function testDumpAbandonedReplacement(): void * @param string $method * @param mixed $expectedValue */ - public function testKeys($key, $value, $method = null, $expectedValue = null): void + public function testKeys(string $key, $value, string $method = null, $expectedValue = null): void { - $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - - $this->packageExpects('get'.ucfirst($method ?: $key), $value); - $this->packageExpects('isAbandoned', $value); + $package = $this->getRootPackage(); - if ($method !== 'transportOptions') { - $this->packageExpects('getTransportOptions', array()); - } + // @phpstan-ignore-next-line + $package->{'set'.ucfirst($method ?: $key)}($value); - $config = $this->dumper->dump($this->package); + $config = $this->dumper->dump($package); $this->assertSame($expectedValue ?: $value, $config[$key]); } @@ -177,13 +156,13 @@ public function provideKeys(): array ), array( 'require', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array('foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), 'requires', array('foo/bar' => '1.0.0'), ), array( 'require-dev', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_DEV_REQUIRE, '1.0.0')), + array('foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_DEV_REQUIRE, '1.0.0')), 'devRequires', array('foo/bar' => '1.0.0'), ), @@ -202,13 +181,19 @@ public function provideKeys(): array ), array( 'require', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), new Link('bar', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array( + 'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + 'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + ), 'requires', array('bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'), ), array( 'require-dev', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), new Link('bar', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array( + 'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + 'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + ), 'devRequires', array('bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'), ), @@ -220,19 +205,28 @@ public function provideKeys(): array ), array( 'provide', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), new Link('bar', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array( + 'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + 'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + ), 'provides', array('bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'), ), array( 'replace', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), new Link('bar', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array( + 'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + 'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + ), 'replaces', array('bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'), ), array( 'conflict', - array(new Link('foo', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), new Link('bar', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0')), + array( + 'foo/bar' => new Link('dummy/pkg', 'foo/bar', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + 'bar/baz' => new Link('dummy/pkg', 'bar/baz', new Constraint('=', '1.0.0.0'), Link::TYPE_REQUIRE, '1.0.0'), + ), 'conflicts', array('bar/baz' => '1.0.0', 'foo/bar' => '1.0.0'), ), @@ -243,18 +237,4 @@ public function provideKeys(): array ), ); } - - /** - * @param string $method - * @param mixed $value - */ - private function packageExpects($method, $value): \Composer\Test\Package\Dumper\ArrayDumperTest - { - $this->package - ->expects($this->any()) - ->method($method) - ->will($this->returnValue($value)); - - return $this; - } } diff --git a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php index cc961575e86c..2324ad0c25c7 100644 --- a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php @@ -139,7 +139,7 @@ public function parseDumpProvider(): array * * @return array */ - protected function fixConfigWhenLoadConfigIsFalse($config): array + protected function fixConfigWhenLoadConfigIsFalse(array $config): array { $expectedConfig = $config; unset($expectedConfig['transport-options']); @@ -155,7 +155,7 @@ protected function fixConfigWhenLoadConfigIsFalse($config): array * * @param array $config */ - public function testParseDumpDefaultLoadConfig($config): void + public function testParseDumpDefaultLoadConfig(array $config): void { $package = $this->loader->load($config); $dumper = new ArrayDumper; @@ -168,7 +168,7 @@ public function testParseDumpDefaultLoadConfig($config): void * * @param array $config */ - public function testParseDumpTrueLoadConfig($config): void + public function testParseDumpTrueLoadConfig(array $config): void { $loader = new ArrayLoader(null, true); $package = $loader->load($config); @@ -182,7 +182,7 @@ public function testParseDumpTrueLoadConfig($config): void * * @param array $config */ - public function testParseDumpFalseLoadConfig($config): void + public function testParseDumpFalseLoadConfig(array $config): void { $loader = new ArrayLoader(null, false); $package = $loader->load($config); @@ -299,7 +299,7 @@ public function providePluginApiVersions(): array * * @param string $apiVersion */ - public function testPluginApiVersionAreKeptAsDeclared($apiVersion): void + public function testPluginApiVersionAreKeptAsDeclared(string $apiVersion): void { $links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, array('composer-plugin-api' => $apiVersion)); diff --git a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php index a2fa3730ab81..a669f669f964 100644 --- a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php @@ -28,7 +28,7 @@ class RootPackageLoaderTest extends TestCase * * @return RootPackage|RootAliasPackage */ - protected function loadPackage($data): \Composer\Package\PackageInterface + protected function loadPackage(array $data): \Composer\Package\PackageInterface { $manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager') ->disableOriginalConstructor() diff --git a/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php b/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php index 0b214cb56ea9..a8204a76f909 100644 --- a/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php @@ -23,7 +23,7 @@ class ValidatingArrayLoaderTest extends TestCase * * @param array $config */ - public function testLoadSuccess($config): void + public function testLoadSuccess(array $config): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $internalLoader @@ -212,7 +212,7 @@ public function successProvider(): array * @param array $config * @param string[] $expectedErrors */ - public function testLoadFailureThrowsException($config, $expectedErrors): void + public function testLoadFailureThrowsException(array $config, array $expectedErrors): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL); @@ -233,7 +233,7 @@ public function testLoadFailureThrowsException($config, $expectedErrors): void * @param array $config * @param string[] $expectedWarnings */ - public function testLoadWarnings($config, $expectedWarnings): void + public function testLoadWarnings(array $config, array $expectedWarnings): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL); @@ -252,7 +252,7 @@ public function testLoadWarnings($config, $expectedWarnings): void * @param string[] $expectedWarnings * @param bool $mustCheck */ - public function testLoadSkipsWarningDataWhenIgnoringErrors($config, $expectedWarnings, $mustCheck = true): void + public function testLoadSkipsWarningDataWhenIgnoringErrors(array $config, array $expectedWarnings, bool $mustCheck = true): void { if (!$mustCheck) { $this->assertTrue(true); diff --git a/tests/Composer/Test/Package/LockerTest.php b/tests/Composer/Test/Package/LockerTest.php index 17168f62a14b..d2913e36ddda 100644 --- a/tests/Composer/Test/Package/LockerTest.php +++ b/tests/Composer/Test/Package/LockerTest.php @@ -93,41 +93,8 @@ public function testSetLockData(): void $jsonContent = $this->getJsonContent() . ' '; $locker = new Locker(new NullIO, $json, $inst, $jsonContent); - $package1 = $this->createPackageMock(); - $package2 = $this->createPackageMock(); - - $package1 - ->expects($this->atLeastOnce()) - ->method('getPrettyName') - ->will($this->returnValue('pkg1')); - $package1 - ->expects($this->atLeastOnce()) - ->method('getPrettyVersion') - ->will($this->returnValue('1.0.0-beta')); - $package1 - ->expects($this->atLeastOnce()) - ->method('getVersion') - ->will($this->returnValue('1.0.0.0-beta')); - - $package2 - ->expects($this->atLeastOnce()) - ->method('getPrettyName') - ->will($this->returnValue('pkg2')); - $package2 - ->expects($this->atLeastOnce()) - ->method('getPrettyVersion') - ->will($this->returnValue('0.1.10')); - $package2 - ->expects($this->atLeastOnce()) - ->method('getVersion') - ->will($this->returnValue('0.1.10.0')); - - foreach (array($package1, $package2) as $package) { - $package - ->expects($this->atLeastOnce()) - ->method('getTransportOptions') - ->will($this->returnValue(array())); - } + $package1 = $this->getPackage('pkg1', '1.0.0-beta'); + $package2 = $this->getPackage('pkg2', '0.1.10'); $contentHash = md5(trim($jsonContent)); @@ -140,8 +107,8 @@ public function testSetLockData(): void 'This file is @gener'.'ated automatically', ), 'content-hash' => $contentHash, 'packages' => array( - array('name' => 'pkg1', 'version' => '1.0.0-beta'), - array('name' => 'pkg2', 'version' => '0.1.10'), + array('name' => 'pkg1', 'version' => '1.0.0-beta', 'type' => 'library'), + array('name' => 'pkg2', 'version' => '0.1.10', 'type' => 'library'), ), 'packages-dev' => array(), 'aliases' => array(), diff --git a/tests/Composer/Test/Package/Version/VersionParserTest.php b/tests/Composer/Test/Package/Version/VersionParserTest.php index e467ba25e6f4..2f120a7f8bfe 100644 --- a/tests/Composer/Test/Package/Version/VersionParserTest.php +++ b/tests/Composer/Test/Package/Version/VersionParserTest.php @@ -23,7 +23,7 @@ class VersionParserTest extends TestCase * @param string[] $pairs * @param array> $result */ - public function testParseNameVersionPairs($pairs, $result): void + public function testParseNameVersionPairs(array $pairs, array $result): void { $versionParser = new VersionParser(); @@ -48,7 +48,7 @@ public function provideParseNameVersionPairsData(): array * @param string $to * @param bool $expected */ - public function testIsUpgrade($from, $to, $expected): void + public function testIsUpgrade(string $from, string $to, bool $expected): void { $this->assertSame($expected, VersionParser::isUpgrade($from, $to)); } diff --git a/tests/Composer/Test/Package/Version/VersionSelectorTest.php b/tests/Composer/Test/Package/Version/VersionSelectorTest.php index 7a8041031168..4ff61029cc17 100644 --- a/tests/Composer/Test/Package/Version/VersionSelectorTest.php +++ b/tests/Composer/Test/Package/Version/VersionSelectorTest.php @@ -299,7 +299,7 @@ public function testFalseReturnedOnNoPackages(): void * @param string|null $branchAlias * @param string $packageName */ - public function testFindRecommendedRequireVersion($prettyVersion, $expectedVersion, $branchAlias = null, $packageName = 'foo/bar'): void + public function testFindRecommendedRequireVersion(string $prettyVersion, string $expectedVersion, ?string $branchAlias = null, string $packageName = 'foo/bar'): void { $repositorySet = $this->createMockRepositorySet(); $versionSelector = new VersionSelector($repositorySet); @@ -362,7 +362,7 @@ public function provideRecommendedRequireVersionPackages(): array * * @return Package */ - private function createPackage($version): Package + private function createPackage(string $version): Package { $parser = new VersionParser(); diff --git a/tests/Composer/Test/Platform/VersionTest.php b/tests/Composer/Test/Platform/VersionTest.php index f2cf6f8f2838..4ae361bb554c 100644 --- a/tests/Composer/Test/Platform/VersionTest.php +++ b/tests/Composer/Test/Platform/VersionTest.php @@ -79,7 +79,7 @@ public static function provideOpenSslVersions(): array * @param bool $fipsExpected * @param string|null $normalizedVersion */ - public function testParseOpensslVersions($input, $parsedVersion, $fipsExpected = false, $normalizedVersion = null): void + public function testParseOpensslVersions(string $input, string $parsedVersion, bool $fipsExpected = false, ?string $normalizedVersion = null): void { self::assertSame($parsedVersion, Version::parseOpenssl($input, $isFips)); self::assertSame($fipsExpected, $isFips); @@ -104,7 +104,7 @@ public function provideLibJpegVersions(): array * @param string $input * @param string $parsedVersion */ - public function testParseLibjpegVersion($input, $parsedVersion): void + public function testParseLibjpegVersion(string $input, string $parsedVersion): void { self::assertSame($parsedVersion, Version::parseLibjpeg($input)); } @@ -124,7 +124,7 @@ public function provideZoneinfoVersions(): array * @param string $input * @param string $parsedVersion */ - public function testParseZoneinfoVersion($input, $parsedVersion): void + public function testParseZoneinfoVersion(string $input, string $parsedVersion): void { self::assertSame($parsedVersion, Version::parseZoneinfoVersion($input)); } diff --git a/tests/Composer/Test/Plugin/PluginInstallerTest.php b/tests/Composer/Test/Plugin/PluginInstallerTest.php index 325f26671d4e..32b2afc36017 100644 --- a/tests/Composer/Test/Plugin/PluginInstallerTest.php +++ b/tests/Composer/Test/Plugin/PluginInstallerTest.php @@ -83,6 +83,15 @@ protected function setUp(): void $dm = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->disableOriginalConstructor() ->getMock(); + $dm->expects($this->any()) + ->method('install') + ->will($this->returnValue(\React\Promise\resolve())); + $dm->expects($this->any()) + ->method('update') + ->will($this->returnValue(\React\Promise\resolve())); + $dm->expects($this->any()) + ->method('remove') + ->will($this->returnValue(\React\Promise\resolve())); $this->repository = $this->getMockBuilder('Composer\Repository\InstalledRepositoryInterface')->getMock(); @@ -280,7 +289,7 @@ public function testRegisterPluginOnlyOneTime(): void * * @return void */ - private function setPluginApiVersionWithPlugins($newPluginApiVersion, array $plugins = array()): void + private function setPluginApiVersionWithPlugins(string $newPluginApiVersion, array $plugins = array()): void { // reset the plugin manager's installed plugins $this->pm = $this->getMockBuilder('Composer\Plugin\PluginManager') @@ -421,23 +430,12 @@ public function invalidImplementationClassNames(): array ); } - /** @return mixed[] */ - public function nonExistingOrInvalidImplementationClassTypes(): array - { - return array( - array('\stdClass'), - array('NonExistentClassLikeMiddleClass'), - ); - } - /** * @dataProvider invalidImplementationClassNames - * @param callable $invalidImplementationClassNames + * @param mixed $invalidImplementationClassNames * @param class-string<\Throwable> $expect - * - * @return void */ - public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, $expect = 'UnexpectedValueException'): void + public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, string $expect = 'UnexpectedValueException'): void { self::expectException($expect); @@ -455,7 +453,6 @@ public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImpleme $this->pm->getPluginCapability($plugin, $capabilityApi); } - /** @return void */ public function testQueryingNonProvidedCapabilityReturnsNullSafely(): void { $capabilityApi = 'Composer\Plugin\Capability\MadeUpCapability'; @@ -472,13 +469,19 @@ public function testQueryingNonProvidedCapabilityReturnsNullSafely(): void $this->assertNull($this->pm->getPluginCapability($plugin, $capabilityApi)); } + /** @return mixed[] */ + public function nonExistingOrInvalidImplementationClassTypes(): array + { + return array( + array('\stdClass'), + array('NonExistentClassLikeMiddleClass'), + ); + } + /** * @dataProvider nonExistingOrInvalidImplementationClassTypes - * @param callable $wrongImplementationClassTypes - * - * @return void */ - public function testQueryingWithNonExistingOrWrongCapabilityClassTypesThrows($wrongImplementationClassTypes): void + public function testQueryingWithNonExistingOrWrongCapabilityClassTypesThrows(string $wrongImplementationClassTypes): void { $this->testQueryingWithInvalidCapabilityClassNameThrows($wrongImplementationClassTypes, 'RuntimeException'); } diff --git a/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php b/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php index 7d9c94a753cc..2c21d869dd6c 100644 --- a/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php +++ b/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php @@ -45,7 +45,7 @@ public function getAskConfirmationBadData(): array * * @param string $answer */ - public function testAskConfirmationBadAnswer($answer): void + public function testAskConfirmationBadAnswer(string $answer): void { list($input, $dialog) = $this->createInput($answer."\n"); @@ -64,7 +64,7 @@ public function testAskConfirmationBadAnswer($answer): void * @param bool $expected * @param bool $default */ - public function testAskConfirmation($question, $expected, $default = true): void + public function testAskConfirmation(string $question, bool $expected, bool $default = true): void { list($input, $dialog) = $this->createInput($question."\n"); @@ -105,7 +105,7 @@ public function testAskConfirmationWithCustomTrueAndFalseAnswer(): void * * @return resource */ - protected function getInputStream($input) + protected function getInputStream(string $input) { $stream = fopen('php://memory', 'r+', false); $this->assertNotFalse($stream); @@ -131,7 +131,7 @@ protected function createOutputInterface(): StreamOutput * * @phpstan-return array{ArrayInput, QuestionHelper} */ - protected function createInput($entry): array + protected function createInput(string $entry): array { $input = new ArrayInput(array('--no-interaction')); $input->setStream($this->getInputStream($entry)); diff --git a/tests/Composer/Test/Repository/ComposerRepositoryTest.php b/tests/Composer/Test/Repository/ComposerRepositoryTest.php index f6076b3f5db2..fcfc2fa4cbee 100644 --- a/tests/Composer/Test/Repository/ComposerRepositoryTest.php +++ b/tests/Composer/Test/Repository/ComposerRepositoryTest.php @@ -279,7 +279,7 @@ public function testSearchWithAbandonedPackages(): void * @param string $url * @param string $repositoryUrl */ - public function testCanonicalizeUrl($expected, $url, $repositoryUrl): void + public function testCanonicalizeUrl(string $expected, string $url, string $repositoryUrl): void { $repository = new ComposerRepository( array('url' => $repositoryUrl), diff --git a/tests/Composer/Test/Repository/CompositeRepositoryTest.php b/tests/Composer/Test/Repository/CompositeRepositoryTest.php index 1cf8cbe846d2..edf914e73ef7 100644 --- a/tests/Composer/Test/Repository/CompositeRepositoryTest.php +++ b/tests/Composer/Test/Repository/CompositeRepositoryTest.php @@ -132,7 +132,7 @@ public function testCount(): void * @param string $method * @param mixed[] $args */ - public function testNoRepositories($method, $args): void + public function testNoRepositories(string $method, array $args): void { $repo = new CompositeRepository(array()); $this->assertEquals(array(), call_user_func_array(array($repo, $method), $args)); diff --git a/tests/Composer/Test/Repository/FilterRepositoryTest.php b/tests/Composer/Test/Repository/FilterRepositoryTest.php index 3a1c34e11f63..eb96d876f64b 100644 --- a/tests/Composer/Test/Repository/FilterRepositoryTest.php +++ b/tests/Composer/Test/Repository/FilterRepositoryTest.php @@ -40,7 +40,7 @@ public function setUp(): void * @param string[] $expected * @param array{only?: array, exclude?: array, canonical?: bool} $config */ - public function testRepoMatching($expected, $config): void + public function testRepoMatching(array $expected, $config): void { $repo = new FilterRepository($this->arrayRepo, $config); $packages = $repo->getPackages(); diff --git a/tests/Composer/Test/Repository/PathRepositoryTest.php b/tests/Composer/Test/Repository/PathRepositoryTest.php index 9717a445744e..5d688878789a 100644 --- a/tests/Composer/Test/Repository/PathRepositoryTest.php +++ b/tests/Composer/Test/Repository/PathRepositoryTest.php @@ -14,6 +14,7 @@ use Composer\Repository\PathRepository; use Composer\Test\TestCase; +use Composer\Util\Platform; class PathRepositoryTest extends TestCase { @@ -140,7 +141,7 @@ public function testUrlRemainsRelative(): void $repositoryUrl = implode(DIRECTORY_SEPARATOR, array(realpath(realpath(__DIR__)), 'Fixtures', 'path', 'with-version')); // getcwd() not necessarily match __DIR__ // PHP Bug https://bugs.php.net/bug.php?id=73797 - $relativeUrl = ltrim(substr($repositoryUrl, strlen(realpath(realpath(getcwd())))), DIRECTORY_SEPARATOR); + $relativeUrl = ltrim(substr($repositoryUrl, strlen(realpath(realpath(Platform::getCwd())))), DIRECTORY_SEPARATOR); $repository = new PathRepository(array('url' => $relativeUrl), $ioInterface, $config); $packages = $repository->getPackages(); diff --git a/tests/Composer/Test/Repository/PlatformRepositoryTest.php b/tests/Composer/Test/Repository/PlatformRepositoryTest.php index 68418d72b7f7..22445b4df459 100644 --- a/tests/Composer/Test/Repository/PlatformRepositoryTest.php +++ b/tests/Composer/Test/Repository/PlatformRepositoryTest.php @@ -1085,7 +1085,7 @@ public static function provideLibraryTestCases(): array */ public function testLibraryInformation( $extensions, - $info, + ?string $info, array $expectations, array $functions = array(), array $constants = array(), @@ -1199,7 +1199,7 @@ function ($package): bool { * * @return void */ - private function assertPackageLinks($context, array $expectedLinks, PackageInterface $sourcePackage, array $links): void + private function assertPackageLinks(string $context, array $expectedLinks, PackageInterface $sourcePackage, array $links): void { self::assertCount(count($expectedLinks), $links, sprintf('%s: expected package count to match', $context)); @@ -1263,7 +1263,7 @@ public static function providePlatformPackages(): array * @param bool $expectation * @dataProvider providePlatformPackages */ - public function testValidPlatformPackages($packageName, $expectation): void + public function testValidPlatformPackages(string $packageName, bool $expectation): void { self::assertSame($expectation, PlatformRepository::isPlatformPackage($packageName)); } @@ -1280,7 +1280,7 @@ class ResourceBundleStub * * @return ResourceBundleStub */ - public static function create($locale, $bundleName, $fallback): ResourceBundleStub + public static function create(string $locale, string $bundleName, bool $fallback): ResourceBundleStub { Assert::assertSame(3, func_num_args()); Assert::assertSame('root', $locale); @@ -1314,7 +1314,7 @@ class ImagickStub /** * @param string $versionString */ - public function __construct($versionString) + public function __construct(string $versionString) { $this->versionString = $versionString; } diff --git a/tests/Composer/Test/Repository/RepositoryManagerTest.php b/tests/Composer/Test/Repository/RepositoryManagerTest.php index 14db37204e48..fcf826e14478 100644 --- a/tests/Composer/Test/Repository/RepositoryManagerTest.php +++ b/tests/Composer/Test/Repository/RepositoryManagerTest.php @@ -15,6 +15,7 @@ use Composer\Repository\RepositoryManager; use Composer\Test\TestCase; use Composer\Util\Filesystem; +use Composer\Config; class RepositoryManagerTest extends TestCase { @@ -39,7 +40,7 @@ public function testPrepend(): void { $rm = new RepositoryManager( $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - $this->getMockBuilder('Composer\Config')->getMock(), + new Config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock() ); @@ -59,7 +60,7 @@ public function testPrepend(): void * @param array $options * @param class-string<\Throwable>|null $exception */ - public function testRepoCreation($type, $options, ?string $exception = null): void + public function testRepoCreation(string $type, array $options, ?string $exception = null): void { if ($exception !== null) { self::expectException($exception); @@ -67,19 +68,13 @@ public function testRepoCreation($type, $options, ?string $exception = null): vo $rm = new RepositoryManager( $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), - $config = $this->getMockBuilder('Composer\Config')->onlyMethods(array('get'))->getMock(), + $config = new Config, $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(), $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock() ); $tmpdir = $this->tmpdir; - $config - ->expects($this->any()) - ->method('get') - ->will($this->returnCallback(function ($arg) use ($tmpdir): ?string { - return 'cache-repo-dir' === $arg ? $tmpdir : null; - })) - ; + $config->merge(['config' => ['cache-repo-dir' => $tmpdir]]); $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository'); $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository'); diff --git a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php index cd51b6c3cc60..1857cf262ae6 100644 --- a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php @@ -61,7 +61,7 @@ public static function supportProvider(): array * @param string $url * @param bool $assertion */ - public function testSupport($url, $assertion): void + public function testSupport(string $url, bool $assertion): void { $config = new Config(); $result = FossilDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url); diff --git a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php index 144852f5a725..d616e3798883 100644 --- a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php @@ -99,7 +99,7 @@ public function testGetRootIdentifierWrongScmType(): void $driver->getRootIdentifier(); } - public function testDriver(): \Composer\Repository\Vcs\GitBitbucketDriver + public function testDriver(): GitBitbucketDriver { $driver = $this->getDriver(array('url' => 'https://bitbucket.org/user/repo.git')); @@ -195,7 +195,7 @@ public function testDriver(): \Composer\Repository\Vcs\GitBitbucketDriver * @depends testDriver * @param \Composer\Repository\Vcs\VcsDriverInterface $driver */ - public function testGetParams($driver): void + public function testGetParams(\Composer\Repository\Vcs\VcsDriverInterface $driver): void { $url = 'https://bitbucket.org/user/repo.git'; diff --git a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php index 8482b28bdea0..005f0c8172cf 100644 --- a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php @@ -193,6 +193,7 @@ public function testPublicRepository2(): void $data = $gitHubDriver->getComposerInformation($identifier); + $this->assertIsArray($data); $this->assertArrayNotHasKey('abandoned', $data); } @@ -230,6 +231,7 @@ public function testPublicRepositoryArchived(): void $data = $gitHubDriver->getComposerInformation($sha); + $this->assertIsArray($data); $this->assertTrue($data['abandoned']); } @@ -327,7 +329,7 @@ public function initializeInvalidReoUrl(): void * @param bool $expected * @param string $repoUrl */ - public function testSupports($expected, $repoUrl): void + public function testSupports(bool $expected, string $repoUrl): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); @@ -353,7 +355,7 @@ public function supportsProvider(): array * * @return void */ - protected function setAttribute($object, $attribute, $value): void + protected function setAttribute($object, string $attribute, $value): void { $attr = new \ReflectionProperty($object, $attribute); $attr->setAccessible(true); diff --git a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php index b2706d613ecb..812c1bf05b4e 100644 --- a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php @@ -92,7 +92,7 @@ public function provideInitializeUrls(): array * @param string $url * @param string $apiUrl */ - public function testInitialize($url, $apiUrl): \Composer\Repository\Vcs\GitLabDriver + public function testInitialize(string $url, string $apiUrl): GitLabDriver { // @link http://doc.gitlab.com/ce/api/projects.html#get-single-project $projectData = <<assertSame($expected, GitLabDriver::supports($this->io, $this->config, $url)); } diff --git a/tests/Composer/Test/Repository/Vcs/HgDriverTest.php b/tests/Composer/Test/Repository/Vcs/HgDriverTest.php index fd94cf94536e..0d6948415c9d 100644 --- a/tests/Composer/Test/Repository/Vcs/HgDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/HgDriverTest.php @@ -50,7 +50,7 @@ protected function tearDown(): void * * @param string $repositoryUrl */ - public function testSupports($repositoryUrl): void + public function testSupports(string $repositoryUrl): void { $this->assertTrue( HgDriver::supports($this->io, $this->config, $repositoryUrl) diff --git a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php index 00acd67df0f0..f1787e71c271 100644 --- a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php @@ -102,7 +102,7 @@ protected function overrideDriverInternalPerforce(Perforce $perforce): void * * @return Config */ - protected function getTestConfig($testPath): Config + protected function getTestConfig(string $testPath): Config { $config = new Config(); $config->merge(array('config' => array('home' => $testPath))); diff --git a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php index f08891a41c6c..e18f64af3e8a 100644 --- a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php @@ -100,7 +100,7 @@ public static function supportProvider(): array * @param string $url * @param bool $assertion */ - public function testSupport($url, $assertion): void + public function testSupport(string $url, bool $assertion): void { $config = new Config(); $result = SvnDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url); diff --git a/tests/Composer/Test/Repository/VcsRepositoryTest.php b/tests/Composer/Test/Repository/VcsRepositoryTest.php index 819dcd08d866..a4e1753970ae 100644 --- a/tests/Composer/Test/Repository/VcsRepositoryTest.php +++ b/tests/Composer/Test/Repository/VcsRepositoryTest.php @@ -13,6 +13,7 @@ namespace Composer\Test\Repository; use Composer\Test\TestCase; +use Composer\Util\Platform; use Symfony\Component\Process\ExecutableFinder; use Composer\Package\Dumper\ArrayDumper; use Composer\Repository\VcsRepository; @@ -51,7 +52,7 @@ protected function initialize(): void return; } - $oldCwd = getcwd(); + $oldCwd = Platform::getCwd(); self::$composerHome = $this->getUniqueTmpDirectory(); self::$gitRepo = $this->getUniqueTmpDirectory(); @@ -64,7 +65,7 @@ protected function initialize(): void // init $process = new ProcessExecutor; $exec = function ($command) use ($process): void { - $cwd = getcwd(); + $cwd = Platform::getCwd(); if ($process->execute($command, $output, $cwd) !== 0) { throw new \RuntimeException('Failed to execute '.$command.': '.$process->getErrorOutput()); } diff --git a/tests/Composer/Test/TestCase.php b/tests/Composer/Test/TestCase.php index a8136edb5f00..0e61bb87ab29 100644 --- a/tests/Composer/Test/TestCase.php +++ b/tests/Composer/Test/TestCase.php @@ -100,7 +100,7 @@ protected static function getVersionParser(): VersionParser * @param string $version * @return Constraint */ - protected function getVersionConstraint($operator, $version): Constraint + protected function getVersionConstraint($operator, string $version): Constraint { $constraint = new Constraint( $operator, @@ -113,7 +113,7 @@ protected function getVersionConstraint($operator, $version): Constraint } /** - * @template PackageClass of PackageInterface + * @template PackageClass of CompletePackage|CompleteAliasPackage * * @param string $class FQCN to be instantiated * @param string $name @@ -124,18 +124,25 @@ protected function getVersionConstraint($operator, $version): Constraint * @phpstan-param class-string $class * @phpstan-return PackageClass */ - protected function getPackage($name, $version, $class = 'Composer\Package\CompletePackage') + protected function getPackage(string $name = 'dummy/pkg', string $version = '1.0.0', string $class = 'Composer\Package\CompletePackage'): BasePackage { $normVersion = self::getVersionParser()->normalize($version); return new $class($name, $normVersion, $version); } + protected function getRootPackage(string $name = '__root__', string $version = '1.0.0'): RootPackage + { + $normVersion = self::getVersionParser()->normalize($version); + + return new RootPackage($name, $normVersion, $version); + } + /** * @param string $version * @return AliasPackage|RootAliasPackage|CompleteAliasPackage */ - protected function getAliasPackage(Package $package, $version): \Composer\Package\AliasPackage + protected function getAliasPackage(Package $package, string $version): AliasPackage { $normVersion = self::getVersionParser()->normalize($version); @@ -172,11 +179,22 @@ protected function configureLinks(PackageInterface $package, array $config): voi } } + /** + * @param array $configOptions + */ + protected function getConfig(array $configOptions = [], bool $useEnvironment = false): Config + { + $config = new Config($useEnvironment); + $config->merge(['config' => $configOptions], 'test'); + + return $config; + } + /** * @param string $directory * @return void */ - protected static function ensureDirectoryExistsAndClear($directory): void + protected static function ensureDirectoryExistsAndClear(string $directory): void { $fs = new Filesystem(); @@ -196,7 +214,7 @@ protected static function ensureDirectoryExistsAndClear($directory): void * * @throws \PHPUnit\Framework\SkippedTestError */ - protected function skipIfNotExecutable($executableName): void + protected function skipIfNotExecutable(string $executableName): void { if (!isset(self::$executableCache[$executableName])) { $finder = new ExecutableFinder(); @@ -215,7 +233,7 @@ protected function skipIfNotExecutable($executableName): void * * @return string The transformed command */ - protected function getCmd($cmd): string + protected function getCmd(string $cmd): string { if (Platform::isWindows()) { $cmd = Preg::replaceCallback("/('[^']*')/", function ($m) { diff --git a/tests/Composer/Test/Util/AuthHelperTest.php b/tests/Composer/Test/Util/AuthHelperTest.php index d12f87066dcf..b179688e2a4e 100644 --- a/tests/Composer/Test/Util/AuthHelperTest.php +++ b/tests/Composer/Test/Util/AuthHelperTest.php @@ -158,7 +158,7 @@ public function gitlabPrivateTokenProvider(): array * * @param string $password */ - public function testAddAuthenticationHeaderWithGitlabPrivateToken($password): void + public function testAddAuthenticationHeaderWithGitlabPrivateToken(string $password): void { $headers = array( 'Accept-Encoding: gzip', @@ -235,7 +235,7 @@ public function bitbucketPublicUrlProvider(): array * * @param string $url */ - public function testAddAuthenticationHeaderWithBitbucketPublicUrl($url): void + public function testAddAuthenticationHeaderWithBitbucketPublicUrl(string $url): void { $headers = array( 'Accept-Encoding: gzip', @@ -299,7 +299,7 @@ public function basicHttpAuthenticationProvider(): array * * @phpstan-param array{username: string|null, password: string|null} $auth */ - public function testAddAuthenticationHeaderWithBasicHttpAuthentication($url, $origin, $auth): void + public function testAddAuthenticationHeaderWithBasicHttpAuthentication(string $url, string $origin, array $auth): void { $headers = array( 'Accept-Encoding: gzip', @@ -337,7 +337,7 @@ public function testAddAuthenticationHeaderWithBasicHttpAuthentication($url, $or * * @param string $url */ - public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl($url): void + public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl(string $url): void { $this->assertTrue($this->authHelper->isPublicBitBucketDownload($url)); } @@ -377,8 +377,7 @@ public function testStoreAuthAutomatically(): void $configSource->expects($this->once()) ->method('addConfigSetting') - ->with('http-basic.'.$origin, $auth) - ->willReturn($configSource); + ->with('http-basic.'.$origin, $auth); $this->authHelper->storeAuth($origin, $storeAuth); } @@ -429,8 +428,7 @@ public function testStoreAuthWithPromptYesAnswer(): void $configSource->expects($this->once()) ->method('addConfigSetting') - ->with('http-basic.'.$origin, $auth) - ->willReturn($configSource); + ->with('http-basic.'.$origin, $auth); $this->authHelper->storeAuth($origin, $storeAuth); } @@ -521,7 +519,7 @@ public function testStoreAuthWithPromptInvalidAnswer(): void * * @phpstan-param array{username: string|null, password: string|null} $auth */ - private function expectsAuthentication($origin, $auth): void + private function expectsAuthentication(string $origin, array $auth): void { $this->io->expects($this->once()) ->method('hasAuthentication') diff --git a/tests/Composer/Test/Util/BitbucketTest.php b/tests/Composer/Test/Util/BitbucketTest.php index 643b1f64e415..525e90456e8b 100644 --- a/tests/Composer/Test/Util/BitbucketTest.php +++ b/tests/Composer/Test/Util/BitbucketTest.php @@ -111,7 +111,7 @@ public function testRequestAccessTokenWithValidOAuthConsumer(): void ); } - public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): \Composer\Util\Bitbucket + public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): Bitbucket { $this->config->expects($this->once()) ->method('get') @@ -411,7 +411,7 @@ public function testAuthorizeOAuthInteractivelyWithRequestAccessTokenFailure(): * * @return void */ - private function setExpectationsForStoringAccessToken($removeBasicAuth = false): void + private function setExpectationsForStoringAccessToken(bool $removeBasicAuth = false): void { $configSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->expects($this->once()) diff --git a/tests/Composer/Test/Util/FilesystemTest.php b/tests/Composer/Test/Util/FilesystemTest.php index dc6706b27a31..20298d534685 100644 --- a/tests/Composer/Test/Util/FilesystemTest.php +++ b/tests/Composer/Test/Util/FilesystemTest.php @@ -59,7 +59,7 @@ protected function tearDown(): void * @param string $expected * @param bool $static */ - public function testFindShortestPathCode($a, $b, $directory, $expected, $static = false): void + public function testFindShortestPathCode(string $a, string $b, bool $directory, string $expected, bool $static = false): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->findShortestPathCode($a, $b, $directory, $static)); @@ -122,7 +122,7 @@ public function providePathCouplesAsCode(): array * @param string $expected * @param bool $directory */ - public function testFindShortestPath($a, $b, $expected, $directory = false): void + public function testFindShortestPath(string $a, string $b, string $expected, bool $directory = false): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->findShortestPath($a, $b, $directory)); @@ -207,7 +207,7 @@ public function testDirectorySize(): void * @param string $expected * @param string $actual */ - public function testNormalizePath($expected, $actual): void + public function testNormalizePath(string $expected, string $actual): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->normalizePath($actual)); diff --git a/tests/Composer/Test/Util/GitTest.php b/tests/Composer/Test/Util/GitTest.php index e6df4e1eda70..c91a34248683 100644 --- a/tests/Composer/Test/Util/GitTest.php +++ b/tests/Composer/Test/Util/GitTest.php @@ -47,7 +47,7 @@ protected function setUp(): void * @param string $protocol * @param string $expectedUrl */ - public function testRunCommandPublicGitHubRepositoryNotInitialClone($protocol, $expectedUrl): void + public function testRunCommandPublicGitHubRepositoryNotInitialClone(string $protocol, string $expectedUrl): void { $commandCallable = function ($url) use ($expectedUrl): string { $this->assertSame($expectedUrl, $url); @@ -99,7 +99,7 @@ public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteracti * @param string $expectedUrl * @param int $expectedFailuresBeforeSuccess */ - public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication($gitUrl, $protocol, $gitHubToken, $expectedUrl, $expectedFailuresBeforeSuccess): void + public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication(string $gitUrl, string $protocol, string $gitHubToken, string $expectedUrl, int $expectedFailuresBeforeSuccess): void { $commandCallable = function ($url) use ($expectedUrl): string { if ($url !== $expectedUrl) { @@ -148,7 +148,7 @@ public function privateGithubWithCredentialsProvider(): array * * @return void */ - private function mockConfig($protocol): void + private function mockConfig(string $protocol): void { $this->config ->method('get') diff --git a/tests/Composer/Test/Util/Http/ProxyHelperTest.php b/tests/Composer/Test/Util/Http/ProxyHelperTest.php index 15fd85069659..4de4c654ae16 100644 --- a/tests/Composer/Test/Util/Http/ProxyHelperTest.php +++ b/tests/Composer/Test/Util/Http/ProxyHelperTest.php @@ -49,7 +49,7 @@ protected function tearDown(): void * * @param string $url */ - public function testThrowsOnMalformedUrl($url): void + public function testThrowsOnMalformedUrl(string $url): void { $_SERVER['http_proxy'] = $url; @@ -71,7 +71,7 @@ public function dataMalformed(): array * @param string $url * @param string $expected */ - public function testUrlFormatting($url, $expected): void + public function testUrlFormatting(string $url, string $expected): void { $_SERVER['http_proxy'] = $url; @@ -96,7 +96,7 @@ public function dataFormatting(): array * @param string $expected * @param int $index */ - public function testLowercaseOverridesUppercase(array $server, $expected, $index): void + public function testLowercaseOverridesUppercase(array $server, string $expected, int $index): void { $_SERVER = array_merge($_SERVER, $server); @@ -121,7 +121,7 @@ public function dataCaseOverrides(): array * @param string $expected * @param int $index */ - public function testCGIUpperCaseOverridesHttp(array $server, $expected, $index): void + public function testCGIUpperCaseOverridesHttp(array $server, string $expected, int $index): void { $_SERVER = array_merge($_SERVER, $server); @@ -162,7 +162,7 @@ public function testNoHttpProxyDoesNotUseHttpsProxy(): void * * @phpstan-param array{http: array{proxy: string, header?: string}} $expected */ - public function testGetContextOptions($url, $expected): void + public function testGetContextOptions(string $url, array $expected): void { $this->assertEquals($expected, ProxyHelper::getContextOptions($url)); } @@ -190,7 +190,7 @@ public function dataContextOptions(): array * @param string $requestUrl * @param mixed[] $expected */ - public function testSetRequestFullUri($requestUrl, $expected): void + public function testSetRequestFullUri(string $requestUrl, array $expected): void { $options = array(); ProxyHelper::setRequestFullUri($requestUrl, $options); diff --git a/tests/Composer/Test/Util/Http/ProxyManagerTest.php b/tests/Composer/Test/Util/Http/ProxyManagerTest.php index 729e12da3cd4..ea5eb78f72e7 100644 --- a/tests/Composer/Test/Util/Http/ProxyManagerTest.php +++ b/tests/Composer/Test/Util/Http/ProxyManagerTest.php @@ -77,7 +77,7 @@ public function testGetProxyForRequestThrowsOnBadProxyUrl(): void * @param bool $expectedSecure * @param string $expectedMessage */ - public function testGetProxyForRequest($server, $url, $expectedUrl, $expectedOptions, $expectedSecure, $expectedMessage): void + public function testGetProxyForRequest(array $server, string $url, string $expectedUrl, array $expectedOptions, bool $expectedSecure, string $expectedMessage): void { $_SERVER = array_merge($_SERVER, $server); $proxyManager = ProxyManager::getInstance(); @@ -136,10 +136,8 @@ public function dataRequest(): array * @dataProvider dataStatus * * @param array $server - * @param bool $expectedStatus - * @param string $expectedMessage */ - public function testGetStatus($server, $expectedStatus, $expectedMessage): void + public function testGetStatus(array $server, bool $expectedStatus, ?string $expectedMessage): void { $_SERVER = array_merge($_SERVER, $server); $proxyManager = ProxyManager::getInstance(); @@ -148,7 +146,7 @@ public function testGetStatus($server, $expectedStatus, $expectedMessage): void $this->assertSame($expectedStatus, $status); - if ($expectedMessage) { + if ($expectedMessage !== null) { $condition = stripos($message, $expectedMessage) !== false; } else { $condition = $expectedMessage === $message; diff --git a/tests/Composer/Test/Util/Http/RequestProxyTest.php b/tests/Composer/Test/Util/Http/RequestProxyTest.php index 120ff826345a..474c6857e152 100644 --- a/tests/Composer/Test/Util/Http/RequestProxyTest.php +++ b/tests/Composer/Test/Util/Http/RequestProxyTest.php @@ -23,7 +23,7 @@ class RequestProxyTest extends TestCase * @param string $url * @param bool $expectedSecure */ - public function testIsSecure($url, $expectedSecure): void + public function testIsSecure(string $url, bool $expectedSecure): void { $proxy = new RequestProxy($url, array(), ''); @@ -47,7 +47,7 @@ public function dataSecure(): array * @param string $format * @param string $expected */ - public function testGetFormattedUrlFormat($url, $format, $expected): void + public function testGetFormattedUrlFormat(string $url, string $format, string $expected): void { $proxy = new RequestProxy($url, array(), $url); diff --git a/tests/Composer/Test/Util/NoProxyPatternTest.php b/tests/Composer/Test/Util/NoProxyPatternTest.php index c70c9774dce9..7b00da615361 100644 --- a/tests/Composer/Test/Util/NoProxyPatternTest.php +++ b/tests/Composer/Test/Util/NoProxyPatternTest.php @@ -24,7 +24,7 @@ class NoProxyPatternTest extends TestCase * @param string $url * @param bool $expected */ - public function testHostName($noproxy, $url, $expected): void + public function testHostName(string $noproxy, string $url, bool $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); @@ -55,7 +55,7 @@ public function dataHostName(): array * @param string $url * @param bool $expected */ - public function testIpAddress($noproxy, $url, $expected): void + public function testIpAddress(string $noproxy, string $url, bool $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); @@ -84,7 +84,7 @@ public function dataIpAddress(): array * @param string $url * @param bool $expected */ - public function testIpRange($noproxy, $url, $expected): void + public function testIpRange(string $noproxy, string $url, bool $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); @@ -113,7 +113,7 @@ public function dataIpRange(): array * @param string $url * @param bool $expected */ - public function testPort($noproxy, $url, $expected): void + public function testPort(string $noproxy, string $url, bool $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); @@ -140,7 +140,7 @@ public function dataPort(): array * * @return string */ - private function getUrl($url): string + private function getUrl(string $url): string { if (parse_url($url, PHP_URL_SCHEME)) { return $url; diff --git a/tests/Composer/Test/Util/PackageSorterTest.php b/tests/Composer/Test/Util/PackageSorterTest.php index 4f25f56331f0..63734925fb68 100644 --- a/tests/Composer/Test/Util/PackageSorterTest.php +++ b/tests/Composer/Test/Util/PackageSorterTest.php @@ -108,7 +108,7 @@ public function sortingOrdersDependenciesHigherThanPackageDataProvider(): array * @param Package[] $packages * @param string[] $expectedOrderedList */ - public function testSortingOrdersDependenciesHigherThanPackage($packages, $expectedOrderedList): void + public function testSortingOrdersDependenciesHigherThanPackage(array $packages, array $expectedOrderedList): void { $sortedPackages = PackageSorter::sortPackages($packages); $sortedPackageNames = array_map(function ($package): string { @@ -124,7 +124,7 @@ public function testSortingOrdersDependenciesHigherThanPackage($packages, $expec * * @return Package */ - private function createPackage($name, $requires): Package + private function createPackage(string $name, array $requires): Package { $package = new Package($name, '1.0.0.0', '1.0.0'); diff --git a/tests/Composer/Test/Util/PerforceTest.php b/tests/Composer/Test/Util/PerforceTest.php index 4e3f7d5b9f02..b42f484b36f5 100644 --- a/tests/Composer/Test/Util/PerforceTest.php +++ b/tests/Composer/Test/Util/PerforceTest.php @@ -73,7 +73,7 @@ public function getMockIOInterface() * * @return void */ - protected function createNewPerforceWithWindowsFlag($flag): void + protected function createNewPerforceWithWindowsFlag(bool $flag): void { $this->perforce = new Perforce($this->repoConfig, self::TEST_PORT, self::TEST_PATH, $this->processExecutor, $flag, $this->io); } @@ -615,7 +615,7 @@ public static function getComposerJson(): string * * @return string[] */ - private function getExpectedClientSpec($withStream): array + private function getExpectedClientSpec(bool $withStream): array { $expectedArray = array( 'Client: composer_perforce_TEST_depot', diff --git a/tests/Composer/Test/Util/ProcessExecutorTest.php b/tests/Composer/Test/Util/ProcessExecutorTest.php index c0ef2f43e3de..c1aac5ad7278 100644 --- a/tests/Composer/Test/Util/ProcessExecutorTest.php +++ b/tests/Composer/Test/Util/ProcessExecutorTest.php @@ -73,7 +73,7 @@ public function testTimeout(): void * @param string $command * @param string $expectedCommandOutput */ - public function testHidePasswords($command, $expectedCommandOutput): void + public function testHidePasswords(string $command, string $expectedCommandOutput): void { $process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG)); $process->execute($command, $output); @@ -141,7 +141,7 @@ public function testExecuteAsyncCancel(): void * @param string $win * @param string $unix */ - public function testEscapeArgument($argument, $win, $unix): void + public function testEscapeArgument($argument, string $win, string $unix): void { $expected = defined('PHP_WINDOWS_VERSION_BUILD') ? $win : $unix; $this->assertSame($expected, ProcessExecutor::escape($argument)); diff --git a/tests/Composer/Test/Util/RemoteFilesystemTest.php b/tests/Composer/Test/Util/RemoteFilesystemTest.php index 06df39b8812e..eebe8f90001c 100644 --- a/tests/Composer/Test/Util/RemoteFilesystemTest.php +++ b/tests/Composer/Test/Util/RemoteFilesystemTest.php @@ -279,7 +279,7 @@ public function provideBitbucketPublicDownloadUrls(): array * @param string $contents * @dataProvider provideBitbucketPublicDownloadUrls */ - public function testBitBucketPublicDownload($url, $contents): void + public function testBitBucketPublicDownload(string $url, string $contents): void { /** @var ConsoleIO $io */ $io = $this @@ -302,7 +302,7 @@ public function testBitBucketPublicDownload($url, $contents): void * @param string $contents * @dataProvider provideBitbucketPublicDownloadUrls */ - public function testBitBucketPublicDownloadWithAuthConfigured($url, $contents): void + public function testBitBucketPublicDownloadWithAuthConfigured(string $url, string $contents): void { /** @var MockObject|ConsoleIO $io */ $io = $this @@ -343,7 +343,7 @@ public function testBitBucketPublicDownloadWithAuthConfigured($url, $contents): * * @return mixed[] */ - private function callGetOptionsForUrl(IOInterface $io, array $args = array(), array $options = array(), $fileUrl = ''): array + private function callGetOptionsForUrl(IOInterface $io, array $args = array(), array $options = array(), string $fileUrl = ''): array { $fs = new RemoteFilesystem($io, $this->getConfigMock(), $options); $ref = new ReflectionMethod($fs, 'getOptionsForUrl'); @@ -385,7 +385,7 @@ private function getConfigMock() * * @return void */ - private function callCallbackGet(RemoteFilesystem $fs, $notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax): void + private function callCallbackGet(RemoteFilesystem $fs, int $notificationCode, int $severity, string $message, int $messageCode, int $bytesTransferred, int $bytesMax): void { $ref = new ReflectionMethod($fs, 'callbackGet'); $ref->setAccessible(true); @@ -399,7 +399,7 @@ private function callCallbackGet(RemoteFilesystem $fs, $notificationCode, $sever * * @return void */ - private function setAttribute($object, $attribute, $value): void + private function setAttribute($object, string $attribute, $value): void { $attr = new ReflectionProperty($object, $attribute); $attr->setAccessible(true); @@ -413,7 +413,7 @@ private function setAttribute($object, $attribute, $value): void * * @return void */ - private function assertAttributeEqualsCustom($value, $attribute, $object): void + private function assertAttributeEqualsCustom($value, string $attribute, $object): void { $attr = new ReflectionProperty($object, $attribute); $attr->setAccessible(true); diff --git a/tests/Composer/Test/Util/StreamContextFactoryTest.php b/tests/Composer/Test/Util/StreamContextFactoryTest.php index 0d90672ba4fb..ca78f1c4c1f9 100644 --- a/tests/Composer/Test/Util/StreamContextFactoryTest.php +++ b/tests/Composer/Test/Util/StreamContextFactoryTest.php @@ -39,7 +39,7 @@ protected function tearDown(): void * @param mixed[] $expectedParams * @param mixed[] $defaultParams */ - public function testGetContext($expectedOptions, $defaultOptions, $expectedParams, $defaultParams): void + public function testGetContext(array $expectedOptions, array $defaultOptions, array $expectedParams, array $defaultParams): void { $context = StreamContextFactory::getContext('http://example.org', $defaultOptions, $defaultParams); $options = stream_context_get_options($context); @@ -167,7 +167,7 @@ public function testHttpsProxyOverride(): void * @param string $expected * @param string $proxy */ - public function testSSLProxy($expected, $proxy): void + public function testSSLProxy(string $expected, string $proxy): void { $_SERVER['http_proxy'] = $proxy; diff --git a/tests/Composer/Test/Util/SvnTest.php b/tests/Composer/Test/Util/SvnTest.php index 7aa7c73b2198..b6d6062f936e 100644 --- a/tests/Composer/Test/Util/SvnTest.php +++ b/tests/Composer/Test/Util/SvnTest.php @@ -27,7 +27,7 @@ class SvnTest extends TestCase * * @dataProvider urlProvider */ - public function testCredentials($url, $expect): void + public function testCredentials(string $url, string $expect): void { $svn = new Svn($url, new NullIO, new Config()); $reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialString'); diff --git a/tests/Composer/Test/Util/TlsHelperTest.php b/tests/Composer/Test/Util/TlsHelperTest.php index 1bc7d9151980..c6f1514f0cae 100644 --- a/tests/Composer/Test/Util/TlsHelperTest.php +++ b/tests/Composer/Test/Util/TlsHelperTest.php @@ -24,7 +24,7 @@ class TlsHelperTest extends TestCase * @param string $hostname * @param string[] $certNames */ - public function testCheckCertificateHost($expectedResult, $hostname, $certNames): void + public function testCheckCertificateHost(bool $expectedResult, string $hostname, array $certNames): void { $certificate['subject']['commonName'] = $expectedCn = array_shift($certNames); $certificate['extensions']['subjectAltName'] = $certNames ? 'DNS:'.implode(',DNS:', $certNames) : ''; diff --git a/tests/Composer/Test/Util/UrlTest.php b/tests/Composer/Test/Util/UrlTest.php index 650d5387591b..3a8b084d5444 100644 --- a/tests/Composer/Test/Util/UrlTest.php +++ b/tests/Composer/Test/Util/UrlTest.php @@ -26,7 +26,7 @@ class UrlTest extends TestCase * @param array $conf * @param string $ref */ - public function testUpdateDistReference($url, $expectedUrl, $conf = array(), $ref = 'newref'): void + public function testUpdateDistReference(string $url, string $expectedUrl, array $conf = array(), string $ref = 'newref'): void { $config = new Config(); $config->merge(array('config' => $conf)); @@ -70,7 +70,7 @@ public static function distRefsProvider(): array * @param string $expected * @param string $url */ - public function testSanitize($expected, $url): void + public function testSanitize(string $expected, string $url): void { $this->assertSame($expected, Url::sanitize($url)); }