From 6da38f83a0d5acc71793f337b525fa2faff9468e Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Tue, 22 Feb 2022 16:47:09 +0100 Subject: [PATCH 1/6] Add parameter types to all the things --- .php-cs-fixer.php | 8 +- bin/compile | 1 + src/Composer/Autoload/AutoloadGenerator.php | 56 ++-- src/Composer/Autoload/ClassMapGenerator.php | 19 +- src/Composer/Autoload/PhpFileCleaner.php | 12 +- src/Composer/Cache.php | 24 +- src/Composer/Command/ArchiveCommand.php | 5 +- src/Composer/Command/BaseCommand.php | 4 +- .../Command/BaseDependencyCommand.php | 6 +- .../Command/CheckPlatformReqsCommand.php | 2 +- src/Composer/Command/ConfigCommand.php | 8 +- src/Composer/Command/CreateProjectCommand.php | 14 +- src/Composer/Command/DiagnoseCommand.php | 6 +- src/Composer/Command/ExecCommand.php | 2 +- src/Composer/Command/HomeCommand.php | 4 +- src/Composer/Command/InitCommand.php | 14 +- src/Composer/Command/LicensesCommand.php | 2 +- src/Composer/Command/RequireCommand.php | 8 +- src/Composer/Command/ScriptAliasCommand.php | 8 +- src/Composer/Command/SelfUpdateCommand.php | 14 +- src/Composer/Command/ShowCommand.php | 28 +- src/Composer/Command/UpdateCommand.php | 2 +- src/Composer/Command/ValidateCommand.php | 2 +- src/Composer/Compiler.php | 8 +- src/Composer/Config.php | 32 +-- src/Composer/Config/ConfigSourceInterface.php | 16 +- src/Composer/Config/JsonConfigSource.php | 6 +- src/Composer/Console/Application.php | 17 +- src/Composer/Console/GithubActionError.php | 6 +- src/Composer/DependencyResolver/Decisions.php | 24 +- .../DependencyResolver/DefaultPolicy.php | 14 +- .../DependencyResolver/LockTransaction.php | 6 +- .../Operation/InstallOperation.php | 2 +- .../Operation/OperationInterface.php | 2 +- .../Operation/UninstallOperation.php | 2 +- .../Operation/UpdateOperation.php | 2 +- .../DependencyResolver/PolicyInterface.php | 6 +- src/Composer/DependencyResolver/Pool.php | 16 +- .../DependencyResolver/PoolBuilder.php | 12 +- .../DependencyResolver/PoolOptimizer.php | 4 +- src/Composer/DependencyResolver/Problem.php | 16 +- src/Composer/DependencyResolver/Request.php | 6 +- src/Composer/DependencyResolver/Rule.php | 4 +- .../DependencyResolver/Rule2Literals.php | 2 +- src/Composer/DependencyResolver/RuleSet.php | 4 +- .../DependencyResolver/RuleSetGenerator.php | 2 +- .../DependencyResolver/RuleWatchChain.php | 2 +- .../DependencyResolver/RuleWatchGraph.php | 4 +- .../DependencyResolver/RuleWatchNode.php | 4 +- src/Composer/DependencyResolver/Solver.php | 10 +- .../DependencyResolver/SolverBugException.php | 2 +- .../SolverProblemsException.php | 2 +- .../DependencyResolver/Transaction.php | 4 +- src/Composer/Downloader/ArchiveDownloader.php | 15 +- .../Downloader/ChangeReportInterface.php | 2 +- src/Composer/Downloader/DownloadManager.php | 26 +- .../Downloader/DownloaderInterface.php | 12 +- .../Downloader/DvcsDownloaderInterface.php | 2 +- src/Composer/Downloader/FileDownloader.php | 27 +- .../Downloader/FilesystemException.php | 2 +- src/Composer/Downloader/FossilDownloader.php | 12 +- src/Composer/Downloader/GitDownloader.php | 36 +-- src/Composer/Downloader/GzipDownloader.php | 4 +- src/Composer/Downloader/HgDownloader.php | 14 +- src/Composer/Downloader/PathDownloader.php | 16 +- .../Downloader/PerforceDownloader.php | 16 +- src/Composer/Downloader/PharDownloader.php | 2 +- src/Composer/Downloader/RarDownloader.php | 2 +- src/Composer/Downloader/SvnDownloader.php | 18 +- src/Composer/Downloader/TarDownloader.php | 2 +- .../Downloader/TransportException.php | 6 +- .../VcsCapableDownloaderInterface.php | 2 +- src/Composer/Downloader/VcsDownloader.php | 34 +-- src/Composer/Downloader/XzDownloader.php | 2 +- src/Composer/Downloader/ZipDownloader.php | 15 +- src/Composer/EventDispatcher/Event.php | 2 +- .../EventDispatcher/EventDispatcher.php | 21 +- src/Composer/Factory.php | 8 +- .../IgnoreAllPlatformRequirementFilter.php | 2 +- .../IgnoreListPlatformRequirementFilter.php | 4 +- ...IgnoreNothingPlatformRequirementFilter.php | 2 +- .../PlatformRequirementFilterInterface.php | 2 +- src/Composer/IO/BaseIO.php | 6 +- src/Composer/IO/BufferIO.php | 2 +- src/Composer/IO/ConsoleIO.php | 20 +- src/Composer/IO/IOInterface.php | 34 +-- src/Composer/IO/NullIO.php | 8 +- src/Composer/Installer.php | 50 ++-- src/Composer/Installer/BinaryInstaller.php | 14 +- .../Installer/InstallationManager.php | 12 +- src/Composer/Installer/InstallerEvent.php | 2 +- src/Composer/Installer/InstallerInterface.php | 6 +- src/Composer/Installer/LibraryInstaller.php | 2 +- src/Composer/Installer/PackageEvent.php | 2 +- src/Composer/Installer/ProjectInstaller.php | 4 +- .../Installer/SuggestedPackagesReporter.php | 8 +- src/Composer/Json/JsonFile.php | 18 +- src/Composer/Json/JsonFormatter.php | 2 +- src/Composer/Json/JsonManipulator.php | 34 +-- src/Composer/Json/JsonValidationException.php | 2 +- src/Composer/Package/AliasPackage.php | 22 +- .../Archiver/ArchivableFilesFilter.php | 2 +- .../Archiver/ArchivableFilesFinder.php | 2 +- .../Package/Archiver/ArchiveManager.php | 4 +- .../Package/Archiver/ArchiverInterface.php | 4 +- .../Package/Archiver/BaseExcludeFilter.php | 10 +- .../Archiver/ComposerExcludeFilter.php | 2 +- .../Package/Archiver/GitExcludeFilter.php | 4 +- src/Composer/Package/BasePackage.php | 6 +- src/Composer/Package/Comparer/Comparer.php | 14 +- src/Composer/Package/CompleteAliasPackage.php | 8 +- src/Composer/Package/CompletePackage.php | 6 +- .../Package/CompletePackageInterface.php | 6 +- src/Composer/Package/Dumper/ArrayDumper.php | 2 +- src/Composer/Package/Link.php | 6 +- src/Composer/Package/Loader/ArrayLoader.php | 14 +- .../Package/Loader/LoaderInterface.php | 2 +- .../Package/Loader/RootPackageLoader.php | 6 +- .../Package/Loader/ValidatingArrayLoader.php | 14 +- src/Composer/Package/Locker.php | 10 +- src/Composer/Package/Package.php | 58 ++-- src/Composer/Package/PackageInterface.php | 40 ++- src/Composer/Package/RootAliasPackage.php | 2 +- src/Composer/Package/RootPackage.php | 14 +- src/Composer/Package/RootPackageInterface.php | 4 +- .../Package/Version/StabilityFilter.php | 2 +- .../Package/Version/VersionGuesser.php | 16 +- .../Package/Version/VersionParser.php | 2 +- .../Package/Version/VersionSelector.php | 4 +- src/Composer/Platform/Runtime.php | 16 +- src/Composer/Platform/Version.php | 16 +- src/Composer/Plugin/CommandEvent.php | 2 +- src/Composer/Plugin/PluginManager.php | 16 +- src/Composer/Plugin/PostFileDownloadEvent.php | 4 +- src/Composer/Plugin/PreCommandRunEvent.php | 2 +- src/Composer/Plugin/PreFileDownloadEvent.php | 6 +- src/Composer/Plugin/PrePoolCreateEvent.php | 2 +- .../Question/StrictConfirmationQuestion.php | 2 +- src/Composer/Repository/ArrayRepository.php | 4 +- .../Repository/ArtifactRepository.php | 2 +- .../Repository/ComposerRepository.php | 33 ++- .../Repository/CompositeRepository.php | 2 +- .../Repository/FilesystemRepository.php | 11 +- src/Composer/Repository/FilterRepository.php | 4 +- .../Repository/InstalledRepository.php | 4 +- .../Repository/PlatformRepository.php | 14 +- src/Composer/Repository/RepositoryFactory.php | 4 +- .../Repository/RepositoryInterface.php | 14 +- src/Composer/Repository/RepositoryManager.php | 8 +- src/Composer/Repository/RepositorySet.php | 14 +- src/Composer/Repository/Vcs/FossilDriver.php | 10 +- .../Repository/Vcs/GitBitbucketDriver.php | 16 +- src/Composer/Repository/Vcs/GitDriver.php | 10 +- src/Composer/Repository/Vcs/GitHubDriver.php | 16 +- src/Composer/Repository/Vcs/GitLabDriver.php | 20 +- src/Composer/Repository/Vcs/HgDriver.php | 10 +- .../Repository/Vcs/PerforceDriver.php | 16 +- src/Composer/Repository/Vcs/SvnDriver.php | 20 +- src/Composer/Repository/Vcs/VcsDriver.php | 10 +- .../Repository/Vcs/VcsDriverInterface.php | 14 +- src/Composer/Repository/VcsRepository.php | 8 +- .../Repository/VersionCacheInterface.php | 2 +- .../Repository/WritableArrayRepository.php | 1 - .../WritableRepositoryInterface.php | 2 +- src/Composer/Script/Event.php | 2 +- src/Composer/SelfUpdate/Keys.php | 2 +- src/Composer/SelfUpdate/Versions.php | 4 +- src/Composer/Util/AuthHelper.php | 8 +- src/Composer/Util/Bitbucket.php | 12 +- src/Composer/Util/ComposerMirror.php | 6 +- src/Composer/Util/ConfigValidator.php | 2 +- src/Composer/Util/ErrorHandler.php | 2 +- src/Composer/Util/Filesystem.php | 70 ++--- src/Composer/Util/Git.php | 14 +- src/Composer/Util/GitHub.php | 4 +- src/Composer/Util/GitLab.php | 6 +- src/Composer/Util/Hg.php | 4 +- src/Composer/Util/Http/CurlDownloader.php | 18 +- src/Composer/Util/Http/ProxyHelper.php | 10 +- src/Composer/Util/Http/ProxyManager.php | 4 +- src/Composer/Util/Http/RequestProxy.php | 4 +- src/Composer/Util/Http/Response.php | 8 +- src/Composer/Util/HttpDownloader.php | 26 +- src/Composer/Util/NoProxyPattern.php | 28 +- src/Composer/Util/Perforce.php | 36 +-- src/Composer/Util/Platform.php | 36 ++- src/Composer/Util/ProcessExecutor.php | 24 +- src/Composer/Util/RemoteFilesystem.php | 18 +- src/Composer/Util/Silencer.php | 9 +- src/Composer/Util/StreamContextFactory.php | 4 +- src/Composer/Util/Svn.php | 33 +-- src/Composer/Util/SyncHelper.php | 2 +- src/Composer/Util/Tar.php | 2 +- src/Composer/Util/TlsHelper.php | 6 +- src/Composer/Util/Url.php | 6 +- src/Composer/Util/Zip.php | 4 +- src/bootstrap.php | 2 +- tests/Composer/Test/AllFunctionalTest.php | 9 +- tests/Composer/Test/ApplicationTest.php | 2 +- .../Test/Autoload/AutoloadGeneratorTest.php | 8 +- .../Test/Autoload/ClassLoaderTest.php | 2 +- .../Test/Autoload/ClassMapGeneratorTest.php | 4 +- .../Test/Command/ArchiveCommandTest.php | 3 +- .../Test/Command/RunScriptCommandTest.php | 2 +- .../Test/Config/JsonConfigSourceTest.php | 10 +- tests/Composer/Test/ConfigTest.php | 8 +- .../DependencyResolver/PoolBuilderTest.php | 9 +- .../DependencyResolver/PoolOptimizerTest.php | 4 +- .../Test/DependencyResolver/PoolTest.php | 2 +- .../Test/Downloader/ArchiveDownloaderTest.php | 4 +- .../Test/Downloader/DownloadManagerTest.php | 6 +- .../Test/Downloader/FileDownloaderTest.php | 249 +++++------------- .../Test/Downloader/FossilDownloaderTest.php | 4 +- .../Test/Downloader/GitDownloaderTest.php | 10 +- .../Test/Downloader/HgDownloaderTest.php | 2 +- .../Downloader/PerforceDownloaderTest.php | 11 +- .../Test/Downloader/XzDownloaderTest.php | 27 +- .../Test/Downloader/ZipDownloaderTest.php | 2 +- .../EventDispatcher/EventDispatcherTest.php | 8 +- ...IgnoreAllPlatformRequirementFilterTest.php | 2 +- ...gnoreListPlatformRequirementFilterTest.php | 2 +- ...reNothingPlatformRequirementFilterTest.php | 2 +- tests/Composer/Test/InstalledVersionsTest.php | 18 +- .../Test/Installer/BinaryInstallerTest.php | 2 +- tests/Composer/Test/InstallerTest.php | 77 +++--- .../Composer/Test/Json/ComposerSchemaTest.php | 2 +- tests/Composer/Test/Json/JsonFileTest.php | 4 +- .../Test/Json/JsonManipulatorTest.php | 10 +- .../Test/Json/JsonValidationExceptionTest.php | 4 +- tests/Composer/Test/Mock/FactoryMock.php | 2 - .../Test/Mock/ProcessExecutorMock.php | 10 +- .../Archiver/ArchivableFilesFinderTest.php | 4 +- .../Package/Archiver/ArchiveManagerTest.php | 5 +- .../Test/Package/Archiver/ArchiverTest.php | 2 +- .../Package/Archiver/GitExcludeFilterTest.php | 2 +- .../Package/Archiver/PharArchiverTest.php | 5 +- .../Test/Package/Archiver/ZipArchiverTest.php | 8 +- .../Composer/Test/Package/BasePackageTest.php | 4 +- .../Test/Package/CompletePackageTest.php | 6 +- .../Test/Package/Dumper/ArrayDumperTest.php | 4 +- .../Test/Package/Loader/ArrayLoaderTest.php | 10 +- .../Package/Loader/RootPackageLoaderTest.php | 2 +- .../Loader/ValidatingArrayLoaderTest.php | 8 +- .../Package/Version/VersionParserTest.php | 4 +- .../Package/Version/VersionSelectorTest.php | 4 +- tests/Composer/Test/Platform/VersionTest.php | 6 +- .../Test/Plugin/PluginInstallerTest.php | 32 +-- .../StrictConfirmationQuestionTest.php | 8 +- .../Repository/ComposerRepositoryTest.php | 2 +- .../Repository/CompositeRepositoryTest.php | 2 +- .../Test/Repository/FilterRepositoryTest.php | 2 +- .../Test/Repository/PathRepositoryTest.php | 3 +- .../Repository/PlatformRepositoryTest.php | 10 +- .../Test/Repository/RepositoryManagerTest.php | 15 +- .../Test/Repository/Vcs/FossilDriverTest.php | 2 +- .../Repository/Vcs/GitBitbucketDriverTest.php | 4 +- .../Test/Repository/Vcs/GitHubDriverTest.php | 4 +- .../Test/Repository/Vcs/GitLabDriverTest.php | 8 +- .../Test/Repository/Vcs/HgDriverTest.php | 2 +- .../Repository/Vcs/PerforceDriverTest.php | 2 +- .../Test/Repository/Vcs/SvnDriverTest.php | 2 +- .../Test/Repository/VcsRepositoryTest.php | 5 +- tests/Composer/Test/TestCase.php | 30 ++- tests/Composer/Test/Util/AuthHelperTest.php | 10 +- tests/Composer/Test/Util/BitbucketTest.php | 4 +- tests/Composer/Test/Util/FilesystemTest.php | 6 +- tests/Composer/Test/Util/GitTest.php | 6 +- .../Test/Util/Http/ProxyHelperTest.php | 12 +- .../Test/Util/Http/ProxyManagerTest.php | 8 +- .../Test/Util/Http/RequestProxyTest.php | 4 +- .../Composer/Test/Util/NoProxyPatternTest.php | 10 +- .../Composer/Test/Util/PackageSorterTest.php | 4 +- tests/Composer/Test/Util/PerforceTest.php | 4 +- .../Test/Util/ProcessExecutorTest.php | 4 +- .../Test/Util/RemoteFilesystemTest.php | 12 +- .../Test/Util/StreamContextFactoryTest.php | 4 +- tests/Composer/Test/Util/SvnTest.php | 2 +- tests/Composer/Test/Util/TlsHelperTest.php | 2 +- tests/Composer/Test/Util/UrlTest.php | 4 +- 279 files changed, 1377 insertions(+), 1504 deletions(-) diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index e2c430166..8e567fe0c 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -16,8 +16,8 @@ $finder = PhpCsFixer\Finder::create() ->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 @@ return $config->setRules([ '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 f9156245f..59e420f3a 100755 --- a/bin/compile +++ b/bin/compile @@ -2,6 +2,7 @@ devMode = (bool) $devMode; } @@ -100,7 +100,7 @@ class AutoloadGenerator * @param bool $classMapAuthoritative * @return void */ - public function setClassMapAuthoritative($classMapAuthoritative) + public function setClassMapAuthoritative(bool $classMapAuthoritative) { $this->classMapAuthoritative = (bool) $classMapAuthoritative; } @@ -112,7 +112,7 @@ class AutoloadGenerator * @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 @@ class AutoloadGenerator * @param bool $runScripts * @return void */ - public function setRunScripts($runScripts = true) + public function setRunScripts(bool $runScripts = true) { $this->runScripts = (bool) $runScripts; } @@ -163,7 +163,7 @@ class AutoloadGenerator * @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 @@ class AutoloadGenerator // 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 @@ EOF; * @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 @@ EOF; /** * @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 @@ EOF; * 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 @@ EOF; * @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 @@ EOF; * @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 @@ EOF; * @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 @@ EOF; * @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 @@ PLATFORM_CHECK; * @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 @@ AUTOLOAD; /** * @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 @@ AUTOLOAD; * @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 @@ INITIALIZER; $path ); if (empty($installPath)) { - $installPath = strtr(getcwd(), '\\', '/'); + $installPath = strtr(Platform::getCwd(), '\\', '/'); } $resolvedPath = realpath($installPath . '/' . $updir); @@ -1271,7 +1271,7 @@ INITIALIZER; * @param string $path * @return string */ - protected function getFileIdentifier(PackageInterface $package, $path) + protected function getFileIdentifier(PackageInterface $package, string $path) { return md5($package->getName() . ':' . $path); } @@ -1369,7 +1369,7 @@ INITIALIZER; * @param string $file * @return void */ -function composerRequire($fileIdentifier, $file) +function composerRequire(string $fileIdentifier, string $file) { 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 8a2db5681..84f946440 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 @@ class ClassMapGenerator * @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 @@ class ClassMapGenerator $map = array(); $filesystem = new Filesystem(); - $cwd = realpath(getcwd()); + $cwd = realpath(Platform::getCwd()); foreach ($path as $file) { $filePath = $file->getPathname(); @@ -157,7 +158,7 @@ class ClassMapGenerator * @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 @@ class ClassMapGenerator 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 @@ class ClassMapGenerator * @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 8fc077418..f1e6048b2 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 @@ class PhpFileCleaner * @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 @@ class PhpFileCleaner * @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 @@ class PhpFileCleaner * @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 @@ class PhpFileCleaner * @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 64c016f31..0f8dc6aa4 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 @@ class Cache * * @return void */ - public function setReadOnly($readOnly) + public function setReadOnly(bool $readOnly) { $this->readOnly = (bool) $readOnly; } @@ -84,7 +84,7 @@ class Cache * * @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 @@ class Cache * * @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 @@ class Cache * * @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 @@ class Cache * * @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 @@ class Cache * * @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 @@ class Cache * * @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 @@ class Cache * @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 @@ class Cache * * @return bool */ - public function gc($ttl, $maxSize) + public function gc(int $ttl, int $maxSize) { if ($this->isEnabled()) { $expire = new \DateTime(); @@ -340,7 +340,7 @@ class Cache * * @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 @@ class Cache * * @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 b785f4ea4..db302b865 100644 --- a/src/Composer/Command/ArchiveCommand.php +++ b/src/Composer/Command/ArchiveCommand.php @@ -25,6 +25,7 @@ use Composer\Plugin\CommandEvent; 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 @@ EOT $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 @@ EOT * * @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 22a290c1d..c06e3ffa5 100644 --- a/src/Composer/Command/BaseCommand.php +++ b/src/Composer/Command/BaseCommand.php @@ -70,7 +70,7 @@ abstract class BaseCommand extends Command * @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 @@ abstract class BaseCommand extends Command * * @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 224d2739e..c2597e7c7 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 @@ class BaseDependencyCommand extends BaseCommand * * @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 @@ class BaseDependencyCommand extends BaseCommand * * @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 8e525e7bf..54e1e9ba1 100644 --- a/src/Composer/Command/CheckPlatformReqsCommand.php +++ b/src/Composer/Command/CheckPlatformReqsCommand.php @@ -174,7 +174,7 @@ EOT * * @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 3e51a4599..3285fd3b4 100644 --- a/src/Composer/Command/ConfigCommand.php +++ b/src/Composer/Command/ConfigCommand.php @@ -175,7 +175,7 @@ EOT 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 @@ EOT * * @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 @@ EOT * * @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 @@ EOT * * @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 d7dcaeaae..4b185a644 100644 --- a/src/Composer/Command/CreateProjectCommand.php +++ b/src/Composer/Command/CreateProjectCommand.php @@ -187,9 +187,9 @@ EOT * @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 @@ EOT ) ) { $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 @@ EOT * @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 @@ EOT // 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 75bec936a..dc4166e05 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -245,7 +245,7 @@ EOT * * @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 @@ EOT * * @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 @@ EOT * @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 8ff06afd4..ac3ed11ab 100644 --- a/src/Composer/Command/ExecCommand.php +++ b/src/Composer/Command/ExecCommand.php @@ -95,7 +95,7 @@ EOT // 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 b83f31e03..798d654df 100644 --- a/src/Composer/Command/HomeCommand.php +++ b/src/Composer/Command/HomeCommand.php @@ -101,7 +101,7 @@ EOT * @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 @@ EOT * @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 8b67c26ab..896e45dca 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -460,7 +460,7 @@ EOT * @param string $author * @return array{name: string, email: string|null} */ - public function parseAuthorString($author) + public function parseAuthorString(string $author) { if (Preg::isMatch('/^(?P[- .,\p{L}\p{N}\p{Mn}\'’"()]+)(?:\s+<(?P.+?)>)?$/u', $author, $match)) { $hasEmail = isset($match['email']) && '' !== $match['email']; @@ -485,7 +485,7 @@ EOT * * @return array */ - protected function formatAuthors($author) + protected function formatAuthors(string $author) { $author = $this->parseAuthorString($author); if (null === $author['email']) { @@ -504,7 +504,7 @@ EOT * * @return string|null */ - public function namespaceFromPackageName($packageName) + public function namespaceFromPackageName(string $packageName) { if (!$packageName || strpos($packageName, '/') === false) { return null; @@ -567,7 +567,7 @@ EOT * * @return bool */ - protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor') + protected function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor') { if (!file_exists($ignoreFile)) { return false; @@ -591,7 +591,7 @@ EOT * * @return void */ - protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/') + protected function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/') { $contents = ""; if (file_exists($ignoreFile)) { @@ -610,7 +610,7 @@ EOT * * @return bool */ - protected function isValidEmail($email) + protected function isValidEmail(string $email) { // assume it's valid if we can't validate it if (!function_exists('filter_var')) { @@ -652,7 +652,7 @@ EOT * @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 f59034282..b51292742 100644 --- a/src/Composer/Command/LicensesCommand.php +++ b/src/Composer/Command/LicensesCommand.php @@ -163,7 +163,7 @@ EOT * @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 5ad66a794..5aa890f02 100644 --- a/src/Composer/Command/RequireCommand.php +++ b/src/Composer/Command/RequireCommand.php @@ -296,7 +296,7 @@ EOT * @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(); @@ -351,7 +351,7 @@ EOT * @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(); @@ -449,7 +449,7 @@ EOT * @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 +480,7 @@ EOT * @param bool $hardExit * @return void */ - public function revertComposerFile($hardExit = true) + public function revertComposerFile(bool $hardExit = true) { $io = $this->getIO(); diff --git a/src/Composer/Command/ScriptAliasCommand.php b/src/Composer/Command/ScriptAliasCommand.php index 2c98c9a66..793127f8c 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 06b0d2d0d..38c0e4cdd 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -397,7 +397,7 @@ TAGSPUBKEY * @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 @@ TAGSPUBKEY * @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 @@ TAGSPUBKEY * * @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 @@ TAGSPUBKEY * @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 @@ TAGSPUBKEY * @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 @@ TAGSPUBKEY * @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 @@ TAGSPUBKEY * @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 ae9350f1e..36fb376dd 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -223,7 +223,7 @@ EOT 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)))); } @@ -628,7 +628,7 @@ EOT * @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) { $name = strtolower($name); $constraint = is_string($version) ? $this->versionParser->parseConstraints($version) : $version; @@ -802,7 +802,7 @@ EOT * * @return void */ - protected function printLinks(CompletePackageInterface $package, $linkType, $title = null) + protected function printLinks(CompletePackageInterface $package, string $linkType, string $title = null) { $title = $title ?: $linkType; $io = $this->getIO(); @@ -923,7 +923,7 @@ EOT * @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 @@ EOT * @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 @@ EOT * @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 @@ EOT * @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 @@ EOT * @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)}(); @@ -1147,8 +1147,8 @@ EOT protected function displayTree( $package, array $packagesInTree, - $previousTreeBar = '├', - $level = 1 + string $previousTreeBar = '├', + int $level = 1 ) { $previousTreeBar = str_replace('├', '│', $previousTreeBar); if (is_array($package) && isset($package['requires'])) { @@ -1197,7 +1197,7 @@ EOT * @return array>|string>> */ protected function addTree( - $name, + string $name, Link $link, InstalledRepository $installedRepo, RepositoryInterface $remoteRepos, @@ -1240,7 +1240,7 @@ EOT * @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 @@ EOT * * @return void */ - private function writeTreeLine($line): void + private function writeTreeLine(string $line): void { $io = $this->getIO(); if (!$io->isDecorated()) { @@ -1342,7 +1342,7 @@ EOT * @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 39decf788..2250f225a 100644 --- a/src/Composer/Command/UpdateCommand.php +++ b/src/Composer/Command/UpdateCommand.php @@ -312,7 +312,7 @@ EOT * @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 8c5ad5aea..e91008f5c 100644 --- a/src/Composer/Command/ValidateCommand.php +++ b/src/Composer/Command/ValidateCommand.php @@ -169,7 +169,7 @@ EOT * * @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 6bf250468..76bc5ce7c 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 @@ class Compiler * @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 @@ class Compiler * * @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 @@ class Compiler * @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 24423a0a4..935cd38da 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 @@ class Config $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 @@ class Config * * @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 @@ class Config * * @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 @@ class Config * * @return array */ - public function all($flags = 0): array + public function all(int $flags = 0): array { $all = array( 'repositories' => $this->getRepositories(), @@ -457,7 +457,7 @@ class Config * @param string $key * @return string */ - public function getSourceOfValue($key): string + public function getSourceOfValue(string $key): string { $this->get($key); @@ -471,7 +471,7 @@ class Config * * @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 @@ class Config * @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 @@ class Config * * @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 @@ class Config * @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 @@ class Config * @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 @@ class Config * * @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 @@ class Config * * @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 a50975442..206f8158c 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); /** * Remove a repository @@ -38,7 +38,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeRepository($name); + public function removeRepository(string $name); /** * Add a config setting @@ -48,7 +48,7 @@ interface ConfigSourceInterface * * @return void */ - public function addConfigSetting($name, $value); + public function addConfigSetting(string $name, $value); /** * Remove a config setting @@ -57,7 +57,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeConfigSetting($name); + public function removeConfigSetting(string $name); /** * Add a property @@ -67,7 +67,7 @@ interface ConfigSourceInterface * * @return void */ - public function addProperty($name, $value); + public function addProperty(string $name, $value); /** * Remove a property @@ -76,7 +76,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeProperty($name); + public function removeProperty(string $name); /** * Add a package link @@ -87,7 +87,7 @@ interface ConfigSourceInterface * * @return void */ - public function addLink($type, $name, $value); + public function addLink(string $type, string $name, string $value); /** * Remove a package link @@ -97,7 +97,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeLink($type, $name); + public function removeLink(string $type, string $name); /** * Gives a user-friendly name to this source (file path or so) diff --git a/src/Composer/Config/JsonConfigSource.php b/src/Composer/Config/JsonConfigSource.php index 84de4f32c..a70471997 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; @@ -214,7 +214,7 @@ class JsonConfigSource implements ConfigSourceInterface * * @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 @@ class JsonConfigSource implements ConfigSourceInterface * @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 5bf8f6ffc..9560eef57 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 @@ class Application extends BaseApplication // 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 @@ class Application extends BaseApplication // 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 @@ class Application extends BaseApplication } 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 @@ class Application extends BaseApplication $result = parent::doRun($input, $output); // chdir back to $oldWorkingDir if set - if (isset($oldWorkingDir)) { + if (isset($oldWorkingDir) && '' !== $oldWorkingDir) { Silencer::call('chdir', $oldWorkingDir); } @@ -424,7 +425,7 @@ class Application extends BaseApplication * @throws \InvalidArgumentException * @return ?\Composer\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) { if (null === $disablePlugins) { $disablePlugins = $this->disablePluginsByDefault; @@ -585,7 +586,7 @@ class Application extends BaseApplication /** * 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 578ac8eca..d73b55851 100644 --- a/src/Composer/Console/GithubActionError.php +++ b/src/Composer/Console/GithubActionError.php @@ -34,7 +34,7 @@ final class GithubActionError * * @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 @@ final class GithubActionError * @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 @@ final class GithubActionError * @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 8740cf7bf..837488681 100644 --- a/src/Composer/DependencyResolver/Decisions.php +++ b/src/Composer/DependencyResolver/Decisions.php @@ -43,7 +43,7 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @param int $literal * @return bool */ - public function satisfy($literal): bool + public function satisfy(int $literal): bool { $packageId = abs($literal); @@ -70,7 +70,7 @@ class Decisions implements \Iterator, \Countable * @param int $literal * @return bool */ - public function conflict($literal): bool + public function conflict(int $literal): bool { $packageId = abs($literal); @@ -84,7 +84,7 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @param int $literalOrPackageId * @return bool */ - public function decidedInstall($literalOrPackageId): bool + public function decidedInstall(int $literalOrPackageId): bool { $packageId = abs($literalOrPackageId); @@ -113,7 +113,7 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @param int $literalOrPackageId * @return Rule|null */ - public function decisionRule($literalOrPackageId): ?Rule + public function decisionRule(int $literalOrPackageId): ?Rule { $packageId = abs($literalOrPackageId); @@ -144,7 +144,7 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @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 @@ class Decisions implements \Iterator, \Countable * @param int $level * @return void */ - protected function addDecision($literal, $level): void + protected function addDecision(int $literal, int $level): void { $packageId = abs($literal); diff --git a/src/Composer/DependencyResolver/DefaultPolicy.php b/src/Composer/DependencyResolver/DefaultPolicy.php index e9add445f..e7610eb22 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 @@ class DefaultPolicy implements 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 { if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) { return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB]; @@ -61,7 +61,7 @@ class DefaultPolicy implements PolicyInterface * @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 @@ class DefaultPolicy implements PolicyInterface * @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 @@ class DefaultPolicy implements PolicyInterface /** * @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 @@ class DefaultPolicy implements PolicyInterface * @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/LockTransaction.php b/src/Composer/DependencyResolver/LockTransaction.php index 4d04a5cd6..3b3da5df2 100644 --- a/src/Composer/DependencyResolver/LockTransaction.php +++ b/src/Composer/DependencyResolver/LockTransaction.php @@ -106,7 +106,7 @@ class LockTransaction extends Transaction * @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 @@ class LockTransaction extends Transaction 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 @@ class LockTransaction extends Transaction * @param array $aliases * @return array */ - public function getAliases($aliases): array + public function getAliases(array $aliases): array { $usedAliases = array(); diff --git a/src/Composer/DependencyResolver/Operation/InstallOperation.php b/src/Composer/DependencyResolver/Operation/InstallOperation.php index 1fe8c0d36..40d0e698d 100644 --- a/src/Composer/DependencyResolver/Operation/InstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/InstallOperation.php @@ -55,7 +55,7 @@ class InstallOperation extends SolverOperation implements OperationInterface * @param bool $lock * @return string */ - public static function format(PackageInterface $package, $lock = false) + public static function format(PackageInterface $package, bool $lock = false) { 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 b0cc29b6d..4cc70987d 100644 --- a/src/Composer/DependencyResolver/Operation/OperationInterface.php +++ b/src/Composer/DependencyResolver/Operation/OperationInterface.php @@ -32,7 +32,7 @@ interface OperationInterface * @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/UninstallOperation.php b/src/Composer/DependencyResolver/Operation/UninstallOperation.php index 35e7ed753..7b4ff8ddb 100644 --- a/src/Composer/DependencyResolver/Operation/UninstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/UninstallOperation.php @@ -55,7 +55,7 @@ class UninstallOperation extends SolverOperation implements OperationInterface * @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 dbfb3d310..e674376f5 100644 --- a/src/Composer/DependencyResolver/Operation/UpdateOperation.php +++ b/src/Composer/DependencyResolver/Operation/UpdateOperation.php @@ -76,7 +76,7 @@ class UpdateOperation extends SolverOperation implements OperationInterface * @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 4651ceb4d..714041dc0 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 9a1a73b3c..94c895c28 100644 --- a/src/Composer/DependencyResolver/Pool.php +++ b/src/Composer/DependencyResolver/Pool.php @@ -60,7 +60,7 @@ class Pool implements \Countable * @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 @@ class Pool implements \Countable * @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 @@ class Pool implements \Countable * @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 @@ class Pool implements \Countable * 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 @@ class Pool implements \Countable * 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 @@ class Pool implements \Countable * @param int $literal * @return BasePackage */ - public function literalToPackage($literal): BasePackage + public function literalToPackage(int $literal): BasePackage { $packageId = abs($literal); @@ -192,7 +192,7 @@ class Pool implements \Countable * @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 @@ class Pool implements \Countable * @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(); diff --git a/src/Composer/DependencyResolver/PoolBuilder.php b/src/Composer/DependencyResolver/PoolBuilder.php index 9766557e6..52c831dc5 100644 --- a/src/Composer/DependencyResolver/PoolBuilder.php +++ b/src/Composer/DependencyResolver/PoolBuilder.php @@ -300,7 +300,7 @@ class PoolBuilder * @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 @@ class PoolBuilder * @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 @@ class PoolBuilder * @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 @@ class PoolBuilder * @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 @@ class PoolBuilder * @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 @@ class PoolBuilder * @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 5c77eda79..6d9b1dd12 100644 --- a/src/Composer/DependencyResolver/PoolOptimizer.php +++ b/src/Composer/DependencyResolver/PoolOptimizer.php @@ -322,7 +322,7 @@ class PoolOptimizer * @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 @@ class PoolOptimizer * @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 77e2975c8..44ad896a9 100644 --- a/src/Composer/DependencyResolver/Problem.php +++ b/src/Composer/DependencyResolver/Problem.php @@ -77,7 +77,7 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 @@ class Problem * @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 508a8f0b2..dde4972f5 100644 --- a/src/Composer/DependencyResolver/Request.php +++ b/src/Composer/DependencyResolver/Request.php @@ -64,7 +64,7 @@ class Request * @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 @@ class Request * @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 @@ class Request * 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 1e2d08daa..c1cc491d2 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -267,7 +267,7 @@ abstract class Rule * @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 @@ abstract class Rule * @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 f07d011fc..cbb40b220 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); diff --git a/src/Composer/DependencyResolver/RuleSet.php b/src/Composer/DependencyResolver/RuleSet.php index 68c2b7905..9fe82e24e 100644 --- a/src/Composer/DependencyResolver/RuleSet.php +++ b/src/Composer/DependencyResolver/RuleSet.php @@ -112,7 +112,7 @@ class RuleSet implements \IteratorAggregate, \Countable * @param int $id * @return Rule */ - public function ruleById($id): Rule + public function ruleById(int $id): Rule { return $this->ruleById[$id]; } @@ -181,7 +181,7 @@ class RuleSet implements \IteratorAggregate, \Countable * @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) { diff --git a/src/Composer/DependencyResolver/RuleSetGenerator.php b/src/Composer/DependencyResolver/RuleSetGenerator.php index 71f86864b..d170db1e3 100644 --- a/src/Composer/DependencyResolver/RuleSetGenerator.php +++ b/src/Composer/DependencyResolver/RuleSetGenerator.php @@ -80,7 +80,7 @@ class RuleSetGenerator * @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 a54032686..f6bab3547 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 03da05ce2..0b74a9888 100644 --- a/src/Composer/DependencyResolver/RuleWatchGraph.php +++ b/src/Composer/DependencyResolver/RuleWatchGraph.php @@ -88,7 +88,7 @@ class RuleWatchGraph * 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 @@ class RuleWatchGraph * @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 136ac4a86..d1e027cd2 100644 --- a/src/Composer/DependencyResolver/RuleWatchNode.php +++ b/src/Composer/DependencyResolver/RuleWatchNode.php @@ -91,7 +91,7 @@ class RuleWatchNode * @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 @@ class RuleWatchNode * @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 43f253969..e90c3b67e 100644 --- a/src/Composer/DependencyResolver/Solver.php +++ b/src/Composer/DependencyResolver/Solver.php @@ -233,7 +233,7 @@ class Solver * @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 @@ class Solver * * @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 @@ class Solver * @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 @@ class Solver * @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 @@ class Solver * @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 31932a265..0a8d453ee 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 fb5dfdde8..9e4896e07 100644 --- a/src/Composer/DependencyResolver/SolverProblemsException.php +++ b/src/Composer/DependencyResolver/SolverProblemsException.php @@ -46,7 +46,7 @@ class SolverProblemsException extends \RuntimeException * @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 2d3272c51..184855e73 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 @@ class Transaction * @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 152dfb9c4..b44d280b5 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; @@ -34,7 +35,7 @@ abstract class ArchiveDownloader extends FileDownloader /** * @return PromiseInterface|null */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { unset($this->cleanupExecuted[$package->getName()]); @@ -44,7 +45,7 @@ abstract class ArchiveDownloader extends FileDownloader /** * @return PromiseInterface|null */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { $this->cleanupExecuted[$package->getName()] = true; @@ -61,7 +62,7 @@ abstract class ArchiveDownloader extends FileDownloader * @throws \RuntimeException * @throws \UnexpectedValueException */ - public function install(PackageInterface $package, $path, $output = true) + public function install(PackageInterface $package, string $path, bool $output = true) { if ($output) { $this->io->writeError(" - " . InstallOperation::format($package) . $this->getInstallOperationAppendix($package, $path)); @@ -83,7 +84,7 @@ abstract class ArchiveDownloader extends FileDownloader $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 @@ abstract class ArchiveDownloader extends FileDownloader // 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); @@ -214,7 +215,7 @@ abstract class ArchiveDownloader extends FileDownloader /** * @inheritDoc */ - protected function getInstallOperationAppendix(PackageInterface $package, $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path) { return ': Extracting archive'; } @@ -228,5 +229,5 @@ abstract class ArchiveDownloader extends FileDownloader * @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); } diff --git a/src/Composer/Downloader/ChangeReportInterface.php b/src/Composer/Downloader/ChangeReportInterface.php index 3fb1dc5d0..60d6efe74 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); } diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index 41e61e0ad..da786378a 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 @@ class DownloadManager * @param bool $preferSource prefer downloading from source * @return DownloadManager */ - public function setPreferSource($preferSource): DownloadManager + public function setPreferSource(bool $preferSource): DownloadManager { $this->preferSource = $preferSource; @@ -72,7 +72,7 @@ class DownloadManager * @param bool $preferDist prefer downloading from dist * @return DownloadManager */ - public function setPreferDist($preferDist): DownloadManager + public function setPreferDist(bool $preferDist): DownloadManager { $this->preferDist = $preferDist; @@ -100,7 +100,7 @@ class DownloadManager * @param DownloaderInterface $downloader downloader instance * @return DownloadManager */ - public function setDownloader($type, DownloaderInterface $downloader): DownloadManager + public function setDownloader(string $type, DownloaderInterface $downloader): DownloadManager { $type = strtolower($type); $this->downloaders[$type] = $downloader; @@ -115,7 +115,7 @@ class DownloadManager * @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 @@ class DownloadManager * @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)); @@ -253,7 +253,7 @@ class DownloadManager * * @return PromiseInterface|null */ - 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); @@ -274,7 +274,7 @@ class DownloadManager * @throws \RuntimeException * @return PromiseInterface|null */ - public function install(PackageInterface $package, $targetDir): ?PromiseInterface + public function install(PackageInterface $package, string $targetDir): ?PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -295,7 +295,7 @@ class DownloadManager * @throws \InvalidArgumentException if initial package is not installed * @return PromiseInterface|null */ - 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); @@ -336,7 +336,7 @@ class DownloadManager if ($promise instanceof PromiseInterface) { return $promise; } - + return \React\Promise\resolve(); }); } @@ -352,7 +352,7 @@ class DownloadManager * * @return PromiseInterface|null */ - public function remove(PackageInterface $package, $targetDir): ?PromiseInterface + public function remove(PackageInterface $package, string $targetDir): ?PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -373,7 +373,7 @@ class DownloadManager * * @return PromiseInterface|null */ - 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 +461,7 @@ class DownloadManager * * @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 b19f902a8..1796754a3 100644 --- a/src/Composer/Downloader/DownloaderInterface.php +++ b/src/Composer/Downloader/DownloaderInterface.php @@ -36,7 +36,7 @@ interface DownloaderInterface * @param string $path download path * @return PromiseInterface|null */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null); /** * Do anything that needs to be done between all downloads have been completed and the actual operation is executed @@ -52,7 +52,7 @@ interface DownloaderInterface * @param PackageInterface $prevPackage previous package instance in case of an update * @return PromiseInterface|null */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null); /** * Installs specific package into specific folder. @@ -61,7 +61,7 @@ interface DownloaderInterface * @param string $path download path * @return PromiseInterface|null */ - public function install(PackageInterface $package, $path); + public function install(PackageInterface $package, string $path); /** * Updates specific package in specific folder from initial to target version. @@ -71,7 +71,7 @@ interface DownloaderInterface * @param string $path download path * @return PromiseInterface|null */ - public function update(PackageInterface $initial, PackageInterface $target, $path); + public function update(PackageInterface $initial, PackageInterface $target, string $path); /** * Removes specific package from specific folder. @@ -80,7 +80,7 @@ interface DownloaderInterface * @param string $path download path * @return PromiseInterface|null */ - public function remove(PackageInterface $package, $path); + public function remove(PackageInterface $package, string $path); /** * Do anything to cleanup changes applied in the prepare or install/update/uninstall steps @@ -95,5 +95,5 @@ interface DownloaderInterface * @param PackageInterface $prevPackage previous package instance in case of an update * @return PromiseInterface|null */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null); + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null); } diff --git a/src/Composer/Downloader/DvcsDownloaderInterface.php b/src/Composer/Downloader/DvcsDownloaderInterface.php index 7fbd4ee3e..8f70472b7 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); } diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index ab347d23d..c871ee47f 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -27,6 +27,7 @@ use Composer\Plugin\PostFileDownloadEvent; 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; @@ -112,7 +113,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @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) { if (!$package->getDistUrl()) { throw new \InvalidArgumentException('The given package is missing url information'); @@ -295,7 +296,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { return \React\Promise\resolve(); } @@ -303,7 +304,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { $fileName = $this->getFileName($package, $path); if (file_exists($fileName)) { @@ -323,7 +324,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface } 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 +337,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @param bool $output */ - public function install(PackageInterface $package, $path, $output = true) + public function install(PackageInterface $package, string $path, bool $output = true) { if ($output) { $this->io->writeError(" - " . InstallOperation::format($package)); @@ -375,7 +376,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @return void */ - protected function addCleanupPath(PackageInterface $package, $path) + protected function addCleanupPath(PackageInterface $package, string $path) { $this->additionalCleanupPaths[$package->getName()][] = $path; } @@ -385,7 +386,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @return void */ - protected function removeCleanupPath(PackageInterface $package, $path) + protected function removeCleanupPath(PackageInterface $package, string $path) { if (isset($this->additionalCleanupPaths[$package->getName()])) { $idx = array_search($path, $this->additionalCleanupPaths[$package->getName()]); @@ -398,7 +399,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, $path) + public function update(PackageInterface $initial, PackageInterface $target, string $path) { $this->io->writeError(" - " . UpdateOperation::format($initial, $target) . $this->getInstallOperationAppendix($target, $path)); @@ -422,7 +423,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @param bool $output */ - public function remove(PackageInterface $package, $path, $output = true) + public function remove(PackageInterface $package, string $path, bool $output = true) { if ($output) { $this->io->writeError(" - " . UninstallOperation::format($package)); @@ -443,7 +444,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @param string $path download path * @return string file name */ - protected function getFileName(PackageInterface $package, $path) + protected function getFileName(PackageInterface $package, string $path) { 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 +456,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @param string $path download path * @return string */ - protected function getInstallOperationAppendix(PackageInterface $package, $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path) { return ''; } @@ -468,7 +469,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @throws \RuntimeException If any problem with the url * @return string url */ - protected function processUrl(PackageInterface $package, $url) + protected function processUrl(PackageInterface $package, string $url) { if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) { throw new \RuntimeException('You must enable the openssl extension to download files via https'); @@ -485,7 +486,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @inheritDoc * @throws \RuntimeException */ - public function getLocalChanges(PackageInterface $package, $targetDir) + public function getLocalChanges(PackageInterface $package, string $targetDir) { $prevIO = $this->io; diff --git a/src/Composer/Downloader/FilesystemException.php b/src/Composer/Downloader/FilesystemException.php index f297e4b98..f9d4e6fbe 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 662828b84..57afb1752 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 @@ class FossilDownloader extends VcsDownloader /** * @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 @@ class FossilDownloader extends VcsDownloader /** * @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 @@ class FossilDownloader extends VcsDownloader /** * @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 @@ class FossilDownloader extends VcsDownloader /** * @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 @@ class FossilDownloader extends VcsDownloader /** * @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 7f7d74c9f..78775e6c3 100644 --- a/src/Composer/Downloader/GitDownloader.php +++ b/src/Composer/Downloader/GitDownloader.php @@ -58,7 +58,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null) + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null) { GitUtil::cleanEnv(); @@ -83,7 +83,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url) + protected function doInstall(PackageInterface $package, string $path, string $url) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -114,7 +114,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -213,7 +213,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path) + public function getLocalChanges(PackageInterface $package, string $path) { GitUtil::cleanEnv(); if (!$this->hasMetadataRepository($path)) { @@ -231,7 +231,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @return null|string */ - public function getUnpushedChanges(PackageInterface $package, $path) + public function getUnpushedChanges(PackageInterface $package, string $path) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -328,7 +328,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, $path, $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update) { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -415,7 +415,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function reapplyChanges($path) + protected function reapplyChanges(string $path) { $path = $this->normalizePath($path); if (!empty($this->hasStashedChanges[$path])) { @@ -438,7 +438,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * @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) { $force = !empty($this->hasDiscardedChanges[$path]) || !empty($this->hasStashedChanges[$path]) ? '-f ' : ''; @@ -505,7 +505,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return void */ - protected function updateOriginUrl($path, $url) + protected function updateOriginUrl(string $path, string $url) { $this->process->execute(sprintf('git remote set-url origin -- %s', ProcessExecutor::escape($url)), $output, $path); $this->setPushUrl($path, $url); @@ -517,7 +517,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return void */ - protected function setPushUrl($path, $url) + protected function setPushUrl(string $path, string $url) { // set push url for github projects if (Preg::isMatch('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) { @@ -534,7 +534,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path) + protected function getCommitLogs(string $fromReference, string $toReference, string $path) { $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function discardChanges($path) + protected function discardChanges(string $path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git clean -df && git reset --hard', $output, $path)) { @@ -572,7 +572,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function stashChanges($path) + protected function stashChanges(string $path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git stash --include-untracked', $output, $path)) { @@ -591,7 +591,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function viewDiff($path) + protected function viewDiff(string $path) { $path = $this->normalizePath($path); if (0 !== $this->process->execute('git diff HEAD', $output, $path)) { @@ -606,7 +606,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return string */ - protected function normalizePath($path) + protected function normalizePath(string $path) { if (Platform::isWindows() && strlen($path) > 0) { $basePath = $path; @@ -630,7 +630,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function hasMetadataRepository($path) + protected function hasMetadataRepository(string $path) { $path = $this->normalizePath($path); @@ -641,7 +641,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * @param string $reference * @return string */ - protected function getShortHash($reference) + protected function getShortHash(string $reference) { 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 5826078a0..b66aeb048 100644 --- a/src/Composer/Downloader/GzipDownloader.php +++ b/src/Composer/Downloader/GzipDownloader.php @@ -24,7 +24,7 @@ use Composer\Util\ProcessExecutor; */ 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 @@ class GzipDownloader extends ArchiveDownloader * * @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 d7db15a23..a9caf53a8 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 @@ class HgDownloader extends VcsDownloader /** * @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 @@ class HgDownloader extends VcsDownloader /** * @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 @@ class HgDownloader extends VcsDownloader /** * @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 @@ class HgDownloader extends VcsDownloader /** * @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 @@ class HgDownloader extends VcsDownloader /** * @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 9c24383c7..c58e7d67a 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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter } 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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter // 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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @inheritDoc */ - protected function getInstallOperationAppendix(PackageInterface $package, $path): string + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { $realUrl = realpath($package->getDistUrl()); diff --git a/src/Composer/Downloader/PerforceDownloader.php b/src/Composer/Downloader/PerforceDownloader.php index ae603a832..1f888b6b4 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 @@ class PerforceDownloader extends VcsDownloader /** * @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 @@ class PerforceDownloader extends VcsDownloader * * @return string|null */ - private function getLabelFromSourceReference($ref): ?string + private function getLabelFromSourceReference(string $ref): ?string { $pos = strpos($ref, '@'); if (false !== $pos) { @@ -74,7 +74,7 @@ class PerforceDownloader extends VcsDownloader * * @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 @@ class PerforceDownloader extends VcsDownloader /** * @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 @@ class PerforceDownloader extends VcsDownloader /** * @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 @@ class PerforceDownloader extends VcsDownloader /** * @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 @@ class PerforceDownloader extends VcsDownloader /** * @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 b91b2ec1e..b4a1d9c75 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 ea9c63604..af467ef5e 100644 --- a/src/Composer/Downloader/RarDownloader.php +++ b/src/Composer/Downloader/RarDownloader.php @@ -28,7 +28,7 @@ use RarArchive; */ 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 7dd58493e..f3418735b 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) { SvnUtil::cleanEnv(); $util = new SvnUtil($url, $this->io, $this->config, $this->process); @@ -45,7 +45,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, $path, $url) + protected function doInstall(PackageInterface $package, string $path, string $url) { SvnUtil::cleanEnv(); $ref = $package->getSourceReference(); @@ -67,7 +67,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url) { SvnUtil::cleanEnv(); $ref = $target->getSourceReference(); @@ -91,7 +91,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, $path) + public function getLocalChanges(PackageInterface $package, string $path) { if (!$this->hasMetadataRepository($path)) { return null; @@ -114,7 +114,7 @@ class SvnDownloader extends VcsDownloader * @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) { $util = new SvnUtil($baseUrl, $this->io, $this->config, $this->process); $util->setCacheCredentials($this->cacheCredentials); @@ -130,7 +130,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, $path, $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update) { if (!$changes = $this->getLocalChanges($package, $path)) { return \React\Promise\resolve(); @@ -191,7 +191,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function getCommitLogs($fromReference, $toReference, $path) + protected function getCommitLogs(string $fromReference, string $toReference, string $path) { if (Preg::isMatch('{@(\d+)$}', $fromReference) && Preg::isMatch('{@(\d+)$}', $toReference)) { // retrieve the svn base url from the checkout folder @@ -236,7 +236,7 @@ class SvnDownloader extends VcsDownloader * * @return PromiseInterface */ - protected function discardChanges($path) + protected function discardChanges(string $path) { 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 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function hasMetadataRepository($path) + protected function hasMetadataRepository(string $path) { return is_dir($path.'/.svn'); } diff --git a/src/Composer/Downloader/TarDownloader.php b/src/Composer/Downloader/TarDownloader.php index da4c98289..5d88b8dfa 100644 --- a/src/Composer/Downloader/TarDownloader.php +++ b/src/Composer/Downloader/TarDownloader.php @@ -24,7 +24,7 @@ class TarDownloader extends ArchiveDownloader /** * @inheritDoc */ - protected function extract(PackageInterface $package, $file, $path) + protected function extract(PackageInterface $package, string $file, string $path) { // Can throw an UnexpectedValueException $archive = new \PharData($file); diff --git a/src/Composer/Downloader/TransportException.php b/src/Composer/Downloader/TransportException.php index e36028670..89719becf 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 @@ class TransportException extends \RuntimeException } /** - * @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 39203d5a5..43d07c6c5 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); } diff --git a/src/Composer/Downloader/VcsDownloader.php b/src/Composer/Downloader/VcsDownloader.php index 836925b66..a97d517e2 100644 --- a/src/Composer/Downloader/VcsDownloader.php +++ b/src/Composer/Downloader/VcsDownloader.php @@ -60,7 +60,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null) { if (!$package->getSourceReference()) { throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information'); @@ -93,7 +93,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function prepare($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { if ($type === 'update') { $this->cleanChanges($prevPackage, $path, true); @@ -110,7 +110,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function cleanup($type, PackageInterface $package, $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) { if ($type === 'update' && isset($this->hasCleanedChanges[$prevPackage->getUniqueName()])) { $this->reapplyChanges($path); @@ -123,7 +123,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function install(PackageInterface $package, $path) + public function install(PackageInterface $package, string $path) { if (!$package->getSourceReference()) { throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information'); @@ -158,7 +158,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, $path) + public function update(PackageInterface $initial, PackageInterface $target, string $path) { if (!$target->getSourceReference()) { throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information'); @@ -194,12 +194,12 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function remove(PackageInterface $package, $path) + public function remove(PackageInterface $package, string $path) { $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function getVcsReference(PackageInterface $package, $path) + public function getVcsReference(PackageInterface $package, string $path) { $parser = new VersionParser; $guesser = new VersionGuesser($this->config, $this->process, $parser); @@ -264,7 +264,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @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) { // 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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @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) { } @@ -297,7 +297,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @return PromiseInterface|null */ - abstract protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null); + abstract protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null); /** * Downloads specific package into specific folder. @@ -308,7 +308,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @return PromiseInterface|null */ - abstract protected function doInstall(PackageInterface $package, $path, $url); + abstract protected function doInstall(PackageInterface $package, string $path, string $url); /** * Updates specific package in specific folder from initial to target version. @@ -320,7 +320,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @return PromiseInterface|null */ - abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url); + abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url); /** * Fetches the commit logs between two commits @@ -330,7 +330,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @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); /** * Checks if VCS metadata repository has been initialized @@ -339,7 +339,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @param string $path * @return bool */ - abstract protected function hasMetadataRepository($path); + abstract protected function hasMetadataRepository(string $path); /** * @param string[] $urls diff --git a/src/Composer/Downloader/XzDownloader.php b/src/Composer/Downloader/XzDownloader.php index 2072b05e3..33f3c03d6 100644 --- a/src/Composer/Downloader/XzDownloader.php +++ b/src/Composer/Downloader/XzDownloader.php @@ -24,7 +24,7 @@ use Composer\Util\ProcessExecutor; */ 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 a1f297a9d..e18fd0d80 100644 --- a/src/Composer/Downloader/ZipDownloader.php +++ b/src/Composer/Downloader/ZipDownloader.php @@ -17,6 +17,7 @@ use Composer\Util\IniHelper; 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) { if (null === self::$unzipCommands) { self::$unzipCommands = array(); @@ -105,7 +106,7 @@ class ZipDownloader extends ArchiveDownloader * @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 @@ class ZipDownloader extends ArchiveDownloader $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 @@ class ZipDownloader extends ArchiveDownloader 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 @@ class ZipDownloader extends ArchiveDownloader * @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(); @@ -207,7 +208,7 @@ class ZipDownloader extends ArchiveDownloader * @param string $path Path where to extract file * @return PromiseInterface|null */ - protected function extract(PackageInterface $package, $file, $path) + protected function extract(PackageInterface $package, string $file, string $path) { return $this->extractWithSystemUnzip($package, $file, $path); } @@ -219,7 +220,7 @@ class ZipDownloader extends ArchiveDownloader * @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 8563809f5..c7af569d2 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; diff --git a/src/Composer/EventDispatcher/EventDispatcher.php b/src/Composer/EventDispatcher/EventDispatcher.php index ea6d51792..8cfc8b194 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 @@ class EventDispatcher * @param bool $runScripts * @return $this */ - public function setRunScripts($runScripts = true) + public function setRunScripts(bool $runScripts = true) { $this->runScripts = (bool) $runScripts; @@ -97,7 +96,7 @@ class EventDispatcher * @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) { if (null === $event) { $event = new Event($eventName); @@ -116,7 +115,7 @@ class EventDispatcher * @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()) { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -135,7 +134,7 @@ class EventDispatcher * @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) { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -153,7 +152,7 @@ class EventDispatcher * @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) { assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer')); @@ -343,7 +342,7 @@ class EventDispatcher * * @return int */ - protected function executeTty($exec) + protected function executeTty(string $exec) { if ($this->io->isInteractive()) { return $this->process->executeTty($exec); @@ -378,7 +377,7 @@ class EventDispatcher * * @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 @@ class EventDispatcher * * @return void */ - public function addListener($eventName, $listener, $priority = 0) + public function addListener(string $eventName, callable $listener, int $priority = 0) { $this->listeners[$eventName][$priority][] = $listener; } @@ -520,7 +519,7 @@ class EventDispatcher * @param string $callable * @return bool */ - protected function isPhpScript($callable) + protected function isPhpScript(string $callable) { return false === strpos($callable, ' ') && false !== strpos($callable, '::'); } @@ -531,7 +530,7 @@ class EventDispatcher * @param string $callable * @return bool */ - protected function isComposerScript($callable) + protected function isComposerScript(string $callable) { return strpos($callable, '@') === 0 && strpos($callable, '@php ') !== 0 && strpos($callable, '@putenv ') !== 0; } diff --git a/src/Composer/Factory.php b/src/Composer/Factory.php index e6ef47563..c6980057c 100644 --- a/src/Composer/Factory.php +++ b/src/Composer/Factory.php @@ -164,7 +164,7 @@ class Factory 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 @@ class Factory */ 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 @@ class Factory * * @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 @@ class Factory * @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 ca37baea4..db779c3c1 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 e51d59b39..5a146bfe3 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php @@ -55,7 +55,7 @@ final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFi * @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 @@ final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFi * @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 2262326c3..882275b41 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 52cf83e16..de0fc234a 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 7c951f2c6..807e0ee3a 100644 --- a/src/Composer/IO/BaseIO.php +++ b/src/Composer/IO/BaseIO.php @@ -69,7 +69,7 @@ abstract class BaseIO implements IOInterface /** * @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 @@ abstract class BaseIO implements IOInterface /** * @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 @@ abstract class BaseIO implements IOInterface * * @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 4d7242120..0e9b44a25 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 2fd2cb178..b63baca77 100644 --- a/src/Composer/IO/ConsoleIO.php +++ b/src/Composer/IO/ConsoleIO.php @@ -71,7 +71,7 @@ class ConsoleIO extends BaseIO * * @return void */ - public function enableDebugging($startTime) + public function enableDebugging(float $startTime) { $this->startTime = $startTime; } @@ -119,7 +119,7 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO * * @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 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO /** * @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 @@ class ConsoleIO extends BaseIO * * @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 @@ class ConsoleIO extends BaseIO * @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 0837309d5..66fe735db 100644 --- a/src/Composer/IO/IOInterface.php +++ b/src/Composer/IO/IOInterface.php @@ -72,7 +72,7 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * @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 @@ interface IOInterface extends LoggerInterface * * @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 @@ interface IOInterface extends LoggerInterface * @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 @@ interface IOInterface extends LoggerInterface * * @return bool */ - public function hasAuthentication($repositoryName); + public function hasAuthentication(string $repositoryName); /** * Get the username and password of repository. @@ -218,18 +218,18 @@ interface IOInterface extends LoggerInterface * * @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 278b945b3..88c4a8c74 100644 --- a/src/Composer/IO/NullIO.php +++ b/src/Composer/IO/NullIO.php @@ -62,28 +62,28 @@ class NullIO extends BaseIO /** * @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/Installer.php b/src/Composer/Installer.php index 18b798d7b..fd3cb1417 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -386,7 +386,7 @@ class Installer * @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 @@ class Installer * @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 @@ class Installer * * @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 @@ class Installer * * @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 @@ class Installer * * @return DefaultPolicy */ - private function createPolicy($forUpdate): DefaultPolicy + private function createPolicy(bool $forUpdate): DefaultPolicy { $preferStable = null; $preferLowest = null; @@ -919,7 +919,7 @@ class Installer * * @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 @@ class Installer * * @phpstan-return list */ - private function getRootAliases($forUpdate): array + private function getRootAliases(bool $forUpdate): array { if ($forUpdate) { $aliases = $this->package->getAliases(); @@ -1062,7 +1062,7 @@ class Installer * @param bool $dryRun * @return Installer */ - public function setDryRun($dryRun = true): Installer + public function setDryRun(bool $dryRun = true): Installer { $this->dryRun = (bool) $dryRun; @@ -1085,7 +1085,7 @@ class Installer * @param bool $preferSource * @return Installer */ - public function setPreferSource($preferSource = true): Installer + public function setPreferSource(bool $preferSource = true): Installer { $this->preferSource = (bool) $preferSource; @@ -1098,7 +1098,7 @@ class Installer * @param bool $preferDist * @return Installer */ - public function setPreferDist($preferDist = true): Installer + public function setPreferDist(bool $preferDist = true): Installer { $this->preferDist = (bool) $preferDist; @@ -1111,7 +1111,7 @@ class Installer * @param bool $optimizeAutoloader * @return Installer */ - public function setOptimizeAutoloader($optimizeAutoloader): Installer + public function setOptimizeAutoloader(bool $optimizeAutoloader): Installer { $this->optimizeAutoloader = (bool) $optimizeAutoloader; if (!$this->optimizeAutoloader) { @@ -1130,7 +1130,7 @@ class Installer * @param bool $classMapAuthoritative * @return Installer */ - public function setClassMapAuthoritative($classMapAuthoritative): Installer + public function setClassMapAuthoritative(bool $classMapAuthoritative): Installer { $this->classMapAuthoritative = (bool) $classMapAuthoritative; if ($this->classMapAuthoritative) { @@ -1148,7 +1148,7 @@ class Installer * @param string|null $apcuAutoloaderPrefix * @return Installer */ - public function setApcuAutoloader($apcuAutoloader, $apcuAutoloaderPrefix = null): Installer + public function setApcuAutoloader(bool $apcuAutoloader, ?string $apcuAutoloaderPrefix = null): Installer { $this->apcuAutoloader = $apcuAutoloader; $this->apcuAutoloaderPrefix = $apcuAutoloaderPrefix; @@ -1162,7 +1162,7 @@ class Installer * @param bool $update * @return Installer */ - public function setUpdate($update): Installer + public function setUpdate(bool $update): Installer { $this->update = (bool) $update; @@ -1175,7 +1175,7 @@ class Installer * @param bool $install * @return Installer */ - public function setInstall($install): Installer + public function setInstall(bool $install): Installer { $this->install = (bool) $install; @@ -1188,7 +1188,7 @@ class Installer * @param bool $devMode * @return Installer */ - public function setDevMode($devMode = true): Installer + public function setDevMode(bool $devMode = true): Installer { $this->devMode = (bool) $devMode; @@ -1203,7 +1203,7 @@ class Installer * @param bool $dumpAutoloader * @return Installer */ - public function setDumpAutoloader($dumpAutoloader = true): Installer + public function setDumpAutoloader(bool $dumpAutoloader = true): Installer { $this->dumpAutoloader = (bool) $dumpAutoloader; @@ -1219,7 +1219,7 @@ class 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): Installer { $this->runScripts = (bool) $runScripts; @@ -1245,7 +1245,7 @@ class Installer * @param bool $verbose * @return Installer */ - public function setVerbose($verbose = true): Installer + public function setVerbose(bool $verbose = true): Installer { $this->verbose = (bool) $verbose; @@ -1299,7 +1299,7 @@ class Installer * @param bool $updateMirrors * @return Installer */ - public function setUpdateMirrors($updateMirrors): Installer + public function setUpdateMirrors(bool $updateMirrors): Installer { $this->updateMirrors = $updateMirrors; @@ -1330,7 +1330,7 @@ class 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): Installer { 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 @@ class Installer * @param bool $preferStable * @return Installer */ - public function setPreferStable($preferStable = true): Installer + public function setPreferStable(bool $preferStable = true): Installer { $this->preferStable = (bool) $preferStable; @@ -1360,7 +1360,7 @@ class Installer * @param bool $preferLowest * @return Installer */ - public function setPreferLowest($preferLowest = true): Installer + public function setPreferLowest(bool $preferLowest = true): Installer { $this->preferLowest = (bool) $preferLowest; @@ -1375,7 +1375,7 @@ class Installer * @param bool $writeLock * @return Installer */ - public function setWriteLock($writeLock = true): Installer + public function setWriteLock(bool $writeLock = true): Installer { $this->writeLock = (bool) $writeLock; @@ -1390,7 +1390,7 @@ class Installer * @param bool $executeOperations * @return Installer */ - public function setExecuteOperations($executeOperations = true): Installer + public function setExecuteOperations(bool $executeOperations = true): Installer { $this->executeOperations = (bool) $executeOperations; diff --git a/src/Composer/Installer/BinaryInstaller.php b/src/Composer/Installer/BinaryInstaller.php index 4af59ad23..05f3c0b34 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 @@ class BinaryInstaller * * @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 @@ class BinaryInstaller * * @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 @@ class BinaryInstaller * * @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 @@ class BinaryInstaller * * @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 @@ class BinaryInstaller * * @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 @@ class BinaryInstaller * * @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 788d367e7..7d3150d60 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -125,7 +125,7 @@ class InstallationManager * @throws \InvalidArgumentException if installer for provided type is not registered * @return InstallerInterface */ - public function getInstaller($type) + public function getInstaller(string $type) { $type = strtolower($type); @@ -192,7 +192,7 @@ class InstallationManager * * @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) { /** @var PromiseInterface[] */ $cleanupPromises = array(); @@ -316,7 +316,7 @@ class InstallationManager * * @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 @@ class InstallationManager * * @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(); @@ -553,7 +553,7 @@ class InstallationManager if ($promise instanceof PromiseInterface) { return $promise; } - + return \React\Promise\resolve(); }); } @@ -627,7 +627,7 @@ class InstallationManager * * @return void */ - public function setOutputProgress($outputProgress) + public function setOutputProgress(bool $outputProgress) { $this->outputProgress = $outputProgress; } diff --git a/src/Composer/Installer/InstallerEvent.php b/src/Composer/Installer/InstallerEvent.php index ee81754d9..88dc7b737 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); diff --git a/src/Composer/Installer/InstallerInterface.php b/src/Composer/Installer/InstallerInterface.php index fd3015e83..8ddbed4e6 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 @@ interface InstallerInterface * @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 @@ interface InstallerInterface * @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 f5525341d..7d88a6d9b 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 ac9145943..177869fb9 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); diff --git a/src/Composer/Installer/ProjectInstaller.php b/src/Composer/Installer/ProjectInstaller.php index 7e31fdaf9..60c499f95 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 @@ class ProjectInstaller implements InstallerInterface * @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 17e51b5f6..3b1c92651 100644 --- a/src/Composer/Installer/SuggestedPackagesReporter.php +++ b/src/Composer/Installer/SuggestedPackagesReporter.php @@ -63,7 +63,7 @@ class SuggestedPackagesReporter * @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 @@ class SuggestedPackagesReporter * @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 @@ class SuggestedPackagesReporter * @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 @@ class SuggestedPackagesReporter * @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 aa81fb61a..b16af75ac 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; @@ -124,7 +124,7 @@ class JsonFile * @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 @@ class JsonFile * @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 @@ class JsonFile * @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) { $content = file_get_contents($this->path); $data = json_decode($content); @@ -239,7 +239,7 @@ class JsonFile * @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 @@ class JsonFile * @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 @@ class JsonFile /** * 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 @@ class JsonFile * @throws ParsingException * @return bool true on success */ - protected static function validateSyntax($json, $file = null) + protected static function validateSyntax(string $json, string $file = null) { $parser = new JsonParser(); $result = $parser->lint($json); diff --git a/src/Composer/Json/JsonFormatter.php b/src/Composer/Json/JsonFormatter.php index dd705db78..de6882689 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 8a309086d..68de5dd4a 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 === '') { @@ -70,7 +70,7 @@ class JsonManipulator * @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) { $decoded = JsonFile::parseJson($this->contents); @@ -165,12 +165,12 @@ class JsonManipulator } /** - * @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) { return $this->addSubNode('repositories', $name, $config, $append); } @@ -179,7 +179,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeRepository($name) + public function removeRepository(string $name) { return $this->removeSubNode('repositories', $name); } @@ -189,7 +189,7 @@ class JsonManipulator * @param mixed $value * @return bool */ - public function addConfigSetting($name, $value) + public function addConfigSetting(string $name, $value) { return $this->addSubNode('config', $name, $value); } @@ -198,7 +198,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeConfigSetting($name) + public function removeConfigSetting(string $name) { return $this->removeSubNode('config', $name); } @@ -208,7 +208,7 @@ class JsonManipulator * @param mixed $value * @return bool */ - public function addProperty($name, $value) + public function addProperty(string $name, $value) { if (strpos($name, 'suggest.') === 0) { return $this->addSubNode('suggest', substr($name, 8), $value); @@ -229,7 +229,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeProperty($name) + public function removeProperty(string $name) { if (strpos($name, 'suggest.') === 0) { return $this->removeSubNode('suggest', substr($name, 8)); @@ -253,7 +253,7 @@ class JsonManipulator * @param bool $append * @return bool */ - public function addSubNode($mainNode, $name, $value, $append = true) + public function addSubNode(string $mainNode, string $name, $value, bool $append = true) { $decoded = JsonFile::parseJson($this->contents); @@ -363,7 +363,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeSubNode($mainNode, $name) + public function removeSubNode(string $mainNode, string $name) { $decoded = JsonFile::parseJson($this->contents); @@ -468,7 +468,7 @@ class JsonManipulator * @param mixed $content * @return bool */ - public function addMainKey($key, $content) + public function addMainKey(string $key, $content) { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); @@ -512,7 +512,7 @@ class JsonManipulator * @param string $key * @return bool */ - public function removeMainKey($key) + public function removeMainKey(string $key) { $decoded = JsonFile::parseJson($this->contents); @@ -549,7 +549,7 @@ class JsonManipulator * @param string $key * @return bool */ - public function removeMainKeyIfEmpty($key) + public function removeMainKeyIfEmpty(string $key) { $decoded = JsonFile::parseJson($this->contents); @@ -569,7 +569,7 @@ class JsonManipulator * @param int $depth * @return string */ - public function format($data, $depth = 0) + public function format($data, int $depth = 0) { if (is_array($data)) { reset($data); diff --git a/src/Composer/Json/JsonValidationException.php b/src/Composer/Json/JsonValidationException.php index 35f61d32d..1187b2f99 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 5c2645eb1..3d82debb6 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()); @@ -164,7 +164,7 @@ class AliasPackage extends BasePackage * * @return mixed */ - public function setRootPackageAlias($value) + public function setRootPackageAlias(bool $value) { return $this->rootPackageAlias = $value; } @@ -249,7 +249,7 @@ class AliasPackage extends BasePackage return $this->aliasOf->getExtra(); } - public function setInstallationSource($type): void + public function setInstallationSource(?string $type): void { $this->aliasOf->setInstallationSource($type); } @@ -279,12 +279,12 @@ class AliasPackage extends BasePackage 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 +314,7 @@ class AliasPackage extends BasePackage return $this->aliasOf->getDistReference(); } - public function setDistReference($reference): void + public function setDistReference(?string $reference): void { $this->aliasOf->setDistReference($reference); } @@ -334,7 +334,7 @@ class AliasPackage extends BasePackage return $this->aliasOf->getTransportOptions(); } - public function setDistMirrors($mirrors): void + public function setDistMirrors(?array $mirrors): void { $this->aliasOf->setDistMirrors($mirrors); } @@ -359,7 +359,7 @@ class AliasPackage extends BasePackage return $this->aliasOf->getIncludePaths(); } - public function getReleaseDate(): ?\DateTime + public function getReleaseDate(): ?\DateTimeInterface { return $this->aliasOf->getReleaseDate(); } @@ -384,17 +384,17 @@ class AliasPackage extends BasePackage 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 9a5be1a19..8af84271d 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFilter.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFilter.php @@ -40,7 +40,7 @@ class ArchivableFilesFilter extends FilterIterator * * @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 31e81e295..fd589d7a2 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 de8ff52e8..236304e69 100644 --- a/src/Composer/Package/Archiver/ArchiveManager.php +++ b/src/Composer/Package/Archiver/ArchiveManager.php @@ -68,7 +68,7 @@ class ArchiveManager * * @return $this */ - public function setOverwriteFiles($overwriteFiles) + public function setOverwriteFiles(bool $overwriteFiles) { $this->overwriteFiles = $overwriteFiles; @@ -121,7 +121,7 @@ class ArchiveManager * @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 a9038ca76..f18e8b45f 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 @@ interface ArchiverInterface * * @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 2fbd22796..21a8db5d8 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 @@ abstract class BaseExcludeFilter * * @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 @@ abstract class BaseExcludeFilter * * @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 @@ abstract class BaseExcludeFilter * * @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 @@ abstract class BaseExcludeFilter * * @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 3a5a5179d..07d1e162d 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 351ca4e7d..d81dc7693 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 @@ class GitExcludeFilter extends BaseExcludeFilter * * @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 f46cec9fd..f29bee056 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); @@ -257,7 +257,7 @@ abstract class BasePackage implements PackageInterface * @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') { $cleanedAllowPattern = str_replace('\\*', '.*', preg_quote($allowPattern)); @@ -271,7 +271,7 @@ abstract class BasePackage implements PackageInterface * @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') { $packageNames = array_map( function ($packageName): string { diff --git a/src/Composer/Package/Comparer/Comparer.php b/src/Composer/Package/Comparer/Comparer.php index d7c2a5fc7..d9d5a20f1 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 @@ class Comparer * * @return void */ - public function setUpdate($update): void + public function setUpdate(string $update): void { $this->update = $update; } @@ -52,7 +54,7 @@ class Comparer * * @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 @@ class Comparer $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 @@ class Comparer /** * @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 ea2dfad45..f69ad6298 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 @@ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterf return $this->aliasOf->getDescription(); } - public function setDescription($description): void + public function setDescription(?string $description): void { $this->aliasOf->setDescription($description); } @@ -95,7 +95,7 @@ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterf return $this->aliasOf->getHomepage(); } - public function setHomepage($homepage): void + public function setHomepage(?string $homepage): void { $this->aliasOf->setHomepage($homepage); } @@ -150,7 +150,7 @@ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterf 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 5a6ec4cb2..1234ddf0c 100644 --- a/src/Composer/Package/CompletePackage.php +++ b/src/Composer/Package/CompletePackage.php @@ -127,7 +127,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setDescription($description) + public function setDescription(?string $description) { $this->description = $description; } @@ -143,7 +143,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setHomepage($homepage) + public function setHomepage(?string $homepage) { $this->homepage = $homepage; } @@ -215,7 +215,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setArchiveName($name) + public function setArchiveName(?string $name) { $this->archiveName = $name; } diff --git a/src/Composer/Package/CompletePackageInterface.php b/src/Composer/Package/CompletePackageInterface.php index 00e4a088e..e65cc0c4c 100644 --- a/src/Composer/Package/CompletePackageInterface.php +++ b/src/Composer/Package/CompletePackageInterface.php @@ -90,7 +90,7 @@ interface CompletePackageInterface extends PackageInterface * @param string $description * @return void */ - public function setDescription($description); + public function setDescription(string $description); /** * Returns the package homepage @@ -105,7 +105,7 @@ interface CompletePackageInterface extends PackageInterface * @param string $homepage * @return void */ - public function setHomepage($homepage); + public function setHomepage(string $homepage); /** * Returns an array of authors of the package @@ -189,7 +189,7 @@ interface CompletePackageInterface extends PackageInterface * @param string $name * @return void */ - public function setArchiveName($name); + public function setArchiveName(string $name); /** * Returns a list of patterns to exclude from package archives diff --git a/src/Composer/Package/Dumper/ArrayDumper.php b/src/Composer/Package/Dumper/ArrayDumper.php index fd54a516f..e5ca23985 100644 --- a/src/Composer/Package/Dumper/ArrayDumper.php +++ b/src/Composer/Package/Dumper/ArrayDumper.php @@ -87,7 +87,7 @@ class ArrayDumper $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 8e613a565..75f744bd1 100644 --- a/src/Composer/Package/Link.php +++ b/src/Composer/Package/Link.php @@ -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); diff --git a/src/Composer/Package/Loader/ArrayLoader.php b/src/Composer/Package/Loader/ArrayLoader.php index 16cede400..b7fe52207 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; @@ -108,7 +108,7 @@ class ArrayLoader implements LoaderInterface * * @phpstan-param class-string $class */ - private function createObject(array $config, $class) + private function createObject(array $config, string $class) { if (!isset($config['name'])) { throw new \UnexpectedValueException('Unknown package has no name defined ('.json_encode($config).').'); @@ -141,7 +141,7 @@ class ArrayLoader implements LoaderInterface * * @return RootPackage|RootAliasPackage|CompletePackage|CompleteAliasPackage */ - private function configureObject(PackageInterface $package, array $config) + private function configureObject(PackageInterface $package, array $config): PackageInterface { if (!$package instanceof CompletePackage) { throw new \LogicException('ArrayLoader expects instances of the Composer\Package\CompletePackage class to function correctly'); @@ -321,7 +321,7 @@ class ArrayLoader implements LoaderInterface * * @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 @@ class ArrayLoader implements LoaderInterface * * @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 @@ class ArrayLoader implements LoaderInterface * @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 @@ class ArrayLoader implements LoaderInterface * * @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/LoaderInterface.php b/src/Composer/Package/Loader/LoaderInterface.php index 9a89d68aa..01c1910da 100644 --- a/src/Composer/Package/Loader/LoaderInterface.php +++ b/src/Composer/Package/Loader/LoaderInterface.php @@ -37,5 +37,5 @@ interface LoaderInterface * * @phpstan-param class-string $class */ - public function load(array $config, $class = 'Composer\Package\CompletePackage'); + public function load(array $config, string $class = 'Composer\Package\CompletePackage'); } diff --git a/src/Composer/Package/Loader/RootPackageLoader.php b/src/Composer/Package/Loader/RootPackageLoader.php index 9c0c47c8f..0ab5cefec 100644 --- a/src/Composer/Package/Loader/RootPackageLoader.php +++ b/src/Composer/Package/Loader/RootPackageLoader.php @@ -69,7 +69,7 @@ class RootPackageLoader extends ArrayLoader * * @phpstan-param class-string $class */ - public function load(array $config, $class = 'Composer\Package\RootPackage', $cwd = null) + public function load(array $config, $class = 'Composer\Package\RootPackage', ?string $cwd = null) { 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 +88,7 @@ class RootPackageLoader extends ArrayLoader 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 +224,7 @@ class RootPackageLoader extends ArrayLoader * @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 2a1278448..85f4cb67e 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(); @@ -450,7 +450,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @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 @@ class ValidatingArrayLoader implements LoaderInterface * @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 @@ class ValidatingArrayLoader implements LoaderInterface * * @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 @@ class ValidatingArrayLoader implements LoaderInterface * * @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 @@ class ValidatingArrayLoader implements LoaderInterface * @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 @@ class ValidatingArrayLoader implements LoaderInterface * * @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 1702d2ba9..6dc77cf5b 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 @@ class Locker * * @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 @@ class Locker * @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 @@ class Locker * @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 @@ class Locker * * @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 7549c4008..ed5d52ee8 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); @@ -130,7 +130,7 @@ class Package extends BasePackage * * @return void */ - public function setType($type) + public function setType(string $type) { $this->type = $type; } @@ -152,11 +152,9 @@ class Package extends BasePackage } /** - * @param string $targetDir - * * @return void */ - public function setTargetDir($targetDir) + public function setTargetDir(?string $targetDir) { $this->targetDir = $targetDir; } @@ -214,7 +212,7 @@ class Package extends BasePackage * * @return void */ - public function setInstallationSource($type) + public function setInstallationSource(?string $type) { $this->installationSource = $type; } @@ -228,11 +226,9 @@ class Package extends BasePackage } /** - * @param string $type - * * @return void */ - public function setSourceType($type) + public function setSourceType(?string $type) { $this->sourceType = $type; } @@ -246,11 +242,9 @@ class Package extends BasePackage } /** - * @param string $url - * * @return void */ - public function setSourceUrl($url) + public function setSourceUrl(?string $url) { $this->sourceUrl = $url; } @@ -264,11 +258,9 @@ class Package extends BasePackage } /** - * @param string $reference - * * @return void */ - public function setSourceReference($reference) + public function setSourceReference(?string $reference) { $this->sourceReference = $reference; } @@ -282,11 +274,9 @@ class Package extends BasePackage } /** - * @inheritDoc - * * @return void */ - public function setSourceMirrors($mirrors) + public function setSourceMirrors(?array $mirrors) { $this->sourceMirrors = $mirrors; } @@ -312,7 +302,7 @@ class Package extends BasePackage * * @return void */ - public function setDistType($type) + public function setDistType(?string $type) { $this->distType = $type; } @@ -330,7 +320,7 @@ class Package extends BasePackage * * @return void */ - public function setDistUrl($url) + public function setDistUrl(?string $url) { $this->distUrl = $url; } @@ -348,7 +338,7 @@ class Package extends BasePackage * * @return void */ - public function setDistReference($reference) + public function setDistReference(?string $reference) { $this->distReference = $reference; } @@ -366,7 +356,7 @@ class Package extends BasePackage * * @return void */ - public function setDistSha1Checksum($sha1checksum) + public function setDistSha1Checksum(?string $sha1checksum) { $this->distSha1Checksum = $sha1checksum; } @@ -380,11 +370,9 @@ class Package extends BasePackage } /** - * @inheritDoc - * * @return void */ - public function setDistMirrors($mirrors) + public function setDistMirrors(?array $mirrors) { $this->distMirrors = $mirrors; } @@ -438,13 +426,9 @@ class Package extends BasePackage } /** - * Set the releaseDate - * - * @param \DateTime $releaseDate - * * @return void */ - public function setReleaseDate(\DateTime $releaseDate) + public function setReleaseDate(?\DateTimeInterface $releaseDate) { $this->releaseDate = $releaseDate; } @@ -671,7 +655,7 @@ class Package extends BasePackage * * @return void */ - public function setNotificationUrl($notificationUrl) + public function setNotificationUrl(string $notificationUrl) { $this->notificationUrl = $notificationUrl; } @@ -689,7 +673,7 @@ class Package extends BasePackage * * @return void */ - public function setIsDefaultBranch($defaultBranch) + public function setIsDefaultBranch(bool $defaultBranch) { $this->isDefaultBranch = $defaultBranch; } @@ -705,7 +689,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function setSourceDistReferences($reference) + public function setSourceDistReferences(string $reference) { $this->setSourceReference($reference); @@ -731,7 +715,7 @@ class Package extends BasePackage * * @return void */ - public function replaceVersion($version, $prettyVersion) + public function replaceVersion(string $version, string $prettyVersion) { $this->version = $version; $this->prettyVersion = $prettyVersion; @@ -751,7 +735,7 @@ class Package extends BasePackage * * @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) { if (!$url) { return array(); @@ -788,7 +772,7 @@ class Package extends BasePackage * @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 a566298c8..50512bfe5 100644 --- a/src/Composer/Package/PackageInterface.php +++ b/src/Composer/Package/PackageInterface.php @@ -52,7 +52,7 @@ interface PackageInterface * * @return string[] An array of strings referring to this package */ - public function getNames($provides = true); + public function getNames(bool $provides = true); /** * Allows the solver to set an id for this package to refer to it. @@ -61,7 +61,7 @@ interface PackageInterface * * @return void */ - public function setId($id); + public function setId(int $id); /** * Retrieves the package's id set through setId @@ -101,12 +101,12 @@ interface PackageInterface /** * 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); /** * Returns source from which this package was installed (source/dist). @@ -152,10 +152,10 @@ interface PackageInterface public function getSourceMirrors(); /** - * @param ?array $mirrors + * @param null|array $mirrors * @return void */ - public function setSourceMirrors($mirrors); + public function setSourceMirrors(?array $mirrors); /** * Returns the type of the distribution archive of this version, e.g. zip, tarball @@ -200,10 +200,10 @@ interface PackageInterface public function getDistMirrors(); /** - * @param ?array $mirrors + * @param null|array $mirrors * @return void */ - public function setDistMirrors($mirrors); + public function setDistMirrors(?array $mirrors); /** * Returns the version of this package @@ -230,12 +230,12 @@ interface PackageInterface * * @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); /** * Returns the release date of the package * - * @return ?\DateTime + * @return ?\DateTimeInterface */ public function getReleaseDate(); @@ -404,39 +404,29 @@ interface PackageInterface public function setTransportOptions(array $options); /** - * @param string $reference - * * @return void */ - public function setSourceReference($reference); + public function setSourceReference(?string $reference); /** - * @param string $url - * * @return void */ - public function setDistUrl($url); + public function setDistUrl(?string $url); /** - * @param string $type - * * @return void */ - public function setDistType($type); + public function setDistType(?string $type); /** - * @param string $reference - * * @return void */ - public function setDistReference($reference); + public function setDistReference(?string $reference); /** * 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); } diff --git a/src/Composer/Package/RootAliasPackage.php b/src/Composer/Package/RootAliasPackage.php index adf69b6b0..7c780189f 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 38375dc73..07bd31d6f 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 @@ class RootPackage extends CompletePackage implements RootPackageInterface } /** - * {@inerhitDoc} + * @inheritDoc */ - public function setPreferStable($preferStable): void + public function setPreferStable(bool $preferStable): void { $this->preferStable = $preferStable; } @@ -83,7 +83,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface } /** - * {@inerhitDoc} + * @inheritDoc */ public function setConfig(array $config): void { @@ -99,7 +99,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface } /** - * {@inerhitDoc} + * @inheritDoc */ public function setReferences(array $references): void { @@ -115,7 +115,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface } /** - * {@inerhitDoc} + * @inheritDoc */ public function setAliases(array $aliases): void { diff --git a/src/Composer/Package/RootPackageInterface.php b/src/Composer/Package/RootPackageInterface.php index 32cc44750..a1783f875 100644 --- a/src/Composer/Package/RootPackageInterface.php +++ b/src/Composer/Package/RootPackageInterface.php @@ -158,7 +158,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setMinimumStability($minimumStability); + public function setMinimumStability(string $minimumStability); /** * Set the preferStable @@ -167,7 +167,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setPreferStable($preferStable); + public function setPreferStable(bool $preferStable); /** * Set the config diff --git a/src/Composer/Package/Version/StabilityFilter.php b/src/Composer/Package/Version/StabilityFilter.php index 81f4ec063..4280d7499 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 d5b0bf907..30961de4b 100644 --- a/src/Composer/Package/Version/VersionGuesser.php +++ b/src/Composer/Package/Version/VersionGuesser.php @@ -66,7 +66,7 @@ class VersionGuesser * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 @@ class VersionGuesser * * @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 2d11bf0e4..44b7dce62 100644 --- a/src/Composer/Package/Version/VersionParser.php +++ b/src/Composer/Package/Version/VersionParser.php @@ -76,7 +76,7 @@ class VersionParser extends SemverVersionParser * * @return bool */ - public static function isUpgrade($normalizedFrom, $normalizedTo) + public static function isUpgrade(string $normalizedFrom, string $normalizedTo) { if ($normalizedFrom === $normalizedTo) { return true; diff --git a/src/Composer/Package/Version/VersionSelector.php b/src/Composer/Package/Version/VersionSelector.php index 431bdb851..cc8fe2382 100644 --- a/src/Composer/Package/Version/VersionSelector.php +++ b/src/Composer/Package/Version/VersionSelector.php @@ -68,7 +68,7 @@ class VersionSelector * @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 @@ class VersionSelector * * @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 a5d228027..6ccdbf546 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 @@ class Runtime * * @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 @@ class Runtime * * @return bool */ - public function hasFunction($fn): bool + public function hasFunction(string $fn): bool { return function_exists($fn); } @@ -52,7 +52,7 @@ class Runtime * * @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 @@ class Runtime * * @return bool */ - public function hasClass($class): bool + public function hasClass(string $class): bool { return class_exists($class, false); } @@ -74,7 +74,7 @@ class Runtime * @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 @@ class Runtime * * @return string */ - public function getExtensionVersion($extension): string + public function getExtensionVersion(string $extension): string { return phpversion($extension); } @@ -107,7 +107,7 @@ class Runtime * @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 d2b4d1171..0731a1cec 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 @@ class Version * @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 @@ class Version * @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 @@ class Version * @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 @@ class Version * @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 @@ class Version * @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 @@ class Version * * @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 650757ff9..03d621eb5 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 b849de107..537f3b6ec 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 @@ class PluginManager * * @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 @@ class PluginManager * * @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 @@ class PluginManager * * @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 @@ class PluginManager * * @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 @@ class PluginManager * * @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 @@ class PluginManager * @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 @@ class PluginManager * @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 80489af9d..5fecd9b01 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 @@ class PostFileDownloadEvent extends Event * @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 2c534a68e..bb0d9a9a4 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 5b9b0307a..762952840 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 @@ class PreFileDownloadEvent extends Event * * @return void */ - public function setProcessedUrl($processedUrl): void + public function setProcessedUrl(string $processedUrl): void { $this->processedUrl = $processedUrl; } @@ -117,7 +117,7 @@ class PreFileDownloadEvent extends Event * * @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 d64e96d95..c647378ac 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 bcb339bda..c656a6126 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 518616445..096ab9820 100644 --- a/src/Composer/Repository/ArrayRepository.php +++ b/src/Composer/Repository/ArrayRepository.php @@ -146,7 +146,7 @@ class ArrayRepository implements RepositoryInterface /** * @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'; @@ -266,7 +266,7 @@ class ArrayRepository implements RepositoryInterface * * @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 7db28bcab..0739ba1bc 100644 --- a/src/Composer/Repository/ArtifactRepository.php +++ b/src/Composer/Repository/ArtifactRepository.php @@ -73,7 +73,7 @@ class ArtifactRepository extends ArrayRepository implements ConfigurableReposito * * @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 9e6adbaf6..edb382264 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -271,7 +271,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return string[] */ - public function getPackageNames($packageFilter = null) + public function getPackageNames(?string $packageFilter = null) { $hasProviders = $this->hasProviders(); @@ -431,7 +431,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null) + public function search(string $query, int $mode = 0, ?string $type = null) { $this->loadRootServerFile(600); @@ -661,10 +661,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito 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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return mixed[] */ - private function loadIncludes($data): array + private function loadIncludes(array $data): array { $packages = array(); @@ -1251,7 +1248,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @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 e34ce7357..3d31aa1de 100644 --- a/src/Composer/Repository/CompositeRepository.php +++ b/src/Composer/Repository/CompositeRepository.php @@ -125,7 +125,7 @@ class CompositeRepository implements RepositoryInterface /** * @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 ea9a0eeb1..990df2910 100644 --- a/src/Composer/Repository/FilesystemRepository.php +++ b/src/Composer/Repository/FilesystemRepository.php @@ -19,6 +19,7 @@ use Composer\Package\AliasPackage; 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; @@ -134,7 +135,7 @@ class FilesystemRepository extends WritableArrayRepository $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 @@ class FilesystemRepository extends WritableArrayRepository * * @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 @@ class FilesystemRepository extends WritableArrayRepository * * @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 @@ class FilesystemRepository extends WritableArrayRepository } 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 fc5acd776..db678a3f3 100644 --- a/src/Composer/Repository/FilterRepository.php +++ b/src/Composer/Repository/FilterRepository.php @@ -135,7 +135,7 @@ class FilterRepository implements RepositoryInterface /** * @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 @@ class FilterRepository implements RepositoryInterface * * @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 e99ed95db..c31573721 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 @@ class InstalledRepository extends CompositeRepository * @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 4722f9899..4952d234c 100644 --- a/src/Composer/Repository/PlatformRepository.php +++ b/src/Composer/Repository/PlatformRepository.php @@ -93,7 +93,7 @@ class PlatformRepository extends ArrayRepository * @param string $name * @return bool */ - public function isPlatformPackageDisabled($name): bool + public function isPlatformPackageDisabled(string $name): bool { return isset($this->disabledPackages[$name]); } @@ -586,7 +586,7 @@ class PlatformRepository extends ArrayRepository * * @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 @@ class PlatformRepository extends ArrayRepository * * @return void */ - private function addExtension($name, $prettyVersion): void + private function addExtension(string $name, ?string $prettyVersion): void { $extraDescription = null; @@ -653,7 +653,7 @@ class PlatformRepository extends ArrayRepository * @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 @@ class PlatformRepository extends ArrayRepository * * @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 @@ class PlatformRepository extends ArrayRepository * @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 @@ class PlatformRepository extends ArrayRepository 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 9dbfcb1bb..80e03eff8 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 @@ class RepositoryFactory * @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 9debf589d..0de31edd3 100644 --- a/src/Composer/Repository/RepositoryInterface.php +++ b/src/Composer/Repository/RepositoryInterface.php @@ -46,7 +46,7 @@ interface RepositoryInterface extends \Countable * * @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 @@ interface RepositoryInterface extends \Countable * * @return BasePackage[] */ - public function findPackages($name, $constraint = null); + public function findPackages(string $name, $constraint = null); /** * Returns list of registered packages. @@ -86,14 +86,14 @@ interface RepositoryInterface extends \Countable /** * 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 @@ interface RepositoryInterface extends \Countable * @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 a230c25e9..913768028 100644 --- a/src/Composer/Repository/RepositoryManager.php +++ b/src/Composer/Repository/RepositoryManager.php @@ -62,7 +62,7 @@ class RepositoryManager * * @return PackageInterface|null */ - public function findPackage($name, $constraint) + public function findPackage(string $name, $constraint) { foreach ($this->repositories as $repository) { /** @var RepositoryInterface $repository */ @@ -82,7 +82,7 @@ class RepositoryManager * * @return PackageInterface[] */ - public function findPackages($name, $constraint) + public function findPackages(string $name, $constraint) { $packages = array(); @@ -128,7 +128,7 @@ class RepositoryManager * @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) { if (!isset($this->repositoryClasses[$type])) { throw new \InvalidArgumentException('Repository type is not registered: '.$type); @@ -162,7 +162,7 @@ class RepositoryManager * * @return void */ - public function setRepositoryClass($type, $class) + public function setRepositoryClass(string $type, $class) { $this->repositoryClasses[$type] = $class; } diff --git a/src/Composer/Repository/RepositorySet.php b/src/Composer/Repository/RepositorySet.php index b01ce59f9..d13a423e0 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 @@ class RepositorySet * * @return void */ - public function allowInstalledRepositories($allow = true): void + public function allowInstalledRepositories(bool $allow = true): void { $this->allowInstalledRepositories = $allow; } @@ -169,7 +169,7 @@ class RepositorySet * @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 @@ class RepositorySet * @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 @@ class RepositorySet * @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 @@ class RepositorySet * * @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 @@ class RepositorySet * * @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 8304c61c8..7015f833f 100644 --- a/src/Composer/Repository/Vcs/FossilDriver.php +++ b/src/Composer/Repository/Vcs/FossilDriver.php @@ -141,7 +141,7 @@ class FossilDriver extends VcsDriver /** * @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 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier): ?array + public function getDist(string $identifier): ?array { return null; } @@ -157,7 +157,7 @@ class FossilDriver extends VcsDriver /** * @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,7 +172,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier): ?\DateTime + public function getChangeDate(string $identifier): ?\DateTime { $this->process->execute('fossil finfo -b -n 1 composer.json', $output, $this->checkoutDir); list(, $date) = explode(' ', trim($output), 3); @@ -222,7 +222,7 @@ class FossilDriver extends VcsDriver /** * @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 dd4033991..fba97fa42 100644 --- a/src/Composer/Repository/Vcs/GitBitbucketDriver.php +++ b/src/Composer/Repository/Vcs/GitBitbucketDriver.php @@ -131,7 +131,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getComposerInformation($identifier); @@ -205,7 +205,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getFileContent($file, $identifier); @@ -232,7 +232,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getChangeDate($identifier); @@ -259,7 +259,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getSource($identifier); @@ -271,7 +271,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { if ($this->fallbackDriver) { return $this->fallbackDriver->getDist($identifier); @@ -383,7 +383,7 @@ class GitBitbucketDriver extends VcsDriver * * @phpstan-impure */ - protected function fetchWithOAuthCredentials($url, $fetchingRepoData = false) + protected function fetchWithOAuthCredentials(string $url, bool $fetchingRepoData = false) { try { return parent::getContents($url); @@ -445,7 +445,7 @@ class GitBitbucketDriver extends VcsDriver * @param string $url * @return void */ - protected function setupFallbackDriver($url) + protected function setupFallbackDriver(string $url) { $this->fallbackDriver = new GitDriver( array('url' => $url), @@ -527,7 +527,7 @@ class GitBitbucketDriver extends VcsDriver /** * @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) { 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 cd69d5743..f8ee7b32d 100644 --- a/src/Composer/Repository/Vcs/GitDriver.php +++ b/src/Composer/Repository/Vcs/GitDriver.php @@ -120,7 +120,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -128,7 +128,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { return null; } @@ -136,7 +136,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { $resource = sprintf('%s:%s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute(sprintf('git show %s', $resource), $content, $this->repoDir); @@ -151,7 +151,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { $this->process->execute(sprintf( 'git -c log.showSignature=false log -1 --format=%%at %s', @@ -206,7 +206,7 @@ class GitDriver extends VcsDriver /** * @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) { 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 33d7e8cd3..2f532297e 100644 --- a/src/Composer/Repository/Vcs/GitHubDriver.php +++ b/src/Composer/Repository/Vcs/GitHubDriver.php @@ -130,7 +130,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -149,7 +149,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier; @@ -159,7 +159,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier) { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -287,7 +287,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); @@ -305,7 +305,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); @@ -379,7 +379,7 @@ class GitHubDriver extends VcsDriver /** * @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) { if (!Preg::isMatch('#^((?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) { return false; @@ -430,7 +430,7 @@ class GitHubDriver extends VcsDriver * * @param bool $fetchingRepoData */ - protected function getContents($url, $fetchingRepoData = false) + protected function getContents(string $url, bool $fetchingRepoData = false) { try { return parent::getContents($url); @@ -588,7 +588,7 @@ class GitHubDriver extends VcsDriver * * @return void */ - protected function setupGitDriver($url) + protected function setupGitDriver(string $url) { $this->gitDriver = new GitDriver( array('url' => $url), diff --git a/src/Composer/Repository/Vcs/GitLabDriver.php b/src/Composer/Repository/Vcs/GitLabDriver.php index 85ac75049..3c5e4d16b 100644 --- a/src/Composer/Repository/Vcs/GitLabDriver.php +++ b/src/Composer/Repository/Vcs/GitLabDriver.php @@ -184,7 +184,7 @@ class GitLabDriver extends VcsDriver /** * @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,7 +216,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier): ?\DateTime + public function getChangeDate(string $identifier): ?\DateTime { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); @@ -256,7 +256,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier): ?array + public function getDist(string $identifier): ?array { $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier; @@ -266,7 +266,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier): array + public function getSource(string $identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -333,7 +333,7 @@ class GitLabDriver extends VcsDriver * @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 @@ class GitLabDriver extends VcsDriver * * @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 @@ class GitLabDriver extends VcsDriver * * @return void */ - protected function setupGitDriver($url): void + protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( array('url' => $url), @@ -469,7 +469,7 @@ class GitLabDriver extends VcsDriver * * @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 @@ class GitLabDriver extends VcsDriver * * @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 @@ class GitLabDriver extends VcsDriver * * @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 e9b83d6c5..575ce7263 100644 --- a/src/Composer/Repository/Vcs/HgDriver.php +++ b/src/Composer/Repository/Vcs/HgDriver.php @@ -108,7 +108,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -116,7 +116,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { return null; } @@ -124,7 +124,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { $resource = sprintf('hg cat -r %s %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($resource, $content, $this->repoDir); @@ -139,7 +139,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { $this->process->execute( sprintf( @@ -208,7 +208,7 @@ class HgDriver extends VcsDriver /** * @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) { 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 b178257f2..34e4d09c2 100644 --- a/src/Composer/Repository/Vcs/PerforceDriver.php +++ b/src/Composer/Repository/Vcs/PerforceDriver.php @@ -55,7 +55,7 @@ class PerforceDriver extends VcsDriver * * @return void */ - private function initPerforce($repoConfig): void + private function initPerforce(array $repoConfig): void { if (!empty($this->perforce)) { return; @@ -72,7 +72,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { return $this->perforce->getFileContent($file, $identifier); } @@ -80,7 +80,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { return null; } @@ -112,7 +112,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { return null; } @@ -120,7 +120,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { return array( 'type' => 'perforce', @@ -141,7 +141,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function hasComposerFile($identifier) + public function hasComposerFile(string $identifier) { $composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier); @@ -151,7 +151,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getContents($url) + public function getContents(string $url) { throw new \BadMethodCallException('Not implemented/used in PerforceDriver'); } @@ -159,7 +159,7 @@ class PerforceDriver extends VcsDriver /** * @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) { if ($deep || Preg::isMatch('#\b(perforce|p4)\b#i', $url)) { return Perforce::checkServerExists($url, new ProcessExecutor($io)); diff --git a/src/Composer/Repository/Vcs/SvnDriver.php b/src/Composer/Repository/Vcs/SvnDriver.php index c54b04838..82d91721d 100644 --- a/src/Composer/Repository/Vcs/SvnDriver.php +++ b/src/Composer/Repository/Vcs/SvnDriver.php @@ -109,7 +109,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource(string $identifier) { return array('type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier); } @@ -117,7 +117,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist(string $identifier) { return null; } @@ -125,7 +125,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - protected function shouldCache($identifier) + protected function shouldCache(string $identifier) { return $this->cache && Preg::isMatch('{@\d+$}', $identifier); } @@ -133,7 +133,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier) { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier.'.json')) { @@ -165,7 +165,7 @@ class SvnDriver extends VcsDriver * @param string $file * @param string $identifier */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { $identifier = '/' . trim($identifier, '/') . '/'; @@ -194,7 +194,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate(string $identifier) { $identifier = '/' . trim($identifier, '/') . '/'; @@ -306,7 +306,7 @@ class SvnDriver extends VcsDriver /** * @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) { $url = self::normalizeUrl($url); if (Preg::isMatch('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) { @@ -353,7 +353,7 @@ class SvnDriver extends VcsDriver * * @return string */ - protected static function normalizeUrl($url) + protected static function normalizeUrl(string $url) { $fs = new Filesystem(); if ($fs->isAbsolutePath($url)) { @@ -372,7 +372,7 @@ class SvnDriver extends VcsDriver * @throws \RuntimeException * @return string */ - protected function execute($command, $url) + protected function execute(string $command, string $url) { if (null === $this->util) { $this->util = new SvnUtil($this->baseUrl, $this->io, $this->config, $this->process); @@ -400,7 +400,7 @@ class SvnDriver extends VcsDriver * * @return string */ - protected function buildIdentifier($baseDir, $revision) + protected function buildIdentifier(string $baseDir, int $revision) { return rtrim($baseDir, '/') . $this->packagePath . '/@' . $revision; } diff --git a/src/Composer/Repository/Vcs/VcsDriver.php b/src/Composer/Repository/Vcs/VcsDriver.php index b7f7fb976..abc4feb23 100644 --- a/src/Composer/Repository/Vcs/VcsDriver.php +++ b/src/Composer/Repository/Vcs/VcsDriver.php @@ -79,7 +79,7 @@ abstract class VcsDriver implements VcsDriverInterface * @param string $identifier * @return bool */ - protected function shouldCache($identifier) + protected function shouldCache(string $identifier) { return $this->cache && Preg::isMatch('{^[a-f0-9]{40}$}iD', $identifier); } @@ -87,7 +87,7 @@ abstract class VcsDriver implements VcsDriverInterface /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier) { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { @@ -111,7 +111,7 @@ abstract class VcsDriver implements VcsDriverInterface * * @return array|null */ - protected function getBaseComposerInformation($identifier) + protected function getBaseComposerInformation(string $identifier) { $composerFileContent = $this->getFileContent('composer.json', $identifier); @@ -131,7 +131,7 @@ abstract class VcsDriver implements VcsDriverInterface /** * @inheritDoc */ - public function hasComposerFile($identifier) + public function hasComposerFile(string $identifier) { try { return (bool) $this->getComposerInformation($identifier); @@ -165,7 +165,7 @@ abstract class VcsDriver implements VcsDriverInterface * @return Response * @throws TransportException */ - protected function getContents($url) + protected function getContents(string $url) { $options = $this->repoConfig['options'] ?? array(); diff --git a/src/Composer/Repository/Vcs/VcsDriverInterface.php b/src/Composer/Repository/Vcs/VcsDriverInterface.php index b8c5e842d..ff3a2cdce 100644 --- a/src/Composer/Repository/Vcs/VcsDriverInterface.php +++ b/src/Composer/Repository/Vcs/VcsDriverInterface.php @@ -33,7 +33,7 @@ interface VcsDriverInterface * @param string $identifier Any identifier to a specific branch/tag/commit * @return mixed[] containing all infos from the composer.json file */ - public function getComposerInformation($identifier); + public function getComposerInformation(string $identifier); /** * Return the content of $file or null if the file does not exist. @@ -42,7 +42,7 @@ interface VcsDriverInterface * @param string $identifier * @return string|null */ - public function getFileContent($file, $identifier); + public function getFileContent(string $file, string $identifier); /** * Get the changedate for $identifier. @@ -50,7 +50,7 @@ interface VcsDriverInterface * @param string $identifier * @return \DateTime|null */ - public function getChangeDate($identifier); + public function getChangeDate(string $identifier); /** * Return the root identifier (trunk, master, default/tip ..) @@ -78,14 +78,14 @@ interface VcsDriverInterface * * @return array{type: string, url: string, reference: string, shasum: string}|null */ - public function getDist($identifier); + public function getDist(string $identifier); /** * @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); /** * Return the URL of the repository @@ -101,7 +101,7 @@ interface VcsDriverInterface * @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); /** * Performs any cleanup necessary as the driver is not longer needed @@ -119,5 +119,5 @@ interface VcsDriverInterface * @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); } diff --git a/src/Composer/Repository/VcsRepository.php b/src/Composer/Repository/VcsRepository.php index 11d8df0e9..9a2120098 100644 --- a/src/Composer/Repository/VcsRepository.php +++ b/src/Composer/Repository/VcsRepository.php @@ -434,7 +434,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt * * @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) { // 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 +457,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt * * @return string|false */ - private function validateBranch($branch) + private function validateBranch(string $branch) { try { $normalizedBranch = $this->versionParser->normalizeBranch($branch); @@ -477,7 +477,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt * * @return string|false */ - private function validateTag($version) + private function validateTag(string $version) { try { return $this->versionParser->normalize($version); @@ -496,7 +496,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt * * @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 80de9833c..93572c10a 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 eb6b595db..722cc68f1 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; diff --git a/src/Composer/Repository/WritableRepositoryInterface.php b/src/Composer/Repository/WritableRepositoryInterface.php index 376af2108..8e7eac21e 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 3ddf2eae0..3c1bccdb2 100644 --- a/src/Composer/Script/Event.php +++ b/src/Composer/Script/Event.php @@ -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; diff --git a/src/Composer/SelfUpdate/Keys.php b/src/Composer/SelfUpdate/Keys.php index 8c33a436f..e8ce93045 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 ce959479d..ea51319f7 100644 --- a/src/Composer/SelfUpdate/Versions.php +++ b/src/Composer/SelfUpdate/Versions.php @@ -63,7 +63,7 @@ class Versions * * @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 @@ class Versions * * @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 26eab08b2..54cb83f58 100644 --- a/src/Composer/Util/AuthHelper.php +++ b/src/Composer/Util/AuthHelper.php @@ -41,7 +41,7 @@ class AuthHelper * * @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 @@ class AuthHelper * 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 @@ class AuthHelper * * @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 @@ class AuthHelper * * @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 5eb6b8fe6..4ce3b7599 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 @@ class Bitbucket * @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 @@ class Bitbucket * @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 @@ class Bitbucket * @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 @@ class Bitbucket * * @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 @@ class Bitbucket * @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 948bccee3..26afb80e5 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 @@ class ComposerMirror * * @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 @@ class ComposerMirror * * @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 b0dd79fad..4d2f50d2d 100644 --- a/src/Composer/Util/ConfigValidator.php +++ b/src/Composer/Util/ConfigValidator.php @@ -48,7 +48,7 @@ class ConfigValidator * * @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 257f7ce29..fa2459e2c 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 99aa803c9..c60dd80ec 100644 --- a/src/Composer/Util/Filesystem.php +++ b/src/Composer/Util/Filesystem.php @@ -38,7 +38,7 @@ class Filesystem * * @return bool */ - public function remove($file) + public function remove(string $file) { if (is_dir($file)) { return $this->removeDirectory($file); @@ -57,7 +57,7 @@ class Filesystem * @param string $dir * @return bool */ - public function isDirEmpty($dir) + public function isDirEmpty(string $dir) { $finder = Finder::create() ->ignoreVCS(false) @@ -74,7 +74,7 @@ class Filesystem * * @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 @@ class Filesystem * @throws \RuntimeException * @return bool */ - public function removeDirectory($directory) + public function removeDirectory(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { @@ -142,7 +142,7 @@ class Filesystem * @throws \RuntimeException * @return PromiseInterface */ - public function removeDirectoryAsync($directory) + public function removeDirectoryAsync(string $directory) { $edgeCaseResult = $this->removeEdgeCases($directory); if ($edgeCaseResult !== null) { @@ -177,7 +177,7 @@ class Filesystem * * @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 @@ class Filesystem * @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 @@ class Filesystem * * @return void */ - public function ensureDirectoryExists($directory) + public function ensureDirectoryExists(string $directory) { if (!is_dir($directory)) { if (file_exists($directory)) { @@ -279,7 +279,7 @@ class Filesystem * @throws \RuntimeException * @return bool */ - public function unlink($path) + public function unlink(string $path) { $unlinked = @$this->unlinkImplementation($path); if (!$unlinked) { @@ -310,7 +310,7 @@ class Filesystem * @throws \RuntimeException * @return bool */ - public function rmdir($path) + public function rmdir(string $path) { $deleted = @rmdir($path); if (!$deleted) { @@ -345,7 +345,7 @@ class Filesystem * * @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 @@ class Filesystem * @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 @@ class Filesystem * * @return void */ - public function rename($source, $target) + public function rename(string $source, string $target) { if (true === @rename($source, $target)) { return; @@ -445,7 +445,7 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * @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 @@ class Filesystem * * @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 @@ class Filesystem * @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 @@ class Filesystem * * @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 @@ class Filesystem * * @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 @@ class Filesystem * @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 @@ class Filesystem * * @return bool */ - public function isSymlinkedDirectory($directory) + public function isSymlinkedDirectory(string $directory) { if (!is_dir($directory)) { return false; @@ -767,7 +767,7 @@ class Filesystem * * @return bool */ - private function unlinkSymlinkedDirectory($directory): bool + private function unlinkSymlinkedDirectory(string $directory): bool { $resolved = $this->resolveSymlinkedDirectorySymlink($directory); @@ -781,7 +781,7 @@ class Filesystem * * @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 @@ class Filesystem * * @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 @@ class Filesystem * @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 @@ class Filesystem * @param string $junction * @return bool */ - public function removeJunction($junction) + public function removeJunction(string $junction) { if (!Platform::isWindows()) { return false; @@ -887,7 +887,7 @@ class Filesystem * * @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 @@ class Filesystem * * @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 @@ class Filesystem * * @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 27dc75a0d..7c9482a5c 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -49,7 +49,7 @@ class Git * * @return void */ - public function runCommand($commandCallable, $url, $cwd, $initialClone = false) + public function runCommand(callable $commandCallable, string $url, ?string $cwd, bool $initialClone = false) { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -272,7 +272,7 @@ class Git * * @return bool */ - public function syncMirror($url, $dir) + public function syncMirror(string $url, string $dir) { 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 @@ class Git * * @return bool */ - public function fetchRefOrSyncMirror($url, $dir, $ref) + public function fetchRefOrSyncMirror(string $url, string $dir, string $ref) { if ($this->checkRefIsInMirror($dir, $ref)) { return true; @@ -349,7 +349,7 @@ class Git * * @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 @@ class Git * * @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; @@ -441,7 +441,7 @@ class Git * * @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(); @@ -476,7 +476,7 @@ class Git * * @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 f20cb2376..4390bb8ac 100644 --- a/src/Composer/Util/GitHub.php +++ b/src/Composer/Util/GitHub.php @@ -54,7 +54,7 @@ class GitHub * @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 @@ class GitHub * @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 4bd61d792..97c920dde 100644 --- a/src/Composer/Util/GitLab.php +++ b/src/Composer/Util/GitLab.php @@ -55,7 +55,7 @@ class GitLab * * @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 @@ class GitLab * * @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 @@ class GitLab * * @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 da8c3329a..7797fe1a4 100644 --- a/src/Composer/Util/Hg.php +++ b/src/Composer/Util/Hg.php @@ -53,7 +53,7 @@ class Hg * * @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 @@ class Hg * * @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 eeff04e1f..327c09976 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 @@ class CurlDownloader * @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 @@ class CurlDownloader * @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 @@ class CurlDownloader * @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 @@ class CurlDownloader * * @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 @@ class CurlDownloader * @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 @@ class CurlDownloader * @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 db19db62d..49c89c215 100644 --- a/src/Composer/Util/Http/ProxyHelper.php +++ b/src/Composer/Util/Http/ProxyHelper.php @@ -64,7 +64,7 @@ class ProxyHelper * * @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 @@ class ProxyHelper * * @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 @@ class ProxyHelper * * @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 @@ class ProxyHelper * @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 @@ class ProxyHelper * * @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 5f11c8242..df7db9f5f 100644 --- a/src/Composer/Util/Http/ProxyManager.php +++ b/src/Composer/Util/Http/ProxyManager.php @@ -83,7 +83,7 @@ class ProxyManager * @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 @@ class ProxyManager * @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 e60c1a19c..eaf3f9452 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 @@ class RequestProxy * @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 4c9072fac..5556b6754 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 @@ class Response * @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 @@ class Response * @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 b919680f2..80d1385c0 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 @@ class HttpDownloader * @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 @@ class HttpDownloader * @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 @@ class HttpDownloader * @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 @@ class HttpDownloader * @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 @@ class HttpDownloader } /** - * @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 @@ class HttpDownloader * @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 @@ class HttpDownloader * * @return void */ - public function wait($index = null) + public function wait(?int $index = null) { do { $jobCount = $this->countActiveJobs($index); @@ -366,7 +364,7 @@ class HttpDownloader * @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 @@ class HttpDownloader * @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 @@ class HttpDownloader * @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 a81a88a5b..2ae475561 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 @@ class NoProxyPattern * * @return bool */ - public function test($url): bool + public function test(string $url): bool { if ($this->noproxy) { return true; @@ -77,7 +77,7 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @return string */ - private function ipGetMask($prefix, $size): string + private function ipGetMask(int $prefix, int $size): string { $mask = ''; @@ -305,7 +305,7 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 @@ class NoProxyPattern * * @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 559e8c311..058180783 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 @@ class Perforce * * @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) { return new Perforce($repoConfig, $port, $path, $process, Platform::isWindows(), $io); } @@ -96,7 +96,7 @@ class Perforce * * @return bool */ - public static function checkServerExists($url, ProcessExecutor $processExecutor) + public static function checkServerExists(string $url, ProcessExecutor $processExecutor) { return 0 === $processExecutor->execute('p4 -p ' . ProcessExecutor::escape($url) . ' info -s', $ignoredOutput); } @@ -138,7 +138,7 @@ class Perforce * * @return void */ - public function initializeDepotAndBranch($depot, $branch) + public function initializeDepotAndBranch(?string $depot, ?string $branch) { if (isset($depot)) { $this->p4Depot = $depot; @@ -209,7 +209,7 @@ class Perforce * * @return void */ - public function initializePath($path) + public function initializePath(string $path) { $this->path = $path; $fs = $this->getFilesystem(); @@ -229,7 +229,7 @@ class Perforce * * @return void */ - public function setStream($stream) + public function setStream(string $stream) { $this->p4Stream = $stream; $index = strrpos($stream, '/'); @@ -268,7 +268,7 @@ class Perforce * * @return string */ - public function getStreamWithoutLabel($stream) + public function getStreamWithoutLabel(string $stream) { $index = strpos($stream, '@'); if ($index === false) { @@ -299,7 +299,7 @@ class Perforce * * @return void */ - public function setUser($user) + public function setUser(?string $user) { $this->p4User = $user; } @@ -330,7 +330,7 @@ class Perforce * @param string $name * @return ?string */ - protected function getP4variable($name) + protected function getP4variable(string $name) { if ($this->windowsFlag) { $command = 'p4 set'; @@ -385,7 +385,7 @@ class Perforce * * @return non-empty-string */ - public function generateP4Command($command, $useClient = true) + public function generateP4Command(string $command, bool $useClient = true) { $p4Command = 'p4 '; $p4Command .= '-u ' . $this->getUser() . ' '; @@ -436,9 +436,9 @@ class Perforce * * @return void */ - public function syncCodeBase($sourceReference) + public function syncCodeBase(?string $sourceReference) { - $prevDir = getcwd(); + $prevDir = Platform::getCwd(); chdir($this->path); $p4SyncCommand = $this->generateP4Command('sync -f '); if (null !== $sourceReference) { @@ -514,7 +514,7 @@ class Perforce * * @return int */ - public function windowsLogin($password) + public function windowsLogin(?string $password) { $command = $this->generateP4Command(' login -a'); @@ -548,7 +548,7 @@ class Perforce * * @return mixed|void */ - public function getComposerInformation($identifier) + public function getComposerInformation(string $identifier) { $composerFileContent = $this->getFileContent('composer.json', $identifier); @@ -565,7 +565,7 @@ class Perforce * * @return string|null */ - public function getFileContent($file, $identifier) + public function getFileContent(string $file, string $identifier) { $path = $this->getFilePath($file, $identifier); @@ -586,7 +586,7 @@ class Perforce * * @return string|null */ - public function getFilePath($file, $identifier) + public function getFilePath(string $file, string $identifier) { $index = strpos($identifier, '@'); if ($index === false) { @@ -690,7 +690,7 @@ class Perforce * @param string $reference * @return mixed|null */ - protected function getChangeList($reference) + protected function getChangeList(string $reference) { $index = strpos($reference, '@'); if ($index === false) { @@ -713,7 +713,7 @@ class Perforce * @param string $toReference * @return mixed|null */ - public function getCommitLogs($fromReference, $toReference) + public function getCommitLogs(string $fromReference, string $toReference) { $fromChangeList = $this->getChangeList($fromReference); if ($fromChangeList === null) { diff --git a/src/Composer/Util/Platform.php b/src/Composer/Util/Platform.php index d237f8ea1..4e58cecbb 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 @@ class Platform * @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 @@ class Platform * @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 @@ class Platform * @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 @@ class Platform * @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 fb661bac4..05060bbfb 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -65,10 +65,10 @@ class ProcessExecutor * @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) { if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); @@ -81,10 +81,10 @@ class ProcessExecutor * 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) { if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); @@ -95,12 +95,12 @@ class ProcessExecutor /** * @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); @@ -140,7 +140,7 @@ class ProcessExecutor * @param string $cwd the working directory * @return PromiseInterface */ - public function executeAsync($command, $cwd = null) + public function executeAsync($command, ?string $cwd = null) { 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'); @@ -210,7 +210,7 @@ class ProcessExecutor * @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) { @@ -321,10 +321,10 @@ class ProcessExecutor } /** - * @param ?string $output + * @param null|string $output * @return string[] */ - public function splitLines($output) + public function splitLines(?string $output) { $output = trim((string) $output); @@ -349,7 +349,7 @@ class ProcessExecutor * * @return void */ - public function outputHandler($type, $buffer) + public function outputHandler($type, string $buffer) { if ($this->captureOutput) { return; @@ -380,7 +380,7 @@ class ProcessExecutor * @param int $timeout the timeout in seconds * @return void */ - public static function setTimeout($timeout) + public static function setTimeout(int $timeout) { static::$timeout = $timeout; } diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 1d6866f7a..2d4865b07 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 @@ class RemoteFilesystem * * @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()): bool { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); } @@ -121,7 +121,7 @@ class RemoteFilesystem * * @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); } @@ -217,7 +217,7 @@ class RemoteFilesystem * * @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 @@ class RemoteFilesystem * * @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 @@ class RemoteFilesystem * * @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): void { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: @@ -592,7 +592,7 @@ class RemoteFilesystem * * @return void */ - protected function promptAuthAndRetry($httpStatus, $reason = null, $headers = array()): void + protected function promptAuthAndRetry($httpStatus, ?string $reason = null, array $headers = array()): void { $result = $this->authHelper->promptAuthIfNeeded($this->fileUrl, $this->originUrl, $httpStatus, $reason, $headers); @@ -610,7 +610,7 @@ class RemoteFilesystem * * @return mixed[] */ - protected function getOptionsForUrl($originUrl, $additionalOptions): array + protected function getOptionsForUrl(string $originUrl, array $additionalOptions): array { $tlsOptions = array(); $headers = array(); @@ -698,7 +698,7 @@ class RemoteFilesystem * * @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 75a97575b..484b5a5c7 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 @@ class Silencer /** * 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 7448990d3..a4b1dbd4a 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 @@ final class StreamContextFactory * @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 5c47d408c..86416e56d 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 @@ class Svn * 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 @@ class Svn * @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 @@ class Svn * @param bool $cacheCredentials * @return void */ - public function setCacheCredentials($cacheCredentials): void + public function setCacheCredentials(bool $cacheCredentials): void { $this->cacheCredentials = $cacheCredentials; } @@ -205,7 +196,7 @@ class Svn * @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 @@ class 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 f61d02dbe..c245d2132 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 9d4f7f112..05f2229f0 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 697a66b17..78829e60e 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 @@ final class TlsHelper * @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 @@ final class TlsHelper * * @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 d118054d2..6089da925 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 @@ class Url * @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 @@ class Url * @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 3e448048d..342c1d3b7 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 @@ class Zip * * @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 9b33ec1b0..39eba0065 100644 --- a/src/bootstrap.php +++ b/src/bootstrap.php @@ -14,7 +14,7 @@ * @param string $file * @return ?\Composer\Autoload\ClassLoader */ -function includeIfExists($file) +function includeIfExists(string $file) { return file_exists($file) ? include $file : null; } diff --git a/tests/Composer/Test/AllFunctionalTest.php b/tests/Composer/Test/AllFunctionalTest.php index 12bd95e3d..2bebf801c 100644 --- a/tests/Composer/Test/AllFunctionalTest.php +++ b/tests/Composer/Test/AllFunctionalTest.php @@ -14,6 +14,7 @@ namespace Composer\Test; 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 @@ class AllFunctionalTest extends TestCase * @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 @@ class AllFunctionalTest extends TestCase * @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 @@ class AllFunctionalTest extends TestCase * @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 30aab4988..e0674c4fa 100644 --- a/tests/Composer/Test/ApplicationTest.php +++ b/tests/Composer/Test/ApplicationTest.php @@ -84,7 +84,7 @@ class ApplicationTest extends TestCase * @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 06c12cfb5..507d161b1 100644 --- a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php +++ b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php @@ -122,7 +122,7 @@ class AutoloadGeneratorTest extends TestCase return $ret; })); - $this->origDir = getcwd(); + $this->origDir = Platform::getCwd(); chdir($this->workingDir); $this->im = $this->getMockBuilder('Composer\Installer\InstallationManager') @@ -1705,11 +1705,11 @@ EOF; * @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 @@ EOF; * * @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 d11c522a9..27f96d6b7 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 5315c4b33..302ab6094 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 @@ class ClassMapGeneratorTest extends TestCase * @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 88cc15fe1..9ad7bf73f 100644 --- a/tests/Composer/Test/Command/ArchiveCommandTest.php +++ b/tests/Composer/Test/Command/ArchiveCommandTest.php @@ -16,6 +16,7 @@ use Composer\Composer; 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 @@ class ArchiveCommandTest extends TestCase ->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/RunScriptCommandTest.php b/tests/Composer/Test/Command/RunScriptCommandTest.php index 7a9d7aef8..200ae7c9a 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 fd0e1f3e4..818e22db3 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 @@ class JsonConfigSourceTest extends TestCase * * @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 @@ class JsonConfigSourceTest extends TestCase * * @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 @@ class JsonConfigSourceTest extends TestCase * * @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 @@ class JsonConfigSourceTest extends TestCase * * @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 17f4384c2..924806e60 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 @@ class ConfigTest extends TestCase * * @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 @@ class ConfigTest extends TestCase * * @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 92b9840a8..913fa5470 100644 --- a/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php @@ -30,6 +30,7 @@ use Composer\Package\Version\VersionParser; 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 @@ class PoolBuilderTest extends TestCase return $pkg; }; - $oldCwd = getcwd(); + $oldCwd = Platform::getCwd(); chdir(__DIR__.'/Fixtures/poolbuilder/'); $repositorySet = new RepositorySet($minimumStability, $stabilityFlags, $rootAliases, $rootReferences); @@ -149,7 +150,7 @@ class PoolBuilderTest extends TestCase * @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 @@ class PoolBuilderTest extends TestCase * @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 1f78a4013..a9f87feaa 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 @@ class PoolOptimizerTest extends TestCase * @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 c4c5185ae..3d24f9fdf 100644 --- a/tests/Composer/Test/DependencyResolver/PoolTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolTest.php @@ -61,7 +61,7 @@ class PoolTest extends TestCase * @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 00e31a3cb..4b95b2bd9 100644 --- a/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php @@ -93,7 +93,7 @@ class ArchiveDownloaderTest extends TestCase * @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 @@ class ArchiveDownloaderTest extends TestCase * @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 b3eb77c26..7fa25f717 100644 --- a/tests/Composer/Test/Downloader/DownloadManagerTest.php +++ b/tests/Composer/Test/Downloader/DownloadManagerTest.php @@ -630,13 +630,13 @@ class DownloadManagerTest extends TestCase /** * @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) { diff --git a/tests/Composer/Test/Downloader/FileDownloaderTest.php b/tests/Composer/Test/Downloader/FileDownloaderTest.php index d3f9c0056..c14735162 100644 --- a/tests/Composer/Test/Downloader/FileDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FileDownloaderTest.php @@ -20,33 +20,30 @@ use Composer\Test\TestCase; 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 @@ class FileDownloaderTest extends TestCase ->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 @@ class FileDownloaderTest extends TestCase 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 @@ class FileDownloaderTest extends TestCase })) ; - $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 @@ class FileDownloaderTest extends TestCase { $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'))); + $package = $this->getPackage(); + $package->setDistUrl('url'); - $rootPackageMock = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - $rootPackageMock->expects($this->any()) - ->method('getScripts') - ->will($this->returnValue(array())); + $rootPackage = $this->getRootPackage(); - $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'; - } - })); + $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 @@ class FileDownloaderTest extends TestCase ); })); - $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 @@ class FileDownloaderTest extends TestCase { $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'))); + $package = $this->getPackage(); + $package->setDistUrl('url'); - $rootPackageMock = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); - $rootPackageMock->expects($this->any()) - ->method('getScripts') - ->will($this->returnValue(array())); + $rootPackage = $this->getRootPackage(); - $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'; - } - })); + $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 @@ class FileDownloaderTest extends TestCase ); })); - $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 @@ class FileDownloaderTest extends TestCase { $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 @@ class FileDownloaderTest extends TestCase ->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']); + + $downloader = $this->getDownloader(null, $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, $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 @@ class FileDownloaderTest extends TestCase 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 @@ class FileDownloaderTest extends TestCase ); $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 2ba0e33f0..932fa5a36 100644 --- a/tests/Composer/Test/Downloader/FossilDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FossilDownloaderTest.php @@ -42,10 +42,10 @@ class FossilDownloaderTest extends TestCase * @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 fce2ba033..91b90b369 100644 --- a/tests/Composer/Test/Downloader/GitDownloaderTest.php +++ b/tests/Composer/Test/Downloader/GitDownloaderTest.php @@ -62,7 +62,7 @@ class GitDownloaderTest extends TestCase * @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 @@ class GitDownloaderTest extends TestCase * @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 @@ class GitDownloaderTest extends TestCase * @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 @@ composer https://github.com/old/url (push) * @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 81a039a24..135194263 100644 --- a/tests/Composer/Test/Downloader/HgDownloaderTest.php +++ b/tests/Composer/Test/Downloader/HgDownloaderTest.php @@ -42,7 +42,7 @@ class HgDownloaderTest extends TestCase * @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 16bd4d128..f8a8e16c6 100644 --- a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php +++ b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php @@ -53,16 +53,9 @@ class PerforceDownloaderTest extends TestCase $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 1f2501d37..f20129bfb 100644 --- a/tests/Composer/Test/Downloader/XzDownloaderTest.php +++ b/tests/Composer/Test/Downloader/XzDownloaderTest.php @@ -51,33 +51,18 @@ class XzDownloaderTest extends TestCase 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 49e9dcda4..9b0ca2382 100644 --- a/tests/Composer/Test/Downloader/ZipDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ZipDownloaderTest.php @@ -57,7 +57,7 @@ class ZipDownloaderTest extends TestCase * @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); diff --git a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php index 57b8efb5c..fc57a1241 100644 --- a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php +++ b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php @@ -56,7 +56,7 @@ class EventDispatcherTest extends TestCase * * @param string $command */ - public function testDispatcherCanExecuteSingleCommandLineScript($command): void + public function testDispatcherCanExecuteSingleCommandLineScript(string $command): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -85,7 +85,7 @@ class EventDispatcherTest extends TestCase * * @param bool $devMode */ - public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($devMode): void + public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents(bool $devMode): void { $composer = $this->createComposerInstance(); @@ -288,7 +288,7 @@ class EventDispatcherTest extends TestCase 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 @@ class EventDispatcherTest extends TestCase * * @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 d7dcd9b33..1c3b79a6e 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 47af67fd2..dd1f71d85 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 8b5b1f897..02b6ad50c 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 9cfb96faf..e23e90ece 100644 --- a/tests/Composer/Test/InstalledVersionsTest.php +++ b/tests/Composer/Test/InstalledVersionsTest.php @@ -74,7 +74,7 @@ class InstalledVersionsTest extends TestCase * @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 @@ class InstalledVersionsTest extends TestCase * @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 @@ class InstalledVersionsTest extends TestCase * @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 @@ class InstalledVersionsTest extends TestCase /** * @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 @@ class InstalledVersionsTest extends TestCase /** * @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 @@ class InstalledVersionsTest extends TestCase /** * @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 821bc3ce4..28b1f0fc0 100644 --- a/tests/Composer/Test/Installer/BinaryInstallerTest.php +++ b/tests/Composer/Test/Installer/BinaryInstallerTest.php @@ -68,7 +68,7 @@ class BinaryInstallerTest extends TestCase * @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/InstallerTest.php b/tests/Composer/Test/InstallerTest.php index a38d02424..04e4346c0 100644 --- a/tests/Composer/Test/InstallerTest.php +++ b/tests/Composer/Test/InstallerTest.php @@ -21,7 +21,6 @@ use Symfony\Component\Console\Command\Command; 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 @@ class InstallerTest extends TestCase * @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 @@ class InstallerTest extends TestCase * @param PackageInterface[] $packages * @return mixed[] */ - protected function makePackagesComparable($packages): array + protected function makePackagesComparable(array $packages): array { $dumper = new ArrayDumper(); @@ -190,7 +189,7 @@ class InstallerTest extends TestCase $cases[] = array( $a, - new ArrayRepository(array($b)), + [new ArrayRepository(array($b))], array( 'install' => array($b), ), @@ -210,7 +209,7 @@ class InstallerTest extends TestCase $cases[] = array( $a, - new ArrayRepository(array($a, $b)), + [new ArrayRepository(array($a, $b))], array( 'install' => array($b), ), @@ -225,19 +224,19 @@ class InstallerTest extends TestCase * @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 @@ class InstallerTest extends TestCase * @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 @@ class InstallerTest extends TestCase * @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 @@ class InstallerTest extends TestCase /** * @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 @@ class InstallerTest extends TestCase * @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 @@ class InstallerTest extends TestCase * @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 474523b46..e6aea2271 100644 --- a/tests/Composer/Test/Json/ComposerSchemaTest.php +++ b/tests/Composer/Test/Json/ComposerSchemaTest.php @@ -94,7 +94,7 @@ class ComposerSchemaTest extends TestCase * @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 131730c9d..02ede63dc 100644 --- a/tests/Composer/Test/Json/JsonFileTest.php +++ b/tests/Composer/Test/Json/JsonFileTest.php @@ -351,7 +351,7 @@ class JsonFileTest extends TestCase * @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 @@ class JsonFileTest extends TestCase * @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 6d0900b91..533751132 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 @@ class JsonManipulatorTest extends TestCase * @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 @@ class JsonManipulatorTest extends TestCase * @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 79c436833..863368303 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 @@ class JsonValidationExceptionTest extends TestCase { 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 8db24fe11..17e21c83b 100644 --- a/tests/Composer/Test/Mock/FactoryMock.php +++ b/tests/Composer/Test/Mock/FactoryMock.php @@ -14,7 +14,6 @@ namespace Composer\Test\Mock; 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\Repository\RepositoryManager; 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 277ead749..97f4c3f56 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 @@ class ProcessExecutorMock extends ProcessExecutor 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 @@ class ProcessExecutorMock extends ProcessExecutor public function executeTty($command, $cwd = null): int { + $cwd = $cwd ?? Platform::getCwd(); if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); } @@ -125,10 +127,10 @@ class ProcessExecutorMock extends ProcessExecutor * @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 = ''; @@ -174,7 +176,7 @@ class ProcessExecutorMock extends ProcessExecutor 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 ad9bce604..8ef013b27 100644 --- a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php @@ -279,7 +279,7 @@ class ArchivableFilesFinderTest extends TestCase * * @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 @@ class ArchivableFilesFinderTest extends TestCase * * @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 8d620fbc9..04f098355 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php @@ -18,6 +18,7 @@ use Composer\Package\Archiver\ArchiveManager; 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 @@ class ArchiveManagerTest extends ArchiverTest * * @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 @@ class ArchiveManagerTest extends ArchiverTest */ 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 5ac901d1b..eecd8dff2 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiverTest.php @@ -55,7 +55,7 @@ abstract class ArchiverTest extends TestCase 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 2c8f96a2e..32c255cfc 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 5c571316a..22ebb83d5 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 @@ class PharArchiverTest extends ArchiverTest */ protected function setupDummyRepo(): void { - $currentWorkDir = getcwd(); + $currentWorkDir = Platform::getCwd(); chdir($this->testDir); $this->writeFile('file.txt', 'content', $currentWorkDir); @@ -72,7 +73,7 @@ class PharArchiverTest extends ArchiverTest * * @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 e88711a4c..7e4fb7f89 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 @@ class ZipArchiverTest extends ArchiverTest ); if (!Platform::isWindows()) { - $files['foo' . getcwd() . '/file.txt'] = null; + $files['foo' . Platform::getCwd() . '/file.txt'] = null; } } // Set up repository @@ -89,7 +89,7 @@ class ZipArchiverTest extends ArchiverTest */ 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 @@ class ZipArchiverTest extends ArchiverTest * * @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 3b92316b2..90921bc7c 100644 --- a/tests/Composer/Test/Package/BasePackageTest.php +++ b/tests/Composer/Test/Package/BasePackageTest.php @@ -49,7 +49,7 @@ class BasePackageTest extends TestCase * @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 @@ class BasePackageTest extends TestCase * * @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 2f8de80d1..4f57dff14 100644 --- a/tests/Composer/Test/Package/CompletePackageTest.php +++ b/tests/Composer/Test/Package/CompletePackageTest.php @@ -40,7 +40,7 @@ class CompletePackageTest extends TestCase * @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 @@ class CompletePackageTest extends TestCase * @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 @@ class CompletePackageTest extends TestCase * @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 b5ee6d073..6b4315363 100644 --- a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php +++ b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php @@ -95,7 +95,7 @@ class ArrayDumperTest extends TestCase * @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(); @@ -248,7 +248,7 @@ class ArrayDumperTest extends TestCase * @param string $method * @param mixed $value */ - private function packageExpects($method, $value): \Composer\Test\Package\Dumper\ArrayDumperTest + private function packageExpects(string $method, $value): ArrayDumperTest { $this->package ->expects($this->any()) diff --git a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php index cc961575e..2324ad0c2 100644 --- a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php @@ -139,7 +139,7 @@ class ArrayLoaderTest extends TestCase * * @return array */ - protected function fixConfigWhenLoadConfigIsFalse($config): array + protected function fixConfigWhenLoadConfigIsFalse(array $config): array { $expectedConfig = $config; unset($expectedConfig['transport-options']); @@ -155,7 +155,7 @@ class ArrayLoaderTest extends TestCase * * @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 @@ class ArrayLoaderTest extends TestCase * * @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 @@ class ArrayLoaderTest extends TestCase * * @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 @@ class ArrayLoaderTest extends TestCase * * @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 a2fa3730a..a669f669f 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 0b214cb56..a8204a76f 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 @@ class ValidatingArrayLoaderTest extends TestCase * @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 @@ class ValidatingArrayLoaderTest extends TestCase * @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 @@ class ValidatingArrayLoaderTest extends TestCase * @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/Version/VersionParserTest.php b/tests/Composer/Test/Package/Version/VersionParserTest.php index e467ba25e..2f120a7f8 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 @@ class VersionParserTest extends TestCase * @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 7a8041031..4ff61029c 100644 --- a/tests/Composer/Test/Package/Version/VersionSelectorTest.php +++ b/tests/Composer/Test/Package/Version/VersionSelectorTest.php @@ -299,7 +299,7 @@ class VersionSelectorTest extends TestCase * @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 @@ class VersionSelectorTest extends TestCase * * @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 f2cf6f8f2..4ae361bb5 100644 --- a/tests/Composer/Test/Platform/VersionTest.php +++ b/tests/Composer/Test/Platform/VersionTest.php @@ -79,7 +79,7 @@ class VersionTest extends TestCase * @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 @@ class VersionTest extends TestCase * @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 @@ class VersionTest extends TestCase * @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 325f26671..dcc0ecabf 100644 --- a/tests/Composer/Test/Plugin/PluginInstallerTest.php +++ b/tests/Composer/Test/Plugin/PluginInstallerTest.php @@ -280,7 +280,7 @@ class PluginInstallerTest extends TestCase * * @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 +421,12 @@ class PluginInstallerTest extends TestCase ); } - /** @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 +444,6 @@ class PluginInstallerTest extends TestCase $this->pm->getPluginCapability($plugin, $capabilityApi); } - /** @return void */ public function testQueryingNonProvidedCapabilityReturnsNullSafely(): void { $capabilityApi = 'Composer\Plugin\Capability\MadeUpCapability'; @@ -472,13 +460,19 @@ class PluginInstallerTest extends TestCase $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 7d9c94a75..2c21d869d 100644 --- a/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php +++ b/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php @@ -45,7 +45,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @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 @@ class StrictConfirmationQuestionTest extends TestCase * @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 @@ class StrictConfirmationQuestionTest extends TestCase * * @return resource */ - protected function getInputStream($input) + protected function getInputStream(string $input) { $stream = fopen('php://memory', 'r+', false); $this->assertNotFalse($stream); @@ -131,7 +131,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @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 f6076b3f5..fcfc2fa4c 100644 --- a/tests/Composer/Test/Repository/ComposerRepositoryTest.php +++ b/tests/Composer/Test/Repository/ComposerRepositoryTest.php @@ -279,7 +279,7 @@ class ComposerRepositoryTest extends TestCase * @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 1cf8cbe84..edf914e73 100644 --- a/tests/Composer/Test/Repository/CompositeRepositoryTest.php +++ b/tests/Composer/Test/Repository/CompositeRepositoryTest.php @@ -132,7 +132,7 @@ class CompositeRepositoryTest extends TestCase * @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 3a1c34e11..eb96d876f 100644 --- a/tests/Composer/Test/Repository/FilterRepositoryTest.php +++ b/tests/Composer/Test/Repository/FilterRepositoryTest.php @@ -40,7 +40,7 @@ class FilterRepositoryTest extends TestCase * @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 9717a4457..5d6888787 100644 --- a/tests/Composer/Test/Repository/PathRepositoryTest.php +++ b/tests/Composer/Test/Repository/PathRepositoryTest.php @@ -14,6 +14,7 @@ namespace Composer\Test\Repository; use Composer\Repository\PathRepository; use Composer\Test\TestCase; +use Composer\Util\Platform; class PathRepositoryTest extends TestCase { @@ -140,7 +141,7 @@ class PathRepositoryTest extends TestCase $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 68418d72b..22445b4df 100644 --- a/tests/Composer/Test/Repository/PlatformRepositoryTest.php +++ b/tests/Composer/Test/Repository/PlatformRepositoryTest.php @@ -1085,7 +1085,7 @@ Linked Version => 1.2.11', */ public function testLibraryInformation( $extensions, - $info, + ?string $info, array $expectations, array $functions = array(), array $constants = array(), @@ -1199,7 +1199,7 @@ Linked Version => 1.2.11', * * @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 @@ Linked Version => 1.2.11', * @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 14db37204..fcf826e14 100644 --- a/tests/Composer/Test/Repository/RepositoryManagerTest.php +++ b/tests/Composer/Test/Repository/RepositoryManagerTest.php @@ -15,6 +15,7 @@ namespace Composer\Test\Repository; use Composer\Repository\RepositoryManager; use Composer\Test\TestCase; use Composer\Util\Filesystem; +use Composer\Config; class RepositoryManagerTest extends TestCase { @@ -39,7 +40,7 @@ class RepositoryManagerTest extends TestCase { $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 @@ class RepositoryManagerTest extends TestCase * @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 @@ class RepositoryManagerTest extends TestCase $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 cd51b6c3c..1857cf262 100644 --- a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php @@ -61,7 +61,7 @@ class FossilDriverTest extends TestCase * @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 144852f5a..d616e3798 100644 --- a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php @@ -99,7 +99,7 @@ class GitBitbucketDriverTest extends TestCase $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 @@ class GitBitbucketDriverTest extends TestCase * @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 8482b28bd..77debc3c7 100644 --- a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php @@ -327,7 +327,7 @@ class GitHubDriverTest extends TestCase * @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 +353,7 @@ class GitHubDriverTest extends TestCase * * @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 b2706d613..812c1bf05 100644 --- a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php @@ -92,7 +92,7 @@ class GitLabDriverTest extends TestCase * @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 fd94cf945..0d6948415 100644 --- a/tests/Composer/Test/Repository/Vcs/HgDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/HgDriverTest.php @@ -50,7 +50,7 @@ class HgDriverTest extends TestCase * * @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 00acd67df..f1787e71c 100644 --- a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php @@ -102,7 +102,7 @@ class PerforceDriverTest extends TestCase * * @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 f08891a41..e18f64af3 100644 --- a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php @@ -100,7 +100,7 @@ class SvnDriverTest extends TestCase * @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 819dcd08d..a4e175397 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 @@ class VcsRepositoryTest extends TestCase return; } - $oldCwd = getcwd(); + $oldCwd = Platform::getCwd(); self::$composerHome = $this->getUniqueTmpDirectory(); self::$gitRepo = $this->getUniqueTmpDirectory(); @@ -64,7 +65,7 @@ class VcsRepositoryTest extends TestCase // 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 a8136edb5..e901822ba 100644 --- a/tests/Composer/Test/TestCase.php +++ b/tests/Composer/Test/TestCase.php @@ -100,7 +100,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $version * @return Constraint */ - protected function getVersionConstraint($operator, $version): Constraint + protected function getVersionConstraint($operator, string $version): Constraint { $constraint = new Constraint( $operator, @@ -124,18 +124,25 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @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') { $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 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase } } + /** + * @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 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * * @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 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * * @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 d12f87066..cf0a9e8fc 100644 --- a/tests/Composer/Test/Util/AuthHelperTest.php +++ b/tests/Composer/Test/Util/AuthHelperTest.php @@ -158,7 +158,7 @@ class AuthHelperTest extends TestCase * * @param string $password */ - public function testAddAuthenticationHeaderWithGitlabPrivateToken($password): void + public function testAddAuthenticationHeaderWithGitlabPrivateToken(string $password): void { $headers = array( 'Accept-Encoding: gzip', @@ -235,7 +235,7 @@ class AuthHelperTest extends TestCase * * @param string $url */ - public function testAddAuthenticationHeaderWithBitbucketPublicUrl($url): void + public function testAddAuthenticationHeaderWithBitbucketPublicUrl(string $url): void { $headers = array( 'Accept-Encoding: gzip', @@ -299,7 +299,7 @@ class AuthHelperTest extends TestCase * * @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 @@ class AuthHelperTest extends TestCase * * @param string $url */ - public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl($url): void + public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl(string $url): void { $this->assertTrue($this->authHelper->isPublicBitBucketDownload($url)); } @@ -521,7 +521,7 @@ class AuthHelperTest extends TestCase * * @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 643b1f64e..525e90456 100644 --- a/tests/Composer/Test/Util/BitbucketTest.php +++ b/tests/Composer/Test/Util/BitbucketTest.php @@ -111,7 +111,7 @@ class BitbucketTest extends TestCase ); } - public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): \Composer\Util\Bitbucket + public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): Bitbucket { $this->config->expects($this->once()) ->method('get') @@ -411,7 +411,7 @@ class BitbucketTest extends TestCase * * @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 dc6706b27..20298d534 100644 --- a/tests/Composer/Test/Util/FilesystemTest.php +++ b/tests/Composer/Test/Util/FilesystemTest.php @@ -59,7 +59,7 @@ class FilesystemTest extends TestCase * @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 @@ class FilesystemTest extends TestCase * @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 @@ class FilesystemTest extends TestCase * @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 e6df4e1ed..c91a34248 100644 --- a/tests/Composer/Test/Util/GitTest.php +++ b/tests/Composer/Test/Util/GitTest.php @@ -47,7 +47,7 @@ class GitTest extends TestCase * @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 @@ class GitTest extends TestCase * @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 @@ class GitTest extends TestCase * * @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 15fd85069..4de4c654a 100644 --- a/tests/Composer/Test/Util/Http/ProxyHelperTest.php +++ b/tests/Composer/Test/Util/Http/ProxyHelperTest.php @@ -49,7 +49,7 @@ class ProxyHelperTest extends TestCase * * @param string $url */ - public function testThrowsOnMalformedUrl($url): void + public function testThrowsOnMalformedUrl(string $url): void { $_SERVER['http_proxy'] = $url; @@ -71,7 +71,7 @@ class ProxyHelperTest extends TestCase * @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 @@ class ProxyHelperTest extends TestCase * @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 @@ class ProxyHelperTest extends TestCase * @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 @@ class ProxyHelperTest extends TestCase * * @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 @@ class ProxyHelperTest extends TestCase * @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 729e12da3..ea5eb78f7 100644 --- a/tests/Composer/Test/Util/Http/ProxyManagerTest.php +++ b/tests/Composer/Test/Util/Http/ProxyManagerTest.php @@ -77,7 +77,7 @@ class ProxyManagerTest extends TestCase * @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 @@ class ProxyManagerTest extends TestCase * @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 @@ class ProxyManagerTest extends TestCase $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 120ff8263..474c6857e 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 @@ class RequestProxyTest extends TestCase * @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 c70c9774d..7b00da615 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 @@ class NoProxyPatternTest extends TestCase * @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 @@ class NoProxyPatternTest extends TestCase * @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 @@ class NoProxyPatternTest extends TestCase * @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 @@ class NoProxyPatternTest extends TestCase * * @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 4f25f5633..63734925f 100644 --- a/tests/Composer/Test/Util/PackageSorterTest.php +++ b/tests/Composer/Test/Util/PackageSorterTest.php @@ -108,7 +108,7 @@ class PackageSorterTest extends TestCase * @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 @@ class PackageSorterTest extends TestCase * * @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 4e3f7d5b9..b42f484b3 100644 --- a/tests/Composer/Test/Util/PerforceTest.php +++ b/tests/Composer/Test/Util/PerforceTest.php @@ -73,7 +73,7 @@ class PerforceTest extends TestCase * * @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 @@ class PerforceTest extends TestCase * * @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 c0ef2f43e..c1aac5ad7 100644 --- a/tests/Composer/Test/Util/ProcessExecutorTest.php +++ b/tests/Composer/Test/Util/ProcessExecutorTest.php @@ -73,7 +73,7 @@ class ProcessExecutorTest extends TestCase * @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 @@ class ProcessExecutorTest extends TestCase * @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 06df39b88..eebe8f900 100644 --- a/tests/Composer/Test/Util/RemoteFilesystemTest.php +++ b/tests/Composer/Test/Util/RemoteFilesystemTest.php @@ -279,7 +279,7 @@ class RemoteFilesystemTest extends TestCase * @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 @@ class RemoteFilesystemTest extends TestCase * @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 @@ class RemoteFilesystemTest extends TestCase * * @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 @@ class RemoteFilesystemTest extends TestCase * * @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 @@ class RemoteFilesystemTest extends TestCase * * @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 @@ class RemoteFilesystemTest extends TestCase * * @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 0d90672ba..ca78f1c4c 100644 --- a/tests/Composer/Test/Util/StreamContextFactoryTest.php +++ b/tests/Composer/Test/Util/StreamContextFactoryTest.php @@ -39,7 +39,7 @@ class StreamContextFactoryTest extends TestCase * @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 @@ class StreamContextFactoryTest extends TestCase * @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 7aa7c73b2..b6d6062f9 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 1bc7d9151..c6f1514f0 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 650d53875..3a8b084d5 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 @@ class UrlTest extends TestCase * @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)); } From 225b4d7c27f88a1ee53c892f7f0a012829cc5d34 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Tue, 22 Feb 2022 16:57:56 +0100 Subject: [PATCH 2/6] Add some more return types --- src/Composer/DependencyResolver/GenericRule.php | 2 +- src/Composer/DependencyResolver/MultiConflictRule.php | 2 +- src/Composer/DependencyResolver/Rule2Literals.php | 2 +- src/Composer/Package/Link.php | 2 +- src/Composer/Repository/PlatformRepository.php | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Composer/DependencyResolver/GenericRule.php b/src/Composer/DependencyResolver/GenericRule.php index c86aa19cb..ab010db0e 100644 --- a/src/Composer/DependencyResolver/GenericRule.php +++ b/src/Composer/DependencyResolver/GenericRule.php @@ -77,7 +77,7 @@ class GenericRule extends Rule * * @return string */ - public function __toString() + public function __toString(): string { $result = $this->isDisabled() ? 'disabled(' : '('; diff --git a/src/Composer/DependencyResolver/MultiConflictRule.php b/src/Composer/DependencyResolver/MultiConflictRule.php index a7fcb0036..104d578a8 100644 --- a/src/Composer/DependencyResolver/MultiConflictRule.php +++ b/src/Composer/DependencyResolver/MultiConflictRule.php @@ -96,7 +96,7 @@ class MultiConflictRule extends Rule * * @return string */ - public function __toString() + public function __toString(): string { // TODO multi conflict? $result = $this->isDisabled() ? 'disabled(multi(' : '(multi('; diff --git a/src/Composer/DependencyResolver/Rule2Literals.php b/src/Composer/DependencyResolver/Rule2Literals.php index cbb40b220..9545686c8 100644 --- a/src/Composer/DependencyResolver/Rule2Literals.php +++ b/src/Composer/DependencyResolver/Rule2Literals.php @@ -108,7 +108,7 @@ class Rule2Literals extends Rule * * @return string */ - public function __toString() + public function __toString(): string { $result = $this->isDisabled() ? 'disabled(' : '('; diff --git a/src/Composer/Package/Link.php b/src/Composer/Package/Link.php index 75f744bd1..a7628a720 100644 --- a/src/Composer/Package/Link.php +++ b/src/Composer/Package/Link.php @@ -150,7 +150,7 @@ class Link /** * @return string */ - public function __toString() + public function __toString(): string { return $this->source.' '.$this->description.' '.$this->target.' ('.$this->constraint.')'; } diff --git a/src/Composer/Repository/PlatformRepository.php b/src/Composer/Repository/PlatformRepository.php index 4952d234c..461191e4a 100644 --- a/src/Composer/Repository/PlatformRepository.php +++ b/src/Composer/Repository/PlatformRepository.php @@ -327,8 +327,8 @@ class PlatformRepository extends ArrayRepository } // 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 From e52071a92c7f5c34c373ab880e1d0b37cc435c42 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Tue, 22 Feb 2022 20:20:18 +0100 Subject: [PATCH 3/6] Revert some return types for symfony/flex compatibility --- src/Composer/Util/RemoteFilesystem.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 2d4865b07..4d666fc30 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -106,7 +106,7 @@ class RemoteFilesystem * * @return bool true */ - public function copy(string $originUrl, string $fileUrl, string $fileName, bool $progress = true, array $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); } @@ -131,7 +131,7 @@ class RemoteFilesystem * * @return mixed[] Options */ - public function getOptions(): array + public function getOptions() { return $this->options; } @@ -142,7 +142,7 @@ class RemoteFilesystem * @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 @@ class RemoteFilesystem * * @return bool */ - public function isTlsDisabled(): bool + public function isTlsDisabled() { return $this->disableTls === true; } @@ -162,7 +162,7 @@ class RemoteFilesystem * * @return string[] */ - public function getLastHeaders(): array + public function getLastHeaders() { return $this->lastHeaders; } @@ -171,7 +171,7 @@ class RemoteFilesystem * @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 @@ class RemoteFilesystem * @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) { @@ -554,7 +554,7 @@ class RemoteFilesystem * * @throws TransportException */ - protected function callbackGet(int $notificationCode, int $severity, ?string $message, int $messageCode, int $bytesTransferred, int $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 @@ class RemoteFilesystem * * @return void */ - protected function promptAuthAndRetry($httpStatus, ?string $reason = null, array $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 @@ class RemoteFilesystem * * @return mixed[] */ - protected function getOptionsForUrl(string $originUrl, array $additionalOptions): array + protected function getOptionsForUrl(string $originUrl, array $additionalOptions) { $tlsOptions = array(); $headers = array(); From 7abc8da7d3fa2db2f259517d84acb753399fab07 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Tue, 22 Feb 2022 22:10:52 +0100 Subject: [PATCH 4/6] Add more types --- src/Composer/Command/DiagnoseCommand.php | 2 +- src/Composer/Command/InitCommand.php | 15 +-- src/Composer/Command/RequireCommand.php | 15 +-- src/Composer/Command/ShowCommand.php | 24 ++-- src/Composer/Config/ConfigSourceInterface.php | 18 +-- src/Composer/Config/JsonConfigSource.php | 18 +-- src/Composer/Console/Application.php | 8 +- .../Operation/InstallOperation.php | 6 +- .../Operation/SolverOperation.php | 2 +- src/Composer/Downloader/ArchiveDownloader.php | 19 +-- .../Downloader/ChangeReportInterface.php | 2 +- src/Composer/Downloader/DownloadManager.php | 45 +++---- .../Downloader/DownloaderInterface.php | 26 ++-- .../Downloader/DvcsDownloaderInterface.php | 2 +- src/Composer/Downloader/FileDownloader.php | 42 +++--- src/Composer/Downloader/FossilDownloader.php | 6 +- src/Composer/Downloader/GitDownloader.php | 34 ++--- src/Composer/Downloader/GzipDownloader.php | 2 +- src/Composer/Downloader/HgDownloader.php | 6 +- src/Composer/Downloader/PathDownloader.php | 8 +- .../Downloader/PerforceDownloader.php | 6 +- src/Composer/Downloader/PharDownloader.php | 2 +- src/Composer/Downloader/RarDownloader.php | 2 +- src/Composer/Downloader/SvnDownloader.php | 18 +-- src/Composer/Downloader/TarDownloader.php | 3 +- .../VcsCapableDownloaderInterface.php | 2 +- src/Composer/Downloader/VcsDownloader.php | 36 ++--- src/Composer/Downloader/XzDownloader.php | 2 +- src/Composer/Downloader/ZipDownloader.php | 6 +- src/Composer/EventDispatcher/Event.php | 10 +- .../EventDispatcher/EventDispatcher.php | 32 ++--- .../Installer/InstallationManager.php | 32 ++--- src/Composer/Installer/InstallerEvent.php | 10 +- src/Composer/Installer/PackageEvent.php | 12 +- src/Composer/Json/JsonFile.php | 8 +- src/Composer/Json/JsonManipulator.php | 30 ++--- src/Composer/Package/AliasPackage.php | 10 +- src/Composer/Package/BasePackage.php | 32 ++--- src/Composer/Package/CompletePackage.php | 50 +++---- .../Package/CompletePackageInterface.php | 52 ++++---- src/Composer/Package/Link.php | 14 +- src/Composer/Package/Package.php | 126 +++++++++--------- src/Composer/Package/PackageInterface.php | 108 +++++++-------- src/Composer/Package/RootPackageInterface.php | 46 ++++--- .../Package/Version/VersionParser.php | 6 +- src/Composer/Repository/RepositoryManager.php | 18 +-- src/Composer/Repository/Vcs/FossilDriver.php | 4 +- .../Repository/Vcs/GitBitbucketDriver.php | 40 +++--- src/Composer/Repository/Vcs/GitDriver.php | 22 +-- src/Composer/Repository/Vcs/GitHubDriver.php | 44 +++--- src/Composer/Repository/Vcs/GitLabDriver.php | 10 +- src/Composer/Repository/Vcs/HgDriver.php | 22 +-- .../Repository/Vcs/PerforceDriver.php | 31 ++--- src/Composer/Repository/Vcs/SvnDriver.php | 32 ++--- src/Composer/Repository/Vcs/VcsDriver.php | 16 +-- .../Repository/Vcs/VcsDriverInterface.php | 30 ++--- src/Composer/Repository/VcsRepository.php | 16 ++- src/Composer/Script/Event.php | 6 +- src/Composer/Util/Git.php | 12 +- src/Composer/Util/Perforce.php | 74 +++++----- src/Composer/Util/ProcessExecutor.php | 69 +++++----- .../Composer/Test/Command/InitCommandTest.php | 29 ++-- .../Test/Downloader/DownloadManagerTest.php | 54 +++++--- .../Test/Downloader/ZipDownloaderTest.php | 4 +- .../Test/Installer/LibraryInstallerTest.php | 9 +- .../Test/Mock/ProcessExecutorMock.php | 4 +- .../Test/Package/Dumper/ArrayDumperTest.php | 98 ++++++-------- tests/Composer/Test/Package/LockerTest.php | 41 +----- .../Test/Plugin/PluginInstallerTest.php | 9 ++ .../Test/Repository/Vcs/GitHubDriverTest.php | 2 + tests/Composer/Test/Util/AuthHelperTest.php | 6 +- 71 files changed, 807 insertions(+), 850 deletions(-) diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index dc4166e05..8ed6ed0f4 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') diff --git a/src/Composer/Command/InitCommand.php b/src/Composer/Command/InitCommand.php index 896e45dca..4f3cebbd8 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -456,11 +456,10 @@ EOT } /** - * @private * @param string $author * @return array{name: string, email: string|null} */ - public function parseAuthorString(string $author) + private function parseAuthorString(string $author) { 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 @@ EOT * * @return array */ - protected function formatAuthors(string $author) + protected function formatAuthors(string $author): array { $author = $this->parseAuthorString($author); if (null === $author['email']) { @@ -504,7 +503,7 @@ EOT * * @return string|null */ - public function namespaceFromPackageName(string $packageName) + public function namespaceFromPackageName(string $packageName): ?string { if (!$packageName || strpos($packageName, '/') === false) { return null; @@ -526,7 +525,7 @@ EOT /** * @return array */ - protected function getGitConfig() + protected function getGitConfig(): array { if (null !== $this->gitConfig) { return $this->gitConfig; @@ -567,7 +566,7 @@ EOT * * @return bool */ - protected function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor') + protected function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor'): bool { if (!file_exists($ignoreFile)) { return false; @@ -591,7 +590,7 @@ EOT * * @return void */ - protected function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/') + protected function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/'): void { $contents = ""; if (file_exists($ignoreFile)) { @@ -610,7 +609,7 @@ EOT * * @return bool */ - protected function isValidEmail(string $email) + protected function isValidEmail(string $email): bool { // assume it's valid if we can't validate it if (!function_exists('filter_var')) { diff --git a/src/Composer/Command/RequireCommand.php b/src/Composer/Command/RequireCommand.php index 5aa890f02..5a65ccec9 100644 --- a/src/Composer/Command/RequireCommand.php +++ b/src/Composer/Command/RequireCommand.php @@ -335,15 +335,6 @@ EOT ); } - /** - * @private - * @return void - */ - public function markSolverComplete() - { - $this->dependencyResolutionCompleted = true; - } - /** * @param array $requirements * @param string $requireKey @@ -358,7 +349,9 @@ EOT $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(); @@ -480,7 +473,7 @@ EOT * @param bool $hardExit * @return void */ - public function revertComposerFile(bool $hardExit = true) + public function revertComposerFile(bool $hardExit = true): void { $io = $this->getIO(); diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php index 36fb376dd..775d858e9 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -602,7 +602,7 @@ EOT /** * @return string[] */ - protected function getRootRequires() + protected function getRootRequires(): array { $rootPackage = $this->requireComposer()->getPackage(); @@ -677,7 +677,7 @@ EOT * * @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 @@ EOT * * @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 @@ EOT * * @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 @@ EOT * * @return void */ - protected function printLinks(CompletePackageInterface $package, string $linkType, string $title = null) + protected function printLinks(CompletePackageInterface $package, string $linkType, string $title = null): void { $title = $title ?: $linkType; $io = $this->getIO(); @@ -820,7 +820,7 @@ EOT * * @return void */ - protected function printLicenses(CompletePackageInterface $package) + protected function printLicenses(CompletePackageInterface $package): void { $spdxLicenses = new SpdxLicenses(); @@ -852,7 +852,7 @@ EOT * * @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(), @@ -1030,7 +1030,7 @@ EOT * * @return void */ - protected function initStyles(OutputInterface $output) + protected function initStyles(OutputInterface $output): void { $this->colors = array( 'green', @@ -1052,7 +1052,7 @@ EOT * @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 @@ EOT PackageInterface $package, InstalledRepository $installedRepo, RepositoryInterface $remoteRepos - ) { + ): array { $requires = $package->getRequires(); ksort($requires); $children = array(); @@ -1149,7 +1149,7 @@ EOT array $packagesInTree, string $previousTreeBar = '├', int $level = 1 - ) { + ): void { $previousTreeBar = str_replace('├', '│', $previousTreeBar); if (is_array($package) && isset($package['requires'])) { $requires = $package['requires']; @@ -1202,7 +1202,7 @@ EOT InstalledRepository $installedRepo, RepositoryInterface $remoteRepos, array $packagesInTree - ) { + ): array { $children = array(); list($package) = $this->getPackage( $installedRepo, diff --git a/src/Composer/Config/ConfigSourceInterface.php b/src/Composer/Config/ConfigSourceInterface.php index 206f8158c..7cb590de6 100644 --- a/src/Composer/Config/ConfigSourceInterface.php +++ b/src/Composer/Config/ConfigSourceInterface.php @@ -29,7 +29,7 @@ interface ConfigSourceInterface * * @return void */ - public function addRepository(string $name, $config, bool $append = true); + public function addRepository(string $name, $config, bool $append = true): void; /** * Remove a repository @@ -38,7 +38,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeRepository(string $name); + public function removeRepository(string $name): void; /** * Add a config setting @@ -48,7 +48,7 @@ interface ConfigSourceInterface * * @return void */ - public function addConfigSetting(string $name, $value); + public function addConfigSetting(string $name, $value): void; /** * Remove a config setting @@ -57,7 +57,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeConfigSetting(string $name); + public function removeConfigSetting(string $name): void; /** * Add a property @@ -67,7 +67,7 @@ interface ConfigSourceInterface * * @return void */ - public function addProperty(string $name, $value); + public function addProperty(string $name, $value): void; /** * Remove a property @@ -76,7 +76,7 @@ interface ConfigSourceInterface * * @return void */ - public function removeProperty(string $name); + public function removeProperty(string $name): void; /** * Add a package link @@ -87,7 +87,7 @@ interface ConfigSourceInterface * * @return void */ - public function addLink(string $type, string $name, string $value); + public function addLink(string $type, string $name, string $value): void; /** * Remove a package link @@ -97,12 +97,12 @@ interface ConfigSourceInterface * * @return void */ - public function removeLink(string $type, string $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 a70471997..cb04bc6e9 100644 --- a/src/Composer/Config/JsonConfigSource.php +++ b/src/Composer/Config/JsonConfigSource.php @@ -52,7 +52,7 @@ class JsonConfigSource implements ConfigSourceInterface /** * @inheritDoc */ - public function getName() + public function getName(): string { return $this->file->getPath(); } @@ -60,7 +60,7 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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 @@ class JsonConfigSource implements ConfigSourceInterface /** * @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]); diff --git a/src/Composer/Console/Application.php b/src/Composer/Console/Application.php index 9560eef57..f2fac34fc 100644 --- a/src/Composer/Console/Application.php +++ b/src/Composer/Console/Application.php @@ -423,9 +423,9 @@ class Application extends BaseApplication * @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(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null) + public function getComposer(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null): ?Composer { if (null === $disablePlugins) { $disablePlugins = $this->disablePluginsByDefault; @@ -460,7 +460,7 @@ class Application extends BaseApplication * * @return void */ - public function resetComposer() + public function resetComposer(): void { $this->composer = null; if (method_exists($this->getIO(), 'resetAuthentications')) { @@ -471,7 +471,7 @@ class Application extends BaseApplication /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } diff --git a/src/Composer/DependencyResolver/Operation/InstallOperation.php b/src/Composer/DependencyResolver/Operation/InstallOperation.php index 40d0e698d..7f66d17e9 100644 --- a/src/Composer/DependencyResolver/Operation/InstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/InstallOperation.php @@ -38,7 +38,7 @@ class InstallOperation extends SolverOperation implements OperationInterface * * @return PackageInterface */ - public function getPackage() + public function getPackage(): PackageInterface { return $this->package; } @@ -46,7 +46,7 @@ class InstallOperation extends SolverOperation implements OperationInterface /** * @inheritDoc */ - public function show($lock) + public function show($lock): string { return self::format($this->package, $lock); } @@ -55,7 +55,7 @@ class InstallOperation extends SolverOperation implements OperationInterface * @param bool $lock * @return string */ - public static function format(PackageInterface $package, bool $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/SolverOperation.php b/src/Composer/DependencyResolver/Operation/SolverOperation.php index ad8855d2c..5aa0957a7 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/Downloader/ArchiveDownloader.php b/src/Composer/Downloader/ArchiveDownloader.php index b44d280b5..fc1900414 100644 --- a/src/Composer/Downloader/ArchiveDownloader.php +++ b/src/Composer/Downloader/ArchiveDownloader.php @@ -33,9 +33,9 @@ abstract class ArchiveDownloader extends FileDownloader protected $cleanupExecuted = array(); /** - * @return PromiseInterface|null + * @return PromiseInterface */ - public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { unset($this->cleanupExecuted[$package->getName()]); @@ -43,9 +43,9 @@ abstract class ArchiveDownloader extends FileDownloader } /** - * @return PromiseInterface|null + * @return PromiseInterface */ - public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) + public function cleanup(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { $this->cleanupExecuted[$package->getName()] = true; @@ -62,7 +62,7 @@ abstract class ArchiveDownloader extends FileDownloader * @throws \RuntimeException * @throws \UnexpectedValueException */ - public function install(PackageInterface $package, string $path, bool $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)); @@ -113,10 +113,6 @@ abstract class ArchiveDownloader extends FileDownloader 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); @@ -215,7 +211,7 @@ abstract class ArchiveDownloader extends FileDownloader /** * @inheritDoc */ - protected function getInstallOperationAppendix(PackageInterface $package, string $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { return ': Extracting archive'; } @@ -227,7 +223,6 @@ abstract class ArchiveDownloader extends FileDownloader * @param string $path Directory * * @throws \UnexpectedValueException If can not extract downloaded file to path - * @return PromiseInterface|null */ - abstract protected function extract(PackageInterface $package, string $file, string $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 60d6efe74..a41cce893 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, string $path); + public function getLocalChanges(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index da786378a..f34a73d37 100644 --- a/src/Composer/Downloader/DownloadManager.php +++ b/src/Composer/Downloader/DownloadManager.php @@ -59,7 +59,7 @@ class DownloadManager * @param bool $preferSource prefer downloading from source * @return DownloadManager */ - public function setPreferSource(bool $preferSource): DownloadManager + public function setPreferSource(bool $preferSource): self { $this->preferSource = $preferSource; @@ -72,7 +72,7 @@ class DownloadManager * @param bool $preferDist prefer downloading from dist * @return DownloadManager */ - public function setPreferDist(bool $preferDist): DownloadManager + public function setPreferDist(bool $preferDist): self { $this->preferDist = $preferDist; @@ -86,7 +86,7 @@ class DownloadManager * * @return DownloadManager */ - public function setPreferences(array $preferences): DownloadManager + public function setPreferences(array $preferences): self { $this->packagePreferences = $preferences; @@ -100,7 +100,7 @@ class DownloadManager * @param DownloaderInterface $downloader downloader instance * @return DownloadManager */ - public function setDownloader(string $type, DownloaderInterface $downloader): DownloadManager + public function setDownloader(string $type, DownloaderInterface $downloader): self { $type = strtolower($type); $this->downloaders[$type] = $downloader; @@ -229,9 +229,6 @@ class DownloadManager } 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 @@ class DownloadManager * @param string $targetDir target dir * @param PackageInterface|null $prevPackage previous package instance in case of updates * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function prepare(string $type, PackageInterface $package, string $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 @@ class DownloadManager * * @throws \InvalidArgumentException if package have no urls to download from * @throws \RuntimeException - * @return PromiseInterface|null + * @return PromiseInterface */ - public function install(PackageInterface $package, string $targetDir): ?PromiseInterface + public function install(PackageInterface $package, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -293,9 +290,9 @@ class DownloadManager * @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, string $targetDir): ?PromiseInterface + public function update(PackageInterface $initial, PackageInterface $target, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($target); @@ -330,18 +327,10 @@ class DownloadManager // 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 @@ class DownloadManager * @param PackageInterface $package package instance * @param string $targetDir target dir * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function remove(PackageInterface $package, string $targetDir): ?PromiseInterface + public function remove(PackageInterface $package, string $targetDir): PromiseInterface { $targetDir = $this->normalizeTargetDir($targetDir); $downloader = $this->getDownloaderForPackage($package); @@ -371,9 +360,9 @@ class DownloadManager * @param string $targetDir target dir * @param PackageInterface|null $prevPackage previous package instance in case of updates * - * @return PromiseInterface|null + * @return PromiseInterface */ - public function cleanup(string $type, PackageInterface $package, string $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); diff --git a/src/Composer/Downloader/DownloaderInterface.php b/src/Composer/Downloader/DownloaderInterface.php index 1796754a3..0b540d4b6 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, string $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 @@ interface DownloaderInterface * @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(string $type, PackageInterface $package, string $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, string $path); + public function install(PackageInterface $package, string $path): PromiseInterface; /** * Updates specific package in specific folder from initial to target version. @@ -69,18 +69,18 @@ interface DownloaderInterface * @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, string $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, string $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 @@ interface DownloaderInterface * @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(string $type, PackageInterface $package, string $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 8f70472b7..45c9b86c5 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, string $path); + public function getUnpushedChanges(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index c871ee47f..c1858d9b8 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -66,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(); @@ -103,7 +101,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): string { return 'dist'; } @@ -113,7 +111,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @param bool $output */ - public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $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'); @@ -296,7 +294,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null) + public function prepare(string $type, PackageInterface $package, string $path, PackageInterface $prevPackage = null): PromiseInterface { return \React\Promise\resolve(); } @@ -304,7 +302,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function cleanup(string $type, PackageInterface $package, string $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)) { @@ -337,7 +335,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @param bool $output */ - public function install(PackageInterface $package, string $path, bool $output = true) + public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface { if ($output) { $this->io->writeError(" - " . InstallOperation::format($package)); @@ -363,7 +361,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @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()]); @@ -376,7 +374,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @return void */ - protected function addCleanupPath(PackageInterface $package, string $path) + protected function addCleanupPath(PackageInterface $package, string $path): void { $this->additionalCleanupPaths[$package->getName()][] = $path; } @@ -386,7 +384,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @return void */ - protected function removeCleanupPath(PackageInterface $package, string $path) + protected function removeCleanupPath(PackageInterface $package, string $path): void { if (isset($this->additionalCleanupPaths[$package->getName()])) { $idx = array_search($path, $this->additionalCleanupPaths[$package->getName()]); @@ -399,22 +397,14 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, string $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); }); } @@ -423,7 +413,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * * @param bool $output */ - public function remove(PackageInterface $package, string $path, bool $output = true) + public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface { if ($output) { $this->io->writeError(" - " . UninstallOperation::format($package)); @@ -444,7 +434,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @param string $path download path * @return string file name */ - protected function getFileName(PackageInterface $package, string $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), '.'); } @@ -456,7 +446,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @param string $path download path * @return string */ - protected function getInstallOperationAppendix(PackageInterface $package, string $path) + protected function getInstallOperationAppendix(PackageInterface $package, string $path): string { return ''; } @@ -469,7 +459,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @throws \RuntimeException If any problem with the url * @return string url */ - protected function processUrl(PackageInterface $package, string $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'); @@ -486,7 +476,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface * @inheritDoc * @throws \RuntimeException */ - public function getLocalChanges(PackageInterface $package, string $targetDir) + public function getLocalChanges(PackageInterface $package, string $targetDir): ?string { $prevIO = $this->io; diff --git a/src/Composer/Downloader/FossilDownloader.php b/src/Composer/Downloader/FossilDownloader.php index 57afb1752..13bd3d25b 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, string $path, string $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 @@ class FossilDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, string $path, string $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 @@ class FossilDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $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); diff --git a/src/Composer/Downloader/GitDownloader.php b/src/Composer/Downloader/GitDownloader.php index 78775e6c3..a842a6ea3 100644 --- a/src/Composer/Downloader/GitDownloader.php +++ b/src/Composer/Downloader/GitDownloader.php @@ -58,7 +58,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null) + protected function doDownload(PackageInterface $package, string $path, string $url, PackageInterface $prevPackage = null): PromiseInterface { GitUtil::cleanEnv(); @@ -83,7 +83,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, string $path, string $url) + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -148,7 +148,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -213,7 +213,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, string $path) + public function getLocalChanges(PackageInterface $package, string $path): ?string { GitUtil::cleanEnv(); if (!$this->hasMetadataRepository($path)) { @@ -231,7 +231,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @return null|string */ - public function getUnpushedChanges(PackageInterface $package, string $path) + public function getUnpushedChanges(PackageInterface $package, string $path): ?string { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -328,7 +328,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, string $path, bool $update) + protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface { GitUtil::cleanEnv(); $path = $this->normalizePath($path); @@ -415,7 +415,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function reapplyChanges(string $path) + protected function reapplyChanges(string $path): void { $path = $this->normalizePath($path); if (!empty($this->hasStashedChanges[$path])) { @@ -438,7 +438,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * @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, string $path, string $reference, string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return void */ - protected function updateOriginUrl(string $path, string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return void */ - protected function setPushUrl(string $path, string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function getCommitLogs(string $fromReference, string $toReference, string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function discardChanges(string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function stashChanges(string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @throws \RuntimeException */ - protected function viewDiff(string $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 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * * @return string */ - protected function normalizePath(string $path) + protected function normalizePath(string $path): string { if (Platform::isWindows() && strlen($path) > 0) { $basePath = $path; @@ -630,7 +630,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface /** * @inheritDoc */ - protected function hasMetadataRepository(string $path) + protected function hasMetadataRepository(string $path): bool { $path = $this->normalizePath($path); @@ -641,7 +641,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface * @param string $reference * @return string */ - protected function getShortHash(string $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 b66aeb048..8949037ec 100644 --- a/src/Composer/Downloader/GzipDownloader.php +++ b/src/Composer/Downloader/GzipDownloader.php @@ -24,7 +24,7 @@ use Composer\Util\ProcessExecutor; */ class GzipDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, string $file, string $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; diff --git a/src/Composer/Downloader/HgDownloader.php b/src/Composer/Downloader/HgDownloader.php index a9caf53a8..0537103b1 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, string $path, string $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,7 +37,7 @@ class HgDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, string $path, string $url): ?PromiseInterface + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { $hgUtils = new HgUtils($this->io, $this->config, $this->process); @@ -59,7 +59,7 @@ class HgDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): ?PromiseInterface + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { $hgUtils = new HgUtils($this->io, $this->config, $this->process); diff --git a/src/Composer/Downloader/PathDownloader.php b/src/Composer/Downloader/PathDownloader.php index c58e7d67a..c85cbef0f 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, string $path, PackageInterface $prevPackage = null, bool $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 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @inheritDoc */ - public function install(PackageInterface $package, string $path, bool $output = true): ?PromiseInterface + public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface { $path = Filesystem::trimTrailingSlash($path); $url = $package->getDistUrl(); @@ -161,7 +161,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter /** * @inheritDoc */ - public function remove(PackageInterface $package, string $path, bool $output = true): ?PromiseInterface + public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface { $path = Filesystem::trimTrailingSlash($path); /** @@ -250,7 +250,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter * * @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 1f888b6b4..559d6ba4a 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, string $path, string $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 @@ class PerforceDownloader extends VcsDownloader /** * @inheritDoc */ - public function doInstall(PackageInterface $package, string $path, string $url): ?PromiseInterface + public function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { $ref = $package->getSourceReference(); $label = $this->getLabelFromSourceReference((string) $ref); @@ -101,7 +101,7 @@ class PerforceDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): ?PromiseInterface + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { return $this->doInstall($target, $path, $url); } diff --git a/src/Composer/Downloader/PharDownloader.php b/src/Composer/Downloader/PharDownloader.php index b4a1d9c75..76517fcd7 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, string $file, string $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 af467ef5e..ef697d797 100644 --- a/src/Composer/Downloader/RarDownloader.php +++ b/src/Composer/Downloader/RarDownloader.php @@ -28,7 +28,7 @@ use RarArchive; */ class RarDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, string $file, string $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 f3418735b..056add89c 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, string $path, string $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 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doInstall(PackageInterface $package, string $path, string $url) + protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface { SvnUtil::cleanEnv(); $ref = $package->getSourceReference(); @@ -67,7 +67,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url) + protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface { SvnUtil::cleanEnv(); $ref = $target->getSourceReference(); @@ -91,7 +91,7 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - public function getLocalChanges(PackageInterface $package, string $path) + public function getLocalChanges(PackageInterface $package, string $path): ?string { if (!$this->hasMetadataRepository($path)) { return null; @@ -114,7 +114,7 @@ class SvnDownloader extends VcsDownloader * @throws \RuntimeException * @return string */ - protected function execute(PackageInterface $package, string $baseUrl, string $command, string $url, string $cwd = null, string $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 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function cleanChanges(PackageInterface $package, string $path, bool $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 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function getCommitLogs(string $fromReference, string $toReference, string $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 @@ class SvnDownloader extends VcsDownloader * * @return PromiseInterface */ - protected function discardChanges(string $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 @@ class SvnDownloader extends VcsDownloader /** * @inheritDoc */ - protected function hasMetadataRepository(string $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 5d88b8dfa..92998aac6 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, string $file, string $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/VcsCapableDownloaderInterface.php b/src/Composer/Downloader/VcsCapableDownloaderInterface.php index 43d07c6c5..38d12c689 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, string $path); + public function getVcsReference(PackageInterface $package, string $path): ?string; } diff --git a/src/Composer/Downloader/VcsDownloader.php b/src/Composer/Downloader/VcsDownloader.php index a97d517e2..12f5140f5 100644 --- a/src/Composer/Downloader/VcsDownloader.php +++ b/src/Composer/Downloader/VcsDownloader.php @@ -52,7 +52,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): string { return 'source'; } @@ -60,7 +60,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function download(PackageInterface $package, string $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function prepare(string $type, PackageInterface $package, string $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function cleanup(string $type, PackageInterface $package, string $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function install(PackageInterface $package, string $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function update(PackageInterface $initial, PackageInterface $target, string $path) + public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface { if (!$target->getSourceReference()) { throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information'); @@ -222,7 +222,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function remove(PackageInterface $package, string $path) + public function remove(PackageInterface $package, string $path): PromiseInterface { $this->io->writeError(" - " . UninstallOperation::format($package)); @@ -238,7 +238,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa /** * @inheritDoc */ - public function getVcsReference(PackageInterface $package, string $path) + public function getVcsReference(PackageInterface $package, string $path): ?string { $parser = new VersionParser; $guesser = new VersionGuesser($this->config, $this->process, $parser); @@ -264,7 +264,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @throws \RuntimeException in case the operation must be aborted */ - protected function cleanChanges(PackageInterface $package, string $path, bool $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 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * * @throws \RuntimeException in case the operation must be aborted or the patch does not apply cleanly */ - protected function reapplyChanges(string $path) + protected function reapplyChanges(string $path): void { } @@ -295,9 +295,9 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @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, string $path, string $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 class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @param string $path download path * @param string $url package url * - * @return PromiseInterface|null + * @return PromiseInterface */ - abstract protected function doInstall(PackageInterface $package, string $path, string $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 class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @param string $path download path * @param string $url package url * - * @return PromiseInterface|null + * @return PromiseInterface */ - abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $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 class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @param string $path the package path * @return string */ - abstract protected function getCommitLogs(string $fromReference, string $toReference, string $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 class VcsDownloader implements DownloaderInterface, ChangeReportInterfa * @param string $path * @return bool */ - abstract protected function hasMetadataRepository(string $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 33f3c03d6..50325603e 100644 --- a/src/Composer/Downloader/XzDownloader.php +++ b/src/Composer/Downloader/XzDownloader.php @@ -24,7 +24,7 @@ use Composer\Util\ProcessExecutor; */ class XzDownloader extends ArchiveDownloader { - protected function extract(PackageInterface $package, string $file, string $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 e18fd0d80..e532bdcdd 100644 --- a/src/Composer/Downloader/ZipDownloader.php +++ b/src/Composer/Downloader/ZipDownloader.php @@ -39,7 +39,7 @@ class ZipDownloader extends ArchiveDownloader /** * @inheritDoc */ - public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $output = true) + public function download(PackageInterface $package, string $path, PackageInterface $prevPackage = null, bool $output = true): PromiseInterface { if (null === self::$unzipCommands) { self::$unzipCommands = array(); @@ -206,9 +206,9 @@ class ZipDownloader extends ArchiveDownloader * * @param string $file File to extract * @param string $path Path where to extract file - * @return PromiseInterface|null + * @return PromiseInterface */ - protected function extract(PackageInterface $package, string $file, string $path) + protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface { return $this->extractWithSystemUnzip($package, $file, $path); } diff --git a/src/Composer/EventDispatcher/Event.php b/src/Composer/EventDispatcher/Event.php index c7af569d2..a3f2294ef 100644 --- a/src/Composer/EventDispatcher/Event.php +++ b/src/Composer/EventDispatcher/Event.php @@ -58,7 +58,7 @@ class Event * * @return string The event name */ - public function getName() + public function getName(): string { return $this->name; } @@ -68,7 +68,7 @@ class Event * * @return string[] The event arguments */ - public function getArguments() + public function getArguments(): array { return $this->args; } @@ -78,7 +78,7 @@ class Event * * @return mixed[] The event flags */ - public function getFlags() + public function getFlags(): array { return $this->flags; } @@ -88,7 +88,7 @@ class Event * * @return bool Whether propagation has been stopped */ - public function isPropagationStopped() + public function isPropagationStopped(): bool { return $this->propagationStopped; } @@ -98,7 +98,7 @@ class Event * * @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 8cfc8b194..941fc2520 100644 --- a/src/Composer/EventDispatcher/EventDispatcher.php +++ b/src/Composer/EventDispatcher/EventDispatcher.php @@ -96,7 +96,7 @@ class EventDispatcher * @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(string $eventName, Event $event = null) + public function dispatch(string $eventName, Event $event = null): int { if (null === $event) { $event = new Event($eventName); @@ -115,7 +115,7 @@ class EventDispatcher * @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(string $eventName, bool $devMode = false, array $additionalArgs = array(), 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')); @@ -134,7 +134,7 @@ class EventDispatcher * @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(string $eventName, bool $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')); @@ -152,7 +152,7 @@ class EventDispatcher * @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(string $eventName, bool $devMode, bool $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')); @@ -342,7 +342,7 @@ class EventDispatcher * * @return int */ - protected function executeTty(string $exec) + protected function executeTty(string $exec): int { if ($this->io->isInteractive()) { return $this->process->executeTty($exec); @@ -354,7 +354,7 @@ class EventDispatcher /** * @return string */ - protected function getPhpExecCommand() + protected function getPhpExecCommand(): string { $finder = new PhpExecutableFinder(); $phpPath = $finder->find(false); @@ -397,7 +397,7 @@ class EventDispatcher * * @return void */ - public function addListener(string $eventName, callable $listener, int $priority = 0) + public function addListener(string $eventName, callable $listener, int $priority = 0): void { $this->listeners[$eventName][$priority][] = $listener; } @@ -407,7 +407,7 @@ class EventDispatcher * * @return void */ - public function removeListener($listener) + public function removeListener($listener): void { foreach ($this->listeners as $eventName => $priorities) { foreach ($priorities as $priority => $listeners) { @@ -429,7 +429,7 @@ class EventDispatcher * * @return void */ - public function addSubscriber(EventSubscriberInterface $subscriber) + public function addSubscriber(EventSubscriberInterface $subscriber): void { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { @@ -450,7 +450,7 @@ class EventDispatcher * @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(); @@ -471,7 +471,7 @@ class EventDispatcher * @param Event $event * @return bool */ - public function hasEventListeners(Event $event) + public function hasEventListeners(Event $event): bool { $listeners = $this->getListeners($event); @@ -484,7 +484,7 @@ class EventDispatcher * @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(); @@ -519,7 +519,7 @@ class EventDispatcher * @param string $callable * @return bool */ - protected function isPhpScript(string $callable) + protected function isPhpScript(string $callable): bool { return false === strpos($callable, ' ') && false !== strpos($callable, '::'); } @@ -530,7 +530,7 @@ class EventDispatcher * @param string $callable * @return bool */ - protected function isComposerScript(string $callable) + protected function isComposerScript(string $callable): bool { return strpos($callable, '@') === 0 && strpos($callable, '@php ') !== 0 && strpos($callable, '@putenv ') !== 0; } @@ -542,7 +542,7 @@ class EventDispatcher * @throws \RuntimeException * @return int */ - protected function pushEvent(Event $event) + protected function pushEvent(Event $event): int { $eventName = $event->getName(); if (in_array($eventName, $this->eventStack)) { @@ -557,7 +557,7 @@ class EventDispatcher * * @return string|null */ - protected function popEvent() + protected function popEvent(): ?string { return array_pop($this->eventStack); } diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index 7d3150d60..8200080b3 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -63,7 +63,7 @@ class InstallationManager /** * @return void */ - public function reset() + public function reset(): void { $this->notifiablePackages = array(); FileDownloader::$downloadMetadata = array(); @@ -76,7 +76,7 @@ class InstallationManager * * @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 @@ class InstallationManager * * @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 @@ class InstallationManager * * @return void */ - public function disablePlugins() + public function disablePlugins(): void { foreach ($this->installers as $i => $installer) { if (!$installer instanceof PluginInstaller) { @@ -125,7 +125,7 @@ class InstallationManager * @throws \InvalidArgumentException if installer for provided type is not registered * @return InstallerInterface */ - public function getInstaller(string $type) + public function getInstaller(string $type): InstallerInterface { $type = strtolower($type); @@ -150,7 +150,7 @@ class InstallationManager * * @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 @@ class InstallationManager * * @return void */ - public function ensureBinariesPresence(PackageInterface $package) + public function ensureBinariesPresence(PackageInterface $package): void { try { $installer = $this->getInstaller($package->getType()); @@ -192,7 +192,7 @@ class InstallationManager * * @return void */ - public function execute(InstalledRepositoryInterface $repo, array $operations, bool $devMode = true, bool $runScripts = true) + public function execute(InstalledRepositoryInterface $repo, array $operations, bool $devMode = true, bool $runScripts = true): void { /** @var PromiseInterface[] */ $cleanupPromises = array(); @@ -511,7 +511,7 @@ class InstallationManager * * @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 @@ class InstallationManager * * @return PromiseInterface|null */ - public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation) + public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface { $initial = $operation->getInitialPackage(); $target = $operation->getTargetPackage(); @@ -569,7 +569,7 @@ class InstallationManager * * @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 @@ class InstallationManager * * @return void */ - public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation) + public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void { $package = $operation->getPackage(); @@ -602,7 +602,7 @@ class InstallationManager * * @return void */ - public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation) + public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void { $package = $operation->getPackage(); @@ -615,7 +615,7 @@ class InstallationManager * @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 @@ class InstallationManager * * @return void */ - public function setOutputProgress(bool $outputProgress) + public function setOutputProgress(bool $outputProgress): void { $this->outputProgress = $outputProgress; } @@ -635,7 +635,7 @@ class InstallationManager /** * @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 88dc7b737..cafd0dc1b 100644 --- a/src/Composer/Installer/InstallerEvent.php +++ b/src/Composer/Installer/InstallerEvent.php @@ -68,7 +68,7 @@ class InstallerEvent extends Event /** * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -76,7 +76,7 @@ class InstallerEvent extends Event /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -84,7 +84,7 @@ class InstallerEvent extends Event /** * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } @@ -92,7 +92,7 @@ class InstallerEvent extends Event /** * @return bool */ - public function isExecutingOperations() + public function isExecutingOperations(): bool { return $this->executeOperations; } @@ -100,7 +100,7 @@ class InstallerEvent extends Event /** * @return Transaction|null */ - public function getTransaction() + public function getTransaction(): ?Transaction { return $this->transaction; } diff --git a/src/Composer/Installer/PackageEvent.php b/src/Composer/Installer/PackageEvent.php index 177869fb9..55029fb93 100644 --- a/src/Composer/Installer/PackageEvent.php +++ b/src/Composer/Installer/PackageEvent.php @@ -81,7 +81,7 @@ class PackageEvent extends Event /** * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -89,7 +89,7 @@ class PackageEvent extends Event /** * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -97,7 +97,7 @@ class PackageEvent extends Event /** * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } @@ -105,7 +105,7 @@ class PackageEvent extends Event /** * @return RepositoryInterface */ - public function getLocalRepo() + public function getLocalRepo(): RepositoryInterface { return $this->localRepo; } @@ -113,7 +113,7 @@ class PackageEvent extends Event /** * @return OperationInterface[] */ - public function getOperations() + public function getOperations(): array { return $this->operations; } @@ -123,7 +123,7 @@ class PackageEvent extends Event * * @return OperationInterface */ - public function getOperation() + public function getOperation(): OperationInterface { return $this->operation; } diff --git a/src/Composer/Json/JsonFile.php b/src/Composer/Json/JsonFile.php index b16af75ac..3ec407f8a 100644 --- a/src/Composer/Json/JsonFile.php +++ b/src/Composer/Json/JsonFile.php @@ -69,7 +69,7 @@ class JsonFile /** * @return string */ - public function getPath() + public function getPath(): string { return $this->path; } @@ -79,7 +79,7 @@ class JsonFile * * @return bool */ - public function exists() + public function exists(): bool { return is_file($this->path); } @@ -188,7 +188,7 @@ class JsonFile * @throws ParsingException * @return bool true on success */ - public function validateSchema(int $schema = self::STRICT_SCHEMA, ?string $schemaFile = null) + public function validateSchema(int $schema = self::STRICT_SCHEMA, ?string $schemaFile = null): bool { $content = file_get_contents($this->path); $data = json_decode($content); @@ -309,7 +309,7 @@ class JsonFile * @throws ParsingException * @return bool true on success */ - protected static function validateSyntax(string $json, string $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/JsonManipulator.php b/src/Composer/Json/JsonManipulator.php index 68de5dd4a..4a8781c64 100644 --- a/src/Composer/Json/JsonManipulator.php +++ b/src/Composer/Json/JsonManipulator.php @@ -58,7 +58,7 @@ class JsonManipulator /** * @return string */ - public function getContents() + public function getContents(): string { return $this->contents . $this->newline; } @@ -70,7 +70,7 @@ class JsonManipulator * @param bool $sortPackages * @return bool */ - public function addLink(string $type, string $package, string $constraint, bool $sortPackages = false) + public function addLink(string $type, string $package, string $constraint, bool $sortPackages = false): bool { $decoded = JsonFile::parseJson($this->contents); @@ -170,7 +170,7 @@ class JsonManipulator * @param bool $append * @return bool */ - public function addRepository(string $name, $config, bool $append = true) + public function addRepository(string $name, $config, bool $append = true): bool { return $this->addSubNode('repositories', $name, $config, $append); } @@ -179,7 +179,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeRepository(string $name) + public function removeRepository(string $name): bool { return $this->removeSubNode('repositories', $name); } @@ -189,7 +189,7 @@ class JsonManipulator * @param mixed $value * @return bool */ - public function addConfigSetting(string $name, $value) + public function addConfigSetting(string $name, $value): bool { return $this->addSubNode('config', $name, $value); } @@ -198,7 +198,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeConfigSetting(string $name) + public function removeConfigSetting(string $name): bool { return $this->removeSubNode('config', $name); } @@ -208,7 +208,7 @@ class JsonManipulator * @param mixed $value * @return bool */ - public function addProperty(string $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 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeProperty(string $name) + public function removeProperty(string $name): bool { if (strpos($name, 'suggest.') === 0) { return $this->removeSubNode('suggest', substr($name, 8)); @@ -253,7 +253,7 @@ class JsonManipulator * @param bool $append * @return bool */ - public function addSubNode(string $mainNode, string $name, $value, bool $append = true) + public function addSubNode(string $mainNode, string $name, $value, bool $append = true): bool { $decoded = JsonFile::parseJson($this->contents); @@ -363,7 +363,7 @@ class JsonManipulator * @param string $name * @return bool */ - public function removeSubNode(string $mainNode, string $name) + public function removeSubNode(string $mainNode, string $name): bool { $decoded = JsonFile::parseJson($this->contents); @@ -468,7 +468,7 @@ class JsonManipulator * @param mixed $content * @return bool */ - public function addMainKey(string $key, $content) + public function addMainKey(string $key, $content): bool { $decoded = JsonFile::parseJson($this->contents); $content = $this->format($content); @@ -512,7 +512,7 @@ class JsonManipulator * @param string $key * @return bool */ - public function removeMainKey(string $key) + public function removeMainKey(string $key): bool { $decoded = JsonFile::parseJson($this->contents); @@ -549,7 +549,7 @@ class JsonManipulator * @param string $key * @return bool */ - public function removeMainKeyIfEmpty(string $key) + public function removeMainKeyIfEmpty(string $key): bool { $decoded = JsonFile::parseJson($this->contents); @@ -569,7 +569,7 @@ class JsonManipulator * @param int $depth * @return string */ - public function format($data, int $depth = 0) + public function format($data, int $depth = 0): string { if (is_array($data)) { reset($data); @@ -597,7 +597,7 @@ class JsonManipulator /** * @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/Package/AliasPackage.php b/src/Composer/Package/AliasPackage.php index 3d82debb6..332c1fe05 100644 --- a/src/Composer/Package/AliasPackage.php +++ b/src/Composer/Package/AliasPackage.php @@ -159,14 +159,10 @@ class AliasPackage extends BasePackage * 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(bool $value) + public function setRootPackageAlias(bool $value): void { - return $this->rootPackageAlias = $value; + $this->rootPackageAlias = $value; } /** @@ -225,7 +221,7 @@ class AliasPackage extends BasePackage return $this->hasSelfVersionRequires; } - public function __toString() + public function __toString(): string { return parent::__toString().' ('.($this->rootPackageAlias ? 'root ' : ''). 'alias of '.$this->aliasOf->getVersion().')'; } diff --git a/src/Composer/Package/BasePackage.php b/src/Composer/Package/BasePackage.php index f29bee056..35be9e75a 100644 --- a/src/Composer/Package/BasePackage.php +++ b/src/Composer/Package/BasePackage.php @@ -78,7 +78,7 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function getName() + public function getName(): string { return $this->name; } @@ -86,7 +86,7 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function getPrettyName() + public function getPrettyName(): string { return $this->prettyName; } @@ -94,7 +94,7 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function getNames($provides = true) + public function getNames($provides = true): array { $names = array( $this->getName() => true, @@ -116,7 +116,7 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function setId($id) + public function setId(int $id): void { $this->id = $id; } @@ -124,7 +124,7 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function getId() + public function getId(): int { return $this->id; } @@ -132,7 +132,7 @@ abstract class BasePackage implements PackageInterface /** * @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 @@ abstract class BasePackage implements PackageInterface /** * @inheritDoc */ - public function getRepository() + public function getRepository(): ?RepositoryInterface { return $this->repository; } @@ -153,7 +153,7 @@ abstract class BasePackage implements PackageInterface * * @return bool */ - public function isPlatform() + public function isPlatform(): bool { return $this->getRepository() instanceof PlatformRepository; } @@ -163,7 +163,7 @@ abstract class BasePackage implements PackageInterface * * @return string */ - public function getUniqueName() + public function getUniqueName(): string { return $this->getName().'-'.$this->getVersion(); } @@ -171,7 +171,7 @@ abstract class BasePackage implements PackageInterface /** * @return bool */ - public function equals(PackageInterface $package) + public function equals(PackageInterface $package): bool { $self = $this; if ($this instanceof AliasPackage) { @@ -189,12 +189,12 @@ abstract class BasePackage implements PackageInterface * * @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 @@ abstract class BasePackage implements PackageInterface /** * @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 @@ abstract class BasePackage implements PackageInterface * * @phpstan-return self::STABILITY_* */ - public function getStabilityPriority() + public function getStabilityPriority(): int { return self::$stabilities[$this->getStability()]; } @@ -257,7 +257,7 @@ abstract class BasePackage implements PackageInterface * @param non-empty-string $wrap Wrap the cleaned string by the given string * @return non-empty-string */ - public static function packageNameToRegexp(string $allowPattern, string $wrap = '{^%s$}i') + public static function packageNameToRegexp(string $allowPattern, string $wrap = '{^%s$}i'): string { $cleanedAllowPattern = str_replace('\\*', '.*', preg_quote($allowPattern)); @@ -271,7 +271,7 @@ abstract class BasePackage implements PackageInterface * @param non-empty-string $wrap * @return non-empty-string */ - public static function packageNamesToRegexp(array $packageNames, string $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/CompletePackage.php b/src/Composer/Package/CompletePackage.php index 1234ddf0c..666f3b0c7 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 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getScripts() + public function getScripts(): array { return $this->scripts; } @@ -63,7 +63,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setRepositories(array $repositories) + public function setRepositories(array $repositories): void { $this->repositories = $repositories; } @@ -71,7 +71,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -79,7 +79,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setLicense(array $license) + public function setLicense(array $license): void { $this->license = $license; } @@ -87,7 +87,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getLicense() + public function getLicense(): array { return $this->license; } @@ -95,7 +95,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setKeywords(array $keywords) + public function setKeywords(array $keywords): void { $this->keywords = $keywords; } @@ -103,7 +103,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getKeywords() + public function getKeywords(): array { return $this->keywords; } @@ -111,7 +111,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setAuthors(array $authors) + public function setAuthors(array $authors): void { $this->authors = $authors; } @@ -119,7 +119,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getAuthors() + public function getAuthors(): array { return $this->authors; } @@ -127,7 +127,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setDescription(?string $description) + public function setDescription(?string $description): void { $this->description = $description; } @@ -135,7 +135,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getDescription() + public function getDescription(): ?string { return $this->description; } @@ -143,7 +143,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setHomepage(?string $homepage) + public function setHomepage(?string $homepage): void { $this->homepage = $homepage; } @@ -151,7 +151,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getHomepage() + public function getHomepage(): ?string { return $this->homepage; } @@ -159,7 +159,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setSupport(array $support) + public function setSupport(array $support): void { $this->support = $support; } @@ -167,7 +167,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getSupport() + public function getSupport(): array { return $this->support; } @@ -175,7 +175,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setFunding(array $funding) + public function setFunding(array $funding): void { $this->funding = $funding; } @@ -183,7 +183,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getFunding() + public function getFunding(): array { return $this->funding; } @@ -191,7 +191,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function isAbandoned() + public function isAbandoned(): bool { return (bool) $this->abandoned; } @@ -199,7 +199,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setAbandoned($abandoned) + public function setAbandoned($abandoned): void { $this->abandoned = $abandoned; } @@ -207,7 +207,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getReplacementPackage() + public function getReplacementPackage(): ?string { return \is_string($this->abandoned) ? $this->abandoned : null; } @@ -215,7 +215,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setArchiveName(?string $name) + public function setArchiveName(?string $name): void { $this->archiveName = $name; } @@ -223,7 +223,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function getArchiveName() + public function getArchiveName(): ?string { return $this->archiveName; } @@ -231,7 +231,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @inheritDoc */ - public function setArchiveExcludes(array $excludes) + public function setArchiveExcludes(array $excludes): void { $this->archiveExcludes = $excludes; } @@ -239,7 +239,7 @@ class CompletePackage extends Package implements CompletePackageInterface /** * @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 e65cc0c4c..35db9e3cb 100644 --- a/src/Composer/Package/CompletePackageInterface.php +++ b/src/Composer/Package/CompletePackageInterface.php @@ -15,6 +15,8 @@ namespace Composer\Package; /** * 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 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * @param string $description * @return void */ - public function setDescription(string $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 @@ interface CompletePackageInterface extends PackageInterface * @param string $homepage * @return void */ - public function setHomepage(string $homepage); + public function setHomepage(string $homepage): void; /** * Returns an array of authors of the package @@ -114,7 +116,7 @@ interface CompletePackageInterface extends PackageInterface * * @return array */ - public function getAuthors(); + public function getAuthors(): array; /** * Set the authors @@ -122,14 +124,14 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * * @return array */ - public function getFunding(); + public function getFunding(): array; /** * Set the funding @@ -154,34 +156,34 @@ interface CompletePackageInterface extends PackageInterface * @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 @@ interface CompletePackageInterface extends PackageInterface * @param string $name * @return void */ - public function setArchiveName(string $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 @@ interface CompletePackageInterface extends PackageInterface * @param string[] $excludes * @return void */ - public function setArchiveExcludes(array $excludes); + public function setArchiveExcludes(array $excludes): void; } diff --git a/src/Composer/Package/Link.php b/src/Composer/Package/Link.php index a7628a720..481988c15 100644 --- a/src/Composer/Package/Link.php +++ b/src/Composer/Package/Link.php @@ -21,22 +21,22 @@ use Composer\Semver\Constraint\ConstraintInterface; */ 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 diff --git a/src/Composer/Package/Package.php b/src/Composer/Package/Package.php index ed5d52ee8..90dc0688f 100644 --- a/src/Composer/Package/Package.php +++ b/src/Composer/Package/Package.php @@ -120,7 +120,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function isDev() + public function isDev(): bool { return $this->dev; } @@ -130,7 +130,7 @@ class Package extends BasePackage * * @return void */ - public function setType(string $type) + public function setType(string $type): void { $this->type = $type; } @@ -138,7 +138,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getType() + public function getType(): string { return $this->type ?: 'library'; } @@ -146,7 +146,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getStability() + public function getStability(): string { return $this->stability; } @@ -154,7 +154,7 @@ class Package extends BasePackage /** * @return void */ - public function setTargetDir(?string $targetDir) + public function setTargetDir(?string $targetDir): void { $this->targetDir = $targetDir; } @@ -162,7 +162,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getTargetDir() + public function getTargetDir(): ?string { if (null === $this->targetDir) { return null; @@ -176,7 +176,7 @@ class Package extends BasePackage * * @return void */ - public function setExtra(array $extra) + public function setExtra(array $extra): void { $this->extra = $extra; } @@ -184,7 +184,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getExtra() + public function getExtra(): array { return $this->extra; } @@ -194,7 +194,7 @@ class Package extends BasePackage * * @return void */ - public function setBinaries(array $binaries) + public function setBinaries(array $binaries): void { $this->binaries = $binaries; } @@ -202,7 +202,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getBinaries() + public function getBinaries(): array { return $this->binaries; } @@ -212,7 +212,7 @@ class Package extends BasePackage * * @return void */ - public function setInstallationSource(?string $type) + public function setInstallationSource(?string $type): void { $this->installationSource = $type; } @@ -220,7 +220,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getInstallationSource() + public function getInstallationSource(): ?string { return $this->installationSource; } @@ -228,7 +228,7 @@ class Package extends BasePackage /** * @return void */ - public function setSourceType(?string $type) + public function setSourceType(?string $type): void { $this->sourceType = $type; } @@ -236,7 +236,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSourceType() + public function getSourceType(): ?string { return $this->sourceType; } @@ -244,7 +244,7 @@ class Package extends BasePackage /** * @return void */ - public function setSourceUrl(?string $url) + public function setSourceUrl(?string $url): void { $this->sourceUrl = $url; } @@ -252,7 +252,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSourceUrl() + public function getSourceUrl(): ?string { return $this->sourceUrl; } @@ -260,7 +260,7 @@ class Package extends BasePackage /** * @return void */ - public function setSourceReference(?string $reference) + public function setSourceReference(?string $reference): void { $this->sourceReference = $reference; } @@ -268,7 +268,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSourceReference() + public function getSourceReference(): ?string { return $this->sourceReference; } @@ -276,7 +276,7 @@ class Package extends BasePackage /** * @return void */ - public function setSourceMirrors(?array $mirrors) + public function setSourceMirrors(?array $mirrors): void { $this->sourceMirrors = $mirrors; } @@ -284,7 +284,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSourceMirrors() + public function getSourceMirrors(): ?array { return $this->sourceMirrors; } @@ -292,7 +292,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSourceUrls() + public function getSourceUrls(): array { return $this->getUrls($this->sourceUrl, $this->sourceMirrors, $this->sourceReference, $this->sourceType, 'source'); } @@ -302,7 +302,7 @@ class Package extends BasePackage * * @return void */ - public function setDistType(?string $type) + public function setDistType(?string $type): void { $this->distType = $type; } @@ -310,7 +310,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistType() + public function getDistType(): ?string { return $this->distType; } @@ -320,7 +320,7 @@ class Package extends BasePackage * * @return void */ - public function setDistUrl(?string $url) + public function setDistUrl(?string $url): void { $this->distUrl = $url; } @@ -328,7 +328,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistUrl() + public function getDistUrl(): ?string { return $this->distUrl; } @@ -338,7 +338,7 @@ class Package extends BasePackage * * @return void */ - public function setDistReference(?string $reference) + public function setDistReference(?string $reference): void { $this->distReference = $reference; } @@ -346,7 +346,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistReference() + public function getDistReference(): ?string { return $this->distReference; } @@ -356,7 +356,7 @@ class Package extends BasePackage * * @return void */ - public function setDistSha1Checksum(?string $sha1checksum) + public function setDistSha1Checksum(?string $sha1checksum): void { $this->distSha1Checksum = $sha1checksum; } @@ -364,7 +364,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistSha1Checksum() + public function getDistSha1Checksum(): ?string { return $this->distSha1Checksum; } @@ -372,7 +372,7 @@ class Package extends BasePackage /** * @return void */ - public function setDistMirrors(?array $mirrors) + public function setDistMirrors(?array $mirrors): void { $this->distMirrors = $mirrors; } @@ -380,7 +380,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistMirrors() + public function getDistMirrors(): ?array { return $this->distMirrors; } @@ -388,7 +388,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDistUrls() + public function getDistUrls(): array { return $this->getUrls($this->distUrl, $this->distMirrors, $this->distReference, $this->distType, 'dist'); } @@ -396,7 +396,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getTransportOptions() + public function getTransportOptions(): array { return $this->transportOptions; } @@ -404,7 +404,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function setTransportOptions(array $options) + public function setTransportOptions(array $options): void { $this->transportOptions = $options; } @@ -412,7 +412,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getVersion() + public function getVersion(): string { return $this->version; } @@ -420,7 +420,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getPrettyVersion() + public function getPrettyVersion(): string { return $this->prettyVersion; } @@ -428,7 +428,7 @@ class Package extends BasePackage /** * @return void */ - public function setReleaseDate(?\DateTimeInterface $releaseDate) + public function setReleaseDate(?\DateTimeInterface $releaseDate): void { $this->releaseDate = $releaseDate; } @@ -436,7 +436,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getReleaseDate() + public function getReleaseDate(): ?\DateTimeInterface { return $this->releaseDate; } @@ -448,7 +448,7 @@ class Package extends BasePackage * * @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'); @@ -460,7 +460,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getRequires() + public function getRequires(): array { return $this->requires; } @@ -472,7 +472,7 @@ class Package extends BasePackage * * @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'); @@ -485,7 +485,7 @@ class Package extends BasePackage * @inheritDoc * @return array */ - public function getConflicts() + public function getConflicts(): array { return $this->conflicts; } @@ -497,7 +497,7 @@ class Package extends BasePackage * * @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'); @@ -510,7 +510,7 @@ class Package extends BasePackage * @inheritDoc * @return array */ - public function getProvides() + public function getProvides(): array { return $this->provides; } @@ -522,7 +522,7 @@ class Package extends BasePackage * * @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'); @@ -535,7 +535,7 @@ class Package extends BasePackage * @inheritDoc * @return array */ - public function getReplaces() + public function getReplaces(): array { return $this->replaces; } @@ -547,7 +547,7 @@ class Package extends BasePackage * * @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'); @@ -559,7 +559,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDevRequires() + public function getDevRequires(): array { return $this->devRequires; } @@ -571,7 +571,7 @@ class Package extends BasePackage * * @return void */ - public function setSuggests(array $suggests) + public function setSuggests(array $suggests): void { $this->suggests = $suggests; } @@ -579,7 +579,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getSuggests() + public function getSuggests(): array { return $this->suggests; } @@ -593,7 +593,7 @@ class Package extends BasePackage * * @phpstan-param AutoloadRules $autoload */ - public function setAutoload(array $autoload) + public function setAutoload(array $autoload): void { $this->autoload = $autoload; } @@ -601,7 +601,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getAutoload() + public function getAutoload(): array { return $this->autoload; } @@ -615,7 +615,7 @@ class Package extends BasePackage * * @phpstan-param DevAutoloadRules $devAutoload */ - public function setDevAutoload(array $devAutoload) + public function setDevAutoload(array $devAutoload): void { $this->devAutoload = $devAutoload; } @@ -623,7 +623,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getDevAutoload() + public function getDevAutoload(): array { return $this->devAutoload; } @@ -635,7 +635,7 @@ class Package extends BasePackage * * @return void */ - public function setIncludePaths(array $includePaths) + public function setIncludePaths(array $includePaths): void { $this->includePaths = $includePaths; } @@ -643,7 +643,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getIncludePaths() + public function getIncludePaths(): array { return $this->includePaths; } @@ -655,7 +655,7 @@ class Package extends BasePackage * * @return void */ - public function setNotificationUrl(string $notificationUrl) + public function setNotificationUrl(string $notificationUrl): void { $this->notificationUrl = $notificationUrl; } @@ -663,7 +663,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function getNotificationUrl() + public function getNotificationUrl(): ?string { return $this->notificationUrl; } @@ -673,7 +673,7 @@ class Package extends BasePackage * * @return void */ - public function setIsDefaultBranch(bool $defaultBranch) + public function setIsDefaultBranch(bool $defaultBranch): void { $this->isDefaultBranch = $defaultBranch; } @@ -681,7 +681,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function isDefaultBranch() + public function isDefaultBranch(): bool { return $this->isDefaultBranch; } @@ -689,7 +689,7 @@ class Package extends BasePackage /** * @inheritDoc */ - public function setSourceDistReferences(string $reference) + public function setSourceDistReferences(string $reference): void { $this->setSourceReference($reference); @@ -715,7 +715,7 @@ class Package extends BasePackage * * @return void */ - public function replaceVersion(string $version, string $prettyVersion) + public function replaceVersion(string $version, string $prettyVersion): void { $this->version = $version; $this->prettyVersion = $prettyVersion; @@ -735,7 +735,7 @@ class Package extends BasePackage * * @phpstan-param list|null $mirrors */ - protected function getUrls(?string $url, ?array $mirrors, ?string $ref, ?string $type, string $urlType) + protected function getUrls(?string $url, ?array $mirrors, ?string $ref, ?string $type, string $urlType): array { if (!$url) { return array(); diff --git a/src/Composer/Package/PackageInterface.php b/src/Composer/Package/PackageInterface.php index 50512bfe5..31a0e78fb 100644 --- a/src/Composer/Package/PackageInterface.php +++ b/src/Composer/Package/PackageInterface.php @@ -17,6 +17,8 @@ use Composer\Repository\RepositoryInterface; /** * 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 @@ interface PackageInterface * * @return string[] An array of strings referring to this package */ - public function getNames(bool $provides = true); + public function getNames(bool $provides = true): array; /** * Allows the solver to set an id for this package to refer to it. @@ -61,42 +63,42 @@ interface PackageInterface * * @return void */ - public function setId(int $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). @@ -106,7 +108,7 @@ interface PackageInterface * * @return void */ - public function setInstallationSource(?string $type); + public function setInstallationSource(?string $type): void; /** * Returns source from which this package was installed (source/dist). @@ -114,110 +116,110 @@ interface PackageInterface * @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 null|array $mirrors * @return void */ - public function setSourceMirrors(?array $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 null|array $mirrors * @return void */ - public function setDistMirrors(?array $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 @@ interface PackageInterface * * @phpstan-param self::DISPLAY_SOURCE_REF_IF_DEV|self::DISPLAY_SOURCE_REF|self::DISPLAY_DIST_REF $displayMode */ - public function getFullPrettyVersion(bool $truncate = true, int $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 ?\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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * * @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 @@ interface PackageInterface * @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 @@ interface PackageInterface * @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 @@ interface PackageInterface * @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 @@ interface PackageInterface * * @return string[] */ - public function getIncludePaths(); + public function getIncludePaths(): array; /** * Stores a reference to the repository that owns the package @@ -338,61 +340,61 @@ interface PackageInterface * * @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,32 +403,32 @@ interface PackageInterface * * @return void */ - public function setTransportOptions(array $options); + public function setTransportOptions(array $options): void; /** * @return void */ - public function setSourceReference(?string $reference); + public function setSourceReference(?string $reference): void; /** * @return void */ - public function setDistUrl(?string $url); + public function setDistUrl(?string $url): void; /** * @return void */ - public function setDistType(?string $type); + public function setDistType(?string $type): void; /** * @return void */ - public function setDistReference(?string $reference); + public function setDistReference(?string $reference): void; /** * Set dist and source references and update dist URL for ones that contain a reference * * @return void */ - public function setSourceDistReferences(string $reference); + public function setSourceDistReferences(string $reference): void; } diff --git a/src/Composer/Package/RootPackageInterface.php b/src/Composer/Package/RootPackageInterface.php index a1783f875..9e74e4ddc 100644 --- a/src/Composer/Package/RootPackageInterface.php +++ b/src/Composer/Package/RootPackageInterface.php @@ -15,6 +15,8 @@ namespace Composer\Package; /** * 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 @@ interface RootPackageInterface extends CompletePackageInterface * * @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 @@ interface RootPackageInterface extends CompletePackageInterface * * @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 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setRequires(array $requires); + public function setRequires(array $requires): void; /** * Set the recommended packages @@ -84,7 +86,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setDevRequires(array $devRequires); + public function setDevRequires(array $devRequires): void; /** * Set the conflicting packages @@ -93,7 +95,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setConflicts(array $conflicts); + public function setConflicts(array $conflicts): void; /** * Set the provided virtual packages @@ -102,7 +104,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setProvides(array $provides); + public function setProvides(array $provides): void; /** * Set the packages this one replaces @@ -111,7 +113,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setReplaces(array $replaces); + public function setReplaces(array $replaces): void; /** * Set the repositories @@ -120,7 +122,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setRepositories(array $repositories); + public function setRepositories(array $repositories): void; /** * Set the autoload mapping @@ -130,7 +132,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setAutoload(array $autoload); + public function setAutoload(array $autoload): void; /** * Set the dev autoload mapping @@ -140,7 +142,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setDevAutoload(array $devAutoload); + public function setDevAutoload(array $devAutoload): void; /** * Set the stabilityFlags @@ -149,7 +151,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setStabilityFlags(array $stabilityFlags); + public function setStabilityFlags(array $stabilityFlags): void; /** * Set the minimumStability @@ -158,7 +160,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setMinimumStability(string $minimumStability); + public function setMinimumStability(string $minimumStability): void; /** * Set the preferStable @@ -167,7 +169,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setPreferStable(bool $preferStable); + public function setPreferStable(bool $preferStable): void; /** * Set the config @@ -176,7 +178,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setConfig(array $config); + public function setConfig(array $config): void; /** * Set the references @@ -185,7 +187,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setReferences(array $references); + public function setReferences(array $references): void; /** * Set the aliases @@ -194,7 +196,7 @@ interface RootPackageInterface extends CompletePackageInterface * * @return void */ - public function setAliases(array $aliases); + public function setAliases(array $aliases): void; /** * Set the suggested packages @@ -203,12 +205,12 @@ interface RootPackageInterface extends CompletePackageInterface * * @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/VersionParser.php b/src/Composer/Package/Version/VersionParser.php index 44b7dce62..faa5002c7 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 @@ class VersionParser extends SemverVersionParser * * @return list */ - public function parseNameVersionPairs(array $pairs) + public function parseNameVersionPairs(array $pairs): array { $pairs = array_values($pairs); $result = array(); @@ -76,7 +76,7 @@ class VersionParser extends SemverVersionParser * * @return bool */ - public static function isUpgrade(string $normalizedFrom, string $normalizedTo) + public static function isUpgrade(string $normalizedFrom, string $normalizedTo): bool { if ($normalizedFrom === $normalizedTo) { return true; diff --git a/src/Composer/Repository/RepositoryManager.php b/src/Composer/Repository/RepositoryManager.php index 913768028..0f119931e 100644 --- a/src/Composer/Repository/RepositoryManager.php +++ b/src/Composer/Repository/RepositoryManager.php @@ -62,7 +62,7 @@ class RepositoryManager * * @return PackageInterface|null */ - public function findPackage(string $name, $constraint) + public function findPackage(string $name, $constraint): ?PackageInterface { foreach ($this->repositories as $repository) { /** @var RepositoryInterface $repository */ @@ -82,7 +82,7 @@ class RepositoryManager * * @return PackageInterface[] */ - public function findPackages(string $name, $constraint) + public function findPackages(string $name, $constraint): array { $packages = array(); @@ -100,7 +100,7 @@ class RepositoryManager * * @return void */ - public function addRepository(RepositoryInterface $repository) + public function addRepository(RepositoryInterface $repository): void { $this->repositories[] = $repository; } @@ -114,7 +114,7 @@ class RepositoryManager * * @return void */ - public function prependRepository(RepositoryInterface $repository) + public function prependRepository(RepositoryInterface $repository): void { array_unshift($this->repositories, $repository); } @@ -128,7 +128,7 @@ class RepositoryManager * @throws \InvalidArgumentException if repository for provided type is not registered * @return RepositoryInterface */ - public function createRepository(string $type, array $config, string $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 @@ class RepositoryManager * * @return void */ - public function setRepositoryClass(string $type, $class) + public function setRepositoryClass(string $type, $class): void { $this->repositoryClasses[$type] = $class; } @@ -172,7 +172,7 @@ class RepositoryManager * * @return RepositoryInterface[] */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -184,7 +184,7 @@ class RepositoryManager * * @return void */ - public function setLocalRepository(InstalledRepositoryInterface $repository) + public function setLocalRepository(InstalledRepositoryInterface $repository): void { $this->localRepository = $repository; } @@ -194,7 +194,7 @@ class RepositoryManager * * @return InstalledRepositoryInterface */ - public function getLocalRepository() + public function getLocalRepository(): InstalledRepositoryInterface { return $this->localRepository; } diff --git a/src/Composer/Repository/Vcs/FossilDriver.php b/src/Composer/Repository/Vcs/FossilDriver.php index 7015f833f..1fb0fb36b 100644 --- a/src/Composer/Repository/Vcs/FossilDriver.php +++ b/src/Composer/Repository/Vcs/FossilDriver.php @@ -172,12 +172,12 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $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')); } /** diff --git a/src/Composer/Repository/Vcs/GitBitbucketDriver.php b/src/Composer/Repository/Vcs/GitBitbucketDriver.php index fba97fa42..1e045c3e9 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 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { if ($this->fallbackDriver) { return $this->fallbackDriver->getUrl(); @@ -99,7 +99,7 @@ class GitBitbucketDriver extends VcsDriver * @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 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation(string $identifier) + public function getComposerInformation(string $identifier): ?array { if ($this->fallbackDriver) { return $this->fallbackDriver->getComposerInformation($identifier); @@ -148,7 +148,7 @@ class GitBitbucketDriver extends VcsDriver } } - if ($composer) { + if ($composer !== null) { // specials for bitbucket if (!isset($composer['support']['source'])) { $label = array_search( @@ -205,7 +205,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent(string $file, string $identifier) + public function getFileContent(string $file, string $identifier): ?string { if ($this->fallbackDriver) { return $this->fallbackDriver->getFileContent($file, $identifier); @@ -232,7 +232,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->fallbackDriver) { return $this->fallbackDriver->getChangeDate($identifier); @@ -253,13 +253,13 @@ class GitBitbucketDriver extends VcsDriver ); $commit = $this->fetchWithOAuthCredentials($resource)->decodeJson(); - return new \DateTime($commit['date']); + return new \DateTimeImmutable($commit['date']); } /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getSource($identifier); @@ -271,7 +271,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { if ($this->fallbackDriver) { return $this->fallbackDriver->getDist($identifier); @@ -290,7 +290,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getTags(); @@ -333,7 +333,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if ($this->fallbackDriver) { return $this->fallbackDriver->getBranches(); @@ -383,7 +383,7 @@ class GitBitbucketDriver extends VcsDriver * * @phpstan-impure */ - protected function fetchWithOAuthCredentials(string $url, bool $fetchingRepoData = false) + protected function fetchWithOAuthCredentials(string $url, bool $fetchingRepoData = false): Response { try { return parent::getContents($url); @@ -413,7 +413,7 @@ class GitBitbucketDriver extends VcsDriver * * @return string */ - protected function generateSshUrl() + protected function generateSshUrl(): string { return 'git@' . $this->originUrl . ':' . $this->owner.'/'.$this->repository.'.git'; } @@ -424,7 +424,7 @@ class GitBitbucketDriver extends VcsDriver * @return true * @throws \RuntimeException */ - protected function attemptCloneFallback() + protected function attemptCloneFallback(): bool { try { $this->setupFallbackDriver($this->generateSshUrl()); @@ -445,7 +445,7 @@ class GitBitbucketDriver extends VcsDriver * @param string $url * @return void */ - protected function setupFallbackDriver(string $url) + protected function setupFallbackDriver(string $url): void { $this->fallbackDriver = new GitDriver( array('url' => $url), @@ -461,7 +461,7 @@ class GitBitbucketDriver extends VcsDriver * @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 @@ class GitBitbucketDriver extends VcsDriver /** * @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 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if ($this->fallbackDriver) { return $this->fallbackDriver->getRootIdentifier(); @@ -527,7 +527,7 @@ class GitBitbucketDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 f8ee7b32d..978db48ec 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 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'master'; @@ -112,7 +112,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -120,7 +120,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -128,7 +128,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { return null; } @@ -136,7 +136,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent(string $file, string $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 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $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 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -206,7 +206,7 @@ class GitDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 2f532297e..548db6e26 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 @@ class GitHubDriver extends VcsDriver /** * @return string */ - public function getRepositoryUrl() + public function getRepositoryUrl(): string { return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository; } @@ -92,7 +92,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); @@ -104,7 +104,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { if ($this->gitDriver) { return $this->gitDriver->getUrl(); @@ -116,7 +116,7 @@ class GitHubDriver extends VcsDriver /** * @return string */ - protected function getApiUrl() + protected function getApiUrl(): string { if ('github.com' === $this->originUrl) { $apiUrl = 'api.github.com'; @@ -130,7 +130,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -149,7 +149,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier; @@ -159,7 +159,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation(string $identifier) + public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -176,7 +176,7 @@ class GitHubDriver extends VcsDriver } } - 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 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent(string $file, string $identifier) + public function getFileContent(string $file, string $identifier): ?string { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); @@ -305,7 +305,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); @@ -314,13 +314,13 @@ class GitHubDriver extends VcsDriver $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 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if ($this->gitDriver) { return $this->gitDriver->getBranches(); @@ -379,7 +379,7 @@ class GitHubDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 @@ class GitHubDriver extends VcsDriver * * @return mixed[]|null */ - public function getRepoData() + public function getRepoData(): ?array { $this->fetchRootIdentifier(); @@ -416,7 +416,7 @@ class GitHubDriver extends VcsDriver * * @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 @@ class GitHubDriver extends VcsDriver * * @param bool $fetchingRepoData */ - protected function getContents(string $url, bool $fetchingRepoData = false) + protected function getContents(string $url, bool $fetchingRepoData = false): Response { try { return parent::getContents($url); @@ -521,7 +521,7 @@ class GitHubDriver extends VcsDriver * @return void * @throws TransportException */ - protected function fetchRootIdentifier() + protected function fetchRootIdentifier(): void { if ($this->repoData) { return; @@ -563,7 +563,7 @@ class GitHubDriver extends VcsDriver * @return true * @throws \RuntimeException */ - protected function attemptCloneFallback() + protected function attemptCloneFallback(): bool { $this->isPrivate = true; @@ -588,7 +588,7 @@ class GitHubDriver extends VcsDriver * * @return void */ - protected function setupGitDriver(string $url) + protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( array('url' => $url), @@ -603,7 +603,7 @@ class GitHubDriver extends VcsDriver /** * @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 3c5e4d16b..047cefa24 100644 --- a/src/Composer/Repository/Vcs/GitLabDriver.php +++ b/src/Composer/Repository/Vcs/GitLabDriver.php @@ -144,7 +144,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation($identifier): array + public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -161,7 +161,7 @@ class GitLabDriver extends VcsDriver } } - 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; @@ -216,17 +216,17 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $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; } /** diff --git a/src/Composer/Repository/Vcs/HgDriver.php b/src/Composer/Repository/Vcs/HgDriver.php index 575ce7263..1faa3c3e3 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 @@ class HgDriver extends VcsDriver /** * @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 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -108,7 +108,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -116,7 +116,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { return null; } @@ -124,7 +124,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent(string $file, string $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 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $this->process->execute( sprintf( @@ -150,13 +150,13 @@ class HgDriver extends VcsDriver $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 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -208,7 +208,7 @@ class HgDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 34e4d09c2..1caad14a7 100644 --- a/src/Composer/Repository/Vcs/PerforceDriver.php +++ b/src/Composer/Repository/Vcs/PerforceDriver.php @@ -18,6 +18,7 @@ use Composer\IO\IOInterface; 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 = ''; @@ -72,7 +73,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent(string $file, string $identifier) + public function getFileContent(string $file, string $identifier): ?string { return $this->perforce->getFileContent($file, $identifier); } @@ -80,7 +81,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { return null; } @@ -88,7 +89,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { return $this->branch; } @@ -96,7 +97,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { return $this->perforce->getBranches(); } @@ -104,7 +105,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getTags() + public function getTags(): array { return $this->perforce->getTags(); } @@ -112,7 +113,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { return null; } @@ -120,7 +121,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { return array( 'type' => 'perforce', @@ -133,7 +134,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -141,7 +142,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function hasComposerFile(string $identifier) + public function hasComposerFile(string $identifier): bool { $composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier); @@ -151,7 +152,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function getContents(string $url) + public function getContents(string $url): Response { throw new \BadMethodCallException('Not implemented/used in PerforceDriver'); } @@ -159,7 +160,7 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 @@ class PerforceDriver extends VcsDriver /** * @inheritDoc */ - public function cleanup() + public function cleanup(): void { $this->perforce->cleanupClientSpec(); $this->perforce = null; @@ -180,7 +181,7 @@ class PerforceDriver extends VcsDriver /** * @return string */ - public function getDepot() + public function getDepot(): string { return $this->depot; } @@ -188,7 +189,7 @@ class PerforceDriver extends VcsDriver /** * @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 82d91721d..0c028b369 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 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { return $this->rootIdentifier ?: $this->trunkPath; } @@ -101,7 +101,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -109,7 +109,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getSource(string $identifier) + public function getSource(string $identifier): array { return array('type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier); } @@ -117,7 +117,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getDist(string $identifier) + public function getDist(string $identifier): ?array { return null; } @@ -125,7 +125,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - protected function shouldCache(string $identifier) + protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{@\d+$}', $identifier); } @@ -133,7 +133,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation(string $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 @@ class SvnDriver extends VcsDriver * @param string $file * @param string $identifier */ - public function getFileContent(string $file, string $identifier) + public function getFileContent(string $file, string $identifier): ?string { $identifier = '/' . trim($identifier, '/') . '/'; @@ -194,7 +194,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate(string $identifier) + public function getChangeDate(string $identifier): ?\DateTimeImmutable { $identifier = '/' . trim($identifier, '/') . '/'; @@ -210,7 +210,7 @@ class SvnDriver extends VcsDriver $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 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if (null === $this->tags) { $tags = array(); @@ -251,7 +251,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -306,7 +306,7 @@ class SvnDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 @@ class SvnDriver extends VcsDriver * * @return string */ - protected static function normalizeUrl(string $url) + protected static function normalizeUrl(string $url): string { $fs = new Filesystem(); if ($fs->isAbsolutePath($url)) { @@ -372,7 +372,7 @@ class SvnDriver extends VcsDriver * @throws \RuntimeException * @return string */ - protected function execute(string $command, string $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 @@ class SvnDriver extends VcsDriver * * @return string */ - protected function buildIdentifier(string $baseDir, int $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 abc4feb23..8656aa69d 100644 --- a/src/Composer/Repository/Vcs/VcsDriver.php +++ b/src/Composer/Repository/Vcs/VcsDriver.php @@ -79,7 +79,7 @@ abstract class VcsDriver implements VcsDriverInterface * @param string $identifier * @return bool */ - protected function shouldCache(string $identifier) + protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{^[a-f0-9]{40}$}iD', $identifier); } @@ -87,7 +87,7 @@ abstract class VcsDriver implements VcsDriverInterface /** * @inheritDoc */ - public function getComposerInformation(string $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 @@ abstract class VcsDriver implements VcsDriverInterface * * @return array|null */ - protected function getBaseComposerInformation(string $identifier) + protected function getBaseComposerInformation(string $identifier): ?array { $composerFileContent = $this->getFileContent('composer.json', $identifier); @@ -121,7 +121,7 @@ abstract class VcsDriver implements VcsDriverInterface $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 @@ abstract class VcsDriver implements VcsDriverInterface /** * @inheritDoc */ - public function hasComposerFile(string $identifier) + public function hasComposerFile(string $identifier): bool { try { return (bool) $this->getComposerInformation($identifier); @@ -148,7 +148,7 @@ abstract class VcsDriver implements VcsDriverInterface * * @return string The correct type of protocol */ - protected function getScheme() + protected function getScheme(): string { if (extension_loaded('openssl')) { return 'https'; @@ -165,7 +165,7 @@ abstract class VcsDriver implements VcsDriverInterface * @return Response * @throws TransportException */ - protected function getContents(string $url) + protected function getContents(string $url): Response { $options = $this->repoConfig['options'] ?? array(); @@ -175,7 +175,7 @@ abstract class VcsDriver implements VcsDriverInterface /** * @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 ff3a2cdce..9acf2e702 100644 --- a/src/Composer/Repository/Vcs/VcsDriverInterface.php +++ b/src/Composer/Repository/Vcs/VcsDriverInterface.php @@ -17,6 +17,7 @@ use Composer\IO\IOInterface; /** * @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(string $identifier); + public function getComposerInformation(string $identifier): ?array; /** * Return the content of $file or null if the file does not exist. @@ -42,57 +43,56 @@ interface VcsDriverInterface * @param string $identifier * @return string|null */ - public function getFileContent(string $file, string $identifier); + public function getFileContent(string $file, string $identifier): ?string; /** * Get the changedate for $identifier. * * @param string $identifier - * @return \DateTime|null */ - public function getChangeDate(string $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(string $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(string $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 @@ interface VcsDriverInterface * @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(string $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 @@ interface VcsDriverInterface * @param bool $deep unless true, only shallow checks (url matching typically) should be done * @return bool */ - public static function supports(IOInterface $io, Config $config, string $url, bool $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 9a2120098..8bbf65730 100644 --- a/src/Composer/Repository/VcsRepository.php +++ b/src/Composer/Repository/VcsRepository.php @@ -121,7 +121,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return void */ - public function setLoader(LoaderInterface $loader) + public function setLoader(LoaderInterface $loader): void { $this->loader = $loader; } @@ -129,7 +129,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return VcsDriverInterface|null */ - public function getDriver() + public function getDriver(): ?VcsDriverInterface { if ($this->driver) { return $this->driver; @@ -167,7 +167,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return bool */ - public function hadInvalidBranches() + public function hadInvalidBranches(): bool { return $this->branchErrorOccurred; } @@ -175,7 +175,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return string[] */ - public function getEmptyReferences() + public function getEmptyReferences(): array { return $this->emptyReferences; } @@ -183,7 +183,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return array<'tags'|'branches', array> */ - public function getVersionTransportExceptions() + public function getVersionTransportExceptions(): array { return $this->versionTransportExceptions; } @@ -254,7 +254,8 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt } 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 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt } try { - if (!$data = $driver->getComposerInformation($identifier)) { + $data = $driver->getComposerInformation($identifier); + if (null === $data) { if ($isVeryVerbose) { $this->io->writeError('Skipped branch '.$branch.', no composer file'); } diff --git a/src/Composer/Script/Event.php b/src/Composer/Script/Event.php index 3c1bccdb2..ed6b7f0ba 100644 --- a/src/Composer/Script/Event.php +++ b/src/Composer/Script/Event.php @@ -67,7 +67,7 @@ class Event extends BaseEvent * * @return Composer */ - public function getComposer() + public function getComposer(): Composer { return $this->composer; } @@ -77,7 +77,7 @@ class Event extends BaseEvent * * @return IOInterface */ - public function getIO() + public function getIO(): IOInterface { return $this->io; } @@ -87,7 +87,7 @@ class Event extends BaseEvent * * @return bool */ - public function isDevMode() + public function isDevMode(): bool { return $this->devMode; } diff --git a/src/Composer/Util/Git.php b/src/Composer/Util/Git.php index 7c9482a5c..be86b3dd0 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -49,7 +49,7 @@ class Git * * @return void */ - public function runCommand(callable $commandCallable, string $url, ?string $cwd, bool $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 @@ class Git * * @return bool */ - public function syncMirror(string $url, string $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 @@ class Git * * @return bool */ - public function fetchRefOrSyncMirror(string $url, string $dir, string $ref) + public function fetchRefOrSyncMirror(string $url, string $dir, string $ref): bool { if ($this->checkRefIsInMirror($dir, $ref)) { return true; @@ -333,7 +333,7 @@ class Git /** * @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', '>=')) { @@ -395,7 +395,7 @@ class Git /** * @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') { @@ -458,7 +458,7 @@ class Git * * @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; diff --git a/src/Composer/Util/Perforce.php b/src/Composer/Util/Perforce.php index 058180783..f10f4b4f0 100644 --- a/src/Composer/Util/Perforce.php +++ b/src/Composer/Util/Perforce.php @@ -85,7 +85,7 @@ class Perforce * * @return self */ - public static function create($repoConfig, string $port, string $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 @@ class Perforce * * @return bool */ - public static function checkServerExists(string $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 @@ class Perforce * * @return void */ - public function initialize($repoConfig) + public function initialize($repoConfig): void { $this->uniquePerforceClientName = $this->generateUniquePerforceClientName(); if (!$repoConfig) { @@ -138,7 +138,7 @@ class Perforce * * @return void */ - public function initializeDepotAndBranch(?string $depot, ?string $branch) + public function initializeDepotAndBranch(?string $depot, ?string $branch): void { if (isset($depot)) { $this->p4Depot = $depot; @@ -159,7 +159,7 @@ class Perforce /** * @return void */ - public function cleanupClientSpec() + public function cleanupClientSpec(): void { $client = $this->getClient(); $task = 'client -d ' . ProcessExecutor::escape($client); @@ -176,7 +176,7 @@ class Perforce * * @return int */ - protected function executeCommand($command) + protected function executeCommand($command): int { $this->commandResult = ''; @@ -186,7 +186,7 @@ class Perforce /** * @return string */ - public function getClient() + public function getClient(): string { if (!isset($this->p4Client)) { $cleanStreamName = str_replace(array('//', '/', '@'), array('', '_', ''), $this->getStream()); @@ -199,7 +199,7 @@ class Perforce /** * @return string */ - protected function getPath() + protected function getPath(): string { return $this->path; } @@ -209,7 +209,7 @@ class Perforce * * @return void */ - public function initializePath(string $path) + public function initializePath(string $path): void { $this->path = $path; $fs = $this->getFilesystem(); @@ -219,7 +219,7 @@ class Perforce /** * @return string */ - protected function getPort() + protected function getPort(): string { return $this->p4Port; } @@ -229,7 +229,7 @@ class Perforce * * @return void */ - public function setStream(string $stream) + public function setStream(string $stream): void { $this->p4Stream = $stream; $index = strrpos($stream, '/'); @@ -242,7 +242,7 @@ class Perforce /** * @return bool */ - public function isStream() + public function isStream(): bool { return is_string($this->p4DepotType) && (strcmp($this->p4DepotType, 'stream') === 0); } @@ -250,7 +250,7 @@ class Perforce /** * @return string */ - public function getStream() + public function getStream(): string { if (!isset($this->p4Stream)) { if ($this->isStream()) { @@ -268,7 +268,7 @@ class Perforce * * @return string */ - public function getStreamWithoutLabel(string $stream) + public function getStreamWithoutLabel(string $stream): string { $index = strpos($stream, '@'); if ($index === false) { @@ -289,7 +289,7 @@ class Perforce /** * @return string|null */ - public function getUser() + public function getUser(): ?string { return $this->p4User; } @@ -299,7 +299,7 @@ class Perforce * * @return void */ - public function setUser(?string $user) + public function setUser(?string $user): void { $this->p4User = $user; } @@ -307,7 +307,7 @@ class Perforce /** * @return void */ - public function queryP4User() + public function queryP4User(): void { $this->getUser(); if (strlen((string) $this->p4User) > 0) { @@ -365,7 +365,7 @@ class Perforce /** * @return string|null */ - public function queryP4Password() + public function queryP4Password(): ?string { if (isset($this->p4Password)) { return $this->p4Password; @@ -400,7 +400,7 @@ class Perforce /** * @return bool */ - public function isLoggedIn() + public function isLoggedIn(): bool { $command = $this->generateP4Command('login -s', false); $exitCode = $this->executeCommand($command); @@ -423,7 +423,7 @@ class Perforce /** * @return void */ - public function connectClient() + public function connectClient(): void { $p4CreateClientCommand = $this->generateP4Command( 'client -i < ' . str_replace(" ", "\\ ", $this->getP4ClientSpec()) @@ -436,7 +436,7 @@ class Perforce * * @return void */ - public function syncCodeBase(?string $sourceReference) + public function syncCodeBase(?string $sourceReference): void { $prevDir = Platform::getCwd(); chdir($this->path); @@ -453,7 +453,7 @@ class Perforce * * @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 @@ class Perforce /** * @return void */ - public function writeP4ClientSpec() + public function writeP4ClientSpec(): void { $clientSpec = $this->getP4ClientSpec(); $spec = fopen($clientSpec, 'w'); @@ -498,7 +498,7 @@ class Perforce * * @return void */ - protected function read($pipe, $name) + protected function read($pipe, $name): void { if (feof($pipe)) { return; @@ -514,7 +514,7 @@ class Perforce * * @return int */ - public function windowsLogin(?string $password) + public function windowsLogin(?string $password): int { $command = $this->generateP4Command(' login -a'); @@ -526,7 +526,7 @@ class Perforce /** * @return void */ - public function p4Login() + public function p4Login(): void { $this->queryP4User(); if (!$this->isLoggedIn()) { @@ -546,14 +546,14 @@ class Perforce /** * @param string $identifier * - * @return mixed|void + * @return mixed[]|null */ - public function getComposerInformation(string $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 @@ class Perforce * * @return string|null */ - public function getFileContent(string $file, string $identifier) + public function getFileContent(string $file, string $identifier): ?string { $path = $this->getFilePath($file, $identifier); @@ -586,7 +586,7 @@ class Perforce * * @return string|null */ - public function getFilePath(string $file, string $identifier) + public function getFilePath(string $file, string $identifier): ?string { $index = strpos($identifier, '@'); if ($index === false) { @@ -646,7 +646,7 @@ class Perforce /** * @return array */ - public function getTags() + public function getTags(): array { $command = $this->generateP4Command('labels'); $this->executeCommand($command); @@ -666,7 +666,7 @@ class Perforce /** * @return bool */ - public function checkStream() + public function checkStream(): bool { $command = $this->generateP4Command('depots', false); $this->executeCommand($command); @@ -690,7 +690,7 @@ class Perforce * @param string $reference * @return mixed|null */ - protected function getChangeList(string $reference) + protected function getChangeList(string $reference): mixed { $index = strpos($reference, '@'); if ($index === false) { @@ -713,7 +713,7 @@ class Perforce * @param string $toReference * @return mixed|null */ - public function getCommitLogs(string $fromReference, string $toReference) + public function getCommitLogs(string $fromReference, string $toReference): mixed { $fromChangeList = $this->getChangeList($fromReference); if ($fromChangeList === null) { @@ -734,7 +734,7 @@ class Perforce /** * @return Filesystem */ - public function getFilesystem() + public function getFilesystem(): Filesystem { if (null === $this->filesystem) { $this->filesystem = new Filesystem($this->process); @@ -746,7 +746,7 @@ class Perforce /** * @return void */ - public function setFilesystem(Filesystem $fs) + public function setFilesystem(Filesystem $fs): void { $this->filesystem = $fs; } diff --git a/src/Composer/Util/ProcessExecutor.php b/src/Composer/Util/ProcessExecutor.php index 05060bbfb..429337708 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -68,7 +68,7 @@ class ProcessExecutor * @param null|string $cwd the working directory * @return int statuscode */ - public function execute($command, &$output = null, ?string $cwd = null) + public function execute($command, &$output = null, ?string $cwd = null): int { if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); @@ -84,7 +84,7 @@ class ProcessExecutor * @param null|string $cwd the working directory * @return int statuscode */ - public function executeTty($command, ?string $cwd = null) + public function executeTty($command, ?string $cwd = null): int { if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); @@ -121,7 +121,10 @@ class ProcessExecutor } } - $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 @@ class ProcessExecutor * @param string $cwd the working directory * @return PromiseInterface */ - public function executeAsync($command, ?string $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,6 +209,25 @@ class ProcessExecutor 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 @@ -253,7 +275,7 @@ class ProcessExecutor * @param ?int $index job id * @return void */ - public function wait($index = null) + public function wait($index = null): void { while (true) { if (!$this->countActiveJobs($index)) { @@ -324,7 +346,7 @@ class ProcessExecutor * @param null|string $output * @return string[] */ - public function splitLines(?string $output) + public function splitLines(?string $output): array { $output = trim((string) $output); @@ -336,42 +358,15 @@ class ProcessExecutor * * @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, string $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 @@ class ProcessExecutor * @param int $timeout the timeout in seconds * @return void */ - public static function setTimeout(int $timeout) + public static function setTimeout(int $timeout): void { static::$timeout = $timeout; } @@ -392,7 +387,7 @@ class ProcessExecutor * * @return string The escaped argument */ - public static function escape($argument) + public static function escape($argument): string { return self::escapeArgument($argument); } diff --git a/tests/Composer/Test/Command/InitCommandTest.php b/tests/Composer/Test/Command/InitCommandTest.php index 69af6cfbc..25af49ed5 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 @@ class InitCommandTest extends TestCase 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 @@ class InitCommandTest extends TestCase 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 @@ class InitCommandTest extends TestCase // \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 @@ class InitCommandTest extends TestCase 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 @@ class InitCommandTest extends TestCase 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 @@ class InitCommandTest extends TestCase 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 @@ class InitCommandTest extends TestCase { $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 @@ class InitCommandTest extends TestCase $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/Downloader/DownloadManagerTest.php b/tests/Composer/Test/Downloader/DownloadManagerTest.php index 7fa25f717..8ff051927 100644 --- a/tests/Composer/Test/Downloader/DownloadManagerTest.php +++ b/tests/Composer/Test/Downloader/DownloadManagerTest.php @@ -223,7 +223,8 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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') @@ -775,7 +785,8 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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 @@ class DownloadManagerTest extends TestCase $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/ZipDownloaderTest.php b/tests/Composer/Test/Downloader/ZipDownloaderTest.php index 9b0ca2382..f7a444412 100644 --- a/tests/Composer/Test/Downloader/ZipDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ZipDownloaderTest.php @@ -335,7 +335,7 @@ class ZipDownloaderTest extends TestCase 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 @@ class MockedZipDownloader extends ZipDownloader 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/Installer/LibraryInstallerTest.php b/tests/Composer/Test/Installer/LibraryInstallerTest.php index 5f2cc55f8..e14a830df 100644 --- a/tests/Composer/Test/Installer/LibraryInstallerTest.php +++ b/tests/Composer/Test/Installer/LibraryInstallerTest.php @@ -151,7 +151,8 @@ class LibraryInstallerTest extends TestCase $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 @@ class LibraryInstallerTest extends TestCase $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 @@ class LibraryInstallerTest extends TestCase $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/Mock/ProcessExecutorMock.php b/tests/Composer/Test/Mock/ProcessExecutorMock.php index 97f4c3f56..897d889ce 100644 --- a/tests/Composer/Test/Mock/ProcessExecutorMock.php +++ b/tests/Composer/Test/Mock/ProcessExecutorMock.php @@ -135,7 +135,9 @@ class ProcessExecutorMock extends ProcessExecutor $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; diff --git a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php index 6b4315363..8b1d5af0c 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 @@ class ArrayDumperTest extends TestCase public function testRootPackage(): void { - $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); + $package = $this->getRootPackage(); + $package->setMinimumStability('dev'); - $this - ->packageExpects('getMinimumStability', 'dev') - ->packageExpects('getTransportOptions', array()) - ; - - $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']); } @@ -97,16 +80,12 @@ class ArrayDumperTest extends TestCase */ public function testKeys(string $key, $value, string $method = null, $expectedValue = null): void { - $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); + $package = $this->getRootPackage(); - $this->packageExpects('get'.ucfirst($method ?: $key), $value); - $this->packageExpects('isAbandoned', $value); + // @phpstan-ignore-next-line + $package->{'set'.ucfirst($method ?: $key)}($value); - if ($method !== 'transportOptions') { - $this->packageExpects('getTransportOptions', array()); - } - - $config = $this->dumper->dump($this->package); + $config = $this->dumper->dump($package); $this->assertSame($expectedValue ?: $value, $config[$key]); } @@ -177,13 +156,13 @@ class ArrayDumperTest extends TestCase ), 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 @@ class ArrayDumperTest extends TestCase ), 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 @@ class ArrayDumperTest extends TestCase ), 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 @@ class ArrayDumperTest extends TestCase ), ); } - - /** - * @param string $method - * @param mixed $value - */ - private function packageExpects(string $method, $value): ArrayDumperTest - { - $this->package - ->expects($this->any()) - ->method($method) - ->will($this->returnValue($value)); - - return $this; - } } diff --git a/tests/Composer/Test/Package/LockerTest.php b/tests/Composer/Test/Package/LockerTest.php index 17168f62a..d2913e36d 100644 --- a/tests/Composer/Test/Package/LockerTest.php +++ b/tests/Composer/Test/Package/LockerTest.php @@ -93,41 +93,8 @@ class LockerTest extends TestCase $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 @@ class LockerTest extends TestCase '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/Plugin/PluginInstallerTest.php b/tests/Composer/Test/Plugin/PluginInstallerTest.php index dcc0ecabf..32b2afc36 100644 --- a/tests/Composer/Test/Plugin/PluginInstallerTest.php +++ b/tests/Composer/Test/Plugin/PluginInstallerTest.php @@ -83,6 +83,15 @@ class PluginInstallerTest extends TestCase $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(); diff --git a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php index 77debc3c7..005f0c817 100644 --- a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php @@ -193,6 +193,7 @@ class GitHubDriverTest extends TestCase $data = $gitHubDriver->getComposerInformation($identifier); + $this->assertIsArray($data); $this->assertArrayNotHasKey('abandoned', $data); } @@ -230,6 +231,7 @@ class GitHubDriverTest extends TestCase $data = $gitHubDriver->getComposerInformation($sha); + $this->assertIsArray($data); $this->assertTrue($data['abandoned']); } diff --git a/tests/Composer/Test/Util/AuthHelperTest.php b/tests/Composer/Test/Util/AuthHelperTest.php index cf0a9e8fc..b179688e2 100644 --- a/tests/Composer/Test/Util/AuthHelperTest.php +++ b/tests/Composer/Test/Util/AuthHelperTest.php @@ -377,8 +377,7 @@ class AuthHelperTest extends TestCase $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 @@ class AuthHelperTest extends TestCase $configSource->expects($this->once()) ->method('addConfigSetting') - ->with('http-basic.'.$origin, $auth) - ->willReturn($configSource); + ->with('http-basic.'.$origin, $auth); $this->authHelper->storeAuth($origin, $storeAuth); } From 14fcfc3ae171c3b6f526f264d18cedafac6e59a4 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Wed, 23 Feb 2022 11:39:26 +0100 Subject: [PATCH 5/6] Update baseline (2244 errors) --- phpstan/baseline.neon | 443 +----------------------------------------- 1 file changed, 9 insertions(+), 434 deletions(-) diff --git a/phpstan/baseline.neon b/phpstan/baseline.neon index 220027402..763f33219 100644 --- a/phpstan/baseline.neon +++ b/phpstan/baseline.neon @@ -117,7 +117,7 @@ parameters: - message: "#^Parameter \\#1 \\$path of function realpath expects string, string\\|false given\\.$#" - count: 3 + count: 2 path: ../src/Composer/Autoload/AutoloadGenerator.php - @@ -127,7 +127,7 @@ parameters: - message: "#^Parameter \\#1 \\$str of function strtr expects string, string\\|false given\\.$#" - count: 3 + count: 2 path: ../src/Composer/Autoload/AutoloadGenerator.php - @@ -240,16 +240,6 @@ parameters: count: 1 path: ../src/Composer/Autoload/ClassMapGenerator.php - - - message: "#^Parameter \\#1 \\$path of function realpath expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Autoload/ClassMapGenerator.php - - - - message: "#^Parameter \\#1 \\$str of function preg_quote expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Autoload/ClassMapGenerator.php - - message: "#^Parameter \\#1 \\$str of function strtr expects string, string\\|false given\\.$#" count: 1 @@ -325,11 +315,6 @@ parameters: count: 1 path: ../src/Composer/Command/ArchiveCommand.php - - - message: "#^Parameter \\#1 \\$from of method Composer\\\\Util\\\\Filesystem\\:\\:findShortestPath\\(\\) expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Command/ArchiveCommand.php - - message: "#^Only booleans are allowed in an if condition, Composer\\\\Composer\\|null given\\.$#" count: 1 @@ -395,11 +380,6 @@ parameters: count: 1 path: ../src/Composer/Command/CheckPlatformReqsCommand.php - - - message: "#^Cannot call method getLockedRepository\\(\\) on Composer\\\\Package\\\\Locker\\|null\\.$#" - count: 2 - path: ../src/Composer/Command/CheckPlatformReqsCommand.php - - message: "#^Only booleans are allowed in a negated boolean, Composer\\\\Semver\\\\Constraint\\\\ConstraintInterface\\|null given\\.$#" count: 1 @@ -470,11 +450,6 @@ parameters: count: 1 path: ../src/Composer/Command/ConfigCommand.php - - - message: "#^Parameter \\#1 \\$path of function realpath expects string, string\\|false given\\.$#" - count: 1 - path: ../src/Composer/Command/ConfigCommand.php - - message: "#^Parameter \\#2 \\$rawContents of method Composer\\\\Command\\\\ConfigCommand\\:\\:listConfiguration\\(\\) expects array\\, 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 @@ -1455,21 +1370,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 +1405,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 +1595,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 +1625,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 +1690,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 +2200,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 +2580,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 +2595,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 +2835,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 +2842,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 +3465,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 @@ -3795,14 +3625,9 @@ parameters: 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\\.$#" - 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 +3905,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 +3935,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 +3952,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 +4290,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 +4457,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 +4480,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 @@ -5170,11 +4975,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 @@ -5460,11 +5260,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 +5680,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 +5775,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 +5900,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 +6195,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 +6365,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 +6415,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 +6455,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 +6525,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 +6535,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 +6550,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 +6600,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 +6615,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 +6668,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 +6753,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 +6778,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 +6828,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 +6848,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 +6880,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 +6973,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 +6998,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 +7113,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 +7150,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 - From 89ce53250e19877a5e985893d593226b4b584819 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Wed, 23 Feb 2022 12:54:07 +0100 Subject: [PATCH 6/6] Final type additions --- phpstan/baseline.neon | 31 ++--------- src/Composer/Autoload/AutoloadGenerator.php | 7 +-- src/Composer/Command/InitCommand.php | 2 +- src/Composer/Command/ShowCommand.php | 12 ++--- src/Composer/DependencyResolver/Decisions.php | 2 +- src/Composer/DependencyResolver/Pool.php | 2 +- src/Composer/DependencyResolver/Rule.php | 2 +- src/Composer/DependencyResolver/RuleSet.php | 2 +- .../EventDispatcher/EventDispatcher.php | 2 +- src/Composer/InstalledVersions.php | 2 + src/Composer/Installer.php | 52 +++++++++---------- .../Package/Archiver/ArchiveManager.php | 2 +- src/Composer/Package/Loader/ArrayLoader.php | 10 ++-- src/Composer/Package/Loader/JsonLoader.php | 7 ++- .../Package/Loader/LoaderInterface.php | 7 ++- .../Package/Loader/RootPackageLoader.php | 6 +-- .../Package/Loader/ValidatingArrayLoader.php | 2 +- src/Composer/Repository/ArrayRepository.php | 6 +-- .../Repository/ComposerRepository.php | 6 +-- .../Repository/FilesystemRepository.php | 2 +- src/Composer/Repository/VcsRepository.php | 2 +- .../Repository/WritableArrayRepository.php | 2 +- src/Composer/Script/Event.php | 6 +-- src/Composer/Util/Git.php | 4 +- src/Composer/Util/Perforce.php | 10 ++-- src/bootstrap.php | 6 +-- tests/Composer/Test/TestCase.php | 4 +- 27 files changed, 82 insertions(+), 116 deletions(-) diff --git a/phpstan/baseline.neon b/phpstan/baseline.neon index 763f33219..8508c981f 100644 --- a/phpstan/baseline.neon +++ b/phpstan/baseline.neon @@ -1095,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 @@ -3530,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 @@ -3616,12 +3606,12 @@ 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\\(\\)$#" + 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\\\\LoaderInterface\\:\\:load\\(\\)$#" count: 1 path: ../src/Composer/Package/Loader/RootPackageLoader.php @@ -4595,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 @@ -4720,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 @@ -4797,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 - @@ -5020,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 diff --git a/src/Composer/Autoload/AutoloadGenerator.php b/src/Composer/Autoload/AutoloadGenerator.php index 825dc17bc..5485565e0 100644 --- a/src/Composer/Autoload/AutoloadGenerator.php +++ b/src/Composer/Autoload/AutoloadGenerator.php @@ -1364,12 +1364,7 @@ INITIALIZER; } } -/** - * @param string $fileIdentifier - * @param string $file - * @return void - */ -function composerRequire(string $fileIdentifier, string $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/Command/InitCommand.php b/src/Composer/Command/InitCommand.php index 4f3cebbd8..1d4dea29b 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -459,7 +459,7 @@ EOT * @param string $author * @return array{name: string, email: string|null} */ - private function parseAuthorString(string $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']; diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php index 775d858e9..8b11a8e33 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -294,7 +294,7 @@ EOT if ( $input->getOption('outdated') && $input->getOption('strict') - && $latestPackage + && null !== $latestPackage && $latestPackage->getFullPrettyVersion() !== $package->getFullPrettyVersion() && (!$latestPackage instanceof CompletePackageInterface || !$latestPackage->isAbandoned()) ) { @@ -415,7 +415,7 @@ EOT foreach ($packages[$type] as $package) { if (is_object($package)) { $latestPackage = $this->findLatestPackage($package, $composer, $platformRepo, $showMinorOnly, $platformReqFilter); - if ($latestPackage === false) { + if ($latestPackage === null) { continue; } @@ -628,7 +628,7 @@ EOT * @throws \InvalidArgumentException * @return array{CompletePackageInterface|null, array} */ - protected function getPackage(InstalledRepository $installedRepo, RepositoryInterface $repos, string $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; @@ -1287,10 +1287,8 @@ EOT /** * 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 @@ EOT $candidate = $candidate->getAliasOf(); } - return $candidate; + return $candidate !== false ? $candidate : null; } /** diff --git a/src/Composer/DependencyResolver/Decisions.php b/src/Composer/DependencyResolver/Decisions.php index 837488681..f9e349024 100644 --- a/src/Composer/DependencyResolver/Decisions.php +++ b/src/Composer/DependencyResolver/Decisions.php @@ -288,7 +288,7 @@ class Decisions implements \Iterator, \Countable return $str; } - public function __toString() + public function __toString(): string { return $this->toString(); } diff --git a/src/Composer/DependencyResolver/Pool.php b/src/Composer/DependencyResolver/Pool.php index 94c895c28..1abbc6382 100644 --- a/src/Composer/DependencyResolver/Pool.php +++ b/src/Composer/DependencyResolver/Pool.php @@ -268,7 +268,7 @@ class Pool implements \Countable return $this->unacceptableFixedOrLockedPackages; } - public function __toString() + public function __toString(): string { $str = "Pool:\n"; diff --git a/src/Composer/DependencyResolver/Rule.php b/src/Composer/DependencyResolver/Rule.php index c1cc491d2..bcf32fb03 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -78,7 +78,7 @@ abstract class Rule */ abstract public function getHash(); - abstract public function __toString(); + abstract public function __toString(): string; /** * @param Rule $rule diff --git a/src/Composer/DependencyResolver/RuleSet.php b/src/Composer/DependencyResolver/RuleSet.php index 9fe82e24e..d430b46a9 100644 --- a/src/Composer/DependencyResolver/RuleSet.php +++ b/src/Composer/DependencyResolver/RuleSet.php @@ -195,7 +195,7 @@ class RuleSet implements \IteratorAggregate, \Countable return $string; } - public function __toString() + public function __toString(): string { return $this->getPrettyString(); } diff --git a/src/Composer/EventDispatcher/EventDispatcher.php b/src/Composer/EventDispatcher/EventDispatcher.php index 941fc2520..d0cd437bd 100644 --- a/src/Composer/EventDispatcher/EventDispatcher.php +++ b/src/Composer/EventDispatcher/EventDispatcher.php @@ -81,7 +81,7 @@ class EventDispatcher * @param bool $runScripts * @return $this */ - public function setRunScripts(bool $runScripts = true) + public function setRunScripts(bool $runScripts = true): self { $this->runScripts = (bool) $runScripts; diff --git a/src/Composer/InstalledVersions.php b/src/Composer/InstalledVersions.php index d50e0c9fc..41bc143c1 100644 --- a/src/Composer/InstalledVersions.php +++ b/src/Composer/InstalledVersions.php @@ -21,6 +21,8 @@ use Composer\Semver\VersionParser; * 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 fd3cb1417..d72525b33 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -1030,7 +1030,7 @@ class Installer * @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 @@ class Installer * @param RepositoryInterface $additionalFixedRepository * @return $this */ - public function setAdditionalFixedRepository(RepositoryInterface $additionalFixedRepository) + public function setAdditionalFixedRepository(RepositoryInterface $additionalFixedRepository): self { $this->additionalFixedRepository = $additionalFixedRepository; @@ -1062,7 +1062,7 @@ class Installer * @param bool $dryRun * @return Installer */ - public function setDryRun(bool $dryRun = true): Installer + public function setDryRun(bool $dryRun = true): self { $this->dryRun = (bool) $dryRun; @@ -1085,7 +1085,7 @@ class Installer * @param bool $preferSource * @return Installer */ - public function setPreferSource(bool $preferSource = true): Installer + public function setPreferSource(bool $preferSource = true): self { $this->preferSource = (bool) $preferSource; @@ -1098,7 +1098,7 @@ class Installer * @param bool $preferDist * @return Installer */ - public function setPreferDist(bool $preferDist = true): Installer + public function setPreferDist(bool $preferDist = true): self { $this->preferDist = (bool) $preferDist; @@ -1111,7 +1111,7 @@ class Installer * @param bool $optimizeAutoloader * @return Installer */ - public function setOptimizeAutoloader(bool $optimizeAutoloader): Installer + public function setOptimizeAutoloader(bool $optimizeAutoloader): self { $this->optimizeAutoloader = (bool) $optimizeAutoloader; if (!$this->optimizeAutoloader) { @@ -1130,7 +1130,7 @@ class Installer * @param bool $classMapAuthoritative * @return Installer */ - public function setClassMapAuthoritative(bool $classMapAuthoritative): Installer + public function setClassMapAuthoritative(bool $classMapAuthoritative): self { $this->classMapAuthoritative = (bool) $classMapAuthoritative; if ($this->classMapAuthoritative) { @@ -1148,7 +1148,7 @@ class Installer * @param string|null $apcuAutoloaderPrefix * @return Installer */ - public function setApcuAutoloader(bool $apcuAutoloader, ?string $apcuAutoloaderPrefix = null): Installer + public function setApcuAutoloader(bool $apcuAutoloader, ?string $apcuAutoloaderPrefix = null): self { $this->apcuAutoloader = $apcuAutoloader; $this->apcuAutoloaderPrefix = $apcuAutoloaderPrefix; @@ -1162,7 +1162,7 @@ class Installer * @param bool $update * @return Installer */ - public function setUpdate(bool $update): Installer + public function setUpdate(bool $update): self { $this->update = (bool) $update; @@ -1175,7 +1175,7 @@ class Installer * @param bool $install * @return Installer */ - public function setInstall(bool $install): Installer + public function setInstall(bool $install): self { $this->install = (bool) $install; @@ -1188,7 +1188,7 @@ class Installer * @param bool $devMode * @return Installer */ - public function setDevMode(bool $devMode = true): Installer + public function setDevMode(bool $devMode = true): self { $this->devMode = (bool) $devMode; @@ -1203,7 +1203,7 @@ class Installer * @param bool $dumpAutoloader * @return Installer */ - public function setDumpAutoloader(bool $dumpAutoloader = true): Installer + public function setDumpAutoloader(bool $dumpAutoloader = true): self { $this->dumpAutoloader = (bool) $dumpAutoloader; @@ -1219,7 +1219,7 @@ class Installer * @return Installer * @deprecated Use setRunScripts(false) on the EventDispatcher instance being injected instead */ - public function setRunScripts(bool $runScripts = true): Installer + public function setRunScripts(bool $runScripts = true): self { $this->runScripts = (bool) $runScripts; @@ -1232,7 +1232,7 @@ class 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 @@ class Installer * @param bool $verbose * @return Installer */ - public function setVerbose(bool $verbose = true): Installer + public function setVerbose(bool $verbose = true): self { $this->verbose = (bool) $verbose; @@ -1275,7 +1275,7 @@ class Installer * * @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 @@ class 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 @@ class Installer * @param bool $updateMirrors * @return Installer */ - public function setUpdateMirrors(bool $updateMirrors): Installer + public function setUpdateMirrors(bool $updateMirrors): self { $this->updateMirrors = $updateMirrors; @@ -1314,7 +1314,7 @@ class 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 @@ class Installer * @param int $updateAllowTransitiveDependencies One of the UPDATE_ constants on the Request class * @return Installer */ - public function setUpdateAllowTransitiveDependencies(int $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 @@ class Installer * @param bool $preferStable * @return Installer */ - public function setPreferStable(bool $preferStable = true): Installer + public function setPreferStable(bool $preferStable = true): self { $this->preferStable = (bool) $preferStable; @@ -1360,7 +1360,7 @@ class Installer * @param bool $preferLowest * @return Installer */ - public function setPreferLowest(bool $preferLowest = true): Installer + public function setPreferLowest(bool $preferLowest = true): self { $this->preferLowest = (bool) $preferLowest; @@ -1375,7 +1375,7 @@ class Installer * @param bool $writeLock * @return Installer */ - public function setWriteLock(bool $writeLock = true): Installer + public function setWriteLock(bool $writeLock = true): self { $this->writeLock = (bool) $writeLock; @@ -1390,7 +1390,7 @@ class Installer * @param bool $executeOperations * @return Installer */ - public function setExecuteOperations(bool $executeOperations = true): Installer + public function setExecuteOperations(bool $executeOperations = true): self { $this->executeOperations = (bool) $executeOperations; @@ -1406,7 +1406,7 @@ class Installer * * @return Installer */ - public function disablePlugins(): Installer + public function disablePlugins(): self { $this->installationManager->disablePlugins(); @@ -1417,7 +1417,7 @@ class 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/Package/Archiver/ArchiveManager.php b/src/Composer/Package/Archiver/ArchiveManager.php index 236304e69..c7f5def61 100644 --- a/src/Composer/Package/Archiver/ArchiveManager.php +++ b/src/Composer/Package/Archiver/ArchiveManager.php @@ -68,7 +68,7 @@ class ArchiveManager * * @return $this */ - public function setOverwriteFiles(bool $overwriteFiles) + public function setOverwriteFiles(bool $overwriteFiles): self { $this->overwriteFiles = $overwriteFiles; diff --git a/src/Composer/Package/Loader/ArrayLoader.php b/src/Composer/Package/Loader/ArrayLoader.php index b7fe52207..cd1f9e2ba 100644 --- a/src/Composer/Package/Loader/ArrayLoader.php +++ b/src/Composer/Package/Loader/ArrayLoader.php @@ -49,7 +49,7 @@ class ArrayLoader implements LoaderInterface /** * @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 @@ class ArrayLoader implements LoaderInterface * * @return list */ - public function loadPackages(array $versions) + public function loadPackages(array $versions): array { $packages = array(); $linkCache = array(); @@ -99,7 +99,7 @@ class ArrayLoader implements LoaderInterface } /** - * @template PackageClass of CompletePackageInterface + * @template PackageClass of CompletePackage * * @param mixed[] $config package data * @param string $class FQCN to be instantiated @@ -108,7 +108,7 @@ class ArrayLoader implements LoaderInterface * * @phpstan-param class-string $class */ - private function createObject(array $config, string $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 @@ class ArrayLoader implements LoaderInterface * * @return RootPackage|RootAliasPackage|CompletePackage|CompleteAliasPackage */ - private function configureObject(PackageInterface $package, array $config): PackageInterface + 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'); diff --git a/src/Composer/Package/Loader/JsonLoader.php b/src/Composer/Package/Loader/JsonLoader.php index 9e9ae689e..4bfeaff8b 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 @@ class JsonLoader /** * @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 01c1910da..c81176ded 100644 --- a/src/Composer/Package/Loader/LoaderInterface.php +++ b/src/Composer/Package/Loader/LoaderInterface.php @@ -17,6 +17,7 @@ use Composer\Package\CompletePackage; 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, string $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 0ab5cefec..89eb27636 100644 --- a/src/Composer/Package/Loader/RootPackageLoader.php +++ b/src/Composer/Package/Loader/RootPackageLoader.php @@ -61,15 +61,13 @@ class RootPackageLoader extends ArrayLoader /** * @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', ?string $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); diff --git a/src/Composer/Package/Loader/ValidatingArrayLoader.php b/src/Composer/Package/Loader/ValidatingArrayLoader.php index 85f4cb67e..997287f44 100644 --- a/src/Composer/Package/Loader/ValidatingArrayLoader.php +++ b/src/Composer/Package/Loader/ValidatingArrayLoader.php @@ -59,7 +59,7 @@ class ValidatingArrayLoader implements LoaderInterface /** * @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(); diff --git a/src/Composer/Repository/ArrayRepository.php b/src/Composer/Repository/ArrayRepository.php index 096ab9820..d1a10e3ea 100644 --- a/src/Composer/Repository/ArrayRepository.php +++ b/src/Composer/Repository/ArrayRepository.php @@ -97,7 +97,7 @@ class ArrayRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackage($name, $constraint) + public function findPackage(string $name, $constraint) { $name = strtolower($name); @@ -121,7 +121,7 @@ class ArrayRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackages($name, $constraint = null) + public function findPackages(string $name, $constraint = null) { // normalize name $name = strtolower($name); @@ -237,7 +237,7 @@ class ArrayRepository implements RepositoryInterface /** * @inheritDoc */ - public function getProviders($packageName) + public function getProviders(string $packageName) { $result = array(); diff --git a/src/Composer/Repository/ComposerRepository.php b/src/Composer/Repository/ComposerRepository.php index edb382264..22f8c5548 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -187,7 +187,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @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 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @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(); @@ -598,7 +598,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito return parent::search($query, $mode); } - public function getProviders($packageName) + public function getProviders(string $packageName) { $this->loadRootServerFile(); $result = array(); diff --git a/src/Composer/Repository/FilesystemRepository.php b/src/Composer/Repository/FilesystemRepository.php index 990df2910..81745ed7b 100644 --- a/src/Composer/Repository/FilesystemRepository.php +++ b/src/Composer/Repository/FilesystemRepository.php @@ -116,7 +116,7 @@ class FilesystemRepository extends WritableArrayRepository /** * 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(); diff --git a/src/Composer/Repository/VcsRepository.php b/src/Composer/Repository/VcsRepository.php index 8bbf65730..9978413c7 100644 --- a/src/Composer/Repository/VcsRepository.php +++ b/src/Composer/Repository/VcsRepository.php @@ -436,7 +436,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt * * @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, string $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 diff --git a/src/Composer/Repository/WritableArrayRepository.php b/src/Composer/Repository/WritableArrayRepository.php index 722cc68f1..6f98ad18d 100644 --- a/src/Composer/Repository/WritableArrayRepository.php +++ b/src/Composer/Repository/WritableArrayRepository.php @@ -57,7 +57,7 @@ class WritableArrayRepository extends ArrayRepository implements WritableReposit /** * @inheritDoc */ - public function write($devMode, InstallationManager $installationManager) + public function write(bool $devMode, InstallationManager $installationManager) { $this->devMode = $devMode; } diff --git a/src/Composer/Script/Event.php b/src/Composer/Script/Event.php index ed6b7f0ba..0f05a7291 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; @@ -97,7 +97,7 @@ class Event extends BaseEvent * * @return ?BaseEvent */ - public function getOriginatingEvent() + public function getOriginatingEvent(): ?BaseEvent { return $this->originatingEvent; } @@ -108,7 +108,7 @@ class Event extends BaseEvent * @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/Util/Git.php b/src/Composer/Util/Git.php index be86b3dd0..f28271c74 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -422,7 +422,7 @@ class Git /** * @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 @@ class Git /** * @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'))) . ')'; } diff --git a/src/Composer/Util/Perforce.php b/src/Composer/Util/Perforce.php index f10f4b4f0..ee21169e1 100644 --- a/src/Composer/Util/Perforce.php +++ b/src/Composer/Util/Perforce.php @@ -151,7 +151,7 @@ class Perforce /** * @return non-empty-string */ - public function generateUniquePerforceClientName() + public function generateUniquePerforceClientName(): string { return gethostname() . "_" . time(); } @@ -281,7 +281,7 @@ class Perforce /** * @return non-empty-string */ - public function getP4ClientSpec() + public function getP4ClientSpec(): string { return $this->path . '/' . $this->getClient() . '.p4.spec'; } @@ -330,7 +330,7 @@ class Perforce * @param string $name * @return ?string */ - protected function getP4variable(string $name) + protected function getP4variable(string $name): ?string { if ($this->windowsFlag) { $command = 'p4 set'; @@ -385,7 +385,7 @@ class Perforce * * @return non-empty-string */ - public function generateP4Command(string $command, bool $useClient = true) + public function generateP4Command(string $command, bool $useClient = true): string { $p4Command = 'p4 '; $p4Command .= '-u ' . $this->getUser() . ' '; @@ -614,7 +614,7 @@ class Perforce /** * @return array{master: string} */ - public function getBranches() + public function getBranches(): array { $possibleBranches = array(); if (!$this->isStream()) { diff --git a/src/bootstrap.php b/src/bootstrap.php index 39eba0065..f61063a4a 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(string $file) +function includeIfExists(string $file): ?\Composer\Autoload\ClassLoader { return file_exists($file) ? include $file : null; } diff --git a/tests/Composer/Test/TestCase.php b/tests/Composer/Test/TestCase.php index e901822ba..0e61bb87a 100644 --- a/tests/Composer/Test/TestCase.php +++ b/tests/Composer/Test/TestCase.php @@ -113,7 +113,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase } /** - * @template PackageClass of PackageInterface + * @template PackageClass of CompletePackage|CompleteAliasPackage * * @param string $class FQCN to be instantiated * @param string $name @@ -124,7 +124,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @phpstan-param class-string $class * @phpstan-return PackageClass */ - protected function getPackage(string $name = 'dummy/pkg', string $version = '1.0.0', string $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);