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();
if ($rootPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
$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);
}, array_keys($mainAutoload['psr-0'])));
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
@ -543,7 +543,7 @@ EOF;
{
$rootPackageMap = array_shift($packageMap);
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);
});
} elseif ($filteredDevPackages) {
@ -797,7 +797,7 @@ EOF;
ksort($requiredExtensions);
$formatToPhpVersionId = function (Bound $bound): int {
$formatToPhpVersionId = static function (Bound $bound): int {
if ($bound->isZero()) {
return 0;
}
@ -812,7 +812,7 @@ EOF;
return $chunks[0] * 10000 + $chunks[1] * 100 + $chunks[2];
};
$formatToHumanReadable = function (Bound $bound) {
$formatToHumanReadable = static function (Bound $bound) {
if ($bound->isZero()) {
return 0;
}
@ -1224,7 +1224,7 @@ INITIALIZER;
$updir = null;
$path = Preg::replaceCallback(
'{^((?:(?:\\\\\\.){1,2}+/)+)}',
function ($matches) use (&$updir): string {
static function ($matches) use (&$updir): string {
if (isset($matches[1])) {
// undo preg_quote for the matched string
$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) {
$target = $link->getTarget();
if (isset($replacedBy[$target])) {
@ -1316,7 +1316,7 @@ INITIALIZER;
return array_filter(
$packageMap,
function ($item) use ($include): bool {
static function ($item) use ($include): bool {
$package = $item[0];
foreach ($package->getNames() as $name) {
if (isset($include[$name])) {

View File

@ -173,7 +173,7 @@ EOT
if (count($packages) > 1) {
$package = reset($packages);
$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();
}, $packages)).'.');
$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);
if ($inverted) {
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();
}, $package->getReplaces()));
}

View File

@ -105,7 +105,7 @@ trait CompletionTrait
$installedRepo = new InstalledRepository($installedRepos);
return array_merge(
array_map(function (PackageInterface $package) {
array_map(static function (PackageInterface $package) {
return $package->getName();
}, $installedRepo->getPackages()),
$platformHint
@ -142,12 +142,12 @@ trait CompletionTrait
$results = array_column($results, 'name');
if ($showVendors) {
$results = array_map(function (string $name): string {
$results = array_map(static function (string $name): string {
return $name.'/';
}, $results);
// 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);
$lenB = \strlen($b);
if ($lenA === $lenB) {
@ -199,9 +199,9 @@ trait CompletionTrait
$repos = new PlatformRepository([], $this->requireComposer()->getConfig()->get('platform'));
$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();
}, $repos->getPackages()), function (string $name) use ($pattern): bool {
}, $repos->getPackages()), static function (string $name) use ($pattern): bool {
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
$booleanValidator = function ($val): bool {
$booleanValidator = static function ($val): bool {
return in_array($val, array('true', 'false', '1', '0'), true);
};
$booleanNormalizer = function ($val): bool {
$booleanNormalizer = static function ($val): bool {
return $val !== 'false' && (bool) $val;
};
@ -333,26 +333,26 @@ EOT
'use-include-path' => array($booleanValidator, $booleanNormalizer),
'use-github-api' => array($booleanValidator, $booleanNormalizer),
'preferred-install' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('auto', 'source', 'dist'), true);
},
function ($val) {
static function ($val) {
return $val;
},
),
'gitlab-protocol' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('git', 'http', 'https'), true);
},
function ($val) {
static function ($val) {
return $val;
},
),
'store-auths' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true);
},
function ($val) {
static function ($val) {
if ('prompt' === $val) {
return 'prompt';
}
@ -361,56 +361,56 @@ EOT
},
),
'notify-on-install' => array($booleanValidator, $booleanNormalizer),
'vendor-dir' => array('is_string', function ($val) {
'vendor-dir' => array('is_string', static function ($val) {
return $val;
}),
'bin-dir' => array('is_string', function ($val) {
'bin-dir' => array('is_string', static function ($val) {
return $val;
}),
'archive-dir' => array('is_string', function ($val) {
'archive-dir' => array('is_string', static function ($val) {
return $val;
}),
'archive-format' => array('is_string', function ($val) {
'archive-format' => array('is_string', static function ($val) {
return $val;
}),
'data-dir' => array('is_string', function ($val) {
'data-dir' => array('is_string', static function ($val) {
return $val;
}),
'cache-dir' => array('is_string', function ($val) {
'cache-dir' => array('is_string', static function ($val) {
return $val;
}),
'cache-files-dir' => array('is_string', function ($val) {
'cache-files-dir' => array('is_string', static function ($val) {
return $val;
}),
'cache-repo-dir' => array('is_string', function ($val) {
'cache-repo-dir' => array('is_string', static function ($val) {
return $val;
}),
'cache-vcs-dir' => array('is_string', function ($val) {
'cache-vcs-dir' => array('is_string', static function ($val) {
return $val;
}),
'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'),
'cache-files-maxsize' => array(
function ($val): bool {
static function ($val): bool {
return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val);
},
function ($val) {
static function ($val) {
return $val;
},
),
'bin-compat' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('auto', 'full', 'symlink'));
},
function ($val) {
static function ($val) {
return $val;
},
),
'discard-changes' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('stash', 'true', 'false', '1', '0'), true);
},
function ($val) {
static function ($val) {
if ('stash' === $val) {
return 'stash';
}
@ -418,7 +418,7 @@ EOT
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;
}),
'sort-packages' => array($booleanValidator, $booleanNormalizer),
@ -429,18 +429,18 @@ EOT
'disable-tls' => array($booleanValidator, $booleanNormalizer),
'secure-http' => array($booleanValidator, $booleanNormalizer),
'cafile' => array(
function ($val): bool {
static function ($val): bool {
return file_exists($val) && Filesystem::isReadable($val);
},
function ($val) {
static function ($val) {
return $val === 'null' ? null : $val;
},
),
'capath' => array(
function ($val): bool {
static function ($val): bool {
return is_dir($val) && Filesystem::isReadable($val);
},
function ($val) {
static function ($val) {
return $val === 'null' ? null : $val;
},
),
@ -449,10 +449,10 @@ EOT
'lock' => array($booleanValidator, $booleanNormalizer),
'allow-plugins' => array($booleanValidator, $booleanNormalizer),
'platform-check' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('php-only', 'true', 'false', '1', '0'), true);
},
function ($val) {
static function ($val) {
if ('php-only' === $val) {
return 'php-only';
}
@ -461,10 +461,10 @@ EOT
},
),
'use-parent-dir' => array(
function ($val): bool {
static function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true);
},
function ($val) {
static function ($val) {
if ('prompt' === $val) {
return 'prompt';
}
@ -475,7 +475,7 @@ EOT
);
$multiConfigValues = array(
'github-protocols' => array(
function ($vals) {
static function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
@ -488,31 +488,31 @@ EOT
return true;
},
function ($vals) {
static function ($vals) {
return $vals;
},
),
'github-domains' => array(
function ($vals) {
static function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
static function ($vals) {
return $vals;
},
),
'gitlab-domains' => array(
function ($vals) {
static function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
static function ($vals) {
return $vals;
},
),
@ -579,26 +579,26 @@ EOT
// handle properties
$uniqueProps = array(
'name' => array('is_string', function ($val) {
'name' => array('is_string', static function ($val) {
return $val;
}),
'type' => array('is_string', function ($val) {
'type' => array('is_string', static function ($val) {
return $val;
}),
'description' => array('is_string', function ($val) {
'description' => array('is_string', static function ($val) {
return $val;
}),
'homepage' => array('is_string', function ($val) {
'homepage' => array('is_string', static function ($val) {
return $val;
}),
'version' => array('is_string', function ($val) {
'version' => array('is_string', static function ($val) {
return $val;
}),
'minimum-stability' => array(
function ($val): bool {
static function ($val): bool {
return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]);
},
function ($val): string {
static function ($val): string {
return VersionParser::normalizeStability($val);
},
),
@ -606,26 +606,26 @@ EOT
);
$multiProps = array(
'keywords' => array(
function ($vals) {
static function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
static function ($vals) {
return $vals;
},
),
'license' => array(
function ($vals) {
static function ($vals) {
if (!is_array($vals)) {
return 'array expected';
}
return true;
},
function ($vals) {
static function ($vals) {
return $vals;
},
),
@ -897,7 +897,7 @@ EOT
}
if (is_array($value)) {
$value = array_map(function ($val) {
$value = array_map(static function ($val) {
return is_array($val) ? json_encode($val) : $val;
}, $value);

View File

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

View File

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

View File

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

View File

@ -33,7 +33,7 @@ class GlobalCommand extends BaseCommand
{
$application = $this->getApplication();
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();
}, $application->all())));

View File

@ -293,7 +293,7 @@ EOT
$name = $io->askAndValidate(
'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ',
function ($value) use ($name) {
static function ($value) use ($name) {
if (null === $value) {
return $name;
}
@ -359,7 +359,7 @@ EOT
$minimumStability = $input->getOption('stability') ?: null;
$minimumStability = $io->askAndValidate(
'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ',
function ($value) use ($minimumStability) {
static function ($value) use ($minimumStability) {
if (null === $value) {
return $minimumStability;
}
@ -433,7 +433,7 @@ EOT
$namespace = $this->namespaceFromPackageName((string) $input->getOption('name'));
$autoload = $io->askAndValidate(
'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) {
return $autoload;
}
@ -514,7 +514,7 @@ EOT
}
$namespace = array_map(
function ($part): string {
static function ($part): string {
$part = Preg::replace('/[^a-z0-9]/i', ' ', $part);
$part = ucwords($part);

View File

@ -167,7 +167,7 @@ EOT
$packageListNames = array_keys($bucket);
$packages = array_filter(
$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);
}
);

View File

@ -186,7 +186,7 @@ trait PackageDiscoveryTrait
$io->writeError($choices);
$io->writeError('');
$validator = function (string $selection) use ($matches, $versionParser) {
$validator = static function (string $selection) use ($matches, $versionParser) {
if ('' === $selection) {
return false;
}
@ -224,7 +224,7 @@ trait PackageDiscoveryTrait
// no constraint yet, determine the best version automatically
if (false !== $package && false === strpos($package, ' ')) {
$validator = function (string $input) {
$validator = static function (string $input) {
$input = trim($input);
return strlen($input) > 0 ? $input : false;
@ -296,7 +296,7 @@ trait PackageDiscoveryTrait
if (count($providers) > 0) {
$constraint = '*';
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->parseConstraints($value);

View File

@ -125,7 +125,7 @@ EOT
$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()];
});

View File

@ -118,7 +118,7 @@ EOT
if (count($input->getArgument('packages')) === 0) {
$this->getIO()->writeError('<info>No unused packages to remove</info>');
$this->setCode(function (): int {
$this->setCode(static function (): int {
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');
$validator = function ($value): string {
$validator = static function ($value): string {
if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) {
throw new \UnexpectedValueException('Invalid input');
}

View File

@ -249,7 +249,7 @@ EOT
if ($input->getOption('no-dev')) {
$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;
}, $packages))));
}
@ -346,7 +346,7 @@ EOT
if ($input->getOption('tree')) {
$rootRequires = $this->getRootRequires();
$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);
});
$arrayTree = array();
@ -1011,7 +1011,7 @@ EOT
if ($licenses = $package->getLicense()) {
$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
if (!$license) {

View File

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

View File

@ -132,7 +132,7 @@ EOT
// extract --with shorthands from the allowlist
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);
});
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
// 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);
});
$updateMirrors = $input->getOption('lock') || count($filteredPackages) != count($packages);

View File

@ -196,13 +196,13 @@ EOT
}
if ($errors) {
$errors = array_map(function ($err): string {
$errors = array_map(static function ($err): string {
return '- ' . $err;
}, $errors);
array_unshift($errors, '# General errors');
}
if ($warnings) {
$warnings = array_map(function ($err): string {
$warnings = array_map(static function ($err): string {
return '- ' . $err;
}, $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 ($publishErrors) {
$publishErrors = array_map(function ($err): string {
$publishErrors = array_map(static function ($err): string {
return '- ' . $err;
}, $publishErrors);

View File

@ -82,7 +82,7 @@ class Compiler
$phar->startBuffering();
$finderSort = function ($a, $b): int {
$finderSort = static function ($a, $b): int {
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
{
$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
// to convert it to "packagist.org": false key on the hashmap otherwise it fails schema validation
if (isset($config['repositories'])) {
@ -91,7 +91,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
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]);
}, $name);
}
@ -102,7 +102,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function addConfigSetting(string $name, $value): void
{
$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)) {
list($key, $host) = explode('.', $key, 2);
if ($authConfig) {
@ -122,7 +122,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function removeConfigSetting(string $name): void
{
$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)) {
list($key, $host) = explode('.', $key, 2);
if ($authConfig) {
@ -141,7 +141,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
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) {
$bits = explode('.', $key);
$last = array_pop($bits);
@ -164,7 +164,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
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) {
$bits = explode('.', $key);
$last = array_pop($bits);
@ -187,7 +187,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
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;
}, $type, $name, $value);
}
@ -197,10 +197,10 @@ class JsonConfigSource implements ConfigSourceInterface
*/
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]);
}, $type, $name);
$this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type): void {
$this->manipulateJson('removeMainKeyIfEmpty', static function (&$config, $type): void {
if (0 === count($config[$type])) {
unset($config[$type]);
}

View File

@ -96,14 +96,14 @@ class Application extends BaseApplication
if (!$shutdownRegistered) {
if (function_exists('pcntl_async_signals') && function_exists('pcntl_signal')) {
pcntl_async_signals(true);
pcntl_signal(SIGINT, function ($sig): void {
pcntl_signal(SIGINT, static function ($sig): void {
exit(130);
});
}
$shutdownRegistered = true;
register_shutdown_function(function (): void {
register_shutdown_function(static function (): void {
$lastError = error_get_last();
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
Silencer::call(function () use ($io): void {
Silencer::call(static function () use ($io): void {
$tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime());
if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) {
$io->writeError(sprintf('<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']);
});

View File

@ -532,7 +532,7 @@ class PoolBuilder
$matches = array();
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()) {
return $package->getName() .' (via replace of '.$name.')';
}

View File

@ -286,7 +286,7 @@ class Problem
if ($packages = $repositorySet->findPackages($packageName, $constraint)) {
$rootReqs = $repositorySet->getRootRequires();
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()));
});
if (0 === count($filtered)) {
@ -296,7 +296,7 @@ class Problem
$tempReqs = $repositorySet->getTemporaryConstraints();
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()));
});
if (0 === count($filtered)) {
@ -306,7 +306,7 @@ class Problem
if ($lockedPackage) {
$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()));
});
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;
});
@ -370,7 +370,7 @@ class Problem
if ($providers = $repositorySet->getProviders($packageName)) {
$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) : '';
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() : '');
}
$packagesNonAlias = array_values(array_filter($packages, function ($p): bool {
$packagesNonAlias = array_values(array_filter($packages, static function ($p): bool {
return !($p instanceof AliasPackage);
}));
if (count($packagesNonAlias) === 1) {

View File

@ -110,7 +110,7 @@ class RuleWatchGraph
if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) {
$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 &&
$otherWatch !== $ruleLiteral &&
!$decisions->conflict($ruleLiteral);

View File

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

View File

@ -71,7 +71,7 @@ class Transaction
*/
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
if ($a->getName() == $b->getName()) {
if ($a instanceof AliasPackage != $b instanceof AliasPackage) {
@ -289,7 +289,7 @@ class Transaction
// is this a downloads modifying plugin or a dependency of one?
if ($isDownloadsModifyingPlugin || count(array_intersect($package->getNames(), $dlModifyingPluginRequires))) {
// get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), function ($req): bool {
$requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req);
});
@ -314,7 +314,7 @@ class Transaction
// is this a plugin or a dependency of a plugin?
if ($isPlugin || count(array_intersect($package->getNames(), $pluginRequires))) {
// get the package's requires, but filter out any platform requirements
$requires = array_filter(array_keys($package->getRequires()), function ($req): bool {
$requires = array_filter(array_keys($package->getRequires()), static function ($req): bool {
return !PlatformRepository::isPlatformPackage($req);
});

View File

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

View File

@ -205,7 +205,7 @@ class DownloadManager
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 (!$sources) {
throw $e;
@ -230,7 +230,7 @@ class DownloadManager
return $handleError($e);
}
$res = $result->then(function ($res) {
$res = $result->then(static function ($res) {
return $res;
}, $handleError);
@ -426,7 +426,7 @@ class DownloadManager
&& !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev())
) {
$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;
});

View File

@ -117,7 +117,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
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);
return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
@ -194,7 +194,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
->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,
// once with $result being the returned $fileName from $accept, and then once for every
// failed request with a null result, which can be skipped.
@ -420,7 +420,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
}
$promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(function ($result) use ($path): void {
return $promise->then(static function ($result) use ($path): void {
if (!$result) {
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);
$commandCallable = function (string $url) use ($path, $command, $cachePath): string {
$commandCallable = static function (string $url) use ($path, $command, $cachePath): string {
return str_replace(
array('%url%', '%path%', '%cachePath%', '%sanitizedUrl%'),
array(
@ -172,7 +172,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
$this->io->writeError($msg);
$commandCallable = function ($url) use ($ref, $command, $cachePath): string {
$commandCallable = static function ($url) use ($ref, $command, $cachePath): string {
return str_replace(
array('%url%', '%ref%', '%cachePath%', '%sanitizedUrl%'),
array(
@ -360,7 +360,7 @@ class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
return parent::cleanChanges($package, $path, $update);
}
$changes = array_map(function ($elem): string {
$changes = array_map(static function ($elem): string {
return ' '.$elem;
}, Preg::split('{\s*\r?\n\s*}', $changes));
$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);
$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));
};
@ -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');
}
$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));
};

View File

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

View File

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

View File

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

View File

@ -56,7 +56,7 @@ class BufferIO extends ConsoleIO
$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]);
if (strlen($pre) === strlen($matches[2])) {

View File

@ -175,7 +175,7 @@ class ConsoleIO extends BaseIO
if (null !== $this->startTime) {
$memoryUsage = memory_get_usage() / 1024 / 1024;
$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);
}, (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) {
$a = $a->getTargetPackage()->getName();
} else {

View File

@ -199,18 +199,18 @@ class InstallationManager
$loop = $this->loop;
$io = $this->io;
$runCleanup = function () use (&$cleanupPromises, $loop): void {
$runCleanup = static function () use (&$cleanupPromises, $loop): void {
$promises = array();
$loop->abortJobs();
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();
if (!$promise instanceof PromiseInterface) {
$resolve();
} else {
$promise->then(function () use ($resolve): void {
$promise->then(static function () use ($resolve): void {
$resolve();
});
}
@ -229,7 +229,7 @@ class InstallationManager
if ($handleInterruptsUnix) {
pcntl_async_signals(true);
$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);
$runCleanup();
@ -241,7 +241,7 @@ class InstallationManager
});
}
if ($handleInterruptsWindows) {
$windowsHandler = function ($event) use ($runCleanup, $io): void {
$windowsHandler = static function ($event) use ($runCleanup, $io): void {
if ($event !== PHP_WINDOWS_EVENT_CTRL_C) {
return;
}
@ -339,7 +339,7 @@ class InstallationManager
}
$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
// as without installation source configured nothing will work
if (!$package->getInstallationSource()) {
@ -453,7 +453,7 @@ class InstallationManager
})->then($cleanupPromises[$index])
->then(function () use ($devMode, $repo): void {
$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>');
throw $e;
@ -466,7 +466,7 @@ class InstallationManager
][$opType] ?? null;
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);
};
}
@ -558,7 +558,7 @@ class InstallationManager
}
$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);
if ($promise instanceof PromiseInterface) {
return $promise;

View File

@ -160,7 +160,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller;
$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);
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
@ -188,7 +188,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller;
$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);
$repo->removePackage($initial);
if (!$repo->hasPackage($target)) {
@ -215,7 +215,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$downloadPath = $this->getPackageBasePath($package);
$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);
$repo->removePackage($package);

View File

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

View File

@ -70,7 +70,7 @@ class JsonFormatter
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
$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]);
if ($l % 2) {

View File

@ -94,7 +94,7 @@ class JsonManipulator
// update existing link
$existingPackage = $packageMatches['package'];
$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 . '"';
}, $links);
} else {
@ -135,7 +135,7 @@ class JsonManipulator
*/
private function sortPackages(array &$packages = array()): void
{
$prefix = function ($requirement): string {
$prefix = static function ($requirement): string {
if (PlatformRepository::isPlatformPackage($requirement)) {
return Preg::replace(
array(
@ -159,7 +159,7 @@ class JsonManipulator
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));
});
}
@ -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'];
}, $this->contents);
@ -437,7 +437,7 @@ class JsonManipulator
$newline = $this->newline;
$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'];
}, $this->contents);

View File

@ -163,7 +163,7 @@ final class ConfigReturnTypeExtension implements DynamicMethodReturnTypeExtensio
$type = TypeCombinator::union(...$types);
} 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);
}, $def['enum']));
} else {

View File

@ -57,7 +57,7 @@ class ArchivableFilesFinder extends \FilterIterator
$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)) {
return false;
}

View File

@ -101,7 +101,7 @@ class ArchiveManager
$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);
}));

View File

@ -84,7 +84,7 @@ abstract class BaseExcludeFilter
{
return array_filter(
array_map(
function ($line) use ($lineParser) {
static function ($line) use ($lineParser) {
$line = trim($line);
if (!$line || 0 === strpos($line, '#')) {
@ -95,7 +95,7 @@ abstract class BaseExcludeFilter
},
$lines
),
function ($pattern): bool {
static function ($pattern): bool {
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
{
$packageNames = array_map(
function ($packageName): string {
static function ($packageName): string {
return BasePackage::packageNameToRegexp($packageName, '%s');
},
$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
// 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)) {
$alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS;
}
@ -457,7 +457,7 @@ class Locker
$locked[] = $spec;
}
usort($locked, function ($a, $b) {
usort($locked, static function ($a, $b) {
$comparison = strcmp($a['name'], $b['name']);
if (0 !== $comparison) {

View File

@ -305,7 +305,7 @@ class VersionGuesser
// sort local branches first then remote ones
// and sort numeric branches below named ones, to make sure if the branch has the same distance from main and 1.10 and 1.9 for example, main is picked
// and sort using natural sort so that 1.10 will appear before 1.9
usort($branches, function ($a, $b): int {
usort($branches, static function ($a, $b): int {
$aRemote = 0 === strpos($a, 'remotes/');
$bRemote = 0 === strpos($b, 'remotes/');

View File

@ -87,7 +87,7 @@ class VersionSelector
if ($this->platformConstraints && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) {
$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();
foreach ($reqs as $name => $link) {

View File

@ -59,7 +59,7 @@ class StrictConfirmationQuestion extends Question
$trueRegex = $this->trueAnswerRegex;
$falseRegex = $this->falseAnswerRegex;
return function ($answer) use ($default, $trueRegex, $falseRegex) {
return static function ($answer) use ($default, $trueRegex, $falseRegex) {
if (is_bool($answer)) {
return $answer;
}
@ -86,7 +86,7 @@ class StrictConfirmationQuestion extends Question
*/
private function getDefaultValidator(): callable
{
return function ($answer): bool {
return static function ($answer): bool {
if (!is_bool($answer)) {
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
* @return list<string>
*/
function (array $results): array {
static function (array $results): array {
return $results;
}
;
@ -367,7 +367,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito
* @param list<string> $results
* @return list<string>
*/
function (array $results) use ($packageFilterRegex): array {
static function (array $results) use ($packageFilterRegex): array {
/** @var list<string> $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.
// Over-specifying covered packages is safe, but may result in increased traffic to your repository.
if (!empty($data['available-package-patterns'])) {
$this->availablePackagePatterns = array_map(function ($pattern): string {
$this->availablePackagePatterns = array_map(static function ($pattern): string {
return BasePackage::packageNameToRegexp($pattern);
}, $data['available-package-patterns']);
$this->hasAvailablePackageList = true;

View File

@ -42,7 +42,7 @@ class CompositeRepository implements RepositoryInterface
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();
}, $this->repositories)).')';
}

View File

@ -153,7 +153,7 @@ class FilesystemRepository extends WritableArrayRepository
}
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']);
});

View File

@ -251,7 +251,7 @@ class InstalledRepository extends CompositeRepository
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();
}, $this->getRepositories())).')';
}

View File

@ -250,7 +250,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn
}
// 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), '/');
}, glob($this->url, $flags));
}

View File

@ -369,7 +369,7 @@ class PlatformRepository extends ArrayRepository
case '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';
}, array_intersect($loadedExtensions, array('dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter')));
$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();
try {
$gitUtil->runCommand(function ($url): string {
$gitUtil->runCommand(static function ($url): string {
return 'git ls-remote --heads -- ' . ProcessExecutor::escape($url);
}, $url, sys_get_temp_dir());
} catch (\RuntimeException $e) {

View File

@ -71,7 +71,7 @@ class HgDriver extends VcsDriver
$fs->removeDirectory($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));
};

View File

@ -50,7 +50,7 @@ class AuthHelper
} elseif ($storeAuth === 'prompt') {
$answer = $this->io->askAndValidate(
'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));
if (in_array($input, array('y','n'))) {
return $input;

View File

@ -58,7 +58,7 @@ class ErrorHandler
self::$io->writeError('<warning>Deprecation Notice: '.$message.' in '.$file.':'.$line.'</warning>');
if (self::$io->isVerbose()) {
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'])) {
return '<warning> '.$a['file'].':'.$a['line'].'</warning>';
}

View File

@ -603,7 +603,7 @@ class Filesystem
}
// 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);
}

View File

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

View File

@ -182,7 +182,7 @@ class CurlDownloader
if ($copyTo) {
$errorMessage = '';
// @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) {
$errorMessage .= "\n";
}

View File

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

View File

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

View File

@ -42,7 +42,7 @@ class PackageSorter
}
$computing = 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
if (isset($computed[$name])) {
return $computed[$name];
@ -76,7 +76,7 @@ class PackageSorter
$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']) {
return $a['weight'] - $b['weight'];
}

View File

@ -108,7 +108,7 @@ class Platform
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
if (Platform::isWindows() && $matches['var'] == 'HOME') {
return (Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE')) . $matches['path'];

View File

@ -156,13 +156,13 @@ class ProcessExecutor
'cwd' => $cwd,
);
$resolver = function ($resolve, $reject) use (&$job): void {
$resolver = static function ($resolve, $reject) use (&$job): void {
$job['status'] = ProcessExecutor::STATUS_QUEUED;
$job['resolve'] = $resolve;
$job['reject'] = $reject;
};
$canceler = function () use (&$job): void {
$canceler = static function () use (&$job): void {
if ($job['status'] === ProcessExecutor::STATUS_QUEUED) {
$job['status'] = ProcessExecutor::STATUS_ABORTED;
}
@ -412,7 +412,7 @@ class ProcessExecutor
}
$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 (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) {
return '://***:***@';

View File

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

View File

@ -245,7 +245,7 @@ final class StreamContextFactory
if (!is_array($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;
});

View File

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

View File

@ -78,7 +78,7 @@ final class TlsHelper
if (isset($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:')) {
return strtolower(ltrim(substr($name, 4)));
}
@ -179,7 +179,7 @@ final class TlsHelper
if (0 === $wildcards) {
// Literal match.
return function ($hostname) use ($certName): bool {
return static function ($hostname) use ($certName): bool {
return $hostname === $certName;
};
}
@ -203,7 +203,7 @@ final class TlsHelper
$wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex);
$wildcardRegex = "{^{$wildcardRegex}$}";
return function ($hostname) use ($wildcardRegex): bool {
return static function ($hostname) use ($wildcardRegex): bool {
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
$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 (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) {
return $m['prefix'].'***:***@';