1
0
Fork 0

Static lambda (#10854)

Lambdas not (indirect) referencing $this must be declared static.
pull/10893/head
Mathias Reker ⚡️ 2022-06-22 14:19:18 +02:00 committed by GitHub
parent ef276d26d6
commit 4131f7cf4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
77 changed files with 206 additions and 206 deletions

View File

@ -284,7 +284,7 @@ EOF;
$mainAutoload = $rootPackage->getAutoload(); $mainAutoload = $rootPackage->getAutoload();
if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) { if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
$levels = substr_count($filesystem->normalizePath($rootPackage->getTargetDir()), '/') + 1; $levels = substr_count($filesystem->normalizePath($rootPackage->getTargetDir()), '/') + 1;
$prefixes = implode(', ', array_map(function ($prefix): string { $prefixes = implode(', ', array_map(static function ($prefix): string {
return var_export($prefix, true); return var_export($prefix, true);
}, array_keys($mainAutoload['psr-0']))); }, array_keys($mainAutoload['psr-0'])));
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true); $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
@ -543,7 +543,7 @@ EOF;
{ {
$rootPackageMap = array_shift($packageMap); $rootPackageMap = array_shift($packageMap);
if (is_array($filteredDevPackages)) { if (is_array($filteredDevPackages)) {
$packageMap = array_filter($packageMap, function ($item) use ($filteredDevPackages): bool { $packageMap = array_filter($packageMap, static function ($item) use ($filteredDevPackages): bool {
return !in_array($item[0]->getName(), $filteredDevPackages, true); return !in_array($item[0]->getName(), $filteredDevPackages, true);
}); });
} elseif ($filteredDevPackages) { } elseif ($filteredDevPackages) {
@ -797,7 +797,7 @@ EOF;
ksort($requiredExtensions); ksort($requiredExtensions);
$formatToPhpVersionId = function (Bound $bound): int { $formatToPhpVersionId = static function (Bound $bound): int {
if ($bound->isZero()) { if ($bound->isZero()) {
return 0; return 0;
} }
@ -812,7 +812,7 @@ EOF;
return $chunks[0] * 10000 + $chunks[1] * 100 + $chunks[2]; return $chunks[0] * 10000 + $chunks[1] * 100 + $chunks[2];
}; };
$formatToHumanReadable = function (Bound $bound) { $formatToHumanReadable = static function (Bound $bound) {
if ($bound->isZero()) { if ($bound->isZero()) {
return 0; return 0;
} }
@ -1224,7 +1224,7 @@ INITIALIZER;
$updir = null; $updir = null;
$path = Preg::replaceCallback( $path = Preg::replaceCallback(
'{^((?:(?:\\\\\\.){1,2}+/)+)}', '{^((?:(?:\\\\\\.){1,2}+/)+)}',
function ($matches) use (&$updir): string { static function ($matches) use (&$updir): string {
if (isset($matches[1])) { if (isset($matches[1])) {
// undo preg_quote for the matched string // undo preg_quote for the matched string
$updir = str_replace('\\.', '.', $matches[1]); $updir = str_replace('\\.', '.', $matches[1]);
@ -1298,7 +1298,7 @@ INITIALIZER;
} }
} }
$add = function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy): void { $add = static function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy): void {
foreach ($package->getRequires() as $link) { foreach ($package->getRequires() as $link) {
$target = $link->getTarget(); $target = $link->getTarget();
if (isset($replacedBy[$target])) { if (isset($replacedBy[$target])) {
@ -1316,7 +1316,7 @@ INITIALIZER;
return array_filter( return array_filter(
$packageMap, $packageMap,
function ($item) use ($include): bool { static function ($item) use ($include): bool {
$package = $item[0]; $package = $item[0];
foreach ($package->getNames() as $name) { foreach ($package->getNames() as $name) {
if (isset($include[$name])) { if (isset($include[$name])) {

View File

@ -173,7 +173,7 @@ EOT
if (count($packages) > 1) { if (count($packages) > 1) {
$package = reset($packages); $package = reset($packages);
$io->writeError('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>'); $io->writeError('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>');
$io->writeError('Alternatives were '.implode(', ', array_map(function ($p): string { $io->writeError('Alternatives were '.implode(', ', array_map(static function ($p): string {
return $p->getPrettyString(); return $p->getPrettyString();
}, $packages)).'.'); }, $packages)).'.');
$io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>'); $io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');

View File

@ -91,7 +91,7 @@ abstract class BaseDependencyCommand extends BaseCommand
$needles = array($needle); $needles = array($needle);
if ($inverted) { if ($inverted) {
foreach ($packages as $package) { foreach ($packages as $package) {
$needles = array_merge($needles, array_map(function (Link $link): string { $needles = array_merge($needles, array_map(static function (Link $link): string {
return $link->getTarget(); return $link->getTarget();
}, $package->getReplaces())); }, $package->getReplaces()));
} }

View File

@ -105,7 +105,7 @@ trait CompletionTrait
$installedRepo = new InstalledRepository($installedRepos); $installedRepo = new InstalledRepository($installedRepos);
return array_merge( return array_merge(
array_map(function (PackageInterface $package) { array_map(static function (PackageInterface $package) {
return $package->getName(); return $package->getName();
}, $installedRepo->getPackages()), }, $installedRepo->getPackages()),
$platformHint $platformHint
@ -142,12 +142,12 @@ trait CompletionTrait
$results = array_column($results, 'name'); $results = array_column($results, 'name');
if ($showVendors) { if ($showVendors) {
$results = array_map(function (string $name): string { $results = array_map(static function (string $name): string {
return $name.'/'; return $name.'/';
}, $results); }, $results);
// sort shorter results first to avoid auto-expanding the completion to a longer string than needed // sort shorter results first to avoid auto-expanding the completion to a longer string than needed
usort($results, function (string $a, string $b) { usort($results, static function (string $a, string $b) {
$lenA = \strlen($a); $lenA = \strlen($a);
$lenB = \strlen($b); $lenB = \strlen($b);
if ($lenA === $lenB) { if ($lenA === $lenB) {
@ -199,9 +199,9 @@ trait CompletionTrait
$repos = new PlatformRepository([], $this->requireComposer()->getConfig()->get('platform')); $repos = new PlatformRepository([], $this->requireComposer()->getConfig()->get('platform'));
$pattern = BasePackage::packageNameToRegexp($input->getCompletionValue().'*'); $pattern = BasePackage::packageNameToRegexp($input->getCompletionValue().'*');
return array_filter(array_map(function (PackageInterface $package) { return array_filter(array_map(static function (PackageInterface $package) {
return $package->getName(); return $package->getName();
}, $repos->getPackages()), function (string $name) use ($pattern): bool { }, $repos->getPackages()), static function (string $name) use ($pattern): bool {
return Preg::isMatch($pattern, $name); return Preg::isMatch($pattern, $name);
}); });
}; };

View File

@ -320,10 +320,10 @@ EOT
$values = $input->getArgument('setting-value'); // what the user is trying to add/change $values = $input->getArgument('setting-value'); // what the user is trying to add/change
$booleanValidator = function ($val): bool { $booleanValidator = static function ($val): bool {
return in_array($val, array('true', 'false', '1', '0'), true); return in_array($val, array('true', 'false', '1', '0'), true);
}; };
$booleanNormalizer = function ($val): bool { $booleanNormalizer = static function ($val): bool {
return $val !== 'false' && (bool) $val; return $val !== 'false' && (bool) $val;
}; };
@ -333,26 +333,26 @@ EOT
'use-include-path' => array($booleanValidator, $booleanNormalizer), 'use-include-path' => array($booleanValidator, $booleanNormalizer),
'use-github-api' => array($booleanValidator, $booleanNormalizer), 'use-github-api' => array($booleanValidator, $booleanNormalizer),
'preferred-install' => array( 'preferred-install' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('auto', 'source', 'dist'), true); return in_array($val, array('auto', 'source', 'dist'), true);
}, },
function ($val) { static function ($val) {
return $val; return $val;
}, },
), ),
'gitlab-protocol' => array( 'gitlab-protocol' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('git', 'http', 'https'), true); return in_array($val, array('git', 'http', 'https'), true);
}, },
function ($val) { static function ($val) {
return $val; return $val;
}, },
), ),
'store-auths' => array( 'store-auths' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true); return in_array($val, array('true', 'false', 'prompt'), true);
}, },
function ($val) { static function ($val) {
if ('prompt' === $val) { if ('prompt' === $val) {
return 'prompt'; return 'prompt';
} }
@ -361,56 +361,56 @@ EOT
}, },
), ),
'notify-on-install' => array($booleanValidator, $booleanNormalizer), 'notify-on-install' => array($booleanValidator, $booleanNormalizer),
'vendor-dir' => array('is_string', function ($val) { 'vendor-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'bin-dir' => array('is_string', function ($val) { 'bin-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'archive-dir' => array('is_string', function ($val) { 'archive-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'archive-format' => array('is_string', function ($val) { 'archive-format' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'data-dir' => array('is_string', function ($val) { 'data-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'cache-dir' => array('is_string', function ($val) { 'cache-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'cache-files-dir' => array('is_string', function ($val) { 'cache-files-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'cache-repo-dir' => array('is_string', function ($val) { 'cache-repo-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'cache-vcs-dir' => array('is_string', function ($val) { 'cache-vcs-dir' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'cache-ttl' => array('is_numeric', 'intval'), 'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'), 'cache-files-ttl' => array('is_numeric', 'intval'),
'cache-files-maxsize' => array( 'cache-files-maxsize' => array(
function ($val): bool { static function ($val): bool {
return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val); return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val);
}, },
function ($val) { static function ($val) {
return $val; return $val;
}, },
), ),
'bin-compat' => array( 'bin-compat' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('auto', 'full', 'symlink')); return in_array($val, array('auto', 'full', 'symlink'));
}, },
function ($val) { static function ($val) {
return $val; return $val;
}, },
), ),
'discard-changes' => array( 'discard-changes' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('stash', 'true', 'false', '1', '0'), true); return in_array($val, array('stash', 'true', 'false', '1', '0'), true);
}, },
function ($val) { static function ($val) {
if ('stash' === $val) { if ('stash' === $val) {
return 'stash'; return 'stash';
} }
@ -418,7 +418,7 @@ EOT
return $val !== 'false' && (bool) $val; return $val !== 'false' && (bool) $val;
}, },
), ),
'autoloader-suffix' => array('is_string', function ($val) { 'autoloader-suffix' => array('is_string', static function ($val) {
return $val === 'null' ? null : $val; return $val === 'null' ? null : $val;
}), }),
'sort-packages' => array($booleanValidator, $booleanNormalizer), 'sort-packages' => array($booleanValidator, $booleanNormalizer),
@ -429,18 +429,18 @@ EOT
'disable-tls' => array($booleanValidator, $booleanNormalizer), 'disable-tls' => array($booleanValidator, $booleanNormalizer),
'secure-http' => array($booleanValidator, $booleanNormalizer), 'secure-http' => array($booleanValidator, $booleanNormalizer),
'cafile' => array( 'cafile' => array(
function ($val): bool { static function ($val): bool {
return file_exists($val) && Filesystem::isReadable($val); return file_exists($val) && Filesystem::isReadable($val);
}, },
function ($val) { static function ($val) {
return $val === 'null' ? null : $val; return $val === 'null' ? null : $val;
}, },
), ),
'capath' => array( 'capath' => array(
function ($val): bool { static function ($val): bool {
return is_dir($val) && Filesystem::isReadable($val); return is_dir($val) && Filesystem::isReadable($val);
}, },
function ($val) { static function ($val) {
return $val === 'null' ? null : $val; return $val === 'null' ? null : $val;
}, },
), ),
@ -449,10 +449,10 @@ EOT
'lock' => array($booleanValidator, $booleanNormalizer), 'lock' => array($booleanValidator, $booleanNormalizer),
'allow-plugins' => array($booleanValidator, $booleanNormalizer), 'allow-plugins' => array($booleanValidator, $booleanNormalizer),
'platform-check' => array( 'platform-check' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('php-only', 'true', 'false', '1', '0'), true); return in_array($val, array('php-only', 'true', 'false', '1', '0'), true);
}, },
function ($val) { static function ($val) {
if ('php-only' === $val) { if ('php-only' === $val) {
return 'php-only'; return 'php-only';
} }
@ -461,10 +461,10 @@ EOT
}, },
), ),
'use-parent-dir' => array( 'use-parent-dir' => array(
function ($val): bool { static function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true); return in_array($val, array('true', 'false', 'prompt'), true);
}, },
function ($val) { static function ($val) {
if ('prompt' === $val) { if ('prompt' === $val) {
return 'prompt'; return 'prompt';
} }
@ -475,7 +475,7 @@ EOT
); );
$multiConfigValues = array( $multiConfigValues = array(
'github-protocols' => array( 'github-protocols' => array(
function ($vals) { static function ($vals) {
if (!is_array($vals)) { if (!is_array($vals)) {
return 'array expected'; return 'array expected';
} }
@ -488,31 +488,31 @@ EOT
return true; return true;
}, },
function ($vals) { static function ($vals) {
return $vals; return $vals;
}, },
), ),
'github-domains' => array( 'github-domains' => array(
function ($vals) { static function ($vals) {
if (!is_array($vals)) { if (!is_array($vals)) {
return 'array expected'; return 'array expected';
} }
return true; return true;
}, },
function ($vals) { static function ($vals) {
return $vals; return $vals;
}, },
), ),
'gitlab-domains' => array( 'gitlab-domains' => array(
function ($vals) { static function ($vals) {
if (!is_array($vals)) { if (!is_array($vals)) {
return 'array expected'; return 'array expected';
} }
return true; return true;
}, },
function ($vals) { static function ($vals) {
return $vals; return $vals;
}, },
), ),
@ -579,26 +579,26 @@ EOT
// handle properties // handle properties
$uniqueProps = array( $uniqueProps = array(
'name' => array('is_string', function ($val) { 'name' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'type' => array('is_string', function ($val) { 'type' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'description' => array('is_string', function ($val) { 'description' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'homepage' => array('is_string', function ($val) { 'homepage' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'version' => array('is_string', function ($val) { 'version' => array('is_string', static function ($val) {
return $val; return $val;
}), }),
'minimum-stability' => array( 'minimum-stability' => array(
function ($val): bool { static function ($val): bool {
return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]); return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]);
}, },
function ($val): string { static function ($val): string {
return VersionParser::normalizeStability($val); return VersionParser::normalizeStability($val);
}, },
), ),
@ -606,26 +606,26 @@ EOT
); );
$multiProps = array( $multiProps = array(
'keywords' => array( 'keywords' => array(
function ($vals) { static function ($vals) {
if (!is_array($vals)) { if (!is_array($vals)) {
return 'array expected'; return 'array expected';
} }
return true; return true;
}, },
function ($vals) { static function ($vals) {
return $vals; return $vals;
}, },
), ),
'license' => array( 'license' => array(
function ($vals) { static function ($vals) {
if (!is_array($vals)) { if (!is_array($vals)) {
return 'array expected'; return 'array expected';
} }
return true; return true;
}, },
function ($vals) { static function ($vals) {
return $vals; return $vals;
}, },
), ),
@ -897,7 +897,7 @@ EOT
} }
if (is_array($value)) { if (is_array($value)) {
$value = array_map(function ($val) { $value = array_map(static function ($val) {
return is_array($val) ? json_encode($val) : $val; return is_array($val) ? json_encode($val) : $val;
}, $value); }, $value);

View File

@ -445,7 +445,7 @@ EOT
@mkdir($directory, 0777, true); @mkdir($directory, 0777, true);
if ($realDir = realpath($directory)) { if ($realDir = realpath($directory)) {
pcntl_async_signals(true); pcntl_async_signals(true);
pcntl_signal(SIGINT, function () use ($realDir): void { pcntl_signal(SIGINT, static function () use ($realDir): void {
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($realDir); $fs->removeDirectory($realDir);
exit(130); exit(130);
@ -456,7 +456,7 @@ EOT
if (function_exists('sapi_windows_set_ctrl_handler') && PHP_SAPI === 'cli') { if (function_exists('sapi_windows_set_ctrl_handler') && PHP_SAPI === 'cli') {
@mkdir($directory, 0777, true); @mkdir($directory, 0777, true);
if ($realDir = realpath($directory)) { if ($realDir = realpath($directory)) {
sapi_windows_set_ctrl_handler(function () use ($realDir): void { sapi_windows_set_ctrl_handler(static function () use ($realDir): void {
$fs = new Filesystem(); $fs = new Filesystem();
$fs->removeDirectory($realDir); $fs->removeDirectory($realDir);
exit(130); exit(130);

View File

@ -520,7 +520,7 @@ EOT
private function checkPlatform() private function checkPlatform()
{ {
$output = ''; $output = '';
$out = function ($msg, $style) use (&$output): void { $out = static function ($msg, $style) use (&$output): void {
$output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL; $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
}; };

View File

@ -109,7 +109,7 @@ EOT
$bins = glob($binDir . '/*'); $bins = glob($binDir . '/*');
$localBins = $composer->getPackage()->getBinaries(); $localBins = $composer->getPackage()->getBinaries();
if ($forDisplay) { if ($forDisplay) {
$localBins = array_map(function ($e) { $localBins = array_map(static function ($e) {
return "$e (local)"; return "$e (local)";
}, $localBins); }, $localBins);
} }

View File

@ -33,7 +33,7 @@ class GlobalCommand extends BaseCommand
{ {
$application = $this->getApplication(); $application = $this->getApplication();
if ($input->mustSuggestArgumentValuesFor('command-name')) { if ($input->mustSuggestArgumentValuesFor('command-name')) {
$suggestions->suggestValues(array_filter(array_map(function (Command $command) { $suggestions->suggestValues(array_filter(array_map(static function (Command $command) {
return $command->isHidden() ? null : $command->getName(); return $command->isHidden() ? null : $command->getName();
}, $application->all()))); }, $application->all())));

View File

@ -293,7 +293,7 @@ EOT
$name = $io->askAndValidate( $name = $io->askAndValidate(
'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ', 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
function ($value) use ($name) { static function ($value) use ($name) {
if (null === $value) { if (null === $value) {
return $name; return $name;
} }
@ -359,7 +359,7 @@ EOT
$minimumStability = $input->getOption('stability') ?: null; $minimumStability = $input->getOption('stability') ?: null;
$minimumStability = $io->askAndValidate( $minimumStability = $io->askAndValidate(
'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ', 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
function ($value) use ($minimumStability) { static function ($value) use ($minimumStability) {
if (null === $value) { if (null === $value) {
return $minimumStability; return $minimumStability;
} }
@ -433,7 +433,7 @@ EOT
$namespace = $this->namespaceFromPackageName((string) $input->getOption('name')); $namespace = $this->namespaceFromPackageName((string) $input->getOption('name'));
$autoload = $io->askAndValidate( $autoload = $io->askAndValidate(
'Add PSR-4 autoload mapping? Maps namespace "'.$namespace.'" to the entered relative path. [<comment>'.$autoload.'</comment>, n to skip]: ', 'Add PSR-4 autoload mapping? Maps namespace "'.$namespace.'" to the entered relative path. [<comment>'.$autoload.'</comment>, n to skip]: ',
function ($value) use ($autoload) { static function ($value) use ($autoload) {
if (null === $value) { if (null === $value) {
return $autoload; return $autoload;
} }
@ -514,7 +514,7 @@ EOT
} }
$namespace = array_map( $namespace = array_map(
function ($part): string { static function ($part): string {
$part = Preg::replace('/[^a-z0-9]/i', ' ', $part); $part = Preg::replace('/[^a-z0-9]/i', ' ', $part);
$part = ucwords($part); $part = ucwords($part);

View File

@ -167,7 +167,7 @@ EOT
$packageListNames = array_keys($bucket); $packageListNames = array_keys($bucket);
$packages = array_filter( $packages = array_filter(
$repo->getPackages(), $repo->getPackages(),
function ($package) use ($requires, $packageListNames): bool { static function ($package) use ($requires, $packageListNames): bool {
return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames); return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames);
} }
); );

View File

@ -186,7 +186,7 @@ trait PackageDiscoveryTrait
$io->writeError($choices); $io->writeError($choices);
$io->writeError(''); $io->writeError('');
$validator = function (string $selection) use ($matches, $versionParser) { $validator = static function (string $selection) use ($matches, $versionParser) {
if ('' === $selection) { if ('' === $selection) {
return false; return false;
} }
@ -224,7 +224,7 @@ trait PackageDiscoveryTrait
// no constraint yet, determine the best version automatically // no constraint yet, determine the best version automatically
if (false !== $package && false === strpos($package, ' ')) { if (false !== $package && false === strpos($package, ' ')) {
$validator = function (string $input) { $validator = static function (string $input) {
$input = trim($input); $input = trim($input);
return strlen($input) > 0 ? $input : false; return strlen($input) > 0 ? $input : false;
@ -296,7 +296,7 @@ trait PackageDiscoveryTrait
if (count($providers) > 0) { if (count($providers) > 0) {
$constraint = '*'; $constraint = '*';
if ($input->isInteractive()) { if ($input->isInteractive()) {
$constraint = $this->getIO()->askAndValidate('Package "<info>'.$name.'</info>" does not exist but is provided by '.count($providers).' packages. Which version constraint would you like to use? [<info>*</info>] ', function ($value) { $constraint = $this->getIO()->askAndValidate('Package "<info>'.$name.'</info>" does not exist but is provided by '.count($providers).' packages. Which version constraint would you like to use? [<info>*</info>] ', static function ($value) {
$parser = new VersionParser(); $parser = new VersionParser();
$parser->parseConstraints($value); $parser->parseConstraints($value);

View File

@ -125,7 +125,7 @@ EOT
$installOrder[$op->getPackage()->getName()] = $index; $installOrder[$op->getPackage()->getName()] = $index;
} }
} }
usort($uninstallOperations, function ($a, $b) use ($installOrder): int { usort($uninstallOperations, static function ($a, $b) use ($installOrder): int {
return $installOrder[$b->getPackage()->getName()] - $installOrder[$a->getPackage()->getName()]; return $installOrder[$b->getPackage()->getName()] - $installOrder[$a->getPackage()->getName()];
}); });

View File

@ -118,7 +118,7 @@ EOT
if (count($input->getArgument('packages')) === 0) { if (count($input->getArgument('packages')) === 0) {
$this->getIO()->writeError('<info>No unused packages to remove</info>'); $this->getIO()->writeError('<info>No unused packages to remove</info>');
$this->setCode(function (): int { $this->setCode(static function (): int {
return 0; return 0;
}); });
} }

View File

@ -372,7 +372,7 @@ TAGSPUBKEY
$io->write('Open <info>https://composer.github.io/pubkeys.html</info> to find the latest keys'); $io->write('Open <info>https://composer.github.io/pubkeys.html</info> to find the latest keys');
$validator = function ($value): string { $validator = static function ($value): string {
if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) {
throw new \UnexpectedValueException('Invalid input'); throw new \UnexpectedValueException('Invalid input');
} }

View File

@ -249,7 +249,7 @@ EOT
if ($input->getOption('no-dev')) { if ($input->getOption('no-dev')) {
$packages = $this->filterRequiredPackages($installedRepo, $rootPkg); $packages = $this->filterRequiredPackages($installedRepo, $rootPkg);
$repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg): PackageInterface { $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(static function ($pkg): PackageInterface {
return clone $pkg; return clone $pkg;
}, $packages)))); }, $packages))));
} }
@ -346,7 +346,7 @@ EOT
if ($input->getOption('tree')) { if ($input->getOption('tree')) {
$rootRequires = $this->getRootRequires(); $rootRequires = $this->getRootRequires();
$packages = $installedRepo->getPackages(); $packages = $installedRepo->getPackages();
usort($packages, function (BasePackage $a, BasePackage $b): int { usort($packages, static function (BasePackage $a, BasePackage $b): int {
return strcmp((string) $a, (string) $b); return strcmp((string) $a, (string) $b);
}); });
$arrayTree = array(); $arrayTree = array();
@ -1011,7 +1011,7 @@ EOT
if ($licenses = $package->getLicense()) { if ($licenses = $package->getLicense()) {
$spdxLicenses = new SpdxLicenses(); $spdxLicenses = new SpdxLicenses();
$json['licenses'] = array_map(function ($licenseId) use ($spdxLicenses) { $json['licenses'] = array_map(static function ($licenseId) use ($spdxLicenses) {
$license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url $license = $spdxLicenses->getLicenseByIdentifier($licenseId); // keys: 0 fullname, 1 osi, 2 url
if (!$license) { if (!$license) {

View File

@ -163,7 +163,7 @@ EOT
foreach ($errors as $path => $changes) { foreach ($errors as $path => $changes) {
if ($input->getOption('verbose')) { if ($input->getOption('verbose')) {
$indentedChanges = implode("\n", array_map(function ($line): string { $indentedChanges = implode("\n", array_map(static function ($line): string {
return ' ' . ltrim($line); return ' ' . ltrim($line);
}, explode("\n", $changes))); }, explode("\n", $changes)));
$io->write('<info>'.$path.'</info>:'); $io->write('<info>'.$path.'</info>:');
@ -179,7 +179,7 @@ EOT
foreach ($unpushedChanges as $path => $changes) { foreach ($unpushedChanges as $path => $changes) {
if ($input->getOption('verbose')) { if ($input->getOption('verbose')) {
$indentedChanges = implode("\n", array_map(function ($line): string { $indentedChanges = implode("\n", array_map(static function ($line): string {
return ' ' . ltrim($line); return ' ' . ltrim($line);
}, explode("\n", $changes))); }, explode("\n", $changes)));
$io->write('<info>'.$path.'</info>:'); $io->write('<info>'.$path.'</info>:');

View File

@ -132,7 +132,7 @@ EOT
// extract --with shorthands from the allowlist // extract --with shorthands from the allowlist
if (count($packages) > 0) { if (count($packages) > 0) {
$allowlistPackagesWithRequirements = array_filter($packages, function ($pkg): bool { $allowlistPackagesWithRequirements = array_filter($packages, static function ($pkg): bool {
return Preg::isMatch('{\S+[ =:]\S+}', $pkg); return Preg::isMatch('{\S+[ =:]\S+}', $pkg);
}); });
foreach ($this->formatRequirements($allowlistPackagesWithRequirements) as $package => $constraint) { foreach ($this->formatRequirements($allowlistPackagesWithRequirements) as $package => $constraint) {
@ -176,7 +176,7 @@ EOT
// the arguments lock/nothing/mirrors are not package names but trigger a mirror update instead // 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 // they are further mutually exclusive with listing actual package names
$filteredPackages = array_filter($packages, function ($package): bool { $filteredPackages = array_filter($packages, static function ($package): bool {
return !in_array($package, array('lock', 'nothing', 'mirrors'), true); return !in_array($package, array('lock', 'nothing', 'mirrors'), true);
}); });
$updateMirrors = $input->getOption('lock') || count($filteredPackages) != count($packages); $updateMirrors = $input->getOption('lock') || count($filteredPackages) != count($packages);

View File

@ -196,13 +196,13 @@ EOT
} }
if ($errors) { if ($errors) {
$errors = array_map(function ($err): string { $errors = array_map(static function ($err): string {
return '- ' . $err; return '- ' . $err;
}, $errors); }, $errors);
array_unshift($errors, '# General errors'); array_unshift($errors, '# General errors');
} }
if ($warnings) { if ($warnings) {
$warnings = array_map(function ($err): string { $warnings = array_map(static function ($err): string {
return '- ' . $err; return '- ' . $err;
}, $warnings); }, $warnings);
array_unshift($warnings, '# General warnings'); array_unshift($warnings, '# General warnings');
@ -213,7 +213,7 @@ EOT
// If checking publish errors, display them as errors, otherwise just show them as warnings // If checking publish errors, display them as errors, otherwise just show them as warnings
if ($publishErrors) { if ($publishErrors) {
$publishErrors = array_map(function ($err): string { $publishErrors = array_map(static function ($err): string {
return '- ' . $err; return '- ' . $err;
}, $publishErrors); }, $publishErrors);

View File

@ -82,7 +82,7 @@ class Compiler
$phar->startBuffering(); $phar->startBuffering();
$finderSort = function ($a, $b): int { $finderSort = static function ($a, $b): int {
return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/')); return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/'));
}; };

View File

@ -62,7 +62,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function addRepository(string $name, $config, bool $append = true): void public function addRepository(string $name, $config, bool $append = true): void
{ {
$this->manipulateJson('addRepository', function (&$config, $repo, $repoConfig) use ($append): void { $this->manipulateJson('addRepository', static 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 // 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 // to convert it to "packagist.org": false key on the hashmap otherwise it fails schema validation
if (isset($config['repositories'])) { if (isset($config['repositories'])) {
@ -91,7 +91,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function removeRepository(string $name): void public function removeRepository(string $name): void
{ {
$this->manipulateJson('removeRepository', function (&$config, $repo): void { $this->manipulateJson('removeRepository', static function (&$config, $repo): void {
unset($config['repositories'][$repo]); unset($config['repositories'][$repo]);
}, $name); }, $name);
} }
@ -102,7 +102,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function addConfigSetting(string $name, $value): void public function addConfigSetting(string $name, $value): void
{ {
$authConfig = $this->authConfig; $authConfig = $this->authConfig;
$this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig): void { $this->manipulateJson('addConfigSetting', static function (&$config, $key, $val) use ($authConfig): void {
if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) {
list($key, $host) = explode('.', $key, 2); list($key, $host) = explode('.', $key, 2);
if ($authConfig) { if ($authConfig) {
@ -122,7 +122,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function removeConfigSetting(string $name): void public function removeConfigSetting(string $name): void
{ {
$authConfig = $this->authConfig; $authConfig = $this->authConfig;
$this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig): void { $this->manipulateJson('removeConfigSetting', static function (&$config, $key) use ($authConfig): void {
if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) { if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) {
list($key, $host) = explode('.', $key, 2); list($key, $host) = explode('.', $key, 2);
if ($authConfig) { if ($authConfig) {
@ -141,7 +141,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function addProperty(string $name, $value): void public function addProperty(string $name, $value): void
{ {
$this->manipulateJson('addProperty', function (&$config, $key, $val): void { $this->manipulateJson('addProperty', static function (&$config, $key, $val): void {
if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) {
$bits = explode('.', $key); $bits = explode('.', $key);
$last = array_pop($bits); $last = array_pop($bits);
@ -164,7 +164,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function removeProperty(string $name): void public function removeProperty(string $name): void
{ {
$this->manipulateJson('removeProperty', function (&$config, $key): void { $this->manipulateJson('removeProperty', static function (&$config, $key): void {
if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) { if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) {
$bits = explode('.', $key); $bits = explode('.', $key);
$last = array_pop($bits); $last = array_pop($bits);
@ -187,7 +187,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function addLink(string $type, string $name, string $value): void public function addLink(string $type, string $name, string $value): void
{ {
$this->manipulateJson('addLink', function (&$config, $type, $name, $value): void { $this->manipulateJson('addLink', static function (&$config, $type, $name, $value): void {
$config[$type][$name] = $value; $config[$type][$name] = $value;
}, $type, $name, $value); }, $type, $name, $value);
} }
@ -197,10 +197,10 @@ class JsonConfigSource implements ConfigSourceInterface
*/ */
public function removeLink(string $type, string $name): void public function removeLink(string $type, string $name): void
{ {
$this->manipulateJson('removeSubNode', function (&$config, $type, $name): void { $this->manipulateJson('removeSubNode', static function (&$config, $type, $name): void {
unset($config[$type][$name]); unset($config[$type][$name]);
}, $type, $name); }, $type, $name);
$this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type): void { $this->manipulateJson('removeMainKeyIfEmpty', static function (&$config, $type): void {
if (0 === count($config[$type])) { if (0 === count($config[$type])) {
unset($config[$type]); unset($config[$type]);
} }

View File

@ -96,14 +96,14 @@ class Application extends BaseApplication
if (!$shutdownRegistered) { if (!$shutdownRegistered) {
if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) { if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) {
pcntl_async_signals(true); pcntl_async_signals(true);
pcntl_signal(SIGINT, function ($sig): void { pcntl_signal(SIGINT, static function ($sig): void {
exit(130); exit(130);
}); });
} }
$shutdownRegistered = true; $shutdownRegistered = true;
register_shutdown_function(function (): void { register_shutdown_function(static function (): void {
$lastError = error_get_last(); $lastError = error_get_last();
if ($lastError && $lastError['message'] && if ($lastError && $lastError['message'] &&
@ -296,7 +296,7 @@ class Application extends BaseApplication
} }
// Check system temp folder for usability as it can cause weird runtime issues otherwise // Check system temp folder for usability as it can cause weird runtime issues otherwise
Silencer::call(function () use ($io): void { Silencer::call(static function () use ($io): void {
$tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime()); $tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime());
if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) { if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) {
$io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir())); $io->writeError(sprintf('<error>PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini</error>', sys_get_temp_dir()));

View File

@ -152,7 +152,7 @@ class LockTransaction extends Transaction
} }
} }
usort($usedAliases, function ($a, $b): int { usort($usedAliases, static function ($a, $b): int {
return strcmp($a['package'], $b['package']); return strcmp($a['package'], $b['package']);
}); });

View File

@ -532,7 +532,7 @@ class PoolBuilder
$matches = array(); $matches = array();
if (isset($rootRequires[$name])) { if (isset($rootRequires[$name])) {
return array_map(function (PackageInterface $package) use ($name): string { return array_map(static function (PackageInterface $package) use ($name): string {
if ($name !== $package->getName()) { if ($name !== $package->getName()) {
return $package->getName() .' (via replace of '.$name.')'; return $package->getName() .' (via replace of '.$name.')';
} }

View File

@ -286,7 +286,7 @@ class Problem
if ($packages = $repositorySet->findPackages($packageName, $constraint)) { if ($packages = $repositorySet->findPackages($packageName, $constraint)) {
$rootReqs = $repositorySet->getRootRequires(); $rootReqs = $repositorySet->getRootRequires();
if (isset($rootReqs[$packageName])) { if (isset($rootReqs[$packageName])) {
$filtered = array_filter($packages, function ($p) use ($rootReqs, $packageName): bool { $filtered = array_filter($packages, static function ($p) use ($rootReqs, $packageName): bool {
return $rootReqs[$packageName]->matches(new Constraint('==', $p->getVersion())); return $rootReqs[$packageName]->matches(new Constraint('==', $p->getVersion()));
}); });
if (0 === count($filtered)) { if (0 === count($filtered)) {
@ -296,7 +296,7 @@ class Problem
$tempReqs = $repositorySet->getTemporaryConstraints(); $tempReqs = $repositorySet->getTemporaryConstraints();
if (isset($tempReqs[$packageName])) { if (isset($tempReqs[$packageName])) {
$filtered = array_filter($packages, function ($p) use ($tempReqs, $packageName): bool { $filtered = array_filter($packages, static function ($p) use ($tempReqs, $packageName): bool {
return $tempReqs[$packageName]->matches(new Constraint('==', $p->getVersion())); return $tempReqs[$packageName]->matches(new Constraint('==', $p->getVersion()));
}); });
if (0 === count($filtered)) { if (0 === count($filtered)) {
@ -306,7 +306,7 @@ class Problem
if ($lockedPackage) { if ($lockedPackage) {
$fixedConstraint = new Constraint('==', $lockedPackage->getVersion()); $fixedConstraint = new Constraint('==', $lockedPackage->getVersion());
$filtered = array_filter($packages, function ($p) use ($fixedConstraint): bool { $filtered = array_filter($packages, static function ($p) use ($fixedConstraint): bool {
return $fixedConstraint->matches(new Constraint('==', $p->getVersion())); return $fixedConstraint->matches(new Constraint('==', $p->getVersion()));
}); });
if (0 === count($filtered)) { if (0 === count($filtered)) {
@ -314,7 +314,7 @@ class Problem
} }
} }
$nonLockedPackages = array_filter($packages, function ($p): bool { $nonLockedPackages = array_filter($packages, static function ($p): bool {
return !$p->getRepository() instanceof LockArrayRepository; return !$p->getRepository() instanceof LockArrayRepository;
}); });
@ -370,7 +370,7 @@ class Problem
if ($providers = $repositorySet->getProviders($packageName)) { if ($providers = $repositorySet->getProviders($packageName)) {
$maxProviders = 20; $maxProviders = 20;
$providersStr = implode(array_map(function ($p): string { $providersStr = implode(array_map(static function ($p): string {
$description = $p['description'] ? ' '.substr($p['description'], 0, 100) : ''; $description = $p['description'] ? ' '.substr($p['description'], 0, 100) : '';
return ' - '.$p['name'].$description."\n"; return ' - '.$p['name'].$description."\n";

View File

@ -281,7 +281,7 @@ abstract class Rule
return 'No package found to satisfy root composer.json require '.$packageName.($constraint ? ' '.$constraint->getPrettyString() : ''); return 'No package found to satisfy root composer.json require '.$packageName.($constraint ? ' '.$constraint->getPrettyString() : '');
} }
$packagesNonAlias = array_values(array_filter($packages, function ($p): bool { $packagesNonAlias = array_values(array_filter($packages, static function ($p): bool {
return !($p instanceof AliasPackage); return !($p instanceof AliasPackage);
})); }));
if (count($packagesNonAlias) === 1) { if (count($packagesNonAlias) === 1) {

View File

@ -110,7 +110,7 @@ class RuleWatchGraph
if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) { if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) {
$ruleLiterals = $node->getRule()->getLiterals(); $ruleLiterals = $node->getRule()->getLiterals();
$alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions): bool { $alternativeLiterals = array_filter($ruleLiterals, static function ($ruleLiteral) use ($literal, $otherWatch, $decisions): bool {
return $literal !== $ruleLiteral && return $literal !== $ruleLiteral &&
$otherWatch !== $ruleLiteral && $otherWatch !== $ruleLiteral &&
!$decisions->conflict($ruleLiteral); !$decisions->conflict($ruleLiteral);

View File

@ -121,7 +121,7 @@ class SolverProblemsException extends \RuntimeException
array_shift($paths); array_shift($paths);
} }
$ignoreExtensionsArguments = implode(" ", array_map(function ($extension) { $ignoreExtensionsArguments = implode(" ", array_map(static function ($extension) {
return "--ignore-platform-req=$extension"; return "--ignore-platform-req=$extension";
}, $missingExtensions)); }, $missingExtensions));

View File

@ -71,7 +71,7 @@ class Transaction
*/ */
private function setResultPackageMaps(array $resultPackages): void private function setResultPackageMaps(array $resultPackages): void
{ {
$packageSort = function (PackageInterface $a, PackageInterface $b): int { $packageSort = static function (PackageInterface $a, PackageInterface $b): int {
// sort alias packages by the same name behind their non alias version // sort alias packages by the same name behind their non alias version
if ($a->getName() == $b->getName()) { if ($a->getName() == $b->getName()) {
if ($a instanceof AliasPackage != $b instanceof AliasPackage) { if ($a instanceof AliasPackage != $b instanceof AliasPackage) {
@ -289,7 +289,7 @@ class Transaction
// is this a downloads modifying plugin or a dependency of one? // is this a downloads modifying plugin or a dependency of one?
if ($isDownloadsModifyingPlugin || count(array_intersect($package->getNames(), $dlModifyingPluginRequires))) { if ($isDownloadsModifyingPlugin || count(array_intersect($package->getNames(), $dlModifyingPluginRequires))) {
// get the package's requires, but filter out any platform requirements // get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), function ($req): bool { $requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req); return !PlatformRepository::isPlatformPackage($req);
}); });
@ -314,7 +314,7 @@ class Transaction
// is this a plugin or a dependency of a plugin? // is this a plugin or a dependency of a plugin?
if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) { if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) {
// get the package's requires, but filter out any platform requirements // get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), function ($req): bool { $requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req); return !PlatformRepository::isPlatformPackage($req);
}); });

View File

@ -124,7 +124,7 @@ abstract class ArchiveDownloader extends FileDownloader
* @param string $dir Directory * @param string $dir Directory
* @return \SplFileInfo[] * @return \SplFileInfo[]
*/ */
$getFolderContent = function ($dir): array { $getFolderContent = static function ($dir): array {
$finder = Finder::create() $finder = Finder::create()
->ignoreVCS(false) ->ignoreVCS(false)
->ignoreDotFiles(false) ->ignoreDotFiles(false)
@ -146,7 +146,7 @@ abstract class ArchiveDownloader extends FileDownloader
* @param string $to Directory * @param string $to Directory
* @return void * @return void
*/ */
$renameRecursively = function ($from, $to) use ($filesystem, $getFolderContent, $package, &$renameRecursively) { $renameRecursively = static function ($from, $to) use ($filesystem, $getFolderContent, $package, &$renameRecursively) {
$contentDir = $getFolderContent($from); $contentDir = $getFolderContent($from);
// move files back out of the temp dir // move files back out of the temp dir
@ -203,7 +203,7 @@ abstract class ArchiveDownloader extends FileDownloader
$this->removeCleanupPath($package, $temporaryDir); $this->removeCleanupPath($package, $temporaryDir);
$this->removeCleanupPath($package, $path); $this->removeCleanupPath($package, $path);
}); });
}, function ($e) use ($cleanup) { }, static function ($e) use ($cleanup) {
$cleanup(); $cleanup();
throw $e; throw $e;

View File

@ -205,7 +205,7 @@ class DownloadManager
return \React\Promise\resolve(null); return \React\Promise\resolve(null);
} }
$handleError = function ($e) use ($sources, $source, $package, $io, $download) { $handleError = static function ($e) use ($sources, $source, $package, $io, $download) {
if ($e instanceof \RuntimeException && !$e instanceof IrrecoverableDownloadException) { if ($e instanceof \RuntimeException && !$e instanceof IrrecoverableDownloadException) {
if (!$sources) { if (!$sources) {
throw $e; throw $e;
@ -230,7 +230,7 @@ class DownloadManager
return $handleError($e); return $handleError($e);
} }
$res = $result->then(function ($res) { $res = $result->then(static function ($res) {
return $res; return $res;
}, $handleError); }, $handleError);
@ -426,7 +426,7 @@ class DownloadManager
&& !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev()) && !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev())
) { ) {
$prevSource = $prevPackage->getInstallationSource(); $prevSource = $prevPackage->getInstallationSource();
usort($sources, function ($a, $b) use ($prevSource): int { usort($sources, static function ($a, $b) use ($prevSource): int {
return $a === $prevSource ? -1 : 1; return $a === $prevSource ? -1 : 1;
}); });

View File

@ -117,7 +117,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
throw new \InvalidArgumentException('The given package is missing url information'); throw new \InvalidArgumentException('The given package is missing url information');
} }
$cacheKeyGenerator = function (PackageInterface $package, $key): string { $cacheKeyGenerator = static function (PackageInterface $package, $key): string {
$cacheKey = sha1($key); $cacheKey = sha1($key);
return $package->getName().'/'.$cacheKey.'.'.$package->getDistType(); return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
@ -194,7 +194,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
->then($accept, $reject); ->then($accept, $reject);
} }
return $result->then(function ($result) use ($fileName, $checksum, $url, $package, $eventDispatcher): string { return $result->then(static 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, // 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 // once with $result being the returned $fileName from $accept, and then once for every
// failed request with a null result, which can be skipped. // failed request with a null result, which can be skipped.
@ -420,7 +420,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
} }
$promise = $this->filesystem->removeDirectoryAsync($path); $promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(function ($result) use ($path): void { return $promise->then(static function ($result) use ($path): void {
if (!$result) { if (!$result) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
} }

View File

@ -114,7 +114,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
$this->io->writeError($msg); $this->io->writeError($msg);
$commandCallable = function (string $url) use ($path, $command, $cachePath): string { $commandCallable = static function (string $url) use ($path, $command, $cachePath): string {
return str_replace( return str_replace(
array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'), array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'),
array( array(
@ -172,7 +172,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
$this->io->writeError($msg); $this->io->writeError($msg);
$commandCallable = function ($url) use ($ref, $command, $cachePath): string { $commandCallable = static function ($url) use ($ref, $command, $cachePath): string {
return str_replace( return str_replace(
array('%url%', '%ref%', '%cachePath%', '%sanitizedUrl%'), array('%url%', '%ref%', '%cachePath%', '%sanitizedUrl%'),
array( array(
@ -360,7 +360,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
return parent::cleanChanges($package, $path, $update); return parent::cleanChanges($package, $path, $update);
} }
$changes = array_map(function ($elem): string { $changes = array_map(static function ($elem): string {
return ' '.$elem; return ' '.$elem;
}, Preg::split('{\s*\r?\n\s*}', $changes)); }, Preg::split('{\s*\r?\n\s*}', $changes));
$this->io->writeError(' <error>'.$package->getPrettyName().' has modified files:</error>'); $this->io->writeError(' <error>'.$package->getPrettyName().' has modified files:</error>');

View File

@ -41,7 +41,7 @@ class HgDownloader extends VcsDownloader
{ {
$hgUtils = new HgUtils($this->io, $this->config, $this->process); $hgUtils = new HgUtils($this->io, $this->config, $this->process);
$cloneCommand = function (string $url) use ($path): string { $cloneCommand = static function (string $url) use ($path): string {
return sprintf('hg clone -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path)); return sprintf('hg clone -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path));
}; };
@ -70,7 +70,7 @@ class HgDownloader extends VcsDownloader
throw new \RuntimeException('The .hg directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information'); throw new \RuntimeException('The .hg directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
} }
$command = function ($url) use ($ref): string { $command = static function ($url) use ($ref): string {
return sprintf('hg pull -- %s && hg up -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($ref)); return sprintf('hg pull -- %s && hg up -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($ref));
}; };

View File

@ -144,7 +144,7 @@ class SvnDownloader extends VcsDownloader
return parent::cleanChanges($package, $path, $update); return parent::cleanChanges($package, $path, $update);
} }
$changes = array_map(function ($elem): string { $changes = array_map(static function ($elem): string {
return ' '.$elem; return ' '.$elem;
}, Preg::split('{\s*\r?\n\s*}', $changes)); }, Preg::split('{\s*\r?\n\s*}', $changes));
$countChanges = count($changes); $countChanges = count($changes);

View File

@ -200,7 +200,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa
} }
if ('' !== trim($logs)) { if ('' !== trim($logs)) {
$logs = implode("\n", array_map(function ($line): string { $logs = implode("\n", array_map(static function ($line): string {
return ' ' . $line; return ' ' . $line;
}, explode("\n", $logs))); }, explode("\n", $logs)));
@ -228,7 +228,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa
$promise = $this->filesystem->removeDirectoryAsync($path); $promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(function (bool $result) use ($path) { return $promise->then(static function (bool $result) use ($path) {
if (!$result) { if (!$result) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.'); throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
} }

View File

@ -292,7 +292,7 @@ class EventDispatcher
if (strpos($exec, '@php ') === 0) { if (strpos($exec, '@php ') === 0) {
$pathAndArgs = substr($exec, 5); $pathAndArgs = substr($exec, 5);
if (Platform::isWindows()) { if (Platform::isWindows()) {
$pathAndArgs = Preg::replaceCallback('{^\S+}', function ($path) { $pathAndArgs = Preg::replaceCallback('{^\S+}', static function ($path) {
return str_replace('/', '\\', $path[0]); return str_replace('/', '\\', $path[0]);
}, $pathAndArgs); }, $pathAndArgs);
} }
@ -314,7 +314,7 @@ class EventDispatcher
} }
if (Platform::isWindows()) { if (Platform::isWindows()) {
$exec = Preg::replaceCallback('{^\S+}', function ($path) { $exec = Preg::replaceCallback('{^\S+}', static function ($path) {
return str_replace('/', '\\', $path[0]); return str_replace('/', '\\', $path[0]);
}, $exec); }, $exec);
} }

View File

@ -56,7 +56,7 @@ class BufferIO extends ConsoleIO
$output = stream_get_contents($this->output->getStream()); $output = stream_get_contents($this->output->getStream());
$output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches): string { $output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", static function ($matches): string {
$pre = strip_tags($matches[1]); $pre = strip_tags($matches[1]);
if (strlen($pre) === strlen($matches[2])) { if (strlen($pre) === strlen($matches[2])) {

View File

@ -175,7 +175,7 @@ class ConsoleIO extends BaseIO
if (null !== $this->startTime) { if (null !== $this->startTime) {
$memoryUsage = memory_get_usage() / 1024 / 1024; $memoryUsage = memory_get_usage() / 1024 / 1024;
$timeSpent = microtime(true) - $this->startTime; $timeSpent = microtime(true) - $this->startTime;
$messages = array_map(function ($message) use ($memoryUsage, $timeSpent): string { $messages = array_map(static function ($message) use ($memoryUsage, $timeSpent): string {
return sprintf('[%.1fMiB/%.2fs] %s', $memoryUsage, $timeSpent, $message); return sprintf('[%.1fMiB/%.2fs] %s', $memoryUsage, $timeSpent, $message);
}, (array) $messages); }, (array) $messages);
} }

View File

@ -533,7 +533,7 @@ class Installer
} }
} }
$sortByName = function ($a, $b): int { $sortByName = static function ($a, $b): int {
if ($a instanceof UpdateOperation) { if ($a instanceof UpdateOperation) {
$a = $a->getTargetPackage()->getName(); $a = $a->getTargetPackage()->getName();
} else { } else {

View File

@ -199,18 +199,18 @@ class InstallationManager
$loop = $this->loop; $loop = $this->loop;
$io = $this->io; $io = $this->io;
$runCleanup = function () use (&$cleanupPromises, $loop): void { $runCleanup = static function () use (&$cleanupPromises, $loop): void {
$promises = array(); $promises = array();
$loop->abortJobs(); $loop->abortJobs();
foreach ($cleanupPromises as $cleanup) { foreach ($cleanupPromises as $cleanup) {
$promises[] = new \React\Promise\Promise(function ($resolve, $reject) use ($cleanup): void { $promises[] = new \React\Promise\Promise(static function ($resolve, $reject) use ($cleanup): void {
$promise = $cleanup(); $promise = $cleanup();
if (!$promise instanceof PromiseInterface) { if (!$promise instanceof PromiseInterface) {
$resolve(); $resolve();
} else { } else {
$promise->then(function () use ($resolve): void { $promise->then(static function () use ($resolve): void {
$resolve(); $resolve();
}); });
} }
@ -229,7 +229,7 @@ class InstallationManager
if ($handleInterruptsUnix) { if ($handleInterruptsUnix) {
pcntl_async_signals(true); pcntl_async_signals(true);
$prevHandler = pcntl_signal_get_handler(SIGINT); $prevHandler = pcntl_signal_get_handler(SIGINT);
pcntl_signal(SIGINT, function ($sig) use ($runCleanup, $prevHandler, $io): void { pcntl_signal(SIGINT, static function ($sig) use ($runCleanup, $prevHandler, $io): void {
$io->writeError('Received SIGINT, aborting', true, IOInterface::DEBUG); $io->writeError('Received SIGINT, aborting', true, IOInterface::DEBUG);
$runCleanup(); $runCleanup();
@ -241,7 +241,7 @@ class InstallationManager
}); });
} }
if ($handleInterruptsWindows) { if ($handleInterruptsWindows) {
$windowsHandler = function ($event) use ($runCleanup, $io): void { $windowsHandler = static function ($event) use ($runCleanup, $io): void {
if ($event !== PHP_WINDOWS_EVENT_CTRL_C) { if ($event !== PHP_WINDOWS_EVENT_CTRL_C) {
return; return;
} }
@ -339,7 +339,7 @@ class InstallationManager
} }
$installer = $this->getInstaller($package->getType()); $installer = $this->getInstaller($package->getType());
$cleanupPromises[$index] = function () use ($opType, $installer, $package, $initialPackage) { $cleanupPromises[$index] = static function () use ($opType, $installer, $package, $initialPackage) {
// avoid calling cleanup if the download was not even initialized for a package // avoid calling cleanup if the download was not even initialized for a package
// as without installation source configured nothing will work // as without installation source configured nothing will work
if (!$package->getInstallationSource()) { if (!$package->getInstallationSource()) {
@ -453,7 +453,7 @@ class InstallationManager
})->then($cleanupPromises[$index]) })->then($cleanupPromises[$index])
->then(function () use ($devMode, $repo): void { ->then(function () use ($devMode, $repo): void {
$repo->write($devMode, $this); $repo->write($devMode, $this);
}, function ($e) use ($opType, $package, $io): void { }, static function ($e) use ($opType, $package, $io): void {
$io->writeError(' <error>' . ucfirst($opType) .' of '.$package->getPrettyName().' failed</error>'); $io->writeError(' <error>' . ucfirst($opType) .' of '.$package->getPrettyName().' failed</error>');
throw $e; throw $e;
@ -466,7 +466,7 @@ class InstallationManager
][$opType] ?? null; ][$opType] ?? null;
if (null !== $eventName && $runScripts && $dispatcher) { if (null !== $eventName && $runScripts && $dispatcher) {
$postExecCallbacks[] = function () use ($dispatcher, $eventName, $devMode, $repo, $allOperations, $operation): void { $postExecCallbacks[] = static function () use ($dispatcher, $eventName, $devMode, $repo, $allOperations, $operation): void {
$dispatcher->dispatchPackageEvent($eventName, $devMode, $repo, $allOperations, $operation); $dispatcher->dispatchPackageEvent($eventName, $devMode, $repo, $allOperations, $operation);
}; };
} }
@ -558,7 +558,7 @@ class InstallationManager
} }
$installer = $this->getInstaller($targetType); $installer = $this->getInstaller($targetType);
$promise = $promise->then(function () use ($installer, $repo, $target): PromiseInterface { $promise = $promise->then(static function () use ($installer, $repo, $target): PromiseInterface {
$promise = $installer->install($repo, $target); $promise = $installer->install($repo, $target);
if ($promise instanceof PromiseInterface) { if ($promise instanceof PromiseInterface) {
return $promise; return $promise;

View File

@ -160,7 +160,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller; $binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($package); $installPath = $this->getInstallPath($package);
return $promise->then(function () use ($binaryInstaller, $installPath, $package, $repo): void { return $promise->then(static function () use ($binaryInstaller, $installPath, $package, $repo): void {
$binaryInstaller->installBinaries($package, $installPath); $binaryInstaller->installBinaries($package, $installPath);
if (!$repo->hasPackage($package)) { if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package); $repo->addPackage(clone $package);
@ -188,7 +188,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller; $binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($target); $installPath = $this->getInstallPath($target);
return $promise->then(function () use ($binaryInstaller, $installPath, $target, $initial, $repo): void { return $promise->then(static function () use ($binaryInstaller, $installPath, $target, $initial, $repo): void {
$binaryInstaller->installBinaries($target, $installPath); $binaryInstaller->installBinaries($target, $installPath);
$repo->removePackage($initial); $repo->removePackage($initial);
if (!$repo->hasPackage($target)) { if (!$repo->hasPackage($target)) {
@ -215,7 +215,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$downloadPath = $this->getPackageBasePath($package); $downloadPath = $this->getPackageBasePath($package);
$filesystem = $this->filesystem; $filesystem = $this->filesystem;
return $promise->then(function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo): void { return $promise->then(static function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo): void {
$binaryInstaller->removeBinaries($package); $binaryInstaller->removeBinaries($package);
$repo->removePackage($package); $repo->removePackage($package);

View File

@ -198,7 +198,7 @@ class SuggestedPackagesReporter
$sourceFilter = array(); $sourceFilter = array();
if ($onlyDependentsOf) { if ($onlyDependentsOf) {
$sourceFilter = array_map(function ($link): string { $sourceFilter = array_map(static function ($link): string {
return $link->getTarget(); return $link->getTarget();
}, array_merge($onlyDependentsOf->getRequires(), $onlyDependentsOf->getDevRequires())); }, array_merge($onlyDependentsOf->getRequires(), $onlyDependentsOf->getDevRequires()));
$sourceFilter[] = $onlyDependentsOf->getName(); $sourceFilter[] = $onlyDependentsOf->getName();

View File

@ -70,7 +70,7 @@ class JsonFormatter
if ($unescapeUnicode && function_exists('mb_convert_encoding')) { if ($unescapeUnicode && function_exists('mb_convert_encoding')) {
// https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha // https://stackoverflow.com/questions/2934563/how-to-decode-unicode-escape-sequences-like-u00ed-to-proper-utf-8-encoded-cha
$buffer = Preg::replaceCallback('/(\\\\+)u([0-9a-f]{4})/i', function ($match) { $buffer = Preg::replaceCallback('/(\\\\+)u([0-9a-f]{4})/i', static function ($match) {
$l = strlen($match[1]); $l = strlen($match[1]);
if ($l % 2) { if ($l % 2) {

View File

@ -94,7 +94,7 @@ class JsonManipulator
// update existing link // update existing link
$existingPackage = $packageMatches['package']; $existingPackage = $packageMatches['package'];
$packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage)); $packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage));
$links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P<separator>\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint): string { $links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P<separator>\s*:\s*)(?&string)}ix', static function ($m) use ($existingPackage, $constraint): string {
return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"'; return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"';
}, $links); }, $links);
} else { } else {
@ -135,7 +135,7 @@ class JsonManipulator
*/ */
private function sortPackages(array &$packages = array()): void private function sortPackages(array &$packages = array()): void
{ {
$prefix = function ($requirement): string { $prefix = static function ($requirement): string {
if (PlatformRepository::isPlatformPackage($requirement)) { if (PlatformRepository::isPlatformPackage($requirement)) {
return Preg::replace( return Preg::replace(
array( array(
@ -159,7 +159,7 @@ class JsonManipulator
return '5-'.$requirement; return '5-'.$requirement;
}; };
uksort($packages, function ($a, $b) use ($prefix): int { uksort($packages, static function ($a, $b) use ($prefix): int {
return strnatcmp($prefix($a), $prefix($b)); return strnatcmp($prefix($a), $prefix($b));
}); });
} }
@ -351,7 +351,7 @@ class JsonManipulator
} }
} }
$this->contents = Preg::replaceCallback($nodeRegex, function ($m) use ($children): string { $this->contents = Preg::replaceCallback($nodeRegex, static function ($m) use ($children): string {
return $m['start'] . $children . $m['end']; return $m['start'] . $children . $m['end'];
}, $this->contents); }, $this->contents);
@ -437,7 +437,7 @@ class JsonManipulator
$newline = $this->newline; $newline = $this->newline;
$indent = $this->indent; $indent = $this->indent;
$this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($indent, $newline): string { $this->contents = Preg::replaceCallback($nodeRegex, static function ($matches) use ($indent, $newline): string {
return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end']; return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end'];
}, $this->contents); }, $this->contents);

View File

@ -163,7 +163,7 @@ final class ConfigReturnTypeExtension implements DynamicMethodReturnTypeExtensio
$type = TypeCombinator::union(...$types); $type = TypeCombinator::union(...$types);
} elseif (isset($def['enum'])) { } elseif (isset($def['enum'])) {
$type = TypeCombinator::union(...array_map(function (string $value): ConstantStringType { $type = TypeCombinator::union(...array_map(static function (string $value): ConstantStringType {
return new ConstantStringType($value); return new ConstantStringType($value);
}, $def['enum'])); }, $def['enum']));
} else { } else {

View File

@ -57,7 +57,7 @@ class ArchivableFilesFinder extends \FilterIterator
$this->finder = new Finder(); $this->finder = new Finder();
$filter = function (\SplFileInfo $file) use ($sources, $filters, $fs): bool { $filter = static function (\SplFileInfo $file) use ($sources, $filters, $fs): bool {
if ($file->isLink() && ($file->getRealPath() === false || strpos($file->getRealPath(), $sources) !== 0)) { if ($file->isLink() && ($file->getRealPath() === false || strpos($file->getRealPath(), $sources) !== 0)) {
return false; return false;
} }

View File

@ -101,7 +101,7 @@ class ArchiveManager
$nameParts[] = substr(sha1($package->getSourceReference()), 0, 6); $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6);
} }
$name = implode('-', array_filter($nameParts, function ($p): bool { $name = implode('-', array_filter($nameParts, static function ($p): bool {
return !empty($p); return !empty($p);
})); }));

View File

@ -84,7 +84,7 @@ abstract class BaseExcludeFilter
{ {
return array_filter( return array_filter(
array_map( array_map(
function ($line) use ($lineParser) { static function ($line) use ($lineParser) {
$line = trim($line); $line = trim($line);
if (!$line || 0 === strpos($line, '#')) { if (!$line || 0 === strpos($line, '#')) {
@ -95,7 +95,7 @@ abstract class BaseExcludeFilter
}, },
$lines $lines
), ),
function ($pattern): bool { static function ($pattern): bool {
return $pattern !== null; return $pattern !== null;
} }
); );

View File

@ -273,7 +273,7 @@ abstract class BasePackage implements PackageInterface
public static function packageNamesToRegexp(array $packageNames, string $wrap = '{^(?:%s)$}iD'): string public static function packageNamesToRegexp(array $packageNames, string $wrap = '{^(?:%s)$}iD'): string
{ {
$packageNames = array_map( $packageNames = array_map(
function ($packageName): string { static function ($packageName): string {
return BasePackage::packageNameToRegexp($packageName, '%s'); return BasePackage::packageNameToRegexp($packageName, '%s');
}, },
$packageNames $packageNames

View File

@ -357,7 +357,7 @@ class Locker
{ {
// keep old default branch names normalized to DEFAULT_BRANCH_ALIAS for BC as that is how Composer 1 outputs the lock file // 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 // when loading the lock file the version is anyway ignored in Composer 2, so it has no adverse effect
$aliases = array_map(function ($alias): array { $aliases = array_map(static function ($alias): array {
if (in_array($alias['version'], array('dev-master', 'dev-trunk', 'dev-default'), true)) { if (in_array($alias['version'], array('dev-master', 'dev-trunk', 'dev-default'), true)) {
$alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS; $alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS;
} }
@ -457,7 +457,7 @@ class Locker
$locked[] = $spec; $locked[] = $spec;
} }
usort($locked, function ($a, $b) { usort($locked, static function ($a, $b) {
$comparison = strcmp($a['name'], $b['name']); $comparison = strcmp($a['name'], $b['name']);
if (0 !== $comparison) { if (0 !== $comparison) {

View File

@ -305,7 +305,7 @@ class VersionGuesser
// sort local branches first then remote ones // 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 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 // and sort using natural sort so that 1.10 will appear before 1.9
usort($branches, function ($a, $b): int { usort($branches, static function ($a, $b): int {
$aRemote = 0 === strpos($a, 'remotes/'); $aRemote = 0 === strpos($a, 'remotes/');
$bRemote = 0 === strpos($b, 'remotes/'); $bRemote = 0 === strpos($b, 'remotes/');

View File

@ -87,7 +87,7 @@ class VersionSelector
if ($this->platformConstraints && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) { if ($this->platformConstraints && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) {
$platformConstraints = $this->platformConstraints; $platformConstraints = $this->platformConstraints;
$candidates = array_filter($candidates, function ($pkg) use ($platformConstraints, $platformRequirementFilter): bool { $candidates = array_filter($candidates, static function ($pkg) use ($platformConstraints, $platformRequirementFilter): bool {
$reqs = $pkg->getRequires(); $reqs = $pkg->getRequires();
foreach ($reqs as $name => $link) { foreach ($reqs as $name => $link) {

View File

@ -59,7 +59,7 @@ class StrictConfirmationQuestion extends Question
$trueRegex = $this->trueAnswerRegex; $trueRegex = $this->trueAnswerRegex;
$falseRegex = $this->falseAnswerRegex; $falseRegex = $this->falseAnswerRegex;
return function ($answer) use ($default, $trueRegex, $falseRegex) { return static function ($answer) use ($default, $trueRegex, $falseRegex) {
if (is_bool($answer)) { if (is_bool($answer)) {
return $answer; return $answer;
} }
@ -86,7 +86,7 @@ class StrictConfirmationQuestion extends Question
*/ */
private function getDefaultValidator(): callable private function getDefaultValidator(): callable
{ {
return function ($answer): bool { return static function ($answer): bool {
if (!is_bool($answer)) { if (!is_bool($answer)) {
throw new InvalidArgumentException('Please answer yes, y, no, or n.'); throw new InvalidArgumentException('Please answer yes, y, no, or n.');
} }

View File

@ -356,7 +356,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito
* @param list<string> $results * @param list<string> $results
* @return list<string> * @return list<string>
*/ */
function (array $results): array { static function (array $results): array {
return $results; return $results;
} }
; ;
@ -367,7 +367,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito
* @param list<string> $results * @param list<string> $results
* @return list<string> * @return list<string>
*/ */
function (array $results) use ($packageFilterRegex): array { static function (array $results) use ($packageFilterRegex): array {
/** @var list<string> $results */ /** @var list<string> $results */
return Preg::grep($packageFilterRegex, $results); return Preg::grep($packageFilterRegex, $results);
} }
@ -1104,7 +1104,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito
// Disables lazy-provider behavior as with available-packages, but may allow much more compact expression of packages covered by this repository. // 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. // Over-specifying covered packages is safe, but may result in increased traffic to your repository.
if (!empty($data['available-package-patterns'])) { if (!empty($data['available-package-patterns'])) {
$this->availablePackagePatterns = array_map(function ($pattern): string { $this->availablePackagePatterns = array_map(static function ($pattern): string {
return BasePackage::packageNameToRegexp($pattern); return BasePackage::packageNameToRegexp($pattern);
}, $data['available-package-patterns']); }, $data['available-package-patterns']);
$this->hasAvailablePackageList = true; $this->hasAvailablePackageList = true;

View File

@ -42,7 +42,7 @@ class CompositeRepository implements RepositoryInterface
public function getRepoName(): string public function getRepoName(): string
{ {
return 'composite repo ('.implode(', ', array_map(function ($repo): string { return 'composite repo ('.implode(', ', array_map(static function ($repo): string {
return $repo->getRepoName(); return $repo->getRepoName();
}, $this->repositories)).')'; }, $this->repositories)).')';
} }

View File

@ -153,7 +153,7 @@ class FilesystemRepository extends WritableArrayRepository
} }
sort($data['dev-package-names']); sort($data['dev-package-names']);
usort($data['packages'], function ($a, $b): int { usort($data['packages'], static function ($a, $b): int {
return strcmp($a['name'], $b['name']); return strcmp($a['name'], $b['name']);
}); });

View File

@ -251,7 +251,7 @@ class InstalledRepository extends CompositeRepository
public function getRepoName(): string public function getRepoName(): string
{ {
return 'installed repo ('.implode(', ', array_map(function ($repo): string { return 'installed repo ('.implode(', ', array_map(static function ($repo): string {
return $repo->getRepoName(); return $repo->getRepoName();
}, $this->getRepositories())).')'; }, $this->getRepositories())).')';
} }

View File

@ -250,7 +250,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn
} }
// Ensure environment-specific path separators are normalized to URL separators // Ensure environment-specific path separators are normalized to URL separators
return array_map(function ($val): string { return array_map(static function ($val): string {
return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/'); return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/');
}, glob($this->url, $flags)); }, glob($this->url, $flags));
} }

View File

@ -369,7 +369,7 @@ class PlatformRepository extends ArrayRepository
case 'libxml': case 'libxml':
// ext/dom, ext/simplexml, ext/xmlreader and ext/xmlwriter use the same libxml as the ext/libxml // ext/dom, ext/simplexml, ext/xmlreader and ext/xmlwriter use the same libxml as the ext/libxml
$libxmlProvides = array_map(function ($extension): string { $libxmlProvides = array_map(static function ($extension): string {
return $extension . '-libxml'; return $extension . '-libxml';
}, array_intersect($loadedExtensions, array('dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter'))); }, array_intersect($loadedExtensions, array('dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter')));
$this->addLibrary($name, $this->runtime->getConstant('LIBXML_DOTTED_VERSION'), 'libxml library version', array(), $libxmlProvides); $this->addLibrary($name, $this->runtime->getConstant('LIBXML_DOTTED_VERSION'), 'libxml library version', array(), $libxmlProvides);

View File

@ -245,7 +245,7 @@ class GitDriver extends VcsDriver
GitUtil::cleanEnv(); GitUtil::cleanEnv();
try { try {
$gitUtil->runCommand(function ($url): string { $gitUtil->runCommand(static function ($url): string {
return 'git ls-remote --heads -- ' . ProcessExecutor::escape($url); return 'git ls-remote --heads -- ' . ProcessExecutor::escape($url);
}, $url, sys_get_temp_dir()); }, $url, sys_get_temp_dir());
} catch (\RuntimeException $e) { } catch (\RuntimeException $e) {

View File

@ -71,7 +71,7 @@ class HgDriver extends VcsDriver
$fs->removeDirectory($this->repoDir); $fs->removeDirectory($this->repoDir);
$repoDir = $this->repoDir; $repoDir = $this->repoDir;
$command = function ($url) use ($repoDir): string { $command = static function ($url) use ($repoDir): string {
return sprintf('hg clone --noupdate -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); return sprintf('hg clone --noupdate -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir));
}; };

View File

@ -50,7 +50,7 @@ class AuthHelper
} elseif ($storeAuth === 'prompt') { } elseif ($storeAuth === 'prompt') {
$answer = $this->io->askAndValidate( $answer = $this->io->askAndValidate(
'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ', 'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ',
function ($value): string { static function ($value): string {
$input = strtolower(substr(trim($value), 0, 1)); $input = strtolower(substr(trim($value), 0, 1));
if (in_array($input, array('y','n'))) { if (in_array($input, array('y','n'))) {
return $input; return $input;

View File

@ -58,7 +58,7 @@ class ErrorHandler
self::$io->writeError('<warning>Deprecation Notice: '.$message.' in '.$file.':'.$line.'</warning>'); self::$io->writeError('<warning>Deprecation Notice: '.$message.' in '.$file.':'.$line.'</warning>');
if (self::$io->isVerbose()) { if (self::$io->isVerbose()) {
self::$io->writeError('<warning>Stack trace:</warning>'); self::$io->writeError('<warning>Stack trace:</warning>');
self::$io->writeError(array_filter(array_map(function ($a): ?string { self::$io->writeError(array_filter(array_map(static function ($a): ?string {
if (isset($a['line'], $a['file'])) { if (isset($a['line'], $a['file'])) {
return '<warning> '.$a['file'].':'.$a['line'].'</warning>'; return '<warning> '.$a['file'].':'.$a['line'].'</warning>';
} }

View File

@ -603,7 +603,7 @@ class Filesystem
} }
// ensure c: is normalized to C: // ensure c: is normalized to C:
$prefix = Preg::replaceCallback('{(^|://)[a-z]:$}i', function (array $m) { return strtoupper($m[0]); }, $prefix); $prefix = Preg::replaceCallback('{(^|://)[a-z]:$}i', static function (array $m) { return strtoupper($m[0]); }, $prefix);
return $prefix.$absolute.implode('/', $parts); return $prefix.$absolute.implode('/', $parts);
} }

View File

@ -282,7 +282,7 @@ class Git
// update the repo if it is a valid git repository // 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) === '.') { if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') {
try { try {
$commandCallable = function ($url): string { $commandCallable = static function ($url): string {
$sanitizedUrl = Preg::replace('{://([^@]+?):(.+?)@}', '://', $url); $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)); 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));
@ -300,7 +300,7 @@ class Git
// clean up directory and do a fresh clone into it // clean up directory and do a fresh clone into it
$this->filesystem->removeDirectory($dir); $this->filesystem->removeDirectory($dir);
$commandCallable = function ($url) use ($dir): string { $commandCallable = static function ($url) use ($dir): string {
return sprintf('git clone --mirror -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir)); return sprintf('git clone --mirror -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir));
}; };
@ -401,7 +401,7 @@ class Git
if ($isLocalPathRepository) { if ($isLocalPathRepository) {
$this->process->execute('git remote show origin', $output, $dir); $this->process->execute('git remote show origin', $output, $dir);
} else { } else {
$commandCallable = function ($url): string { $commandCallable = static function ($url): string {
$sanitizedUrl = Preg::replace('{://([^@]+?):(.+?)@}', '://', $url); $sanitizedUrl = Preg::replace('{://([^@]+?):(.+?)@}', '://', $url);
return sprintf('git remote set-url origin -- %s && git remote show origin && git remote set-url origin -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($sanitizedUrl)); return sprintf('git remote set-url origin -- %s && git remote show origin && git remote set-url origin -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($sanitizedUrl));

View File

@ -182,7 +182,7 @@ class CurlDownloader
if ($copyTo) { if ($copyTo) {
$errorMessage = ''; $errorMessage = '';
// @phpstan-ignore-next-line // @phpstan-ignore-next-line
set_error_handler(function ($code, $msg) use (&$errorMessage): void { set_error_handler(static function ($code, $msg) use (&$errorMessage): void {
if ($errorMessage) { if ($errorMessage) {
$errorMessage .= "\n"; $errorMessage .= "\n";
} }

View File

@ -214,13 +214,13 @@ class HttpDownloader
$rfs = $this->rfs; $rfs = $this->rfs;
if ($this->canUseCurl($job)) { if ($this->canUseCurl($job)) {
$resolver = function ($resolve, $reject) use (&$job): void { $resolver = static function ($resolve, $reject) use (&$job): void {
$job['status'] = HttpDownloader::STATUS_QUEUED; $job['status'] = HttpDownloader::STATUS_QUEUED;
$job['resolve'] = $resolve; $job['resolve'] = $resolve;
$job['reject'] = $reject; $job['reject'] = $reject;
}; };
} else { } else {
$resolver = function ($resolve, $reject) use (&$job, $rfs): void { $resolver = static function ($resolve, $reject) use (&$job, $rfs): void {
// start job // start job
$url = $job['request']['url']; $url = $job['request']['url'];
$options = $job['request']['options']; $options = $job['request']['options'];
@ -246,7 +246,7 @@ class HttpDownloader
$curl = $this->curl; $curl = $this->curl;
$canceler = function () use (&$job, $curl): void { $canceler = static function () use (&$job, $curl): void {
if ($job['status'] === HttpDownloader::STATUS_QUEUED) { if ($job['status'] === HttpDownloader::STATUS_QUEUED) {
$job['status'] = HttpDownloader::STATUS_ABORTED; $job['status'] = HttpDownloader::STATUS_ABORTED;
} }
@ -428,7 +428,7 @@ class HttpDownloader
*/ */
public static function outputWarnings(IOInterface $io, string $url, $data): void public static function outputWarnings(IOInterface $io, string $url, $data): void
{ {
$cleanMessage = function ($msg) use ($io) { $cleanMessage = static function ($msg) use ($io) {
if (!$io->isDecorated()) { if (!$io->isDecorated()) {
$msg = Preg::replace('{'.chr(27).'\\[[;\d]*m}u', '', $msg); $msg = Preg::replace('{'.chr(27).'\\[[;\d]*m}u', '', $msg);
} }

View File

@ -68,9 +68,9 @@ class Loop
$uncaught = null; $uncaught = null;
\React\Promise\all($promises)->then( \React\Promise\all($promises)->then(
function (): void { static function (): void {
}, },
function ($e) use (&$uncaught): void { static function ($e) use (&$uncaught): void {
$uncaught = $e; $uncaught = $e;
} }
); );

View File

@ -42,7 +42,7 @@ class PackageSorter
} }
$computing = array(); $computing = array();
$computed = array(); $computed = array();
$computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList, $weights) { $computeImportance = static function ($name) use (&$computeImportance, &$computing, &$computed, $usageList, $weights) {
// reusing computed importance // reusing computed importance
if (isset($computed[$name])) { if (isset($computed[$name])) {
return $computed[$name]; return $computed[$name];
@ -76,7 +76,7 @@ class PackageSorter
$weightedPackages[] = array('name' => $name, 'weight' => $weight, 'index' => $index); $weightedPackages[] = array('name' => $name, 'weight' => $weight, 'index' => $index);
} }
usort($weightedPackages, function (array $a, array $b): int { usort($weightedPackages, static function (array $a, array $b): int {
if ($a['weight'] !== $b['weight']) { if ($a['weight'] !== $b['weight']) {
return $a['weight'] - $b['weight']; return $a['weight'] - $b['weight'];
} }

View File

@ -108,7 +108,7 @@ class Platform
return self::getUserDirectory() . substr($path, 1); return self::getUserDirectory() . substr($path, 1);
} }
return Preg::replaceCallback('#^(\$|(?P<percent>%))(?P<var>\w++)(?(percent)%)(?P<path>.*)#', function ($matches): string { return Preg::replaceCallback('#^(\$|(?P<percent>%))(?P<var>\w++)(?(percent)%)(?P<path>.*)#', static function ($matches): string {
// Treat HOME as an alias for USERPROFILE on Windows for legacy reasons // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons
if (Platform::isWindows() && $matches['var'] == 'HOME') { if (Platform::isWindows() && $matches['var'] == 'HOME') {
return (Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE')) . $matches['path']; return (Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE')) . $matches['path'];

View File

@ -156,13 +156,13 @@ class ProcessExecutor
'cwd' => $cwd, 'cwd' => $cwd,
); );
$resolver = function ($resolve, $reject) use (&$job): void { $resolver = static function ($resolve, $reject) use (&$job): void {
$job['status'] = ProcessExecutor::STATUS_QUEUED; $job['status'] = ProcessExecutor::STATUS_QUEUED;
$job['resolve'] = $resolve; $job['resolve'] = $resolve;
$job['reject'] = $reject; $job['reject'] = $reject;
}; };
$canceler = function () use (&$job): void { $canceler = static function () use (&$job): void {
if ($job['status'] === ProcessExecutor::STATUS_QUEUED) { if ($job['status'] === ProcessExecutor::STATUS_QUEUED) {
$job['status'] = ProcessExecutor::STATUS_ABORTED; $job['status'] = ProcessExecutor::STATUS_ABORTED;
} }
@ -412,7 +412,7 @@ class ProcessExecutor
} }
$commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command)); $commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command));
$safeCommand = Preg::replaceCallback('{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i', function ($m): string { $safeCommand = Preg::replaceCallback('{://(?P<user>[^:/\s]+):(?P<password>[^@\s/]+)@}i', static 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 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'])) { if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) {
return '://***:***@'; return '://***:***@';

View File

@ -290,7 +290,7 @@ class RemoteFilesystem
$errorMessage = ''; $errorMessage = '';
$errorCode = 0; $errorCode = 0;
$result = false; $result = false;
set_error_handler(function ($code, $msg) use (&$errorMessage): bool { set_error_handler(static function ($code, $msg) use (&$errorMessage): bool {
if ($errorMessage) { if ($errorMessage) {
$errorMessage .= "\n"; $errorMessage .= "\n";
} }
@ -445,7 +445,7 @@ class RemoteFilesystem
} }
$errorMessage = ''; $errorMessage = '';
set_error_handler(function ($code, $msg) use (&$errorMessage): bool { set_error_handler(static function ($code, $msg) use (&$errorMessage): bool {
if ($errorMessage) { if ($errorMessage) {
$errorMessage .= "\n"; $errorMessage .= "\n";
} }

View File

@ -245,7 +245,7 @@ final class StreamContextFactory
if (!is_array($header)) { if (!is_array($header)) {
$header = explode("\r\n", $header); $header = explode("\r\n", $header);
} }
uasort($header, function ($el): int { uasort($header, static function ($el): int {
return stripos($el, 'content-type') === 0 ? 1 : -1; return stripos($el, 'content-type') === 0 ? 1 : -1;
}); });

View File

@ -138,7 +138,7 @@ class Svn
$output = null; $output = null;
$io = $this->io; $io = $this->io;
$handler = function ($type, $buffer) use (&$output, $io, $verbose) { $handler = static function ($type, $buffer) use (&$output, $io, $verbose) {
if ($type !== 'out') { if ($type !== 'out') {
return null; return null;
} }

View File

@ -78,7 +78,7 @@ final class TlsHelper
if (isset($info['extensions']['subjectAltName'])) { if (isset($info['extensions']['subjectAltName'])) {
$subjectAltNames = Preg::split('{\s*,\s*}', $info['extensions']['subjectAltName']); $subjectAltNames = Preg::split('{\s*,\s*}', $info['extensions']['subjectAltName']);
$subjectAltNames = array_filter(array_map(function ($name): ?string { $subjectAltNames = array_filter(array_map(static function ($name): ?string {
if (0 === strpos($name, 'DNS:')) { if (0 === strpos($name, 'DNS:')) {
return strtolower(ltrim(substr($name, 4))); return strtolower(ltrim(substr($name, 4)));
} }
@ -179,7 +179,7 @@ final class TlsHelper
if (0 === $wildcards) { if (0 === $wildcards) {
// Literal match. // Literal match.
return function ($hostname) use ($certName): bool { return static function ($hostname) use ($certName): bool {
return $hostname === $certName; return $hostname === $certName;
}; };
} }
@ -203,7 +203,7 @@ final class TlsHelper
$wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex);
$wildcardRegex = "{^{$wildcardRegex}$}"; $wildcardRegex = "{^{$wildcardRegex}$}";
return function ($hostname) use ($wildcardRegex): bool { return static function ($hostname) use ($wildcardRegex): bool {
return Preg::isMatch($wildcardRegex, $hostname); return Preg::isMatch($wildcardRegex, $hostname);
}; };
} }

View File

@ -113,7 +113,7 @@ class Url
// e.g. https://api.github.com/repositories/9999999999?access_token=github_token // e.g. https://api.github.com/repositories/9999999999?access_token=github_token
$url = Preg::replace('{([&?]access_token=)[^&]+}', '$1***', $url); $url = Preg::replace('{([&?]access_token=)[^&]+}', '$1***', $url);
$url = Preg::replaceCallback('{^(?P<prefix>[a-z0-9]+://)?(?P<user>[^:/\s@]+):(?P<password>[^@\s/]+)@}i', function ($m): string { $url = Preg::replaceCallback('{^(?P<prefix>[a-z0-9]+://)?(?P<user>[^:/\s@]+):(?P<password>[^@\s/]+)@}i', static 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 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'])) { if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) {
return $m['prefix'].'***:***@'; return $m['prefix'].'***:***@';