From 00984f46f2b69dd85c1961bfa8f38bf7e7d8a0c8 Mon Sep 17 00:00:00 2001 From: Alexander Schranz Date: Fri, 18 Feb 2022 22:13:15 +0100 Subject: [PATCH 1/8] Add return types to closures --- src/Composer/Autoload/AutoloadGenerator.php | 12 ++++---- src/Composer/Command/ArchiveCommand.php | 2 +- .../Command/BaseDependencyCommand.php | 2 +- src/Composer/Command/ConfigCommand.php | 28 +++++++++---------- src/Composer/Command/DiagnoseCommand.php | 2 +- src/Composer/Command/InitCommand.php | 2 +- src/Composer/Command/LicensesCommand.php | 2 +- src/Composer/Command/ReinstallCommand.php | 2 +- src/Composer/Command/RemoveCommand.php | 2 +- src/Composer/Command/SelfUpdateCommand.php | 2 +- src/Composer/Command/ShowCommand.php | 4 +-- src/Composer/Command/StatusCommand.php | 4 +-- src/Composer/Command/UpdateCommand.php | 4 +-- src/Composer/Command/ValidateCommand.php | 6 ++-- src/Composer/Compiler.php | 2 +- src/Composer/Config/JsonConfigSource.php | 18 ++++++------ src/Composer/Console/Application.php | 6 ++-- .../DependencyResolver/DefaultPolicy.php | 4 +-- .../DependencyResolver/LockTransaction.php | 2 +- .../DependencyResolver/PoolBuilder.php | 2 +- src/Composer/DependencyResolver/Problem.php | 8 +++--- src/Composer/DependencyResolver/Rule.php | 2 +- .../DependencyResolver/RuleWatchGraph.php | 2 +- .../DependencyResolver/Transaction.php | 6 ++-- src/Composer/Downloader/ArchiveDownloader.php | 4 +-- src/Composer/Downloader/DownloadManager.php | 4 +-- src/Composer/Downloader/FileDownloader.php | 10 +++---- src/Composer/Downloader/GitDownloader.php | 6 ++-- src/Composer/Downloader/HgDownloader.php | 4 +-- src/Composer/Downloader/SvnDownloader.php | 2 +- src/Composer/Downloader/VcsDownloader.php | 2 +- src/Composer/Downloader/ZipDownloader.php | 2 +- src/Composer/IO/BufferIO.php | 2 +- src/Composer/IO/ConsoleIO.php | 2 +- src/Composer/Installer.php | 2 +- .../Installer/InstallationManager.php | 18 ++++++------ src/Composer/Installer/LibraryInstaller.php | 8 +++--- src/Composer/Installer/PluginInstaller.php | 4 +-- .../Installer/SuggestedPackagesReporter.php | 2 +- src/Composer/Json/JsonManipulator.php | 14 +++++----- .../Archiver/ArchivableFilesFinder.php | 2 +- .../Package/Archiver/ArchiveManager.php | 2 +- .../Package/Archiver/BaseExcludeFilter.php | 2 +- src/Composer/Package/BasePackage.php | 2 +- src/Composer/Package/Locker.php | 2 +- .../Package/Version/VersionGuesser.php | 2 +- .../Package/Version/VersionSelector.php | 2 +- .../Question/StrictConfirmationQuestion.php | 2 +- .../Repository/ComposerRepository.php | 10 +++---- .../Repository/CompositeRepository.php | 2 +- .../Repository/FilesystemRepository.php | 2 +- .../Repository/InstalledRepository.php | 2 +- src/Composer/Repository/PathRepository.php | 2 +- .../Repository/PlatformRepository.php | 2 +- src/Composer/Repository/Vcs/GitDriver.php | 2 +- src/Composer/Repository/Vcs/HgDriver.php | 2 +- src/Composer/Util/AuthHelper.php | 2 +- src/Composer/Util/ErrorHandler.php | 2 +- src/Composer/Util/Git.php | 4 +-- src/Composer/Util/HttpDownloader.php | 8 +++--- src/Composer/Util/Platform.php | 2 +- src/Composer/Util/ProcessExecutor.php | 8 +++--- src/Composer/Util/RemoteFilesystem.php | 4 +-- src/Composer/Util/StreamContextFactory.php | 2 +- src/Composer/Util/TlsHelper.php | 6 ++-- src/Composer/Util/Url.php | 2 +- 66 files changed, 146 insertions(+), 146 deletions(-) diff --git a/src/Composer/Autoload/AutoloadGenerator.php b/src/Composer/Autoload/AutoloadGenerator.php index cbabb867bf99..d3560bfcf1b4 100644 --- a/src/Composer/Autoload/AutoloadGenerator.php +++ b/src/Composer/Autoload/AutoloadGenerator.php @@ -290,7 +290,7 @@ public function dump(Config $config, InstalledRepositoryInterface $localRepo, Ro $mainAutoload = $rootPackage->getAutoload(); if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) { $levels = substr_count($filesystem->normalizePath($rootPackage->getTargetDir()), '/') + 1; - $prefixes = implode(', ', array_map(function ($prefix) { + $prefixes = implode(', ', array_map(function ($prefix): string { return var_export($prefix, true); }, array_keys($mainAutoload['psr-0']))); $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true); @@ -554,7 +554,7 @@ public function parseAutoloads(array $packageMap, PackageInterface $rootPackage, { $rootPackageMap = array_shift($packageMap); if (is_array($filteredDevPackages)) { - $packageMap = array_filter($packageMap, function ($item) use ($filteredDevPackages) { + $packageMap = array_filter($packageMap, function ($item) use ($filteredDevPackages): bool { return !in_array($item[0]->getName(), $filteredDevPackages, true); }); } elseif ($filteredDevPackages) { @@ -808,7 +808,7 @@ protected function getPlatformCheck(array $packageMap, $checkPlatform, array $de ksort($requiredExtensions); - $formatToPhpVersionId = function (Bound $bound) { + $formatToPhpVersionId = function (Bound $bound): int { if ($bound->isZero()) { return 0; } @@ -1229,7 +1229,7 @@ protected function parseAutoloadsType(array $packageMap, $type, RootPackageInter $updir = null; $path = Preg::replaceCallback( '{^((?:(?:\\\\\\.){1,2}+/)+)}', - function ($matches) use (&$updir) { + function ($matches) use (&$updir): string { if (isset($matches[1])) { // undo preg_quote for the matched string $updir = str_replace('\\.', '.', $matches[1]); @@ -1300,7 +1300,7 @@ protected function filterPackageMap(array $packageMap, RootPackageInterface $roo } } - $add = function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy) { + $add = function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy): void { foreach ($package->getRequires() as $link) { $target = $link->getTarget(); if (isset($replacedBy[$target])) { @@ -1318,7 +1318,7 @@ protected function filterPackageMap(array $packageMap, RootPackageInterface $roo return array_filter( $packageMap, - function ($item) use ($include) { + function ($item) use ($include): bool { $package = $item[0]; foreach ($package->getNames() as $name) { if (isset($include[$name])) { diff --git a/src/Composer/Command/ArchiveCommand.php b/src/Composer/Command/ArchiveCommand.php index 314c0655443e..b785f4ea4fdc 100644 --- a/src/Composer/Command/ArchiveCommand.php +++ b/src/Composer/Command/ArchiveCommand.php @@ -168,7 +168,7 @@ protected function selectPackage(IOInterface $io, $packageName, $version = null) if (count($packages) > 1) { $package = reset($packages); $io->writeError('Found multiple matches, selected '.$package->getPrettyString().'.'); - $io->writeError('Alternatives were '.implode(', ', array_map(function ($p) { + $io->writeError('Alternatives were '.implode(', ', array_map(function ($p): string { return $p->getPrettyString(); }, $packages)).'.'); $io->writeError('Please use a more specific constraint to pick a different package.'); diff --git a/src/Composer/Command/BaseDependencyCommand.php b/src/Composer/Command/BaseDependencyCommand.php index 11ee03556057..224d2739e9e6 100644 --- a/src/Composer/Command/BaseDependencyCommand.php +++ b/src/Composer/Command/BaseDependencyCommand.php @@ -90,7 +90,7 @@ protected function doExecute(InputInterface $input, OutputInterface $output, $in $needles = array($needle); if ($inverted) { foreach ($packages as $package) { - $needles = array_merge($needles, array_map(function (Link $link) { + $needles = array_merge($needles, array_map(function (Link $link): string { return $link->getTarget(); }, $package->getReplaces())); } diff --git a/src/Composer/Command/ConfigCommand.php b/src/Composer/Command/ConfigCommand.php index 9071f3b926ac..3e51a45995b1 100644 --- a/src/Composer/Command/ConfigCommand.php +++ b/src/Composer/Command/ConfigCommand.php @@ -318,10 +318,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int $values = $input->getArgument('setting-value'); // what the user is trying to add/change - $booleanValidator = function ($val) { + $booleanValidator = function ($val): bool { return in_array($val, array('true', 'false', '1', '0'), true); }; - $booleanNormalizer = function ($val) { + $booleanNormalizer = function ($val): bool { return $val !== 'false' && (bool) $val; }; @@ -331,7 +331,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int 'use-include-path' => array($booleanValidator, $booleanNormalizer), 'use-github-api' => array($booleanValidator, $booleanNormalizer), 'preferred-install' => array( - function ($val) { + function ($val): bool { return in_array($val, array('auto', 'source', 'dist'), true); }, function ($val) { @@ -339,7 +339,7 @@ function ($val) { }, ), 'gitlab-protocol' => array( - function ($val) { + function ($val): bool { return in_array($val, array('git', 'http', 'https'), true); }, function ($val) { @@ -347,7 +347,7 @@ function ($val) { }, ), 'store-auths' => array( - function ($val) { + function ($val): bool { return in_array($val, array('true', 'false', 'prompt'), true); }, function ($val) { @@ -389,7 +389,7 @@ function ($val) { 'cache-ttl' => array('is_numeric', 'intval'), 'cache-files-ttl' => array('is_numeric', 'intval'), 'cache-files-maxsize' => array( - function ($val) { + function ($val): bool { return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val); }, function ($val) { @@ -397,7 +397,7 @@ function ($val) { }, ), 'bin-compat' => array( - function ($val) { + function ($val): bool { return in_array($val, array('auto', 'full', 'symlink')); }, function ($val) { @@ -405,7 +405,7 @@ function ($val) { }, ), 'discard-changes' => array( - function ($val) { + function ($val): bool { return in_array($val, array('stash', 'true', 'false', '1', '0'), true); }, function ($val) { @@ -427,7 +427,7 @@ function ($val) { 'disable-tls' => array($booleanValidator, $booleanNormalizer), 'secure-http' => array($booleanValidator, $booleanNormalizer), 'cafile' => array( - function ($val) { + function ($val): bool { return file_exists($val) && Filesystem::isReadable($val); }, function ($val) { @@ -435,7 +435,7 @@ function ($val) { }, ), 'capath' => array( - function ($val) { + function ($val): bool { return is_dir($val) && Filesystem::isReadable($val); }, function ($val) { @@ -447,7 +447,7 @@ function ($val) { 'lock' => array($booleanValidator, $booleanNormalizer), 'allow-plugins' => array($booleanValidator, $booleanNormalizer), 'platform-check' => array( - function ($val) { + function ($val): bool { return in_array($val, array('php-only', 'true', 'false', '1', '0'), true); }, function ($val) { @@ -459,7 +459,7 @@ function ($val) { }, ), 'use-parent-dir' => array( - function ($val) { + function ($val): bool { return in_array($val, array('true', 'false', 'prompt'), true); }, function ($val) { @@ -593,10 +593,10 @@ function ($vals) { return $val; }), 'minimum-stability' => array( - function ($val) { + function ($val): bool { return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]); }, - function ($val) { + function ($val): string { return VersionParser::normalizeStability($val); }, ), diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index 9d231e2476e0..75bec936aeb0 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -511,7 +511,7 @@ private function outputResult($result): void private function checkPlatform() { $output = ''; - $out = function ($msg, $style) use (&$output) { + $out = function ($msg, $style) use (&$output): void { $output .= '<'.$style.'>'.$msg.''.PHP_EOL; }; diff --git a/src/Composer/Command/InitCommand.php b/src/Composer/Command/InitCommand.php index 6a52fd2467b8..8b67c26abc1f 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -511,7 +511,7 @@ public function namespaceFromPackageName($packageName) } $namespace = array_map( - function ($part) { + function ($part): string { $part = Preg::replace('/[^a-z0-9]/i', ' ', $part); $part = ucwords($part); diff --git a/src/Composer/Command/LicensesCommand.php b/src/Composer/Command/LicensesCommand.php index f63eb53d1c73..f59034282a84 100644 --- a/src/Composer/Command/LicensesCommand.php +++ b/src/Composer/Command/LicensesCommand.php @@ -170,7 +170,7 @@ private function filterRequiredPackages(RepositoryInterface $repo, PackageInterf $packageListNames = array_keys($bucket); $packages = array_filter( $repo->getPackages(), - function ($package) use ($requires, $packageListNames) { + function ($package) use ($requires, $packageListNames): bool { return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames); } ); diff --git a/src/Composer/Command/ReinstallCommand.php b/src/Composer/Command/ReinstallCommand.php index 18c8e4560a2f..926ba983997c 100644 --- a/src/Composer/Command/ReinstallCommand.php +++ b/src/Composer/Command/ReinstallCommand.php @@ -123,7 +123,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $installOrder[$op->getPackage()->getName()] = $index; } } - usort($uninstallOperations, function ($a, $b) use ($installOrder) { + usort($uninstallOperations, function ($a, $b) use ($installOrder): int { return $installOrder[$b->getPackage()->getName()] - $installOrder[$a->getPackage()->getName()]; }); diff --git a/src/Composer/Command/RemoveCommand.php b/src/Composer/Command/RemoveCommand.php index e33675224e7c..fdda37df1fc9 100644 --- a/src/Composer/Command/RemoveCommand.php +++ b/src/Composer/Command/RemoveCommand.php @@ -116,7 +116,7 @@ protected function interact(InputInterface $input, OutputInterface $output) if (count($input->getArgument('packages')) === 0) { $this->getIO()->writeError('No unused packages to remove'); - $this->setCode(function () { + $this->setCode(function (): int { return 0; }); } diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index 5f78e3eb97f2..06b0d2d0d528 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -354,7 +354,7 @@ protected function fetchKeys(IOInterface $io, Config $config): void $io->write('Open https://composer.github.io/pubkeys.html to find the latest keys'); - $validator = function ($value) { + $validator = function ($value): string { if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { throw new \UnexpectedValueException('Invalid input'); } diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php index ab886103122b..ae9350f1e2cb 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -223,7 +223,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('no-dev')) { $packages = $this->filterRequiredPackages($installedRepo, $rootPkg); - $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg) { + $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg): \Composer\Package\PackageInterface { return clone $pkg; }, $packages)))); } @@ -320,7 +320,7 @@ protected function execute(InputInterface $input, OutputInterface $output) if ($input->getOption('tree')) { $rootRequires = $this->getRootRequires(); $packages = $installedRepo->getPackages(); - usort($packages, function (BasePackage $a, BasePackage $b) { + usort($packages, function (BasePackage $a, BasePackage $b): int { return strcmp((string) $a, (string) $b); }); $arrayTree = array(); diff --git a/src/Composer/Command/StatusCommand.php b/src/Composer/Command/StatusCommand.php index 4a7bfe2231d4..8aec0e70dcdb 100644 --- a/src/Composer/Command/StatusCommand.php +++ b/src/Composer/Command/StatusCommand.php @@ -163,7 +163,7 @@ private function doExecute(InputInterface $input): int foreach ($errors as $path => $changes) { if ($input->getOption('verbose')) { - $indentedChanges = implode("\n", array_map(function ($line) { + $indentedChanges = implode("\n", array_map(function ($line): string { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write(''.$path.':'); @@ -179,7 +179,7 @@ private function doExecute(InputInterface $input): int foreach ($unpushedChanges as $path => $changes) { if ($input->getOption('verbose')) { - $indentedChanges = implode("\n", array_map(function ($line) { + $indentedChanges = implode("\n", array_map(function ($line): string { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write(''.$path.':'); diff --git a/src/Composer/Command/UpdateCommand.php b/src/Composer/Command/UpdateCommand.php index 119fab20e6ad..39decf7888e3 100644 --- a/src/Composer/Command/UpdateCommand.php +++ b/src/Composer/Command/UpdateCommand.php @@ -129,7 +129,7 @@ protected function execute(InputInterface $input, OutputInterface $output) // extract --with shorthands from the allowlist if (count($packages) > 0) { - $allowlistPackagesWithRequirements = array_filter($packages, function ($pkg) { + $allowlistPackagesWithRequirements = array_filter($packages, function ($pkg): bool { return Preg::isMatch('{\S+[ =:]\S+}', $pkg); }); foreach ($this->formatRequirements($allowlistPackagesWithRequirements) as $package => $constraint) { @@ -180,7 +180,7 @@ protected function execute(InputInterface $input, OutputInterface $output) // the arguments lock/nothing/mirrors are not package names but trigger a mirror update instead // they are further mutually exclusive with listing actual package names - $filteredPackages = array_filter($packages, function ($package) { + $filteredPackages = array_filter($packages, function ($package): bool { return !in_array($package, array('lock', 'nothing', 'mirrors'), true); }); $updateMirrors = $input->getOption('lock') || count($filteredPackages) != count($packages); diff --git a/src/Composer/Command/ValidateCommand.php b/src/Composer/Command/ValidateCommand.php index ee9ffa811f3c..8c5ad5aeab33 100644 --- a/src/Composer/Command/ValidateCommand.php +++ b/src/Composer/Command/ValidateCommand.php @@ -193,13 +193,13 @@ private function outputResult(IOInterface $io, $name, &$errors, &$warnings, $che } if ($errors) { - $errors = array_map(function ($err) { + $errors = array_map(function ($err): string { return '- ' . $err; }, $errors); array_unshift($errors, '# General errors'); } if ($warnings) { - $warnings = array_map(function ($err) { + $warnings = array_map(function ($err): string { return '- ' . $err; }, $warnings); array_unshift($warnings, '# General warnings'); @@ -210,7 +210,7 @@ private function outputResult(IOInterface $io, $name, &$errors, &$warnings, $che // If checking publish errors, display them as errors, otherwise just show them as warnings if ($publishErrors) { - $publishErrors = array_map(function ($err) { + $publishErrors = array_map(function ($err): string { return '- ' . $err; }, $publishErrors); diff --git a/src/Composer/Compiler.php b/src/Composer/Compiler.php index 6c30d2b6d7cc..6bf2504686a8 100644 --- a/src/Composer/Compiler.php +++ b/src/Composer/Compiler.php @@ -82,7 +82,7 @@ public function compile($pharFile = 'composer.phar'): void $phar->startBuffering(); - $finderSort = function ($a, $b) { + $finderSort = function ($a, $b): int { return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/')); }; diff --git a/src/Composer/Config/JsonConfigSource.php b/src/Composer/Config/JsonConfigSource.php index 798e0af1c994..84de4f32c9fd 100644 --- a/src/Composer/Config/JsonConfigSource.php +++ b/src/Composer/Config/JsonConfigSource.php @@ -62,7 +62,7 @@ public function getName() */ public function addRepository($name, $config, $append = true) { - $this->manipulateJson('addRepository', function (&$config, $repo, $repoConfig) use ($append) { + $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 // to convert it to "packagist.org": false key on the hashmap otherwise it fails schema validation if (isset($config['repositories'])) { @@ -91,7 +91,7 @@ public function addRepository($name, $config, $append = true) */ public function removeRepository($name) { - $this->manipulateJson('removeRepository', function (&$config, $repo) { + $this->manipulateJson('removeRepository', function (&$config, $repo): void { unset($config['repositories'][$repo]); }, $name); } @@ -102,7 +102,7 @@ public function removeRepository($name) public function addConfigSetting($name, $value) { $authConfig = $this->authConfig; - $this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig) { + $this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig): void { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) { list($key, $host) = explode('.', $key, 2); if ($authConfig) { @@ -122,7 +122,7 @@ public function addConfigSetting($name, $value) public function removeConfigSetting($name) { $authConfig = $this->authConfig; - $this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig) { + $this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig): void { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) { list($key, $host) = explode('.', $key, 2); if ($authConfig) { @@ -141,7 +141,7 @@ public function removeConfigSetting($name) */ public function addProperty($name, $value) { - $this->manipulateJson('addProperty', function (&$config, $key, $val) { + $this->manipulateJson('addProperty', function (&$config, $key, $val): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { $bits = explode('.', $key); $last = array_pop($bits); @@ -164,7 +164,7 @@ public function addProperty($name, $value) */ public function removeProperty($name) { - $this->manipulateJson('removeProperty', function (&$config, $key) { + $this->manipulateJson('removeProperty', function (&$config, $key): void { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { $bits = explode('.', $key); $last = array_pop($bits); @@ -187,7 +187,7 @@ public function removeProperty($name) */ public function addLink($type, $name, $value) { - $this->manipulateJson('addLink', function (&$config, $type, $name, $value) { + $this->manipulateJson('addLink', function (&$config, $type, $name, $value): void { $config[$type][$name] = $value; }, $type, $name, $value); } @@ -197,10 +197,10 @@ public function addLink($type, $name, $value) */ public function removeLink($type, $name) { - $this->manipulateJson('removeSubNode', function (&$config, $type, $name) { + $this->manipulateJson('removeSubNode', function (&$config, $type, $name): void { unset($config[$type][$name]); }, $type, $name); - $this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type) { + $this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type): void { if (0 === count($config[$type])) { unset($config[$type]); } diff --git a/src/Composer/Console/Application.php b/src/Composer/Console/Application.php index 0d1b19ce1c2c..5bf8f6ffca9e 100644 --- a/src/Composer/Console/Application.php +++ b/src/Composer/Console/Application.php @@ -94,14 +94,14 @@ public function __construct() if (!$shutdownRegistered) { if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { pcntl_async_signals(true); - pcntl_signal(SIGINT, function ($sig) { + pcntl_signal(SIGINT, function ($sig): void { exit(130); }); } $shutdownRegistered = true; - register_shutdown_function(function () { + register_shutdown_function(function (): void { $lastError = error_get_last(); if ($lastError && $lastError['message'] && @@ -291,7 +291,7 @@ function_exists('php_uname') ? php_uname('s') . ' / ' . php_uname('r') : 'Unknow } // Check system temp folder for usability as it can cause weird runtime issues otherwise - Silencer::call(function () use ($io) { + Silencer::call(function () use ($io): void { $tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime()); if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) { $io->writeError(sprintf('PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini', sys_get_temp_dir())); diff --git a/src/Composer/DependencyResolver/DefaultPolicy.php b/src/Composer/DependencyResolver/DefaultPolicy.php index c4e196f3791b..e9add445ffbd 100644 --- a/src/Composer/DependencyResolver/DefaultPolicy.php +++ b/src/Composer/DependencyResolver/DefaultPolicy.php @@ -66,7 +66,7 @@ public function selectPreferredPackages(Pool $pool, array $literals, $requiredPa $packages = $this->groupLiteralsByName($pool, $literals); foreach ($packages as &$nameLiterals) { - usort($nameLiterals, function ($a, $b) use ($pool, $requiredPackage) { + usort($nameLiterals, function ($a, $b) use ($pool, $requiredPackage): int { return $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true); }); } @@ -79,7 +79,7 @@ public function selectPreferredPackages(Pool $pool, array $literals, $requiredPa $selected = \call_user_func_array('array_merge', array_values($packages)); // now sort the result across all packages to respect replaces across packages - usort($selected, function ($a, $b) use ($pool, $requiredPackage) { + usort($selected, function ($a, $b) use ($pool, $requiredPackage): int { return $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage); }); diff --git a/src/Composer/DependencyResolver/LockTransaction.php b/src/Composer/DependencyResolver/LockTransaction.php index 75da918aedbe..4d04a5cd680c 100644 --- a/src/Composer/DependencyResolver/LockTransaction.php +++ b/src/Composer/DependencyResolver/LockTransaction.php @@ -152,7 +152,7 @@ public function getAliases($aliases): array } } - usort($usedAliases, function ($a, $b) { + usort($usedAliases, function ($a, $b): int { return strcmp($a['package'], $b['package']); }); diff --git a/src/Composer/DependencyResolver/PoolBuilder.php b/src/Composer/DependencyResolver/PoolBuilder.php index 8a3819203e7d..332914d32fd6 100644 --- a/src/Composer/DependencyResolver/PoolBuilder.php +++ b/src/Composer/DependencyResolver/PoolBuilder.php @@ -520,7 +520,7 @@ private function getSkippedRootRequires(Request $request, $name): array $matches = array(); if (isset($rootRequires[$name])) { - return array_map(function (PackageInterface $package) use ($name) { + return array_map(function (PackageInterface $package) use ($name): string { if ($name !== $package->getName()) { return $package->getName() .' (via replace of '.$name.')'; } diff --git a/src/Composer/DependencyResolver/Problem.php b/src/Composer/DependencyResolver/Problem.php index a6e3249e1d1c..77e2975c87f0 100644 --- a/src/Composer/DependencyResolver/Problem.php +++ b/src/Composer/DependencyResolver/Problem.php @@ -286,7 +286,7 @@ public static function getMissingPackageReason(RepositorySet $repositorySet, Req if ($packages = $repositorySet->findPackages($packageName, $constraint)) { $rootReqs = $repositorySet->getRootRequires(); if (isset($rootReqs[$packageName])) { - $filtered = array_filter($packages, function ($p) use ($rootReqs, $packageName) { + $filtered = array_filter($packages, function ($p) use ($rootReqs, $packageName): bool { return $rootReqs[$packageName]->matches(new Constraint('==', $p->getVersion())); }); if (0 === count($filtered)) { @@ -296,7 +296,7 @@ public static function getMissingPackageReason(RepositorySet $repositorySet, Req if ($lockedPackage) { $fixedConstraint = new Constraint('==', $lockedPackage->getVersion()); - $filtered = array_filter($packages, function ($p) use ($fixedConstraint) { + $filtered = array_filter($packages, function ($p) use ($fixedConstraint): bool { return $fixedConstraint->matches(new Constraint('==', $p->getVersion())); }); if (0 === count($filtered)) { @@ -304,7 +304,7 @@ public static function getMissingPackageReason(RepositorySet $repositorySet, Req } } - $nonLockedPackages = array_filter($packages, function ($p) { + $nonLockedPackages = array_filter($packages, function ($p): bool { return !$p->getRepository() instanceof LockArrayRepository; }); @@ -360,7 +360,7 @@ public static function getMissingPackageReason(RepositorySet $repositorySet, Req if ($providers = $repositorySet->getProviders($packageName)) { $maxProviders = 20; - $providersStr = implode(array_map(function ($p) { + $providersStr = implode(array_map(function ($p): string { $description = $p['description'] ? ' '.substr($p['description'], 0, 100) : ''; return " - ${p['name']}".$description."\n"; diff --git a/src/Composer/DependencyResolver/Rule.php b/src/Composer/DependencyResolver/Rule.php index d6863c461136..1e2d08daa949 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -281,7 +281,7 @@ public function getPrettyString(RepositorySet $repositorySet, Request $request, return 'No package found to satisfy root composer.json require '.$packageName.($constraint ? ' '.$constraint->getPrettyString() : ''); } - $packagesNonAlias = array_values(array_filter($packages, function ($p) { + $packagesNonAlias = array_values(array_filter($packages, function ($p): bool { return !($p instanceof AliasPackage); })); if (count($packagesNonAlias) === 1) { diff --git a/src/Composer/DependencyResolver/RuleWatchGraph.php b/src/Composer/DependencyResolver/RuleWatchGraph.php index 089367803b5d..03da05ce256e 100644 --- a/src/Composer/DependencyResolver/RuleWatchGraph.php +++ b/src/Composer/DependencyResolver/RuleWatchGraph.php @@ -110,7 +110,7 @@ public function propagateLiteral($decidedLiteral, $level, Decisions $decisions): if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) { $ruleLiterals = $node->getRule()->getLiterals(); - $alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions) { + $alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions): bool { return $literal !== $ruleLiteral && $otherWatch !== $ruleLiteral && !$decisions->conflict($ruleLiteral); diff --git a/src/Composer/DependencyResolver/Transaction.php b/src/Composer/DependencyResolver/Transaction.php index 2e6640eeeae5..2d3272c51a59 100644 --- a/src/Composer/DependencyResolver/Transaction.php +++ b/src/Composer/DependencyResolver/Transaction.php @@ -71,7 +71,7 @@ public function getOperations(): array */ private function setResultPackageMaps($resultPackages): void { - $packageSort = function (PackageInterface $a, PackageInterface $b) { + $packageSort = function (PackageInterface $a, PackageInterface $b): int { // sort alias packages by the same name behind their non alias version if ($a->getName() == $b->getName()) { if ($a instanceof AliasPackage != $b instanceof AliasPackage) { @@ -289,7 +289,7 @@ private function movePluginsToFront(array $operations): array // is this a downloads modifying plugin or a dependency of one? if ($isDownloadsModifyingPlugin || count(array_intersect($package->getNames(), $dlModifyingPluginRequires))) { // get the package's requires, but filter out any platform requirements - $requires = array_filter(array_keys($package->getRequires()), function ($req) { + $requires = array_filter(array_keys($package->getRequires()), function ($req): bool { return !PlatformRepository::isPlatformPackage($req); }); @@ -314,7 +314,7 @@ private function movePluginsToFront(array $operations): array // is this a plugin or a dependency of a plugin? if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) { // get the package's requires, but filter out any platform requirements - $requires = array_filter(array_keys($package->getRequires()), function ($req) { + $requires = array_filter(array_keys($package->getRequires()), function ($req): bool { return !PlatformRepository::isPlatformPackage($req); }); diff --git a/src/Composer/Downloader/ArchiveDownloader.php b/src/Composer/Downloader/ArchiveDownloader.php index ddbea79c05bd..152dfb9c4ff5 100644 --- a/src/Composer/Downloader/ArchiveDownloader.php +++ b/src/Composer/Downloader/ArchiveDownloader.php @@ -116,7 +116,7 @@ public function install(PackageInterface $package, $path, $output = true) $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path) { + return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path): \React\Promise\PromiseInterface { $filesystem->unlink($fileName); /** @@ -125,7 +125,7 @@ public function install(PackageInterface $package, $path, $output = true) * @param string $dir Directory * @return \SplFileInfo[] */ - $getFolderContent = function ($dir) { + $getFolderContent = function ($dir): array { $finder = Finder::create() ->ignoreVCS(false) ->ignoreDotFiles(false) diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index 55f80208e272..0a7d6c9abc2e 100644 --- a/src/Composer/Downloader/DownloadManager.php +++ b/src/Composer/Downloader/DownloadManager.php @@ -331,7 +331,7 @@ public function update(PackageInterface $initial, PackageInterface $target, $tar // we wipe the dir and do a new install instead of updating it $promise = $initialDownloader->remove($initial, $targetDir); if ($promise) { - return $promise->then(function ($res) use ($target, $targetDir) { + return $promise->then(function ($res) use ($target, $targetDir): ?\React\Promise\PromiseInterface { return $this->install($target, $targetDir); }); } @@ -432,7 +432,7 @@ private function getAvailableSources(PackageInterface $package, PackageInterface && !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev()) ) { $prevSource = $prevPackage->getInstallationSource(); - usort($sources, function ($a, $b) use ($prevSource) { + usort($sources, function ($a, $b) use ($prevSource): int { return $a === $prevSource ? -1 : 1; }); diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index f4bd777dfe77..5b184ec30ffc 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -118,7 +118,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre throw new \InvalidArgumentException('The given package is missing url information'); } - $cacheKeyGenerator = function (PackageInterface $package, $key) { + $cacheKeyGenerator = function (PackageInterface $package, $key): string { $cacheKey = sha1($key); return $package->getName().'/'.$cacheKey.'.'.$package->getDistType(); @@ -195,7 +195,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre ->then($accept, $reject); } - return $result->then(function ($result) use ($fileName, $checksum, $url, $package, $eventDispatcher) { + return $result->then(function ($result) use ($fileName, $checksum, $url, $package, $eventDispatcher): string { // in case of retry, the first call's Promise chain finally calls this twice at the end, // once with $result being the returned $fileName from $accept, and then once for every // failed request with a null result, which can be skipped. @@ -221,7 +221,7 @@ public function download(PackageInterface $package, $path, PackageInterface $pre }); }; - $accept = function ($response) use ($cache, $package, $fileName, &$urls) { + $accept = function ($response) use ($cache, $package, $fileName, &$urls): string { $url = reset($urls); $cacheKey = $url['cacheKey']; FileDownloader::$downloadMetadata[$package->getName()] = @filesize($fileName) ?: $response->getHeader('Content-Length') ?: '?'; @@ -407,7 +407,7 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($target, $path) { + return $promise->then(function () use ($target, $path): ?\React\Promise\PromiseInterface { $promise = $this->install($target, $path, false); return $promise; @@ -426,7 +426,7 @@ public function remove(PackageInterface $package, $path, $output = true) } $promise = $this->filesystem->removeDirectoryAsync($path); - return $promise->then(function ($result) use ($path) { + return $promise->then(function ($result) use ($path): void { if (!$result) { throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); } diff --git a/src/Composer/Downloader/GitDownloader.php b/src/Composer/Downloader/GitDownloader.php index 33ff7922a839..7f7d74c9f275 100644 --- a/src/Composer/Downloader/GitDownloader.php +++ b/src/Composer/Downloader/GitDownloader.php @@ -114,7 +114,7 @@ protected function doInstall(PackageInterface $package, $path, $url) $this->io->writeError($msg); - $commandCallable = function ($url) use ($path, $command, $cachePath) { + $commandCallable = function ($url) use ($path, $command, $cachePath): string { return str_replace( array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'), array( @@ -172,7 +172,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, $this->io->writeError($msg); - $commandCallable = function ($url) use ($ref, $command, $cachePath) { + $commandCallable = function ($url) use ($ref, $command, $cachePath): string { return str_replace( array('%url%', '%ref%', '%cachePath%', '%sanitizedUrl%'), array( @@ -358,7 +358,7 @@ protected function cleanChanges(PackageInterface $package, $path, $update) return parent::cleanChanges($package, $path, $update); } - $changes = array_map(function ($elem) { + $changes = array_map(function ($elem): string { return ' '.$elem; }, Preg::split('{\s*\r?\n\s*}', $changes)); $this->io->writeError(' '.$package->getPrettyName().' has modified files:'); diff --git a/src/Composer/Downloader/HgDownloader.php b/src/Composer/Downloader/HgDownloader.php index 41dfb3e3b903..d7db15a230f1 100644 --- a/src/Composer/Downloader/HgDownloader.php +++ b/src/Composer/Downloader/HgDownloader.php @@ -41,7 +41,7 @@ protected function doInstall(PackageInterface $package, $path, $url): ?PromiseIn { $hgUtils = new HgUtils($this->io, $this->config, $this->process); - $cloneCommand = function ($url) use ($path) { + $cloneCommand = function ($url) use ($path): string { return sprintf('hg clone -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path)); }; @@ -70,7 +70,7 @@ protected function doUpdate(PackageInterface $initial, PackageInterface $target, throw new \RuntimeException('The .hg directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); } - $command = function ($url) use ($ref) { + $command = function ($url) use ($ref): string { return sprintf('hg pull -- %s && hg up -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($ref)); }; diff --git a/src/Composer/Downloader/SvnDownloader.php b/src/Composer/Downloader/SvnDownloader.php index 0d269121c9e0..7dd58493ed8a 100644 --- a/src/Composer/Downloader/SvnDownloader.php +++ b/src/Composer/Downloader/SvnDownloader.php @@ -144,7 +144,7 @@ protected function cleanChanges(PackageInterface $package, $path, $update) return parent::cleanChanges($package, $path, $update); } - $changes = array_map(function ($elem) { + $changes = array_map(function ($elem): string { return ' '.$elem; }, Preg::split('{\s*\r?\n\s*}', $changes)); $countChanges = count($changes); diff --git a/src/Composer/Downloader/VcsDownloader.php b/src/Composer/Downloader/VcsDownloader.php index b87deb044cc4..836925b66246 100644 --- a/src/Composer/Downloader/VcsDownloader.php +++ b/src/Composer/Downloader/VcsDownloader.php @@ -200,7 +200,7 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat } if (trim($logs)) { - $logs = implode("\n", array_map(function ($line) { + $logs = implode("\n", array_map(function ($line): string { return ' ' . $line; }, explode("\n", $logs))); diff --git a/src/Composer/Downloader/ZipDownloader.php b/src/Composer/Downloader/ZipDownloader.php index 1347f296d85f..a1f297a9d3b9 100644 --- a/src/Composer/Downloader/ZipDownloader.php +++ b/src/Composer/Downloader/ZipDownloader.php @@ -127,7 +127,7 @@ private function extractWithSystemUnzip(PackageInterface $package, $file, $path) $executable = $commandSpec[0]; $io = $this->io; - $tryFallback = function ($processError) use ($isLastChance, $io, $file, $path, $package, $executable) { + $tryFallback = function ($processError) use ($isLastChance, $io, $file, $path, $package, $executable): \React\Promise\PromiseInterface { if ($isLastChance) { throw $processError; } diff --git a/src/Composer/IO/BufferIO.php b/src/Composer/IO/BufferIO.php index 3adfb900e72d..4d7242120fcb 100644 --- a/src/Composer/IO/BufferIO.php +++ b/src/Composer/IO/BufferIO.php @@ -56,7 +56,7 @@ public function getOutput(): string $output = stream_get_contents($this->output->getStream()); - $output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches) { + $output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches): string { $pre = strip_tags($matches[1]); if (strlen($pre) === strlen($matches[2])) { diff --git a/src/Composer/IO/ConsoleIO.php b/src/Composer/IO/ConsoleIO.php index b4e19846f39a..2fd2cb178e97 100644 --- a/src/Composer/IO/ConsoleIO.php +++ b/src/Composer/IO/ConsoleIO.php @@ -175,7 +175,7 @@ private function doWrite($messages, $newline, $stderr, $verbosity, $raw = false) if (null !== $this->startTime) { $memoryUsage = memory_get_usage() / 1024 / 1024; $timeSpent = microtime(true) - $this->startTime; - $messages = array_map(function ($message) use ($memoryUsage, $timeSpent) { + $messages = array_map(function ($message) use ($memoryUsage, $timeSpent): string { return sprintf('[%.1fMiB/%.2fs] %s', $memoryUsage, $timeSpent, $message); }, (array) $messages); } diff --git a/src/Composer/Installer.php b/src/Composer/Installer.php index d52e450dd358..18b798d7b923 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -522,7 +522,7 @@ protected function doUpdate(InstalledRepositoryInterface $localRepo, $doInstall) } } - $sortByName = function ($a, $b) { + $sortByName = function ($a, $b): int { if ($a instanceof UpdateOperation) { $a = $a->getTargetPackage()->getName(); } else { diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index cb3aafbd83e1..8102e4537a6d 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -199,18 +199,18 @@ public function execute(InstalledRepositoryInterface $repo, array $operations, $ $loop = $this->loop; $io = $this->io; - $runCleanup = function () use (&$cleanupPromises, $loop) { + $runCleanup = function () use (&$cleanupPromises, $loop): void { $promises = array(); $loop->abortJobs(); foreach ($cleanupPromises as $cleanup) { - $promises[] = new \React\Promise\Promise(function ($resolve, $reject) use ($cleanup) { + $promises[] = new \React\Promise\Promise(function ($resolve, $reject) use ($cleanup): void { $promise = $cleanup(); if (!$promise instanceof PromiseInterface) { $resolve(); } else { - $promise->then(function () use ($resolve) { + $promise->then(function () use ($resolve): void { $resolve(); }); } @@ -229,7 +229,7 @@ public function execute(InstalledRepositoryInterface $repo, array $operations, $ if ($handleInterruptsUnix) { pcntl_async_signals(true); $prevHandler = pcntl_signal_get_handler(SIGINT); - pcntl_signal(SIGINT, function ($sig) use ($runCleanup, $prevHandler, $io) { + pcntl_signal(SIGINT, function ($sig) use ($runCleanup, $prevHandler, $io): void { $io->writeError('Received SIGINT, aborting', true, IOInterface::DEBUG); $runCleanup(); @@ -241,7 +241,7 @@ public function execute(InstalledRepositoryInterface $repo, array $operations, $ }); } if ($handleInterruptsWindows) { - $windowsHandler = function ($event) use ($runCleanup, $io) { + $windowsHandler = function ($event) use ($runCleanup, $io): void { if ($event !== PHP_WINDOWS_EVENT_CTRL_C) { return; } @@ -446,15 +446,15 @@ private function executeBatch(InstalledRepositoryInterface $repo, array $operati $promise = $promise->then(function () use ($opType, $repo, $operation) { return $this->$opType($repo, $operation); })->then($cleanupPromises[$index]) - ->then(function () use ($devMode, $repo) { + ->then(function () use ($devMode, $repo): void { $repo->write($devMode, $this); - }, function ($e) use ($opType, $package, $io) { + }, function ($e) use ($opType, $package, $io): void { $io->writeError(' ' . ucfirst($opType) .' of '.$package->getPrettyName().' failed'); throw $e; }); - $postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation) { + $postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation): void { $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($opType); if (defined($event) && $runScripts && $dispatcher) { $dispatcher->dispatchPackageEvent(constant($event), $devMode, $repo, $allOperations, $operation); @@ -548,7 +548,7 @@ public function update(InstalledRepositoryInterface $repo, UpdateOperation $oper } $installer = $this->getInstaller($targetType); - $promise = $promise->then(function () use ($installer, $repo, $target) { + $promise = $promise->then(function () use ($installer, $repo, $target): ?\React\Promise\PromiseInterface { return $installer->install($repo, $target); }); } diff --git a/src/Composer/Installer/LibraryInstaller.php b/src/Composer/Installer/LibraryInstaller.php index 8fff84d46556..484daf8c837c 100644 --- a/src/Composer/Installer/LibraryInstaller.php +++ b/src/Composer/Installer/LibraryInstaller.php @@ -148,7 +148,7 @@ public function install(InstalledRepositoryInterface $repo, PackageInterface $pa $binaryInstaller = $this->binaryInstaller; $installPath = $this->getInstallPath($package); - return $promise->then(function () use ($binaryInstaller, $installPath, $package, $repo) { + return $promise->then(function () use ($binaryInstaller, $installPath, $package, $repo): void { $binaryInstaller->installBinaries($package, $installPath); if (!$repo->hasPackage($package)) { $repo->addPackage(clone $package); @@ -176,7 +176,7 @@ public function update(InstalledRepositoryInterface $repo, PackageInterface $ini $binaryInstaller = $this->binaryInstaller; $installPath = $this->getInstallPath($target); - return $promise->then(function () use ($binaryInstaller, $installPath, $target, $initial, $repo) { + return $promise->then(function () use ($binaryInstaller, $installPath, $target, $initial, $repo): void { $binaryInstaller->installBinaries($target, $installPath); $repo->removePackage($initial); if (!$repo->hasPackage($target)) { @@ -203,7 +203,7 @@ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $ $downloadPath = $this->getPackageBasePath($package); $filesystem = $this->filesystem; - return $promise->then(function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo) { + return $promise->then(function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo): void { $binaryInstaller->removeBinaries($package); $repo->removePackage($package); @@ -288,7 +288,7 @@ protected function updateCode(PackageInterface $initial, PackageInterface $targe $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($target) { + return $promise->then(function () use ($target): ?\React\Promise\PromiseInterface { return $this->installCode($target); }); } diff --git a/src/Composer/Installer/PluginInstaller.php b/src/Composer/Installer/PluginInstaller.php index ce4c75933f08..2dded4eac6cc 100644 --- a/src/Composer/Installer/PluginInstaller.php +++ b/src/Composer/Installer/PluginInstaller.php @@ -66,7 +66,7 @@ public function install(InstalledRepositoryInterface $repo, PackageInterface $pa $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($package, $repo) { + return $promise->then(function () use ($package, $repo): void { try { Platform::workaroundFilesystemIssues(); $this->getPluginManager()->registerPackage($package, true); @@ -86,7 +86,7 @@ public function update(InstalledRepositoryInterface $repo, PackageInterface $ini $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($initial, $target, $repo) { + return $promise->then(function () use ($initial, $target, $repo): void { try { Platform::workaroundFilesystemIssues(); $this->getPluginManager()->deactivatePackage($initial); diff --git a/src/Composer/Installer/SuggestedPackagesReporter.php b/src/Composer/Installer/SuggestedPackagesReporter.php index e337c43ae9b6..17e51b5f6567 100644 --- a/src/Composer/Installer/SuggestedPackagesReporter.php +++ b/src/Composer/Installer/SuggestedPackagesReporter.php @@ -198,7 +198,7 @@ private function getFilteredSuggestions(InstalledRepository $installedRepo = nul $sourceFilter = array(); if ($onlyDependentsOf) { - $sourceFilter = array_map(function ($link) { + $sourceFilter = array_map(function ($link): string { return $link->getTarget(); }, array_merge($onlyDependentsOf->getRequires(), $onlyDependentsOf->getDevRequires())); $sourceFilter[] = $onlyDependentsOf->getName(); diff --git a/src/Composer/Json/JsonManipulator.php b/src/Composer/Json/JsonManipulator.php index 60cbef0c1c2e..8a309086d6de 100644 --- a/src/Composer/Json/JsonManipulator.php +++ b/src/Composer/Json/JsonManipulator.php @@ -94,7 +94,7 @@ public function addLink($type, $package, $constraint, $sortPackages = false) // update existing link $existingPackage = $packageMatches['package']; $packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage)); - $links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint) { + $links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint): string { return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"'; }, $links); } else { @@ -135,7 +135,7 @@ public function addLink($type, $package, $constraint, $sortPackages = false) */ private function sortPackages(array &$packages = array()): void { - $prefix = function ($requirement) { + $prefix = function ($requirement): string { if (PlatformRepository::isPlatformPackage($requirement)) { return Preg::replace( array( @@ -159,7 +159,7 @@ private function sortPackages(array &$packages = array()): void return '5-'.$requirement; }; - uksort($packages, function ($a, $b) use ($prefix) { + uksort($packages, function ($a, $b) use ($prefix): int { return strnatcmp($prefix($a), $prefix($b)); }); } @@ -297,7 +297,7 @@ public function addSubNode($mainNode, $name, $value, $append = true) // child exists $childRegex = '{'.self::$DEFINES.'(?P"'.preg_quote($name).'"\s*:\s*)(?P(?&json))(?P,?)}x'; if (Preg::isMatch($childRegex, $children, $matches)) { - $children = Preg::replaceCallback($childRegex, function ($matches) use ($subName, $value) { + $children = Preg::replaceCallback($childRegex, function ($matches) use ($subName, $value): string { if ($subName !== null) { $curVal = json_decode($matches['content'], true); if (!is_array($curVal)) { @@ -351,7 +351,7 @@ public function addSubNode($mainNode, $name, $value, $append = true) } } - $this->contents = Preg::replaceCallback($nodeRegex, function ($m) use ($children) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($m) use ($children): string { return $m['start'] . $children . $m['end']; }, $this->contents); @@ -436,7 +436,7 @@ public function removeSubNode($mainNode, $name) $newline = $this->newline; $indent = $this->indent; - $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($indent, $newline) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($indent, $newline): string { return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end']; }, $this->contents); @@ -450,7 +450,7 @@ public function removeSubNode($mainNode, $name) return true; } - $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($name, $subName, $childrenClean) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($name, $subName, $childrenClean): string { if ($subName !== null) { $curVal = json_decode($matches['content'], true); unset($curVal[$name][$subName]); diff --git a/src/Composer/Package/Archiver/ArchivableFilesFinder.php b/src/Composer/Package/Archiver/ArchivableFilesFinder.php index b1d5650ed916..31e81e295fa8 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFinder.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFinder.php @@ -57,7 +57,7 @@ public function __construct($sources, array $excludes, $ignoreFilters = false) $this->finder = new Finder(); - $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs) { + $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs): bool { if ($file->isLink() && strpos($file->getRealPath(), $sources) !== 0) { return false; } diff --git a/src/Composer/Package/Archiver/ArchiveManager.php b/src/Composer/Package/Archiver/ArchiveManager.php index aed992ef49d3..de8ff52e8a67 100644 --- a/src/Composer/Package/Archiver/ArchiveManager.php +++ b/src/Composer/Package/Archiver/ArchiveManager.php @@ -101,7 +101,7 @@ public function getPackageFilename(CompletePackageInterface $package): string $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6); } - $name = implode('-', array_filter($nameParts, function ($p) { + $name = implode('-', array_filter($nameParts, function ($p): bool { return !empty($p); })); diff --git a/src/Composer/Package/Archiver/BaseExcludeFilter.php b/src/Composer/Package/Archiver/BaseExcludeFilter.php index ed63e12956e1..2fbd22796a48 100644 --- a/src/Composer/Package/Archiver/BaseExcludeFilter.php +++ b/src/Composer/Package/Archiver/BaseExcludeFilter.php @@ -95,7 +95,7 @@ function ($line) use ($lineParser) { }, $lines ), - function ($pattern) { + function ($pattern): bool { return $pattern !== null; } ); diff --git a/src/Composer/Package/BasePackage.php b/src/Composer/Package/BasePackage.php index a3ec9c570f6b..f46cec9fdf64 100644 --- a/src/Composer/Package/BasePackage.php +++ b/src/Composer/Package/BasePackage.php @@ -274,7 +274,7 @@ public static function packageNameToRegexp($allowPattern, $wrap = '{^%s$}i') public static function packageNamesToRegexp(array $packageNames, $wrap = '{^(?:%s)$}iD') { $packageNames = array_map( - function ($packageName) { + function ($packageName): string { return BasePackage::packageNameToRegexp($packageName, '%s'); }, $packageNames diff --git a/src/Composer/Package/Locker.php b/src/Composer/Package/Locker.php index 8003dff6ef84..1702d2ba906f 100644 --- a/src/Composer/Package/Locker.php +++ b/src/Composer/Package/Locker.php @@ -357,7 +357,7 @@ public function setLockData(array $packages, $devPackages, array $platformReqs, { // 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 - $aliases = array_map(function ($alias) { + $aliases = array_map(function ($alias): array { if (in_array($alias['version'], array('dev-master', 'dev-trunk', 'dev-default'), true)) { $alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS; } diff --git a/src/Composer/Package/Version/VersionGuesser.php b/src/Composer/Package/Version/VersionGuesser.php index ef6cfa8839dc..d5b0bf90792e 100644 --- a/src/Composer/Package/Version/VersionGuesser.php +++ b/src/Composer/Package/Version/VersionGuesser.php @@ -296,7 +296,7 @@ private function guessFeatureVersion(array $packageConfig, $version, array $bran // sort local branches first then remote ones // and sort numeric branches below named ones, to make sure if the branch has the same distance from main and 1.10 and 1.9 for example, main is picked // and sort using natural sort so that 1.10 will appear before 1.9 - usort($branches, function ($a, $b) { + usort($branches, function ($a, $b): int { $aRemote = 0 === strpos($a, 'remotes/'); $bRemote = 0 === strpos($b, 'remotes/'); diff --git a/src/Composer/Package/Version/VersionSelector.php b/src/Composer/Package/Version/VersionSelector.php index 4a2968db2acd..431bdb851167 100644 --- a/src/Composer/Package/Version/VersionSelector.php +++ b/src/Composer/Package/Version/VersionSelector.php @@ -87,7 +87,7 @@ public function findBestCandidate($packageName, $targetPackageVersion = null, $p if ($this->platformConstraints && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) { $platformConstraints = $this->platformConstraints; - $candidates = array_filter($candidates, function ($pkg) use ($platformConstraints, $platformRequirementFilter) { + $candidates = array_filter($candidates, function ($pkg) use ($platformConstraints, $platformRequirementFilter): bool { $reqs = $pkg->getRequires(); foreach ($reqs as $name => $link) { diff --git a/src/Composer/Question/StrictConfirmationQuestion.php b/src/Composer/Question/StrictConfirmationQuestion.php index 5ec5577c14af..bcb339bda44e 100644 --- a/src/Composer/Question/StrictConfirmationQuestion.php +++ b/src/Composer/Question/StrictConfirmationQuestion.php @@ -86,7 +86,7 @@ private function getDefaultNormalizer(): callable */ private function getDefaultValidator(): callable { - return function ($answer) { + return function ($answer): bool { if (!is_bool($answer)) { throw new InvalidArgumentException('Please answer yes, y, no, or n.'); } diff --git a/src/Composer/Repository/ComposerRepository.php b/src/Composer/Repository/ComposerRepository.php index a5a99f9f5c32..07035c51c902 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -350,7 +350,7 @@ public function getPackageNames($packageFilter = null) * @param list $results * @return list */ - function (array $results) { + function (array $results): array { return $results; } ; @@ -361,7 +361,7 @@ function (array $results) { * @param list $results * @return list */ - function (array $results) use ($packageFilterRegex) { + function (array $results) use ($packageFilterRegex): array { /** @var list $results */ return Preg::grep($packageFilterRegex, $results); } @@ -905,7 +905,7 @@ private function loadAsyncPackages(array $packageNames, array $acceptableStabili } $promises[] = $this->asyncFetchFile($url, $cacheKey, $lastModified) - ->then(function ($response) use (&$packages, &$namesFound, $url, $cacheKey, $contents, $realName, $constraint, $acceptableStabilities, $stabilityFlags, $alreadyLoaded) { + ->then(function ($response) use (&$packages, &$namesFound, $url, $cacheKey, $contents, $realName, $constraint, $acceptableStabilities, $stabilityFlags, $alreadyLoaded): void { $packagesSource = 'downloaded file ('.Url::sanitize($url).')'; if (true === $response) { @@ -1095,7 +1095,7 @@ protected function loadRootServerFile($rootMaxAge = null) // Disables lazy-provider behavior as with available-packages, but may allow much more compact expression of packages covered by this repository. // Over-specifying covered packages is safe, but may result in increased traffic to your repository. if (!empty($data['available-package-patterns'])) { - $this->availablePackagePatterns = array_map(function ($pattern) { + $this->availablePackagePatterns = array_map(function ($pattern): string { return BasePackage::packageNameToRegexp($pattern); }, $data['available-package-patterns']); $this->hasAvailablePackageList = true; @@ -1493,7 +1493,7 @@ private function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null): $degradedMode = &$this->degradedMode; $eventDispatcher = $this->eventDispatcher; - $accept = function ($response) use ($io, $url, $filename, $cache, $cacheKey, $eventDispatcher) { + $accept = function ($response) use ($io, $url, $filename, $cache, $cacheKey, $eventDispatcher): array { // package not found is acceptable for a v2 protocol repository if ($response->getStatusCode() === 404) { $this->packagesNotFoundCache[$filename] = true; diff --git a/src/Composer/Repository/CompositeRepository.php b/src/Composer/Repository/CompositeRepository.php index 67fdb73a27b6..e34ce7357995 100644 --- a/src/Composer/Repository/CompositeRepository.php +++ b/src/Composer/Repository/CompositeRepository.php @@ -42,7 +42,7 @@ public function __construct(array $repositories) public function getRepoName(): string { - return 'composite repo ('.implode(', ', array_map(function ($repo) { + return 'composite repo ('.implode(', ', array_map(function ($repo): string { return $repo->getRepoName(); }, $this->repositories)).')'; } diff --git a/src/Composer/Repository/FilesystemRepository.php b/src/Composer/Repository/FilesystemRepository.php index a6e949445a40..ea9a0eeb1eac 100644 --- a/src/Composer/Repository/FilesystemRepository.php +++ b/src/Composer/Repository/FilesystemRepository.php @@ -150,7 +150,7 @@ public function write($devMode, InstallationManager $installationManager) } sort($data['dev-package-names']); - usort($data['packages'], function ($a, $b) { + usort($data['packages'], function ($a, $b): int { return strcmp($a['name'], $b['name']); }); diff --git a/src/Composer/Repository/InstalledRepository.php b/src/Composer/Repository/InstalledRepository.php index 63fc2c906e89..e99ed95db7f3 100644 --- a/src/Composer/Repository/InstalledRepository.php +++ b/src/Composer/Repository/InstalledRepository.php @@ -251,7 +251,7 @@ public function getDependents($needle, $constraint = null, $invert = false, $rec public function getRepoName(): string { - return 'installed repo ('.implode(', ', array_map(function ($repo) { + return 'installed repo ('.implode(', ', array_map(function ($repo): string { return $repo->getRepoName(); }, $this->getRepositories())).')'; } diff --git a/src/Composer/Repository/PathRepository.php b/src/Composer/Repository/PathRepository.php index 1b8489bb72f8..dcb9c82d54a7 100644 --- a/src/Composer/Repository/PathRepository.php +++ b/src/Composer/Repository/PathRepository.php @@ -251,7 +251,7 @@ private function getUrlMatches(): array } // Ensure environment-specific path separators are normalized to URL separators - return array_map(function ($val) { + return array_map(function ($val): string { return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/'); }, glob($this->url, $flags)); } diff --git a/src/Composer/Repository/PlatformRepository.php b/src/Composer/Repository/PlatformRepository.php index 3fc9d4be3397..4722f9899743 100644 --- a/src/Composer/Repository/PlatformRepository.php +++ b/src/Composer/Repository/PlatformRepository.php @@ -365,7 +365,7 @@ protected function initialize(): void case 'libxml': // ext/dom, ext/simplexml, ext/xmlreader and ext/xmlwriter use the same libxml as the ext/libxml - $libxmlProvides = array_map(function ($extension) { + $libxmlProvides = array_map(function ($extension): string { return $extension . '-libxml'; }, array_intersect($loadedExtensions, array('dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter'))); $this->addLibrary($name, $this->runtime->getConstant('LIBXML_DOTTED_VERSION'), 'libxml library version', array(), $libxmlProvides); diff --git a/src/Composer/Repository/Vcs/GitDriver.php b/src/Composer/Repository/Vcs/GitDriver.php index b91508acd17b..cd69d5743d46 100644 --- a/src/Composer/Repository/Vcs/GitDriver.php +++ b/src/Composer/Repository/Vcs/GitDriver.php @@ -234,7 +234,7 @@ public static function supports(IOInterface $io, Config $config, $url, $deep = f GitUtil::cleanEnv(); try { - $gitUtil->runCommand(function ($url) { + $gitUtil->runCommand(function ($url): string { return 'git ls-remote --heads -- ' . ProcessExecutor::escape($url); }, $url, sys_get_temp_dir()); } catch (\RuntimeException $e) { diff --git a/src/Composer/Repository/Vcs/HgDriver.php b/src/Composer/Repository/Vcs/HgDriver.php index 73bc426e5361..e9b83d6c547c 100644 --- a/src/Composer/Repository/Vcs/HgDriver.php +++ b/src/Composer/Repository/Vcs/HgDriver.php @@ -71,7 +71,7 @@ public function initialize() $fs->removeDirectory($this->repoDir); $repoDir = $this->repoDir; - $command = function ($url) use ($repoDir) { + $command = function ($url) use ($repoDir): string { return sprintf('hg clone --noupdate -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); }; diff --git a/src/Composer/Util/AuthHelper.php b/src/Composer/Util/AuthHelper.php index 59de345d7ab8..26eab08b2fb9 100644 --- a/src/Composer/Util/AuthHelper.php +++ b/src/Composer/Util/AuthHelper.php @@ -50,7 +50,7 @@ public function storeAuth($origin, $storeAuth): void } elseif ($storeAuth === 'prompt') { $answer = $this->io->askAndValidate( 'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ', - function ($value) { + function ($value): string { $input = strtolower(substr(trim($value), 0, 1)); if (in_array($input, array('y','n'))) { return $input; diff --git a/src/Composer/Util/ErrorHandler.php b/src/Composer/Util/ErrorHandler.php index b60c728a0233..257f7ce29117 100644 --- a/src/Composer/Util/ErrorHandler.php +++ b/src/Composer/Util/ErrorHandler.php @@ -56,7 +56,7 @@ public static function handle($level, $message, $file, $line): bool self::$io->writeError('Deprecation Notice: '.$message.' in '.$file.':'.$line.''); if (self::$io->isVerbose()) { self::$io->writeError('Stack trace:'); - self::$io->writeError(array_filter(array_map(function ($a) { + self::$io->writeError(array_filter(array_map(function ($a): ?string { if (isset($a['line'], $a['file'])) { return ' '.$a['file'].':'.$a['line'].''; } diff --git a/src/Composer/Util/Git.php b/src/Composer/Util/Git.php index 4b92c2f775a6..27dc75a0dd9e 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -283,7 +283,7 @@ public function syncMirror($url, $dir) // update the repo if it is a valid git repository if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { try { - $commandCallable = function ($url) { + $commandCallable = function ($url): string { $sanitizedUrl = Preg::replace('{://([^@]+?):(.+?)@}', '://', $url); return sprintf('git remote set-url origin -- %s && git remote update --prune origin && git remote set-url origin -- %s && git gc --auto', ProcessExecutor::escape($url), ProcessExecutor::escape($sanitizedUrl)); @@ -301,7 +301,7 @@ public function syncMirror($url, $dir) // clean up directory and do a fresh clone into it $this->filesystem->removeDirectory($dir); - $commandCallable = function ($url) use ($dir) { + $commandCallable = function ($url) use ($dir): string { return sprintf('git clone --mirror -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir)); }; diff --git a/src/Composer/Util/HttpDownloader.php b/src/Composer/Util/HttpDownloader.php index dcebffa4bf55..b919680f2937 100644 --- a/src/Composer/Util/HttpDownloader.php +++ b/src/Composer/Util/HttpDownloader.php @@ -216,13 +216,13 @@ private function addJob($request, $sync = false): array $rfs = $this->rfs; if ($this->canUseCurl($job)) { - $resolver = function ($resolve, $reject) use (&$job) { + $resolver = function ($resolve, $reject) use (&$job): void { $job['status'] = HttpDownloader::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; } else { - $resolver = function ($resolve, $reject) use (&$job, $rfs) { + $resolver = function ($resolve, $reject) use (&$job, $rfs): void { // start job $url = $job['request']['url']; $options = $job['request']['options']; @@ -248,7 +248,7 @@ private function addJob($request, $sync = false): array $curl = $this->curl; - $canceler = function () use (&$job, $curl) { + $canceler = function () use (&$job, $curl): void { if ($job['status'] === HttpDownloader::STATUS_QUEUED) { $job['status'] = HttpDownloader::STATUS_ABORTED; } @@ -270,7 +270,7 @@ private function addJob($request, $sync = false): array $this->markJobDone(); return $response; - }, function ($e) use (&$job) { + }, function ($e) use (&$job): void { $job['status'] = HttpDownloader::STATUS_FAILED; $job['exception'] = $e; diff --git a/src/Composer/Util/Platform.php b/src/Composer/Util/Platform.php index 1f582a73e00a..d237f8ea10b3 100644 --- a/src/Composer/Util/Platform.php +++ b/src/Composer/Util/Platform.php @@ -82,7 +82,7 @@ public static function expandPath($path): string return self::getUserDirectory() . substr($path, 1); } - return Preg::replaceCallback('#^(\$|(?P%))(?P\w++)(?(percent)%)(?P.*)#', function ($matches) { + return Preg::replaceCallback('#^(\$|(?P%))(?P\w++)(?(percent)%)(?P.*)#', function ($matches): string { // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons if (Platform::isWindows() && $matches['var'] == 'HOME') { return (Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE')) . $matches['path']; diff --git a/src/Composer/Util/ProcessExecutor.php b/src/Composer/Util/ProcessExecutor.php index 809de9810621..fb661bac4d7f 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -153,13 +153,13 @@ public function executeAsync($command, $cwd = null) 'cwd' => $cwd, ); - $resolver = function ($resolve, $reject) use (&$job) { + $resolver = function ($resolve, $reject) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; - $canceler = function () use (&$job) { + $canceler = function () use (&$job): void { if ($job['status'] === ProcessExecutor::STATUS_QUEUED) { $job['status'] = ProcessExecutor::STATUS_ABORTED; } @@ -190,7 +190,7 @@ public function executeAsync($command, $cwd = null) $this->markJobDone(); return $job['process']; - }, function ($e) use (&$job) { + }, function ($e) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_FAILED; $this->markJobDone(); @@ -407,7 +407,7 @@ private function outputCommandRun($command, ?string $cwd, bool $async): void } $commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command)); - $safeCommand = Preg::replaceCallback('{://(?P[^:/\s]+):(?P[^@\s/]+)@}i', function ($m) { + $safeCommand = Preg::replaceCallback('{://(?P[^:/\s]+):(?P[^@\s/]+)@}i', function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx) we obfuscate that if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) { return '://***:***@'; diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 464198f579f9..1d6866f7a583 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -290,7 +290,7 @@ protected function get($originUrl, $fileUrl, $additionalOptions = array(), $file $errorMessage = ''; $errorCode = 0; $result = false; - set_error_handler(function ($code, $msg) use (&$errorMessage) { + set_error_handler(function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } @@ -445,7 +445,7 @@ protected function get($originUrl, $fileUrl, $additionalOptions = array(), $file } $errorMessage = ''; - set_error_handler(function ($code, $msg) use (&$errorMessage) { + set_error_handler(function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } diff --git a/src/Composer/Util/StreamContextFactory.php b/src/Composer/Util/StreamContextFactory.php index f0d8bbe93088..7448990d3df9 100644 --- a/src/Composer/Util/StreamContextFactory.php +++ b/src/Composer/Util/StreamContextFactory.php @@ -245,7 +245,7 @@ private static function fixHttpHeaderField($header): array if (!is_array($header)) { $header = explode("\r\n", $header); } - uasort($header, function ($el) { + uasort($header, function ($el): int { return stripos($el, 'content-type') === 0 ? 1 : -1; }); diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php index bf3aa1ea3e94..697a66b17552 100644 --- a/src/Composer/Util/TlsHelper.php +++ b/src/Composer/Util/TlsHelper.php @@ -78,7 +78,7 @@ public static function getCertificateNames($certificate): ?array if (isset($info['extensions']['subjectAltName'])) { $subjectAltNames = Preg::split('{\s*,\s*}', $info['extensions']['subjectAltName']); - $subjectAltNames = array_filter(array_map(function ($name) { + $subjectAltNames = array_filter(array_map(function ($name): ?string { if (0 === strpos($name, 'DNS:')) { return strtolower(ltrim(substr($name, 4))); } @@ -179,7 +179,7 @@ private static function certNameMatcher($certName): ?callable if (0 === $wildcards) { // Literal match. - return function ($hostname) use ($certName) { + return function ($hostname) use ($certName): bool { return $hostname === $certName; }; } @@ -203,7 +203,7 @@ private static function certNameMatcher($certName): ?callable $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); $wildcardRegex = "{^{$wildcardRegex}$}"; - return function ($hostname) use ($wildcardRegex) { + return function ($hostname) use ($wildcardRegex): bool { return Preg::isMatch($wildcardRegex, $hostname); }; } diff --git a/src/Composer/Util/Url.php b/src/Composer/Util/Url.php index 19e8f5065d1f..d118054d24b6 100644 --- a/src/Composer/Util/Url.php +++ b/src/Composer/Util/Url.php @@ -114,7 +114,7 @@ public static function sanitize($url): string // e.g. https://api.github.com/repositories/9999999999?access_token=github_token $url = Preg::replace('{([&?]access_token=)[^&]+}', '$1***', $url); - $url = Preg::replaceCallback('{^(?P[a-z0-9]+://)?(?P[^:/\s@]+):(?P[^@\s/]+)@}i', function ($m) { + $url = Preg::replaceCallback('{^(?P[a-z0-9]+://)?(?P[^:/\s@]+):(?P[^@\s/]+)@}i', function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx) we obfuscate that if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) { return $m['prefix'].'***:***@'; From 7c5b10a8576e8d66b2fee26ded7a6b48179ce3da Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:18:31 +0100 Subject: [PATCH 2/8] Always return PromiseInterface --- src/Composer/Downloader/DownloadManager.php | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index 0a7d6c9abc2e..41e61e0ad218 100644 --- a/src/Composer/Downloader/DownloadManager.php +++ b/src/Composer/Downloader/DownloadManager.php @@ -330,9 +330,14 @@ public function update(PackageInterface $initial, PackageInterface $target, $tar // if downloader type changed, or update failed and user asks for reinstall, // we wipe the dir and do a new install instead of updating it $promise = $initialDownloader->remove($initial, $targetDir); - if ($promise) { - return $promise->then(function ($res) use ($target, $targetDir): ?\React\Promise\PromiseInterface { - return $this->install($target, $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(); }); } From 4d5328a74d5772fc2855a2c994b39ebffb563d1c Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:20:08 +0100 Subject: [PATCH 3/8] Always return promise --- src/Composer/Downloader/FileDownloader.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index 5b184ec30ffc..ab347d23da37 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -407,10 +407,13 @@ public function update(PackageInterface $initial, PackageInterface $target, $pat $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($target, $path): ?\React\Promise\PromiseInterface { + return $promise->then(function () use ($target, $path): PromiseInterface { $promise = $this->install($target, $path, false); + if ($promise instanceof PromiseInterface) { + return $promise; + } - return $promise; + return \React\Promise\resolve(); }); } From 96ab7dcefe45f041e1b9766f99948ec09fcf619e Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:23:00 +0100 Subject: [PATCH 4/8] Always return promise --- src/Composer/Installer/LibraryInstaller.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Composer/Installer/LibraryInstaller.php b/src/Composer/Installer/LibraryInstaller.php index 484daf8c837c..ce65b2d33a9d 100644 --- a/src/Composer/Installer/LibraryInstaller.php +++ b/src/Composer/Installer/LibraryInstaller.php @@ -288,8 +288,13 @@ protected function updateCode(PackageInterface $initial, PackageInterface $targe $promise = \React\Promise\resolve(); } - return $promise->then(function () use ($target): ?\React\Promise\PromiseInterface { - return $this->installCode($target); + return $promise->then(function () use ($target): PromiseInterface { + $promise = $this->installCode($target); + if ($promise instanceof PromiseInterface) { + return $promise; + } + + return \React\Promise\resolve() }); } From b3ddcedae9afcf289e03cafa95ec8af06e0ccfb0 Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:23:03 +0100 Subject: [PATCH 5/8] Always return promise --- src/Composer/Installer/InstallationManager.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index 8102e4537a6d..69e8ae287d35 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -548,8 +548,13 @@ public function update(InstalledRepositoryInterface $repo, UpdateOperation $oper } $installer = $this->getInstaller($targetType); - $promise = $promise->then(function () use ($installer, $repo, $target): ?\React\Promise\PromiseInterface { - return $installer->install($repo, $target); + $promise = $promise->then(function () use ($installer, $repo, $target): PromiseInterface { + $promise = $installer->install($repo, $target); + if ($promise instanceof PromiseInterface) { + return $promise; + } + + return \React\Promise\resolve() }); } From 3e79b197543f33a5ed2f3b43f4cd7e7607f2c93b Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:24:53 +0100 Subject: [PATCH 6/8] Fix error in ComposerRepo --- src/Composer/Repository/ComposerRepository.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Composer/Repository/ComposerRepository.php b/src/Composer/Repository/ComposerRepository.php index 07035c51c902..9e6adbaf6ac3 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -1493,7 +1493,10 @@ private function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null): $degradedMode = &$this->degradedMode; $eventDispatcher = $this->eventDispatcher; - $accept = function ($response) use ($io, $url, $filename, $cache, $cacheKey, $eventDispatcher): array { + /** + * @return array|true true if the response was a 304 and the cache is fresh + */ + $accept = function ($response) use ($io, $url, $filename, $cache, $cacheKey, $eventDispatcher) { // package not found is acceptable for a v2 protocol repository if ($response->getStatusCode() === 404) { $this->packagesNotFoundCache[$filename] = true; From 009927bd35e586a2c9602cb138397652882378ab Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:31:50 +0100 Subject: [PATCH 7/8] Fix syntax error --- src/Composer/Installer/InstallationManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index 69e8ae287d35..788d367e77b4 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -554,7 +554,7 @@ public function update(InstalledRepositoryInterface $repo, UpdateOperation $oper return $promise; } - return \React\Promise\resolve() + return \React\Promise\resolve(); }); } From d12dde5c7bcae1c1392c733dc035e17561c7b48b Mon Sep 17 00:00:00 2001 From: Jordi Boggiano Date: Mon, 21 Feb 2022 13:32:59 +0100 Subject: [PATCH 8/8] Fix syntax --- src/Composer/Installer/LibraryInstaller.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Composer/Installer/LibraryInstaller.php b/src/Composer/Installer/LibraryInstaller.php index ce65b2d33a9d..f5525341d948 100644 --- a/src/Composer/Installer/LibraryInstaller.php +++ b/src/Composer/Installer/LibraryInstaller.php @@ -294,7 +294,7 @@ protected function updateCode(PackageInterface $initial, PackageInterface $targe return $promise; } - return \React\Promise\resolve() + return \React\Promise\resolve(); }); }