1
0
Fork 0

Merge pull request #10547 from Seldaek/add_returns

Add native return types where possible
pull/10565/head
Jordi Boggiano 2022-02-21 13:57:32 +01:00 committed by GitHub
commit c9baeda95b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
325 changed files with 2669 additions and 2719 deletions

View File

@ -71,7 +71,6 @@ return $config->setRules([
'random_api_migration' => true,
'ternary_to_null_coalescing' => true,
//'declare_strict_types' => true,
//'void_return' => true,
])
->setUsingCache(true)
->setRiskyAllowed(true)

View File

@ -31,15 +31,11 @@ parameters:
- '~^Undefined variable: \$vendorDir$~'
- '~^Undefined variable: \$baseDir$~'
# variable defined in eval
- '~^Undefined variable: \$res$~'
# we don't have different constructors for parent/child
- '~^Unsafe usage of new static\(\)\.$~'
# Ignore some irrelevant errors in test files
- '~Method Composer\\Test\\[^:]+::(setUp(BeforeClass)?|tearDown(AfterClass)?|test[^(]+)\(\) has no return type specified.~'
- '~Method Composer\\Test\\[^:]+::(data\w+|provide\w+|\w+?Provider)\(\) has no return type specified.~'
- '~Method Composer\\Test\\[^:]+::(data\w+|provide\w+|\w+?Provider)\(\) (has no return type specified.|return type has no value type specified in iterable type array.)~'
# PHPUnit assertions as instance methods
- '~Dynamic call to static method PHPUnit\\Framework\\Assert::\w+\(\)~'

View File

@ -290,7 +290,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) {
$prefixes = implode(', ', array_map(function ($prefix): string {
return var_export($prefix, true);
}, array_keys($mainAutoload['psr-0'])));
$baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
@ -441,7 +441,7 @@ EOF;
* @param array<string, true> $scannedFiles
* @return array<class-string, string>
*/
private function addClassMapCode(Filesystem $filesystem, $basePath, $vendorPath, $dir, $excluded, $namespaceFilter, $autoloadType, array $classMap, array &$ambiguousClasses, array &$scannedFiles)
private function addClassMapCode(Filesystem $filesystem, $basePath, $vendorPath, $dir, $excluded, $namespaceFilter, $autoloadType, array $classMap, array &$ambiguousClasses, array &$scannedFiles): array
{
foreach ($this->generateClassMap($dir, $excluded, $namespaceFilter, $autoloadType, true, $scannedFiles) as $class => $path) {
$pathCode = $this->getPathCode($filesystem, $basePath, $vendorPath, $path).",\n";
@ -464,7 +464,7 @@ EOF;
* @param array<string, true> $scannedFiles
* @return array<class-string, string>
*/
private function generateClassMap($dir, $excluded, $namespaceFilter, $autoloadType, $showAmbiguousWarning, array &$scannedFiles)
private function generateClassMap($dir, $excluded, $namespaceFilter, $autoloadType, $showAmbiguousWarning, array &$scannedFiles): array
{
if ($excluded) {
// filter excluded patterns here to only use those matching $dir
@ -554,7 +554,7 @@ EOF;
{
$rootPackageMap = array_shift($packageMap);
if (is_array($filteredDevPackages)) {
$packageMap = array_filter($packageMap, function ($item) use ($filteredDevPackages) {
$packageMap = array_filter($packageMap, function ($item) use ($filteredDevPackages): bool {
return !in_array($item[0]->getName(), $filteredDevPackages, true);
});
} elseif ($filteredDevPackages) {
@ -808,7 +808,7 @@ EOF;
ksort($requiredExtensions);
$formatToPhpVersionId = function (Bound $bound) {
$formatToPhpVersionId = function (Bound $bound): int {
if ($bound->isZero()) {
return 0;
}
@ -1229,7 +1229,7 @@ INITIALIZER;
$updir = null;
$path = Preg::replaceCallback(
'{^((?:(?:\\\\\\.){1,2}+/)+)}',
function ($matches) use (&$updir) {
function ($matches) use (&$updir): string {
if (isset($matches[1])) {
// undo preg_quote for the matched string
$updir = str_replace('\\.', '.', $matches[1]);
@ -1300,7 +1300,7 @@ INITIALIZER;
}
}
$add = function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy) {
$add = function (PackageInterface $package) use (&$add, $packages, &$include, $replacedBy): void {
foreach ($package->getRequires() as $link) {
$target = $link->getTarget();
if (isset($replacedBy[$target])) {
@ -1318,7 +1318,7 @@ INITIALIZER;
return array_filter(
$packageMap,
function ($item) use ($include) {
function ($item) use ($include): bool {
$package = $item[0];
foreach ($package->getNames() as $name) {
if (isset($include[$name])) {

View File

@ -38,7 +38,7 @@ class ClassMapGenerator
* @param string $file The name of the class map file
* @return void
*/
public static function dump($dirs, $file)
public static function dump($dirs, $file): void
{
$maps = array();
@ -61,7 +61,7 @@ class ClassMapGenerator
* @return array<class-string, string> A class map array
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path, $excluded = null, IOInterface $io = null, $namespace = null, $autoloadType = null, &$scannedFiles = array())
public static function createMap($path, $excluded = null, IOInterface $io = null, $namespace = null, $autoloadType = null, &$scannedFiles = array()): array
{
$basePath = $path;
if (is_string($path)) {
@ -157,7 +157,7 @@ class ClassMapGenerator
* @param ?IOInterface $io IO object
* @return array<int, class-string> valid classes
*/
private static function filterByNamespace($classes, $filePath, $baseNamespace, $namespaceType, $basePath, $io)
private static function filterByNamespace($classes, $filePath, $baseNamespace, $namespaceType, $basePath, $io): array
{
$validClasses = array();
$rejectedClasses = array();
@ -215,7 +215,7 @@ class ClassMapGenerator
* @throws \RuntimeException
* @return array<int, class-string> The found classes
*/
private static function findClasses($path)
private static function findClasses($path): array
{
$extraTypes = self::getExtraTypes();
@ -296,7 +296,7 @@ class ClassMapGenerator
/**
* @return string
*/
private static function getExtraTypes()
private static function getExtraTypes(): string
{
static $extraTypes = null;

View File

@ -51,7 +51,7 @@ class PhpFileCleaner
* @param string[] $types
* @return void
*/
public static function setTypeConfig($types)
public static function setTypeConfig($types): void
{
foreach ($types as $type) {
self::$typeConfig[$type[0]] = array(
@ -78,7 +78,7 @@ class PhpFileCleaner
/**
* @return string
*/
public function clean()
public function clean(): string
{
$clean = '';
@ -152,7 +152,7 @@ class PhpFileCleaner
/**
* @return void
*/
private function skipToPhp()
private function skipToPhp(): void
{
while ($this->index < $this->len) {
if ($this->contents[$this->index] === '<' && $this->peek('?')) {
@ -168,7 +168,7 @@ class PhpFileCleaner
* @param string $delimiter
* @return void
*/
private function skipString($delimiter)
private function skipString($delimiter): void
{
$this->index += 1;
while ($this->index < $this->len) {
@ -187,7 +187,7 @@ class PhpFileCleaner
/**
* @return void
*/
private function skipComment()
private function skipComment(): void
{
$this->index += 2;
while ($this->index < $this->len) {
@ -203,7 +203,7 @@ class PhpFileCleaner
/**
* @return void
*/
private function skipToNewline()
private function skipToNewline(): void
{
while ($this->index < $this->len) {
if ($this->contents[$this->index] === "\r" || $this->contents[$this->index] === "\n") {
@ -217,7 +217,7 @@ class PhpFileCleaner
* @param string $delimiter
* @return void
*/
private function skipHeredoc($delimiter)
private function skipHeredoc($delimiter): void
{
$firstDelimiterChar = $delimiter[0];
$delimiterLength = \strlen($delimiter);
@ -260,7 +260,7 @@ class PhpFileCleaner
* @param string $char
* @return bool
*/
private function peek($char)
private function peek($char): bool
{
return $this->index + 1 < $this->len && $this->contents[$this->index + 1] === $char;
}
@ -270,7 +270,7 @@ class PhpFileCleaner
* @param ?array<int, string> $match
* @return bool
*/
private function match($regex, array &$match = null)
private function match($regex, array &$match = null): bool
{
return Preg::isMatch($regex, $this->contents, $match, 0, $this->index);
}

View File

@ -24,7 +24,7 @@ class AboutCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('about')

View File

@ -41,7 +41,7 @@ class ArchiveCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('archive')
@ -168,7 +168,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) {
$io->writeError('Alternatives were '.implode(', ', array_map(function ($p): string {
return $p->getPrettyString();
}, $packages)).'.');
$io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');

View File

@ -50,7 +50,7 @@ class BaseDependencyCommand extends BaseCommand
* @param bool $inverted Whether to invert matching process (why-not vs why behaviour)
* @return int Exit code of the operation.
*/
protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false)
protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false): int
{
// Emit command event on startup
$composer = $this->requireComposer();
@ -90,7 +90,7 @@ class BaseDependencyCommand extends BaseCommand
$needles = array($needle);
if ($inverted) {
foreach ($packages as $package) {
$needles = array_merge($needles, array_map(function (Link $link) {
$needles = array_merge($needles, array_map(function (Link $link): string {
return $link->getTarget();
}, $package->getReplaces()));
}
@ -136,7 +136,7 @@ class BaseDependencyCommand extends BaseCommand
*
* @return void
*/
protected function printTable(OutputInterface $output, $results)
protected function printTable(OutputInterface $output, $results): void
{
$table = array();
$doubles = array();
@ -172,7 +172,7 @@ class BaseDependencyCommand extends BaseCommand
*
* @return void
*/
protected function initStyles(OutputInterface $output)
protected function initStyles(OutputInterface $output): void
{
$this->colors = array(
'green',
@ -197,7 +197,7 @@ class BaseDependencyCommand extends BaseCommand
*
* @return void
*/
protected function printTree($results, $prefix = '', $level = 1)
protected function printTree($results, $prefix = '', $level = 1): void
{
$count = count($results);
$idx = 0;
@ -223,7 +223,7 @@ class BaseDependencyCommand extends BaseCommand
*
* @return void
*/
private function writeTreeLine($line)
private function writeTreeLine($line): void
{
$io = $this->getIO();
if (!$io->isDecorated()) {

View File

@ -26,7 +26,7 @@ class CheckPlatformReqsCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this->setName('check-platform-reqs')
->setDescription('Check that platform requirements are satisfied.')
@ -174,7 +174,7 @@ EOT
*
* @return void
*/
protected function printTable(OutputInterface $output, $results)
protected function printTable(OutputInterface $output, $results): void
{
$rows = array();
foreach ($results as $result) {

View File

@ -25,7 +25,7 @@ class ClearCacheCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('clear-cache')

View File

@ -62,7 +62,7 @@ class ConfigCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('config')
@ -154,7 +154,7 @@ EOT
* @return void
* @throws \Exception
*/
protected function initialize(InputInterface $input, OutputInterface $output)
protected function initialize(InputInterface $input, OutputInterface $output): void
{
parent::initialize($input, $output);
@ -318,10 +318,10 @@ EOT
$values = $input->getArgument('setting-value'); // what the user is trying to add/change
$booleanValidator = function ($val) {
$booleanValidator = function ($val): bool {
return in_array($val, array('true', 'false', '1', '0'), true);
};
$booleanNormalizer = function ($val) {
$booleanNormalizer = function ($val): bool {
return $val !== 'false' && (bool) $val;
};
@ -331,7 +331,7 @@ EOT
'use-include-path' => array($booleanValidator, $booleanNormalizer),
'use-github-api' => array($booleanValidator, $booleanNormalizer),
'preferred-install' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('auto', 'source', 'dist'), true);
},
function ($val) {
@ -339,7 +339,7 @@ EOT
},
),
'gitlab-protocol' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('git', 'http', 'https'), true);
},
function ($val) {
@ -347,7 +347,7 @@ EOT
},
),
'store-auths' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true);
},
function ($val) {
@ -389,7 +389,7 @@ EOT
'cache-ttl' => array('is_numeric', 'intval'),
'cache-files-ttl' => array('is_numeric', 'intval'),
'cache-files-maxsize' => array(
function ($val) {
function ($val): bool {
return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val);
},
function ($val) {
@ -397,7 +397,7 @@ EOT
},
),
'bin-compat' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('auto', 'full', 'symlink'));
},
function ($val) {
@ -405,7 +405,7 @@ EOT
},
),
'discard-changes' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('stash', 'true', 'false', '1', '0'), true);
},
function ($val) {
@ -427,7 +427,7 @@ EOT
'disable-tls' => array($booleanValidator, $booleanNormalizer),
'secure-http' => array($booleanValidator, $booleanNormalizer),
'cafile' => array(
function ($val) {
function ($val): bool {
return file_exists($val) && Filesystem::isReadable($val);
},
function ($val) {
@ -435,7 +435,7 @@ EOT
},
),
'capath' => array(
function ($val) {
function ($val): bool {
return is_dir($val) && Filesystem::isReadable($val);
},
function ($val) {
@ -447,7 +447,7 @@ EOT
'lock' => array($booleanValidator, $booleanNormalizer),
'allow-plugins' => array($booleanValidator, $booleanNormalizer),
'platform-check' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('php-only', 'true', 'false', '1', '0'), true);
},
function ($val) {
@ -459,7 +459,7 @@ EOT
},
),
'use-parent-dir' => array(
function ($val) {
function ($val): bool {
return in_array($val, array('true', 'false', 'prompt'), true);
},
function ($val) {
@ -593,10 +593,10 @@ EOT
return $val;
}),
'minimum-stability' => array(
function ($val) {
function ($val): bool {
return isset(BasePackage::$stabilities[VersionParser::normalizeStability($val)]);
},
function ($val) {
function ($val): string {
return VersionParser::normalizeStability($val);
},
),
@ -810,7 +810,7 @@ EOT
*
* @return void
*/
protected function handleSingleValue($key, array $callbacks, array $values, $method)
protected function handleSingleValue($key, array $callbacks, array $values, $method): void
{
list($validator, $normalizer) = $callbacks;
if (1 !== count($values)) {
@ -845,7 +845,7 @@ EOT
*
* @return void
*/
protected function handleMultiValue($key, array $callbacks, array $values, $method)
protected function handleMultiValue($key, array $callbacks, array $values, $method): void
{
list($validator, $normalizer) = $callbacks;
if (true !== $validation = $validator($values)) {
@ -868,7 +868,7 @@ EOT
*
* @return void
*/
protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null, $showSource = false)
protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null, $showSource = false): void
{
$origK = $k;
$io = $this->getIO();

View File

@ -63,7 +63,7 @@ class CreateProjectCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('create-project')
@ -187,7 +187,7 @@ EOT
* @return int
* @throws \Exception
*/
public function installProject(IOInterface $io, Config $config, InputInterface $input, $packageName = null, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $noInstall = false, PlatformRequirementFilterInterface $platformRequirementFilter = null, $secureHttp = true, $addRepository = false)
public function installProject(IOInterface $io, Config $config, InputInterface $input, $packageName = null, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $noInstall = false, PlatformRequirementFilterInterface $platformRequirementFilter = null, $secureHttp = true, $addRepository = false): int
{
$oldCwd = getcwd();
@ -350,7 +350,7 @@ EOT
* @return bool
* @throws \Exception
*/
protected function installRootPackage(IOInterface $io, Config $config, $packageName, PlatformRequirementFilterInterface $platformRequirementFilter, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, array $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $secureHttp = true)
protected function installRootPackage(IOInterface $io, Config $config, $packageName, PlatformRequirementFilterInterface $platformRequirementFilter, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, array $repositories = null, $disablePlugins = false, $disableScripts = false, $noProgress = false, $secureHttp = true): bool
{
if (!$secureHttp) {
$config->merge(array('config' => array('secure-http' => false)), Config::SOURCE_COMMAND);
@ -443,7 +443,7 @@ EOT
@mkdir($directory, 0777, true);
if ($realDir = realpath($directory)) {
pcntl_async_signals(true);
pcntl_signal(SIGINT, function () use ($realDir) {
pcntl_signal(SIGINT, function () use ($realDir): void {
$fs = new Filesystem();
$fs->removeDirectory($realDir);
exit(130);
@ -454,7 +454,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) {
sapi_windows_set_ctrl_handler(function () use ($realDir): void {
$fs = new Filesystem();
$fs->removeDirectory($realDir);
exit(130);

View File

@ -27,7 +27,7 @@ class DependsCommand extends BaseDependencyCommand
*
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('depends')

View File

@ -260,7 +260,8 @@ EOT
try {
$this->httpDownloader->get($proto . '://repo.packagist.org/packages.json');
} catch (TransportException $e) {
if ($hints = HttpDownloader::getExceptionHints($e)) {
$hints = HttpDownloader::getExceptionHints($e);
if (null !== $hints && count($hints) > 0) {
foreach ($hints as $hint) {
$result[] = $hint;
}
@ -436,7 +437,7 @@ EOT
/**
* @return string
*/
private function getCurlVersion()
private function getCurlVersion(): string
{
if (extension_loaded('curl')) {
if (!HttpDownloader::isCurlEnabled()) {
@ -458,7 +459,7 @@ EOT
*
* @return void
*/
private function outputResult($result)
private function outputResult($result): void
{
$io = $this->getIO();
if (true === $result) {
@ -510,7 +511,7 @@ EOT
private function checkPlatform()
{
$output = '';
$out = function ($msg, $style) use (&$output) {
$out = function ($msg, $style) use (&$output): void {
$output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
};

View File

@ -33,7 +33,7 @@ class FundCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this->setName('fund')
->setDescription('Discover how to help fund the maintenance of your dependencies.')
@ -134,7 +134,7 @@ class FundCommand extends BaseCommand
* @param mixed[] $fundings
* @return mixed[]
*/
private function insertFundingData(array $fundings, CompletePackageInterface $package)
private function insertFundingData(array $fundings, CompletePackageInterface $package): array
{
foreach ($package->getFunding() as $fundingOption) {
list($vendor, $packageName) = explode('/', $package->getPrettyName());

View File

@ -29,7 +29,7 @@ class GlobalCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('global')
@ -121,7 +121,7 @@ EOT
/**
* @inheritDoc
*/
public function isProxyCommand()
public function isProxyCommand(): bool
{
return true;
}

View File

@ -33,7 +33,7 @@ class HomeCommand extends BaseCommand
*
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('browse')
@ -101,7 +101,7 @@ EOT
* @param bool $showOnly
* @return bool
*/
private function handlePackage(CompletePackageInterface $package, $showHomepage, $showOnly)
private function handlePackage(CompletePackageInterface $package, $showHomepage, $showOnly): bool
{
$support = $package->getSupport();
$url = $support['source'] ?? $package->getSourceUrl();
@ -128,7 +128,7 @@ EOT
* @param string $url
* @return void
*/
private function openBrowser($url)
private function openBrowser($url): void
{
$url = ProcessExecutor::escape($url);
@ -158,7 +158,7 @@ EOT
*
* @return RepositoryInterface[]
*/
private function initializeRepos()
private function initializeRepos(): array
{
$composer = $this->tryComposer();

View File

@ -511,7 +511,7 @@ EOT
}
$namespace = array_map(
function ($part) {
function ($part): string {
$part = Preg::replace('/[^a-z0-9]/i', ' ', $part);
$part = ucwords($part);
@ -623,7 +623,7 @@ EOT
/**
* @return void
*/
private function updateDependencies(OutputInterface $output)
private function updateDependencies(OutputInterface $output): void
{
try {
$updateCommand = $this->getApplication()->find('update');
@ -637,7 +637,7 @@ EOT
/**
* @return void
*/
private function runDumpAutoloadCommand(OutputInterface $output)
private function runDumpAutoloadCommand(OutputInterface $output): void
{
try {
$command = $this->getApplication()->find('dump-autoload');
@ -652,7 +652,7 @@ EOT
* @param array<string, string|array<string>> $options
* @return bool
*/
private function hasDependencies($options)
private function hasDependencies($options): bool
{
$requires = (array) $options['require'];
$devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : array();

View File

@ -98,7 +98,7 @@ EOT
$composer = $this->requireComposer();
if ((!$composer->getLocker() || !$composer->getLocker()->isLocked()) && !HttpDownloader::isCurlEnabled()) {
if (!$composer->getLocker()->isLocked() && !HttpDownloader::isCurlEnabled()) {
$io->writeError('<warning>Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled.</warning>');
}

View File

@ -34,7 +34,7 @@ class LicensesCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('licenses')
@ -163,14 +163,14 @@ EOT
* @param array<string, PackageInterface> $bucket
* @return array<string, PackageInterface>
*/
private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array())
private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()): array
{
$requires = array_keys($package->getRequires());
$packageListNames = array_keys($bucket);
$packages = array_filter(
$repo->getPackages(),
function ($package) use ($requires, $packageListNames) {
function ($package) use ($requires, $packageListNames): bool {
return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames);
}
);
@ -191,7 +191,7 @@ EOT
* @param array<string, PackageInterface> $bucket the list to add packages to
* @return array<string, PackageInterface>
*/
public function appendPackages(array $packages, array $bucket)
public function appendPackages(array $packages, array $bucket): array
{
foreach ($packages as $package) {
$bucket[$package->getName()] = $package;

View File

@ -26,7 +26,7 @@ class OutdatedCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('outdated')
@ -105,7 +105,7 @@ EOT
/**
* @inheritDoc
*/
public function isProxyCommand()
public function isProxyCommand(): bool
{
return true;
}

View File

@ -42,7 +42,7 @@ trait PackageDiscoveryTrait
/**
* @return CompositeRepository
*/
protected function getRepos()
protected function getRepos(): CompositeRepository
{
if (null === $this->repos) {
$this->repos = new CompositeRepository(array_merge(

View File

@ -27,7 +27,7 @@ class ProhibitsCommand extends BaseDependencyCommand
*
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('prohibits')

View File

@ -35,7 +35,7 @@ class ReinstallCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('reinstall')
@ -123,7 +123,7 @@ EOT
$installOrder[$op->getPackage()->getName()] = $index;
}
}
usort($uninstallOperations, function ($a, $b) use ($installOrder) {
usort($uninstallOperations, function ($a, $b) use ($installOrder): int {
return $installOrder[$b->getPackage()->getName()] - $installOrder[$a->getPackage()->getName()];
});

View File

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

View File

@ -296,7 +296,7 @@ EOT
* @param string $requireKey
* @return string[]
*/
private function getInconsistentRequireKeys(array $newRequirements, $requireKey)
private function getInconsistentRequireKeys(array $newRequirements, $requireKey): array
{
$requireKeys = $this->getPackagesByRequireKey();
$inconsistentRequirements = array();
@ -315,7 +315,7 @@ EOT
/**
* @return array<string, string>
*/
private function getPackagesByRequireKey()
private function getPackagesByRequireKey(): array
{
$composerDefinition = $this->json->read();
$require = array();
@ -351,7 +351,7 @@ EOT
* @return int
* @throws \Exception
*/
private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, $requireKey, $removeKey)
private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, $requireKey, $removeKey): int
{
// Update packages
$this->resetComposer();
@ -449,7 +449,7 @@ EOT
* @param bool $sortPackages
* @return bool
*/
private function updateFileCleanly(JsonFile $json, array $new, $requireKey, $removeKey, $sortPackages)
private function updateFileCleanly(JsonFile $json, array $new, $requireKey, $removeKey, $sortPackages): bool
{
$contents = file_get_contents($json->getPath());

View File

@ -47,7 +47,7 @@ class RunScriptCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('run-script')
@ -112,7 +112,7 @@ EOT
/**
* @return int
*/
protected function listScripts(OutputInterface $output)
protected function listScripts(OutputInterface $output): int
{
$scripts = $this->requireComposer()->getPackage()->getScripts();

View File

@ -42,7 +42,7 @@ class ScriptAliasCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName($this->script)

View File

@ -33,7 +33,7 @@ class SearchCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('search')

View File

@ -42,7 +42,7 @@ class SelfUpdateCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('self-update')
@ -346,7 +346,7 @@ TAGSPUBKEY
* @return void
* @throws \Exception
*/
protected function fetchKeys(IOInterface $io, Config $config)
protected function fetchKeys(IOInterface $io, Config $config): void
{
if (!$io->isInteractive()) {
throw new \RuntimeException('Public keys can not be fetched in non-interactive mode, please run Composer interactively');
@ -354,7 +354,7 @@ TAGSPUBKEY
$io->write('Open <info>https://composer.github.io/pubkeys.html</info> to find the latest keys');
$validator = function ($value) {
$validator = function ($value): string {
if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) {
throw new \UnexpectedValueException('Invalid input');
}
@ -397,7 +397,7 @@ TAGSPUBKEY
* @return int
* @throws FilesystemException
*/
protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
protected function rollback(OutputInterface $output, $rollbackDir, $localFilename): int
{
$rollbackVersion = $this->getLastBackupVersion($rollbackDir);
if (!$rollbackVersion) {
@ -431,7 +431,7 @@ TAGSPUBKEY
* @throws FilesystemException If the file cannot be moved
* @return bool Whether the phar is valid and has been moved
*/
protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null): bool
{
$io = $this->getIO();
@chmod($newFilename, fileperms($localFilename));
@ -483,7 +483,7 @@ TAGSPUBKEY
*
* @return void
*/
protected function cleanBackups($rollbackDir, $except = null)
protected function cleanBackups($rollbackDir, $except = null): void
{
$finder = $this->getOldInstallationFinder($rollbackDir);
$io = $this->getIO();
@ -520,7 +520,7 @@ TAGSPUBKEY
* @param string $rollbackDir
* @return Finder
*/
protected function getOldInstallationFinder($rollbackDir)
protected function getOldInstallationFinder($rollbackDir): Finder
{
return Finder::create()
->depth(0)
@ -541,7 +541,7 @@ TAGSPUBKEY
* @throws \Exception
* @return bool If the operation succeeded
*/
protected function validatePhar($pharFile, &$error)
protected function validatePhar($pharFile, &$error): bool
{
if (ini_get('phar.readonly')) {
return true;
@ -569,7 +569,7 @@ TAGSPUBKEY
*
* @return bool
*/
protected function isWindowsNonAdminUser()
protected function isWindowsNonAdminUser(): bool
{
if (!Platform::isWindows()) {
return false;
@ -590,7 +590,7 @@ TAGSPUBKEY
* @param string $newFilename The downloaded or backup phar
* @return bool Whether composer.phar has been updated
*/
protected function tryAsWindowsAdmin($localFilename, $newFilename)
protected function tryAsWindowsAdmin($localFilename, $newFilename): bool
{
$io = $this->getIO();

View File

@ -223,7 +223,7 @@ EOT
if ($input->getOption('no-dev')) {
$packages = $this->filterRequiredPackages($installedRepo, $rootPkg);
$repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg) {
$repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg): \Composer\Package\PackageInterface {
return clone $pkg;
}, $packages))));
}
@ -320,7 +320,7 @@ EOT
if ($input->getOption('tree')) {
$rootRequires = $this->getRootRequires();
$packages = $installedRepo->getPackages();
usort($packages, function (BasePackage $a, BasePackage $b) {
usort($packages, function (BasePackage $a, BasePackage $b): int {
return strcmp((string) $a, (string) $b);
});
$arrayTree = array();
@ -923,7 +923,7 @@ EOT
* @param array<string, string> $versions
* @return array<string, string|string[]|null>
*/
private function appendVersions($json, array $versions)
private function appendVersions($json, array $versions): array
{
uasort($versions, 'version_compare');
$versions = array_keys(array_reverse($versions));
@ -936,7 +936,7 @@ EOT
* @param array<string, string|string[]|null> $json
* @return array<string, string|string[]|null>
*/
private function appendLicenses($json, CompletePackageInterface $package)
private function appendLicenses($json, CompletePackageInterface $package): array
{
if ($licenses = $package->getLicense()) {
$spdxLicenses = new SpdxLicenses();
@ -963,7 +963,7 @@ EOT
* @param array<string, string|string[]|null> $json
* @return array<string, string|string[]|null>
*/
private function appendAutoload($json, CompletePackageInterface $package)
private function appendAutoload($json, CompletePackageInterface $package): array
{
if ($package->getAutoload()) {
$autoload = array();
@ -996,7 +996,7 @@ EOT
* @param array<string, string|string[]|null> $json
* @return array<string, string|string[]|null>
*/
private function appendLinks($json, CompletePackageInterface $package)
private function appendLinks($json, CompletePackageInterface $package): array
{
foreach (Link::$TYPES as $linkType) {
$json = $this->appendLink($json, $package, $linkType);
@ -1010,7 +1010,7 @@ EOT
* @param string $linkType
* @return array<string, string|string[]|null>
*/
private function appendLink($json, CompletePackageInterface $package, $linkType)
private function appendLink($json, CompletePackageInterface $package, $linkType): array
{
$links = $package->{'get' . ucfirst($linkType)}();
@ -1240,7 +1240,7 @@ EOT
* @param string $updateStatus
* @return string
*/
private function updateStatusToVersionStyle($updateStatus)
private function updateStatusToVersionStyle($updateStatus): string
{
// 'up-to-date' is printed green
// 'semver-safe-update' is printed red
@ -1251,7 +1251,7 @@ EOT
/**
* @return string
*/
private function getUpdateStatus(PackageInterface $latestPackage, PackageInterface $package)
private function getUpdateStatus(PackageInterface $latestPackage, PackageInterface $package): string
{
if ($latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion()) {
return 'up-to-date';
@ -1275,7 +1275,7 @@ EOT
*
* @return void
*/
private function writeTreeLine($line)
private function writeTreeLine($line): void
{
$io = $this->getIO();
if (!$io->isDecorated()) {
@ -1326,7 +1326,7 @@ EOT
/**
* @return RepositorySet
*/
private function getRepositorySet(Composer $composer)
private function getRepositorySet(Composer $composer): RepositorySet
{
if (!$this->repositorySet) {
$this->repositorySet = new RepositorySet($composer->getPackage()->getMinimumStability(), $composer->getPackage()->getStabilityFlags());
@ -1342,7 +1342,7 @@ EOT
* @param array<PackageInterface> $bucket
* @return array<PackageInterface>
*/
private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array())
private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()): array
{
$requires = $package->getRequires();

View File

@ -40,7 +40,7 @@ class StatusCommand extends BaseCommand
* @return void
* @throws \Symfony\Component\Console\Exception\InvalidArgumentException
*/
protected function configure()
protected function configure(): void
{
$this
->setName('status')
@ -80,7 +80,7 @@ EOT
/**
* @return int
*/
private function doExecute(InputInterface $input)
private function doExecute(InputInterface $input): int
{
// init repos
$composer = $this->requireComposer();
@ -163,7 +163,7 @@ EOT
foreach ($errors as $path => $changes) {
if ($input->getOption('verbose')) {
$indentedChanges = implode("\n", array_map(function ($line) {
$indentedChanges = implode("\n", array_map(function ($line): string {
return ' ' . ltrim($line);
}, explode("\n", $changes)));
$io->write('<info>'.$path.'</info>:');
@ -179,7 +179,7 @@ EOT
foreach ($unpushedChanges as $path => $changes) {
if ($input->getOption('verbose')) {
$indentedChanges = implode("\n", array_map(function ($line) {
$indentedChanges = implode("\n", array_map(function ($line): string {
return ' ' . ltrim($line);
}, explode("\n", $changes)));
$io->write('<info>'.$path.'</info>:');

View File

@ -26,7 +26,7 @@ class SuggestsCommand extends BaseCommand
/**
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('suggests')

View File

@ -129,7 +129,7 @@ EOT
// extract --with shorthands from the allowlist
if (count($packages) > 0) {
$allowlistPackagesWithRequirements = array_filter($packages, function ($pkg) {
$allowlistPackagesWithRequirements = array_filter($packages, function ($pkg): bool {
return Preg::isMatch('{\S+[ =:]\S+}', $pkg);
});
foreach ($this->formatRequirements($allowlistPackagesWithRequirements) as $package => $constraint) {
@ -180,7 +180,7 @@ 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) {
$filteredPackages = array_filter($packages, function ($package): bool {
return !in_array($package, array('lock', 'nothing', 'mirrors'), true);
});
$updateMirrors = $input->getOption('lock') || count($filteredPackages) != count($packages);
@ -245,7 +245,7 @@ EOT
* @param array<string> $packages
* @return array<string>
*/
private function getPackagesInteractively(IOInterface $io, InputInterface $input, OutputInterface $output, Composer $composer, array $packages)
private function getPackagesInteractively(IOInterface $io, InputInterface $input, OutputInterface $output, Composer $composer, array $packages): array
{
if (!$input->isInteractive()) {
throw new \InvalidArgumentException('--interactive cannot be used in non-interactive terminals.');
@ -312,7 +312,7 @@ EOT
* @param string $constraint
* @return Link
*/
private function appendConstraintToLink(Link $link, $constraint)
private function appendConstraintToLink(Link $link, $constraint): Link
{
$parser = new VersionParser;
$oldPrettyString = $link->getConstraint()->getPrettyString();

View File

@ -38,7 +38,7 @@ class ValidateCommand extends BaseCommand
* configure
* @return void
*/
protected function configure()
protected function configure(): void
{
$this
->setName('validate')
@ -169,7 +169,7 @@ EOT
*
* @return void
*/
private function outputResult(IOInterface $io, $name, &$errors, &$warnings, $checkPublish = false, $publishErrors = array(), $checkLock = false, $lockErrors = array(), $printSchemaUrl = false)
private function outputResult(IOInterface $io, $name, &$errors, &$warnings, $checkPublish = false, $publishErrors = array(), $checkLock = false, $lockErrors = array(), $printSchemaUrl = false): void
{
$doPrintSchemaUrl = false;
@ -193,13 +193,13 @@ EOT
}
if ($errors) {
$errors = array_map(function ($err) {
$errors = array_map(function ($err): string {
return '- ' . $err;
}, $errors);
array_unshift($errors, '# General errors');
}
if ($warnings) {
$warnings = array_map(function ($err) {
$warnings = array_map(function ($err): string {
return '- ' . $err;
}, $warnings);
array_unshift($warnings, '# General warnings');
@ -210,7 +210,7 @@ EOT
// If checking publish errors, display them as errors, otherwise just show them as warnings
if ($publishErrors) {
$publishErrors = array_map(function ($err) {
$publishErrors = array_map(function ($err): string {
return '- ' . $err;
}, $publishErrors);

View File

@ -44,7 +44,7 @@ class Compiler
*
* @throws \RuntimeException
*/
public function compile($pharFile = 'composer.phar')
public function compile($pharFile = 'composer.phar'): void
{
if (file_exists($pharFile)) {
unlink($pharFile);
@ -82,7 +82,7 @@ class Compiler
$phar->startBuffering();
$finderSort = function ($a, $b) {
$finderSort = function ($a, $b): int {
return strcmp(strtr($a->getRealPath(), '\\', '/'), strtr($b->getRealPath(), '\\', '/'));
};
@ -201,7 +201,7 @@ class Compiler
* @param \SplFileInfo $file
* @return string
*/
private function getRelativeFilePath($file)
private function getRelativeFilePath($file): string
{
$realPath = $file->getRealPath();
$pathPrefix = dirname(__DIR__, 2).DIRECTORY_SEPARATOR;
@ -217,7 +217,7 @@ class Compiler
*
* @return void
*/
private function addFile(\Phar $phar, \SplFileInfo $file, $strip = true)
private function addFile(\Phar $phar, \SplFileInfo $file, $strip = true): void
{
$path = $this->getRelativeFilePath($file);
$content = file_get_contents($file);
@ -245,7 +245,7 @@ class Compiler
/**
* @return void
*/
private function addComposerBin(\Phar $phar)
private function addComposerBin(\Phar $phar): void
{
$content = file_get_contents(__DIR__.'/../../bin/composer');
$content = Preg::replace('{^#!/usr/bin/env php\s*}', '', $content);
@ -258,7 +258,7 @@ class Compiler
* @param string $source A PHP string
* @return string The PHP string with the whitespace removed
*/
private function stripWhitespace($source)
private function stripWhitespace($source): string
{
if (!function_exists('token_get_all')) {
return $source;
@ -289,7 +289,7 @@ class Compiler
/**
* @return string
*/
private function getStub()
private function getStub(): string
{
$stub = <<<'EOF'
#!/usr/bin/env php

View File

@ -12,15 +12,10 @@
namespace Composer;
use Composer\Package\RootPackageInterface;
use Composer\Package\Locker;
use Composer\Pcre\Preg;
use Composer\Util\Loop;
use Composer\Repository\RepositoryManager;
use Composer\Installer\InstallationManager;
use Composer\Plugin\PluginManager;
use Composer\Downloader\DownloadManager;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
use Composer\Package\Archiver\ArchiveManager;
@ -29,7 +24,7 @@ use Composer\Package\Archiver\ArchiveManager;
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class Composer
class Composer extends PartialComposer
{
/*
* Examples of the following constants in the various configurations they can be in
@ -71,7 +66,7 @@ class Composer
/**
* @return string
*/
public static function getVersion()
public static function getVersion(): string
{
// no replacement done, this must be a source checkout
if (self::VERSION === '@package_version'.'@') {
@ -87,50 +82,20 @@ class Composer
}
/**
* @var RootPackageInterface
* @var Locker
*/
private $package;
/**
* @var ?Locker
*/
private $locker = null;
/**
* @var Loop
*/
private $loop;
/**
* @var Repository\RepositoryManager
*/
private $repositoryManager;
private $locker;
/**
* @var Downloader\DownloadManager
*/
private $downloadManager;
/**
* @var Installer\InstallationManager
*/
private $installationManager;
/**
* @var Plugin\PluginManager
*/
private $pluginManager;
/**
* @var Config
*/
private $config;
/**
* @var EventDispatcher
*/
private $eventDispatcher;
/**
* @var Autoload\AutoloadGenerator
*/
@ -141,178 +106,52 @@ class Composer
*/
private $archiveManager;
/**
* @return void
*/
public function setPackage(RootPackageInterface $package)
{
$this->package = $package;
}
/**
* @return RootPackageInterface
*/
public function getPackage()
{
return $this->package;
}
/**
* @return void
*/
public function setConfig(Config $config)
{
$this->config = $config;
}
/**
* @return Config
*/
public function getConfig()
{
return $this->config;
}
/**
* @return void
*/
public function setLocker(Locker $locker)
public function setLocker(Locker $locker): void
{
$this->locker = $locker;
}
/**
* @return ?Locker
*/
public function getLocker()
public function getLocker(): Locker
{
return $this->locker;
}
/**
* @return void
*/
public function setLoop(Loop $loop)
{
$this->loop = $loop;
}
/**
* @return Loop
*/
public function getLoop()
{
return $this->loop;
}
/**
* @return void
*/
public function setRepositoryManager(RepositoryManager $manager)
{
$this->repositoryManager = $manager;
}
/**
* @return RepositoryManager
*/
public function getRepositoryManager()
{
return $this->repositoryManager;
}
/**
* @return void
*/
public function setDownloadManager(DownloadManager $manager)
public function setDownloadManager(DownloadManager $manager): void
{
$this->downloadManager = $manager;
}
/**
* @return DownloadManager
*/
public function getDownloadManager()
public function getDownloadManager(): DownloadManager
{
return $this->downloadManager;
}
/**
* @return void
*/
public function setArchiveManager(ArchiveManager $manager)
public function setArchiveManager(ArchiveManager $manager): void
{
$this->archiveManager = $manager;
}
/**
* @return ArchiveManager
*/
public function getArchiveManager()
public function getArchiveManager(): ArchiveManager
{
return $this->archiveManager;
}
/**
* @return void
*/
public function setInstallationManager(InstallationManager $manager)
{
$this->installationManager = $manager;
}
/**
* @return InstallationManager
*/
public function getInstallationManager()
{
return $this->installationManager;
}
/**
* @return void
*/
public function setPluginManager(PluginManager $manager)
public function setPluginManager(PluginManager $manager): void
{
$this->pluginManager = $manager;
}
/**
* @return PluginManager
*/
public function getPluginManager()
public function getPluginManager(): PluginManager
{
return $this->pluginManager;
}
/**
* @return void
*/
public function setEventDispatcher(EventDispatcher $eventDispatcher)
{
$this->eventDispatcher = $eventDispatcher;
}
/**
* @return EventDispatcher
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* @return void
*/
public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator)
public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator): void
{
$this->autoloadGenerator = $autoloadGenerator;
}
/**
* @return AutoloadGenerator
*/
public function getAutoloadGenerator()
public function getAutoloadGenerator(): AutoloadGenerator
{
return $this->autoloadGenerator;
}

View File

@ -140,7 +140,7 @@ class Config
/**
* @return void
*/
public function setConfigSource(ConfigSourceInterface $source)
public function setConfigSource(ConfigSourceInterface $source): void
{
$this->configSource = $source;
}
@ -148,7 +148,7 @@ class Config
/**
* @return ConfigSourceInterface
*/
public function getConfigSource()
public function getConfigSource(): ConfigSourceInterface
{
return $this->configSource;
}
@ -156,7 +156,7 @@ class Config
/**
* @return void
*/
public function setAuthConfigSource(ConfigSourceInterface $source)
public function setAuthConfigSource(ConfigSourceInterface $source): void
{
$this->authConfigSource = $source;
}
@ -164,7 +164,7 @@ class Config
/**
* @return ConfigSourceInterface
*/
public function getAuthConfigSource()
public function getAuthConfigSource(): ConfigSourceInterface
{
return $this->authConfigSource;
}
@ -177,7 +177,7 @@ class Config
*
* @return void
*/
public function merge($config, $source = self::SOURCE_UNKNOWN)
public function merge($config, $source = self::SOURCE_UNKNOWN): void
{
// override defaults with given config
if (!empty($config['config']) && is_array($config['config'])) {
@ -263,7 +263,7 @@ class Config
/**
* @return array<int|string, mixed>
*/
public function getRepositories()
public function getRepositories(): array
{
return $this->repositories;
}
@ -441,7 +441,7 @@ class Config
*
* @return array<string, mixed[]>
*/
public function all($flags = 0)
public function all($flags = 0): array
{
$all = array(
'repositories' => $this->getRepositories(),
@ -457,7 +457,7 @@ class Config
* @param string $key
* @return string
*/
public function getSourceOfValue($key)
public function getSourceOfValue($key): string
{
$this->get($key);
@ -471,7 +471,7 @@ class Config
*
* @return void
*/
private function setSourceOfConfigValue($configValue, $path, $source)
private function setSourceOfConfigValue($configValue, $path, $source): void
{
$this->sourceOfConfigValue[$path] = $source;
@ -485,7 +485,7 @@ class Config
/**
* @return array<string, mixed[]>
*/
public function raw()
public function raw(): array
{
return array(
'repositories' => $this->getRepositories(),
@ -499,7 +499,7 @@ class Config
* @param string $key
* @return bool
*/
public function has($key)
public function has($key): bool
{
return array_key_exists($key, $this->config);
}
@ -531,7 +531,7 @@ class Config
* @param string $path
* @return string
*/
private function realpath($path)
private function realpath($path): string
{
if (Preg::isMatch('{^(?:/|[a-z]:|[a-z0-9.]+://)}i', $path)) {
return $path;
@ -563,7 +563,7 @@ class Config
*
* @return void
*/
private function disableRepoByName($name)
private function disableRepoByName($name): void
{
if (isset($this->repositories[$name])) {
unset($this->repositories[$name]);
@ -580,7 +580,7 @@ class Config
*
* @return void
*/
public function prohibitUrlByConfig($url, IOInterface $io = null)
public function prohibitUrlByConfig($url, IOInterface $io = null): void
{
// Return right away if the URL is malformed or custom (see issue #5173)
if (false === filter_var($url, FILTER_VALIDATE_URL)) {
@ -626,7 +626,7 @@ class Config
*
* @return void
*/
public static function disableProcessTimeout()
public static function disableProcessTimeout(): void
{
// Override global timeout set earlier by environment or config
ProcessExecutor::setTimeout(0);

View File

@ -62,7 +62,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function addRepository($name, $config, $append = true)
{
$this->manipulateJson('addRepository', function (&$config, $repo, $repoConfig) use ($append) {
$this->manipulateJson('addRepository', function (&$config, $repo, $repoConfig) use ($append): void {
// if converting from an array format to hashmap format, and there is a {"packagist.org":false} repo, we have
// to convert it to "packagist.org": false key on the hashmap otherwise it fails schema validation
if (isset($config['repositories'])) {
@ -91,7 +91,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function removeRepository($name)
{
$this->manipulateJson('removeRepository', function (&$config, $repo) {
$this->manipulateJson('removeRepository', function (&$config, $repo): void {
unset($config['repositories'][$repo]);
}, $name);
}
@ -102,7 +102,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function addConfigSetting($name, $value)
{
$authConfig = $this->authConfig;
$this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig) {
$this->manipulateJson('addConfigSetting', function (&$config, $key, $val) use ($authConfig): void {
if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) {
list($key, $host) = explode('.', $key, 2);
if ($authConfig) {
@ -122,7 +122,7 @@ class JsonConfigSource implements ConfigSourceInterface
public function removeConfigSetting($name)
{
$authConfig = $this->authConfig;
$this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig) {
$this->manipulateJson('removeConfigSetting', function (&$config, $key) use ($authConfig): void {
if (Preg::isMatch('{^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|bearer|http-basic|platform)\.}', $key)) {
list($key, $host) = explode('.', $key, 2);
if ($authConfig) {
@ -141,7 +141,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function addProperty($name, $value)
{
$this->manipulateJson('addProperty', function (&$config, $key, $val) {
$this->manipulateJson('addProperty', function (&$config, $key, $val): void {
if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) {
$bits = explode('.', $key);
$last = array_pop($bits);
@ -164,7 +164,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function removeProperty($name)
{
$this->manipulateJson('removeProperty', function (&$config, $key) {
$this->manipulateJson('removeProperty', function (&$config, $key): void {
if (strpos($key, 'extra.') === 0 || strpos($key, 'scripts.') === 0) {
$bits = explode('.', $key);
$last = array_pop($bits);
@ -187,7 +187,7 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function addLink($type, $name, $value)
{
$this->manipulateJson('addLink', function (&$config, $type, $name, $value) {
$this->manipulateJson('addLink', function (&$config, $type, $name, $value): void {
$config[$type][$name] = $value;
}, $type, $name, $value);
}
@ -197,10 +197,10 @@ class JsonConfigSource implements ConfigSourceInterface
*/
public function removeLink($type, $name)
{
$this->manipulateJson('removeSubNode', function (&$config, $type, $name) {
$this->manipulateJson('removeSubNode', function (&$config, $type, $name): void {
unset($config[$type][$name]);
}, $type, $name);
$this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type) {
$this->manipulateJson('removeMainKeyIfEmpty', function (&$config, $type): void {
if (0 === count($config[$type])) {
unset($config[$type]);
}
@ -214,7 +214,7 @@ class JsonConfigSource implements ConfigSourceInterface
*
* @return void
*/
private function manipulateJson($method, $fallback, ...$args)
private function manipulateJson($method, $fallback, ...$args): void
{
if ($this->file->exists()) {
if (!is_writable($this->file->getPath())) {
@ -297,7 +297,7 @@ class JsonConfigSource implements ConfigSourceInterface
* @param mixed $value
* @return int
*/
private function arrayUnshiftRef(&$array, &$value)
private function arrayUnshiftRef(&$array, &$value): int
{
$return = array_unshift($array, '');
$array[0] = &$value;

View File

@ -94,14 +94,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) {
pcntl_signal(SIGINT, function ($sig): void {
exit(130);
});
}
$shutdownRegistered = true;
register_shutdown_function(function () {
register_shutdown_function(function (): void {
$lastError = error_get_last();
if ($lastError && $lastError['message'] &&
@ -291,7 +291,7 @@ class Application extends BaseApplication
}
// Check system temp folder for usability as it can cause weird runtime issues otherwise
Silencer::call(function () use ($io) {
Silencer::call(function () use ($io): void {
$tempfile = sys_get_temp_dir() . '/temp-' . md5(microtime());
if (!(file_put_contents($tempfile, __FILE__) && (file_get_contents($tempfile) == __FILE__) && unlink($tempfile) && !file_exists($tempfile))) {
$io->writeError(sprintf('<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()));
@ -358,7 +358,7 @@ class Application extends BaseApplication
* @throws \RuntimeException
* @return string
*/
private function getNewWorkingDir(InputInterface $input)
private function getNewWorkingDir(InputInterface $input): string
{
$workingDir = $input->getParameterOption(array('--working-dir', '-d'));
if (false !== $workingDir && !is_dir($workingDir)) {
@ -371,7 +371,7 @@ class Application extends BaseApplication
/**
* @return void
*/
private function hintCommonErrors(\Exception $exception)
private function hintCommonErrors(\Exception $exception): void
{
$io = $this->getIO();
@ -408,7 +408,8 @@ class Application extends BaseApplication
$io->writeError('<error>Check https://getcomposer.org/doc/06-config.md#process-timeout for details</error>', true, IOInterface::QUIET);
}
if ($hints = HttpDownloader::getExceptionHints($exception)) {
$hints = HttpDownloader::getExceptionHints($exception);
if (null !== $hints && count($hints) > 0) {
foreach ($hints as $hint) {
$io->writeError($hint, true, IOInterface::QUIET);
}
@ -553,13 +554,13 @@ class Application extends BaseApplication
/**
* @return Command\BaseCommand[]
*/
private function getPluginCommands()
private function getPluginCommands(): array
{
$commands = array();
$composer = $this->getComposer(false, false);
if (null === $composer) {
$composer = Factory::createGlobal($this->io);
$composer = Factory::createGlobal($this->io, $this->disablePluginsByDefault, $this->disableScriptsByDefault);
}
if (null !== $composer) {

View File

@ -34,7 +34,7 @@ final class GithubActionError
*
* @return void
*/
public function emit($message, $file = null, $line = null)
public function emit($message, $file = null, $line = null): void
{
if (Platform::getEnv('GITHUB_ACTIONS') && !Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING')) {
$message = $this->escapeData($message);
@ -55,7 +55,7 @@ final class GithubActionError
* @param string $data
* @return string
*/
private function escapeData($data)
private function escapeData($data): string
{
// see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L80-L85
$data = str_replace("%", '%25', $data);
@ -69,7 +69,7 @@ final class GithubActionError
* @param string $property
* @return string
*/
private function escapeProperty($property)
private function escapeProperty($property): string
{
// see https://github.com/actions/toolkit/blob/4f7fb6513a355689f69f0849edeb369a4dc81729/packages/core/src/command.ts#L87-L94
$property = str_replace("%", '%25', $property);

View File

@ -43,7 +43,7 @@ class Decisions implements \Iterator, \Countable
* @param int $level
* @return void
*/
public function decide($literal, $level, Rule $why)
public function decide($literal, $level, Rule $why): void
{
$this->addDecision($literal, $level);
$this->decisionQueue[] = array(
@ -56,7 +56,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literal
* @return bool
*/
public function satisfy($literal)
public function satisfy($literal): bool
{
$packageId = abs($literal);
@ -70,7 +70,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literal
* @return bool
*/
public function conflict($literal)
public function conflict($literal): bool
{
$packageId = abs($literal);
@ -84,7 +84,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literalOrPackageId
* @return bool
*/
public function decided($literalOrPackageId)
public function decided($literalOrPackageId): bool
{
return !empty($this->decisionMap[abs($literalOrPackageId)]);
}
@ -93,7 +93,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literalOrPackageId
* @return bool
*/
public function undecided($literalOrPackageId)
public function undecided($literalOrPackageId): bool
{
return empty($this->decisionMap[abs($literalOrPackageId)]);
}
@ -102,7 +102,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literalOrPackageId
* @return bool
*/
public function decidedInstall($literalOrPackageId)
public function decidedInstall($literalOrPackageId): bool
{
$packageId = abs($literalOrPackageId);
@ -113,7 +113,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literalOrPackageId
* @return int
*/
public function decisionLevel($literalOrPackageId)
public function decisionLevel($literalOrPackageId): int
{
$packageId = abs($literalOrPackageId);
if (isset($this->decisionMap[$packageId])) {
@ -127,7 +127,7 @@ class Decisions implements \Iterator, \Countable
* @param int $literalOrPackageId
* @return Rule|null
*/
public function decisionRule($literalOrPackageId)
public function decisionRule($literalOrPackageId): ?Rule
{
$packageId = abs($literalOrPackageId);
@ -144,7 +144,7 @@ class Decisions implements \Iterator, \Countable
* @param int $queueOffset
* @return array{0: int, 1: Rule} a literal and decision reason
*/
public function atOffset($queueOffset)
public function atOffset($queueOffset): array
{
return $this->decisionQueue[$queueOffset];
}
@ -153,7 +153,7 @@ class Decisions implements \Iterator, \Countable
* @param int $queueOffset
* @return bool
*/
public function validOffset($queueOffset)
public function validOffset($queueOffset): bool
{
return $queueOffset >= 0 && $queueOffset < \count($this->decisionQueue);
}
@ -161,7 +161,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return Rule
*/
public function lastReason()
public function lastReason(): Rule
{
return $this->decisionQueue[\count($this->decisionQueue) - 1][self::DECISION_REASON];
}
@ -169,7 +169,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return int
*/
public function lastLiteral()
public function lastLiteral(): int
{
return $this->decisionQueue[\count($this->decisionQueue) - 1][self::DECISION_LITERAL];
}
@ -177,7 +177,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return void
*/
public function reset()
public function reset(): void
{
while ($decision = array_pop($this->decisionQueue)) {
$this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0;
@ -188,7 +188,7 @@ class Decisions implements \Iterator, \Countable
* @param int $offset
* @return void
*/
public function resetToOffset($offset)
public function resetToOffset($offset): void
{
while (\count($this->decisionQueue) > $offset + 1) {
$decision = array_pop($this->decisionQueue);
@ -199,7 +199,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return void
*/
public function revertLast()
public function revertLast(): void
{
$this->decisionMap[abs($this->lastLiteral())] = 0;
array_pop($this->decisionQueue);
@ -242,7 +242,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return bool
*/
public function isEmpty()
public function isEmpty(): bool
{
return \count($this->decisionQueue) === 0;
}
@ -252,7 +252,7 @@ class Decisions implements \Iterator, \Countable
* @param int $level
* @return void
*/
protected function addDecision($literal, $level)
protected function addDecision($literal, $level): void
{
$packageId = abs($literal);
@ -275,7 +275,7 @@ class Decisions implements \Iterator, \Countable
/**
* @return string
*/
public function toString(Pool $pool = null)
public function toString(Pool $pool = null): string
{
$decisionMap = $this->decisionMap;
ksort($decisionMap);

View File

@ -44,7 +44,7 @@ class DefaultPolicy implements PolicyInterface
*
* @phpstan-param Constraint::STR_OP_* $operator
*/
public function versionCompare(PackageInterface $a, PackageInterface $b, $operator)
public function versionCompare(PackageInterface $a, PackageInterface $b, $operator): bool
{
if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) {
return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB];
@ -61,12 +61,12 @@ class DefaultPolicy implements PolicyInterface
* @param string $requiredPackage
* @return int[]
*/
public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null)
public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null): array
{
$packages = $this->groupLiteralsByName($pool, $literals);
foreach ($packages as &$nameLiterals) {
usort($nameLiterals, function ($a, $b) use ($pool, $requiredPackage) {
usort($nameLiterals, function ($a, $b) use ($pool, $requiredPackage): int {
return $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true);
});
}
@ -79,7 +79,7 @@ class DefaultPolicy implements PolicyInterface
$selected = \call_user_func_array('array_merge', array_values($packages));
// now sort the result across all packages to respect replaces across packages
usort($selected, function ($a, $b) use ($pool, $requiredPackage) {
usort($selected, function ($a, $b) use ($pool, $requiredPackage): int {
return $this->compareByPriority($pool, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage);
});
@ -90,7 +90,7 @@ class DefaultPolicy implements PolicyInterface
* @param int[] $literals
* @return array<string, int[]>
*/
protected function groupLiteralsByName(Pool $pool, $literals)
protected function groupLiteralsByName(Pool $pool, $literals): array
{
$packages = array();
foreach ($literals as $literal) {
@ -111,7 +111,7 @@ class DefaultPolicy implements PolicyInterface
* @param bool $ignoreReplace
* @return int
*/
public function compareByPriority(Pool $pool, BasePackage $a, BasePackage $b, $requiredPackage = null, $ignoreReplace = false)
public function compareByPriority(Pool $pool, BasePackage $a, BasePackage $b, $requiredPackage = null, $ignoreReplace = false): int
{
// prefer aliases to the original package
if ($a->getName() === $b->getName()) {
@ -164,7 +164,7 @@ class DefaultPolicy implements PolicyInterface
*
* @return bool
*/
protected function replaces(BasePackage $source, BasePackage $target)
protected function replaces(BasePackage $source, BasePackage $target): bool
{
foreach ($source->getReplaces() as $link) {
if ($link->getTarget() === $target->getName()
@ -182,7 +182,7 @@ class DefaultPolicy implements PolicyInterface
* @param int[] $literals
* @return int[]
*/
protected function pruneToBestVersion(Pool $pool, $literals)
protected function pruneToBestVersion(Pool $pool, $literals): array
{
$operator = $this->preferLowest ? '<' : '>';
$bestLiterals = array($literals[0]);
@ -213,7 +213,7 @@ class DefaultPolicy implements PolicyInterface
* @param int[] $literals
* @return int[]
*/
protected function pruneRemoteAliases(Pool $pool, array $literals)
protected function pruneRemoteAliases(Pool $pool, array $literals): array
{
$hasLocalAlias = false;

View File

@ -36,7 +36,7 @@ class GenericRule extends Rule
/**
* @return int[]
*/
public function getLiterals()
public function getLiterals(): array
{
return $this->literals;
}
@ -59,7 +59,7 @@ class GenericRule extends Rule
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule)
public function equals(Rule $rule): bool
{
return $this->literals === $rule->getLiterals();
}
@ -67,7 +67,7 @@ class GenericRule extends Rule
/**
* @return bool
*/
public function isAssertion()
public function isAssertion(): bool
{
return 1 === \count($this->literals);
}

View File

@ -62,7 +62,7 @@ class LockTransaction extends Transaction
/**
* @return void
*/
public function setResultPackages(Pool $pool, Decisions $decisions)
public function setResultPackages(Pool $pool, Decisions $decisions): void
{
$this->resultPackages = array('all' => array(), 'non-dev' => array(), 'dev' => array());
foreach ($decisions as $i => $decision) {
@ -82,7 +82,7 @@ class LockTransaction extends Transaction
/**
* @return void
*/
public function setNonDevPackages(LockTransaction $extractionResult)
public function setNonDevPackages(LockTransaction $extractionResult): void
{
$packages = $extractionResult->getNewLockPackages(false);
@ -106,7 +106,7 @@ class LockTransaction extends Transaction
* @param bool $updateMirrors
* @return BasePackage[]
*/
public function getNewLockPackages($devMode, $updateMirrors = false)
public function getNewLockPackages($devMode, $updateMirrors = false): array
{
$packages = array();
foreach ($this->resultPackages[$devMode ? 'dev' : 'non-dev'] as $package) {
@ -137,7 +137,7 @@ class LockTransaction extends Transaction
* @param array<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
* @return array<array{package: string, version: string, alias: string, alias_normalized: string}>
*/
public function getAliases($aliases)
public function getAliases($aliases): array
{
$usedAliases = array();
@ -152,7 +152,7 @@ class LockTransaction extends Transaction
}
}
usort($usedAliases, function ($a, $b) {
usort($usedAliases, function ($a, $b): int {
return strcmp($a['package'], $b['package']);
});

View File

@ -42,7 +42,7 @@ class MultiConflictRule extends Rule
/**
* @return int[]
*/
public function getLiterals()
public function getLiterals(): array
{
return $this->literals;
}
@ -65,7 +65,7 @@ class MultiConflictRule extends Rule
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule)
public function equals(Rule $rule): bool
{
if ($rule instanceof MultiConflictRule) {
return $this->literals === $rule->getLiterals();
@ -77,7 +77,7 @@ class MultiConflictRule extends Rule
/**
* @return bool
*/
public function isAssertion()
public function isAssertion(): bool
{
return false;
}
@ -86,7 +86,7 @@ class MultiConflictRule extends Rule
* @return never
* @throws \RuntimeException
*/
public function disable()
public function disable(): void
{
throw new \RuntimeException("Disabling multi conflict rules is not possible. Please contact composer at https://github.com/composer/composer to let us debug what lead to this situation.");
}

View File

@ -38,7 +38,7 @@ class MarkAliasInstalledOperation extends SolverOperation implements OperationIn
*
* @return AliasPackage
*/
public function getPackage()
public function getPackage(): AliasPackage
{
return $this->package;
}
@ -46,7 +46,7 @@ class MarkAliasInstalledOperation extends SolverOperation implements OperationIn
/**
* @inheritDoc
*/
public function show($lock)
public function show($lock): string
{
return 'Marking <info>'.$this->package->getPrettyName().'</info> (<comment>'.$this->package->getFullPrettyVersion().'</comment>) as installed, alias of <info>'.$this->package->getAliasOf()->getPrettyName().'</info> (<comment>'.$this->package->getAliasOf()->getFullPrettyVersion().'</comment>)';
}

View File

@ -38,7 +38,7 @@ class MarkAliasUninstalledOperation extends SolverOperation implements Operation
*
* @return AliasPackage
*/
public function getPackage()
public function getPackage(): AliasPackage
{
return $this->package;
}
@ -46,7 +46,7 @@ class MarkAliasUninstalledOperation extends SolverOperation implements Operation
/**
* @inheritDoc
*/
public function show($lock)
public function show($lock): string
{
return 'Marking <info>'.$this->package->getPrettyName().'</info> (<comment>'.$this->package->getFullPrettyVersion().'</comment>) as uninstalled, alias of <info>'.$this->package->getAliasOf()->getPrettyName().'</info> (<comment>'.$this->package->getAliasOf()->getFullPrettyVersion().'</comment>)';
}

View File

@ -38,7 +38,7 @@ class UninstallOperation extends SolverOperation implements OperationInterface
*
* @return PackageInterface
*/
public function getPackage()
public function getPackage(): PackageInterface
{
return $this->package;
}
@ -46,7 +46,7 @@ class UninstallOperation extends SolverOperation implements OperationInterface
/**
* @inheritDoc
*/
public function show($lock)
public function show($lock): string
{
return self::format($this->package, $lock);
}
@ -55,7 +55,7 @@ class UninstallOperation extends SolverOperation implements OperationInterface
* @param bool $lock
* @return string
*/
public static function format(PackageInterface $package, $lock = false)
public static function format(PackageInterface $package, $lock = false): string
{
return 'Removing <info>'.$package->getPrettyName().'</info> (<comment>'.$package->getFullPrettyVersion().'</comment>)';
}

View File

@ -49,7 +49,7 @@ class UpdateOperation extends SolverOperation implements OperationInterface
*
* @return PackageInterface
*/
public function getInitialPackage()
public function getInitialPackage(): PackageInterface
{
return $this->initialPackage;
}
@ -59,7 +59,7 @@ class UpdateOperation extends SolverOperation implements OperationInterface
*
* @return PackageInterface
*/
public function getTargetPackage()
public function getTargetPackage(): PackageInterface
{
return $this->targetPackage;
}
@ -67,7 +67,7 @@ class UpdateOperation extends SolverOperation implements OperationInterface
/**
* @inheritDoc
*/
public function show($lock)
public function show($lock): string
{
return self::format($this->initialPackage, $this->targetPackage, $lock);
}
@ -76,7 +76,7 @@ class UpdateOperation extends SolverOperation implements OperationInterface
* @param bool $lock
* @return string
*/
public static function format(PackageInterface $initialPackage, PackageInterface $targetPackage, $lock = false)
public static function format(PackageInterface $initialPackage, PackageInterface $targetPackage, $lock = false): string
{
$fromVersion = $initialPackage->getFullPrettyVersion();
$toVersion = $targetPackage->getFullPrettyVersion();

View File

@ -26,12 +26,12 @@ interface PolicyInterface
*
* @phpstan-param Constraint::STR_OP_* $operator
*/
public function versionCompare(PackageInterface $a, PackageInterface $b, $operator);
public function versionCompare(PackageInterface $a, PackageInterface $b, $operator): bool;
/**
* @param int[] $literals
* @param ?string $requiredPackage
* @return int[]
*/
public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null);
public function selectPreferredPackages(Pool $pool, array $literals, $requiredPackage = null): array;
}

View File

@ -60,7 +60,7 @@ class Pool implements \Countable
* @param string $name
* @return array<string, string>
*/
public function getRemovedVersions($name, ConstraintInterface $constraint)
public function getRemovedVersions($name, ConstraintInterface $constraint): array
{
if (!isset($this->removedVersions[$name])) {
return array();
@ -80,7 +80,7 @@ class Pool implements \Countable
* @param string $objectHash
* @return array<string, string>
*/
public function getRemovedVersionsByPackage($objectHash)
public function getRemovedVersionsByPackage($objectHash): array
{
if (!isset($this->removedVersionsByPackage[$objectHash])) {
return array();
@ -93,7 +93,7 @@ class Pool implements \Countable
* @param BasePackage[] $packages
* @return void
*/
private function setPackages(array $packages)
private function setPackages(array $packages): void
{
$id = 1;
@ -111,7 +111,7 @@ class Pool implements \Countable
/**
* @return BasePackage[]
*/
public function getPackages()
public function getPackages(): array
{
return $this->packages;
}
@ -122,7 +122,7 @@ class Pool implements \Countable
* @param int $id
* @return BasePackage
*/
public function packageById($id)
public function packageById($id): BasePackage
{
return $this->packages[$id - 1];
}
@ -143,7 +143,7 @@ class Pool implements \Countable
* packages must match or null to return all
* @return BasePackage[] A set of packages
*/
public function whatProvides($name, ConstraintInterface $constraint = null)
public function whatProvides($name, ConstraintInterface $constraint = null): array
{
$key = (string) $constraint;
if (isset($this->providerCache[$name][$key])) {
@ -159,7 +159,7 @@ class Pool implements \Countable
* packages must match or null to return all
* @return BasePackage[]
*/
private function computeWhatProvides($name, ConstraintInterface $constraint = null)
private function computeWhatProvides($name, ConstraintInterface $constraint = null): array
{
if (!isset($this->packageByName[$name])) {
return array();
@ -180,7 +180,7 @@ class Pool implements \Countable
* @param int $literal
* @return BasePackage
*/
public function literalToPackage($literal)
public function literalToPackage($literal): BasePackage
{
$packageId = abs($literal);
@ -192,7 +192,7 @@ class Pool implements \Countable
* @param array<int, BasePackage> $installedMap
* @return string
*/
public function literalToPrettyString($literal, $installedMap)
public function literalToPrettyString($literal, $installedMap): string
{
$package = $this->literalToPackage($literal);
@ -212,7 +212,7 @@ class Pool implements \Countable
* @param string $name Name of the package to be matched
* @return bool
*/
public function match(BasePackage $candidate, $name, ConstraintInterface $constraint = null)
public function match(BasePackage $candidate, $name, ConstraintInterface $constraint = null): bool
{
$candidateName = $candidate->getName();
$candidateVersion = $candidate->getVersion();
@ -255,7 +255,7 @@ class Pool implements \Countable
/**
* @return bool
*/
public function isUnacceptableFixedOrLockedPackage(BasePackage $package)
public function isUnacceptableFixedOrLockedPackage(BasePackage $package): bool
{
return \in_array($package, $this->unacceptableFixedOrLockedPackages, true);
}
@ -263,7 +263,7 @@ class Pool implements \Countable
/**
* @return BasePackage[]
*/
public function getUnacceptableFixedOrLockedPackages()
public function getUnacceptableFixedOrLockedPackages(): array
{
return $this->unacceptableFixedOrLockedPackages;
}

View File

@ -158,7 +158,7 @@ class PoolBuilder
* @param RepositoryInterface[] $repositories
* @return Pool
*/
public function buildPool(array $repositories, Request $request)
public function buildPool(array $repositories, Request $request): Pool
{
if ($request->getUpdateAllowList()) {
$this->updateAllowList = $request->getUpdateAllowList();
@ -300,7 +300,7 @@ class PoolBuilder
* @param string $name
* @return void
*/
private function markPackageNameForLoading(Request $request, $name, ConstraintInterface $constraint)
private function markPackageNameForLoading(Request $request, $name, ConstraintInterface $constraint): void
{
// Skip platform requires at this stage
if (PlatformRepository::isPlatformPackage($name)) {
@ -359,7 +359,7 @@ class PoolBuilder
* @param RepositoryInterface[] $repositories
* @return void
*/
private function loadPackagesMarkedForLoading(Request $request, array $repositories)
private function loadPackagesMarkedForLoading(Request $request, array $repositories): void
{
foreach ($this->packagesToLoad as $name => $constraint) {
$this->loadedPackages[$name] = $constraint;
@ -396,7 +396,7 @@ class PoolBuilder
* @param RepositoryInterface[] $repositories
* @return void
*/
private function loadPackage(Request $request, array $repositories, BasePackage $package, $propagateUpdate)
private function loadPackage(Request $request, array $repositories, BasePackage $package, $propagateUpdate): void
{
$index = $this->indexCounter++;
$this->packages[$index] = $package;
@ -501,7 +501,7 @@ class PoolBuilder
* @param string $name packageName
* @return bool
*/
private function isRootRequire(Request $request, $name)
private function isRootRequire(Request $request, $name): bool
{
$rootRequires = $request->getRequires();
@ -512,7 +512,7 @@ class PoolBuilder
* @param string $name
* @return string[]
*/
private function getSkippedRootRequires(Request $request, $name)
private function getSkippedRootRequires(Request $request, $name): array
{
if (!isset($this->skippedLoad[$name])) {
return array();
@ -522,7 +522,7 @@ class PoolBuilder
$matches = array();
if (isset($rootRequires[$name])) {
return array_map(function (PackageInterface $package) use ($name) {
return array_map(function (PackageInterface $package) use ($name): string {
if ($name !== $package->getName()) {
return $package->getName() .' (via replace of '.$name.')';
}
@ -555,7 +555,7 @@ class PoolBuilder
*
* @return bool
*/
private function isUpdateAllowed(BasePackage $package)
private function isUpdateAllowed(BasePackage $package): bool
{
foreach ($this->updateAllowList as $pattern => $void) {
$patternRegexp = BasePackage::packageNameToRegexp($pattern);
@ -570,7 +570,7 @@ class PoolBuilder
/**
* @return void
*/
private function warnAboutNonMatchingUpdateAllowList(Request $request)
private function warnAboutNonMatchingUpdateAllowList(Request $request): void
{
foreach ($this->updateAllowList as $pattern => $void) {
$patternRegexp = BasePackage::packageNameToRegexp($pattern);
@ -602,7 +602,7 @@ class PoolBuilder
* @param string $name
* @return void
*/
private function unlockPackage(Request $request, array $repositories, $name)
private function unlockPackage(Request $request, array $repositories, $name): void
{
foreach ($this->skippedLoad[$name] as $packageOrReplacer) {
// if we unfixed a replaced package name, we also need to unfix the replacer itself
@ -668,7 +668,7 @@ class PoolBuilder
* @param int $index
* @return void
*/
private function removeLoadedPackage(Request $request, array $repositories, BasePackage $package, $index)
private function removeLoadedPackage(Request $request, array $repositories, BasePackage $package, $index): void
{
$repoIndex = array_search($package->getRepository(), $repositories, true);
@ -686,7 +686,7 @@ class PoolBuilder
/**
* @return Pool
*/
private function runOptimizer(Request $request, Pool $pool)
private function runOptimizer(Request $request, Pool $pool): Pool
{
if (null === $this->poolOptimizer) {
return $pool;

View File

@ -71,7 +71,7 @@ class PoolOptimizer
/**
* @return Pool
*/
public function optimize(Request $request, Pool $pool)
public function optimize(Request $request, Pool $pool): Pool
{
$this->prepare($request, $pool);
@ -99,7 +99,7 @@ class PoolOptimizer
/**
* @return void
*/
private function prepare(Request $request, Pool $pool)
private function prepare(Request $request, Pool $pool): void
{
$irremovablePackageConstraintGroups = array();
@ -155,7 +155,7 @@ class PoolOptimizer
/**
* @return void
*/
private function markPackageIrremovable(BasePackage $package)
private function markPackageIrremovable(BasePackage $package): void
{
$this->irremovablePackages[$package->id] = true;
if ($package instanceof AliasPackage) {
@ -173,7 +173,7 @@ class PoolOptimizer
/**
* @return Pool Optimized pool
*/
private function applyRemovalsToPool(Pool $pool)
private function applyRemovalsToPool(Pool $pool): Pool
{
$packages = array();
$removedVersions = array();
@ -193,7 +193,7 @@ class PoolOptimizer
/**
* @return void
*/
private function optimizeByIdenticalDependencies(Request $request, Pool $pool)
private function optimizeByIdenticalDependencies(Request $request, Pool $pool): void
{
$identicalDefinitionsPerPackage = array();
$packageIdenticalDefinitionLookup = array();
@ -278,7 +278,7 @@ class PoolOptimizer
/**
* @return string
*/
private function calculateDependencyHash(BasePackage $package)
private function calculateDependencyHash(BasePackage $package): string
{
$hash = '';
@ -322,7 +322,7 @@ class PoolOptimizer
* @param int $id
* @return void
*/
private function markPackageForRemoval($id)
private function markPackageForRemoval($id): void
{
// We are not allowed to remove packages if they have been marked as irremovable
if (isset($this->irremovablePackages[$id])) {
@ -337,7 +337,7 @@ class PoolOptimizer
* @param array<int, array<string, array{groupHash: string, dependencyHash: string}>> $packageIdenticalDefinitionLookup
* @return void
*/
private function keepPackage(BasePackage $package, $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup)
private function keepPackage(BasePackage $package, $identicalDefinitionsPerPackage, $packageIdenticalDefinitionLookup): void
{
unset($this->packagesToRemove[$package->id]);
@ -389,7 +389,7 @@ class PoolOptimizer
*
* @return void
*/
private function optimizeImpossiblePackagesAway(Request $request, Pool $pool)
private function optimizeImpossiblePackagesAway(Request $request, Pool $pool): void
{
if (count($request->getLockedPackages()) === 0) {
return;

View File

@ -54,7 +54,7 @@ class Problem
* @param Rule $rule A rule which is a reason for this problem
* @return void
*/
public function addRule(Rule $rule)
public function addRule(Rule $rule): void
{
$this->addReason(spl_object_hash($rule), $rule);
}
@ -64,7 +64,7 @@ class Problem
*
* @return array<int, array<int, Rule>> The problem's reasons
*/
public function getReasons()
public function getReasons(): array
{
return $this->reasons;
}
@ -77,7 +77,7 @@ class Problem
* @param array<Rule[]> $learnedPool
* @return string
*/
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array())
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string
{
// TODO doesn't this entirely defeat the purpose of the problem sections? what's the point of sections?
$reasons = call_user_func_array('array_merge', array_reverse($this->reasons));
@ -117,7 +117,7 @@ class Problem
* @return string
* @internal
*/
public static function formatDeduplicatedRules($rules, $indent, RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array())
public static function formatDeduplicatedRules($rules, $indent, RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string
{
$messages = array();
$templates = array();
@ -165,7 +165,7 @@ class Problem
/**
* @return bool
*/
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool)
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool): bool
{
foreach ($this->reasons as $sectionRules) {
foreach ($sectionRules as $rule) {
@ -185,7 +185,7 @@ class Problem
* @param Rule $reason The reason descriptor
* @return void
*/
protected function addReason($id, Rule $reason)
protected function addReason($id, Rule $reason): void
{
// TODO: if a rule is part of a problem description in two sections, isn't this going to remove a message
// that is important to understand the issue?
@ -199,7 +199,7 @@ class Problem
/**
* @return void
*/
public function nextSection()
public function nextSection(): void
{
$this->section++;
}
@ -210,7 +210,7 @@ class Problem
* @param string $packageName
* @return array{0: string, 1: string}
*/
public static function getMissingPackageReason(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $packageName, ConstraintInterface $constraint = null)
public static function getMissingPackageReason(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $packageName, ConstraintInterface $constraint = null): array
{
if (PlatformRepository::isPlatformPackage($packageName)) {
// handle php/php-*/hhvm
@ -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) {
$filtered = array_filter($packages, function ($p) use ($rootReqs, $packageName): bool {
return $rootReqs[$packageName]->matches(new Constraint('==', $p->getVersion()));
});
if (0 === count($filtered)) {
@ -296,7 +296,7 @@ class Problem
if ($lockedPackage) {
$fixedConstraint = new Constraint('==', $lockedPackage->getVersion());
$filtered = array_filter($packages, function ($p) use ($fixedConstraint) {
$filtered = array_filter($packages, function ($p) use ($fixedConstraint): bool {
return $fixedConstraint->matches(new Constraint('==', $p->getVersion()));
});
if (0 === count($filtered)) {
@ -304,7 +304,7 @@ class Problem
}
}
$nonLockedPackages = array_filter($packages, function ($p) {
$nonLockedPackages = array_filter($packages, function ($p): bool {
return !$p->getRepository() instanceof LockArrayRepository;
});
@ -360,7 +360,7 @@ class Problem
if ($providers = $repositorySet->getProviders($packageName)) {
$maxProviders = 20;
$providersStr = implode(array_map(function ($p) {
$providersStr = implode(array_map(function ($p): string {
$description = $p['description'] ? ' '.substr($p['description'], 0, 100) : '';
return " - ${p['name']}".$description."\n";
@ -382,7 +382,7 @@ class Problem
* @param bool $useRemovedVersionGroup
* @return string
*/
public static function getPackageList(array $packages, $isVerbose, Pool $pool = null, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false)
public static function getPackageList(array $packages, $isVerbose, Pool $pool = null, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false): string
{
$prepared = array();
$hasDefaultBranch = array();
@ -427,7 +427,7 @@ class Problem
* @param string $version the effective runtime version of the platform package
* @return ?string a version string or null if it appears the package was artificially disabled
*/
private static function getPlatformPackageVersion(Pool $pool, $packageName, $version)
private static function getPlatformPackageVersion(Pool $pool, $packageName, $version): ?string
{
$available = $pool->whatProvides($packageName);
@ -471,7 +471,7 @@ class Problem
* @param int $maxDev
* @return list<string> a list of pretty versions and '...' where versions were removed
*/
private static function condenseVersionList(array $versions, $max, $maxDev = 16)
private static function condenseVersionList(array $versions, $max, $maxDev = 16): array
{
if (count($versions) <= $max) {
return $versions;
@ -505,7 +505,7 @@ class Problem
* @param PackageInterface[] $packages
* @return bool
*/
private static function hasMultipleNames(array $packages)
private static function hasMultipleNames(array $packages): bool
{
$name = null;
foreach ($packages as $package) {
@ -527,7 +527,7 @@ class Problem
* @param string $reason
* @return array{0: string, 1: string}
*/
private static function computeCheckForLowerPrioRepo(Pool $pool, $isVerbose, $packageName, array $higherRepoPackages, array $allReposPackages, $reason, ConstraintInterface $constraint = null)
private static function computeCheckForLowerPrioRepo(Pool $pool, $isVerbose, $packageName, array $higherRepoPackages, array $allReposPackages, $reason, ConstraintInterface $constraint = null): array
{
$nextRepoPackages = array();
$nextRepo = null;
@ -576,7 +576,7 @@ class Problem
*
* @return string
*/
protected static function constraintToText(ConstraintInterface $constraint = null)
protected static function constraintToText(ConstraintInterface $constraint = null): string
{
return $constraint ? ' '.$constraint->getPrettyString() : '';
}

View File

@ -64,7 +64,7 @@ class Request
* @param string $packageName
* @return void
*/
public function requireName($packageName, ConstraintInterface $constraint = null)
public function requireName($packageName, ConstraintInterface $constraint = null): void
{
$packageName = strtolower($packageName);
@ -85,7 +85,7 @@ class Request
*
* @return void
*/
public function fixPackage(BasePackage $package)
public function fixPackage(BasePackage $package): void
{
$this->fixedPackages[spl_object_hash($package)] = $package;
}
@ -102,7 +102,7 @@ class Request
*
* @return void
*/
public function lockPackage(BasePackage $package)
public function lockPackage(BasePackage $package): void
{
$this->lockedPackages[spl_object_hash($package)] = $package;
}
@ -116,7 +116,7 @@ class Request
*
* @return void
*/
public function fixLockedPackage(BasePackage $package)
public function fixLockedPackage(BasePackage $package): void
{
$this->fixedPackages[spl_object_hash($package)] = $package;
$this->fixedLockedPackages[spl_object_hash($package)] = $package;
@ -125,7 +125,7 @@ class Request
/**
* @return void
*/
public function unlockPackage(BasePackage $package)
public function unlockPackage(BasePackage $package): void
{
unset($this->lockedPackages[spl_object_hash($package)]);
}
@ -135,7 +135,7 @@ class Request
* @param false|self::UPDATE_* $updateAllowTransitiveDependencies
* @return void
*/
public function setUpdateAllowList($updateAllowList, $updateAllowTransitiveDependencies)
public function setUpdateAllowList($updateAllowList, $updateAllowTransitiveDependencies): void
{
$this->updateAllowList = $updateAllowList;
$this->updateAllowTransitiveDependencies = $updateAllowTransitiveDependencies;
@ -144,7 +144,7 @@ class Request
/**
* @return string[]
*/
public function getUpdateAllowList()
public function getUpdateAllowList(): array
{
return $this->updateAllowList;
}
@ -152,7 +152,7 @@ class Request
/**
* @return bool
*/
public function getUpdateAllowTransitiveDependencies()
public function getUpdateAllowTransitiveDependencies(): bool
{
return $this->updateAllowTransitiveDependencies !== self::UPDATE_ONLY_LISTED;
}
@ -160,7 +160,7 @@ class Request
/**
* @return bool
*/
public function getUpdateAllowTransitiveRootDependencies()
public function getUpdateAllowTransitiveRootDependencies(): bool
{
return $this->updateAllowTransitiveDependencies === self::UPDATE_LISTED_WITH_TRANSITIVE_DEPS;
}
@ -168,7 +168,7 @@ class Request
/**
* @return array<string, ConstraintInterface>
*/
public function getRequires()
public function getRequires(): array
{
return $this->requires;
}
@ -176,7 +176,7 @@ class Request
/**
* @return array<string, BasePackage>
*/
public function getFixedPackages()
public function getFixedPackages(): array
{
return $this->fixedPackages;
}
@ -184,7 +184,7 @@ class Request
/**
* @return bool
*/
public function isFixedPackage(BasePackage $package)
public function isFixedPackage(BasePackage $package): bool
{
return isset($this->fixedPackages[spl_object_hash($package)]);
}
@ -192,7 +192,7 @@ class Request
/**
* @return array<string, BasePackage>
*/
public function getLockedPackages()
public function getLockedPackages(): array
{
return $this->lockedPackages;
}
@ -200,7 +200,7 @@ class Request
/**
* @return bool
*/
public function isLockedPackage(PackageInterface $package)
public function isLockedPackage(PackageInterface $package): bool
{
return isset($this->lockedPackages[spl_object_hash($package)]) || isset($this->fixedLockedPackages[spl_object_hash($package)]);
}
@ -208,7 +208,7 @@ class Request
/**
* @return array<string, BasePackage>
*/
public function getFixedOrLockedPackages()
public function getFixedOrLockedPackages(): array
{
return array_merge($this->fixedPackages, $this->lockedPackages);
}
@ -222,7 +222,7 @@ class Request
* Some locked packages may not be in the pool,
* so they have a package->id of -1
*/
public function getPresentMap($packageIds = false)
public function getPresentMap($packageIds = false): array
{
$presentMap = array();
@ -242,7 +242,7 @@ class Request
/**
* @return BasePackage[]
*/
public function getFixedPackagesMap()
public function getFixedPackagesMap(): array
{
$fixedPackagesMap = array();
@ -256,7 +256,7 @@ class Request
/**
* @return ?LockArrayRepository
*/
public function getLockedRepository()
public function getLockedRepository(): ?LockArrayRepository
{
return $this->lockedRepository;
}

View File

@ -71,7 +71,7 @@ abstract class Rule
/**
* @return int[]
*/
abstract public function getLiterals();
abstract public function getLiterals(): array;
/**
* @return int|string
@ -84,12 +84,12 @@ abstract class Rule
* @param Rule $rule
* @return bool
*/
abstract public function equals(Rule $rule);
abstract public function equals(Rule $rule): bool;
/**
* @return int
*/
public function getReason()
public function getReason(): int
{
return ($this->bitfield & (255 << self::BITFIELD_REASON)) >> self::BITFIELD_REASON;
}
@ -105,7 +105,7 @@ abstract class Rule
/**
* @return string|null
*/
public function getRequiredPackage()
public function getRequiredPackage(): ?string
{
$reason = $this->getReason();
@ -128,7 +128,7 @@ abstract class Rule
* @param RuleSet::TYPE_* $type
* @return void
*/
public function setType($type)
public function setType($type): void
{
$this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_TYPE)) | ((255 & $type) << self::BITFIELD_TYPE);
}
@ -136,7 +136,7 @@ abstract class Rule
/**
* @return int
*/
public function getType()
public function getType(): int
{
return ($this->bitfield & (255 << self::BITFIELD_TYPE)) >> self::BITFIELD_TYPE;
}
@ -144,7 +144,7 @@ abstract class Rule
/**
* @return void
*/
public function disable()
public function disable(): void
{
$this->bitfield = ($this->bitfield & ~(255 << self::BITFIELD_DISABLED)) | (1 << self::BITFIELD_DISABLED);
}
@ -152,7 +152,7 @@ abstract class Rule
/**
* @return void
*/
public function enable()
public function enable(): void
{
$this->bitfield &= ~(255 << self::BITFIELD_DISABLED);
}
@ -160,7 +160,7 @@ abstract class Rule
/**
* @return bool
*/
public function isDisabled()
public function isDisabled(): bool
{
return (bool) (($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED);
}
@ -168,7 +168,7 @@ abstract class Rule
/**
* @return bool
*/
public function isEnabled()
public function isEnabled(): bool
{
return !(($this->bitfield & (255 << self::BITFIELD_DISABLED)) >> self::BITFIELD_DISABLED);
}
@ -176,12 +176,12 @@ abstract class Rule
/**
* @return bool
*/
abstract public function isAssertion();
abstract public function isAssertion(): bool;
/**
* @return bool
*/
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool)
public function isCausedByLock(RepositorySet $repositorySet, Request $request, Pool $pool): bool
{
if ($this->getReason() === self::RULE_PACKAGE_REQUIRES) {
if (PlatformRepository::isPlatformPackage($this->reasonData->getTarget())) {
@ -232,7 +232,7 @@ abstract class Rule
* @internal
* @return BasePackage
*/
public function getSourcePackage(Pool $pool)
public function getSourcePackage(Pool $pool): BasePackage
{
$literals = $this->getLiterals();
@ -267,7 +267,7 @@ abstract class Rule
* @param array<Rule[]> $learnedPool
* @return string
*/
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array())
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()): string
{
$literals = $this->getLiterals();
@ -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) {
$packagesNonAlias = array_values(array_filter($packages, function ($p): bool {
return !($p instanceof AliasPackage);
}));
if (count($packagesNonAlias) === 1) {
@ -484,7 +484,7 @@ abstract class Rule
* @param bool $useRemovedVersionGroup
* @return string
*/
protected function formatPackagesUnique(Pool $pool, array $packages, $isVerbose, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false)
protected function formatPackagesUnique(Pool $pool, array $packages, $isVerbose, ConstraintInterface $constraint = null, $useRemovedVersionGroup = false): string
{
foreach ($packages as $index => $package) {
if (!\is_object($package)) {
@ -498,7 +498,7 @@ abstract class Rule
/**
* @return BasePackage
*/
private function deduplicateDefaultBranchAlias(BasePackage $package)
private function deduplicateDefaultBranchAlias(BasePackage $package): BasePackage
{
if ($package instanceof AliasPackage && $package->getPrettyVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
$package = $package->getAliasOf();

View File

@ -45,7 +45,7 @@ class Rule2Literals extends Rule
}
/** @return int[] */
public function getLiterals()
public function getLiterals(): array
{
return array($this->literal1, $this->literal2);
}
@ -66,7 +66,7 @@ class Rule2Literals extends Rule
* @param Rule $rule The rule to check against
* @return bool Whether the rules are equal
*/
public function equals(Rule $rule)
public function equals(Rule $rule): bool
{
// specialized fast-case
if ($rule instanceof self) {
@ -98,7 +98,7 @@ class Rule2Literals extends Rule
}
/** @return false */
public function isAssertion()
public function isAssertion(): bool
{
return false;
}

View File

@ -59,7 +59,7 @@ class RuleSet implements \IteratorAggregate, \Countable
* @param self::TYPE_* $type
* @return void
*/
public function add(Rule $rule, $type)
public function add(Rule $rule, $type): void
{
if (!isset(self::$types[$type])) {
throw new \OutOfBoundsException('Unknown rule type: ' . $type);
@ -112,13 +112,13 @@ class RuleSet implements \IteratorAggregate, \Countable
* @param int $id
* @return Rule
*/
public function ruleById($id)
public function ruleById($id): Rule
{
return $this->ruleById[$id];
}
/** @return array<self::TYPE_*, Rule[]> */
public function getRules()
public function getRules(): array
{
return $this->rules;
}
@ -132,7 +132,7 @@ class RuleSet implements \IteratorAggregate, \Countable
* @param self::TYPE_*|array<self::TYPE_*> $types
* @return RuleSetIterator
*/
public function getIteratorFor($types)
public function getIteratorFor($types): RuleSetIterator
{
if (!\is_array($types)) {
$types = array($types);
@ -154,7 +154,7 @@ class RuleSet implements \IteratorAggregate, \Countable
* @param array<self::TYPE_*>|self::TYPE_* $types
* @return RuleSetIterator
*/
public function getIteratorWithout($types)
public function getIteratorWithout($types): RuleSetIterator
{
if (!\is_array($types)) {
$types = array($types);
@ -170,7 +170,7 @@ class RuleSet implements \IteratorAggregate, \Countable
}
/** @return array{0: 0, 1: 1, 2: 4} */
public function getTypes()
public function getTypes(): array
{
$types = self::$types;
@ -181,7 +181,7 @@ class RuleSet implements \IteratorAggregate, \Countable
* @param bool $isVerbose
* @return string
*/
public function getPrettyString(RepositorySet $repositorySet = null, Request $request = null, Pool $pool = null, $isVerbose = false)
public function getPrettyString(RepositorySet $repositorySet = null, Request $request = null, Pool $pool = null, $isVerbose = false): string
{
$string = "\n";
foreach ($this->rules as $type => $rules) {

View File

@ -56,7 +56,7 @@ class RuleSetGenerator
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData = null)
protected function createRequireRule(BasePackage $package, array $providers, $reason, $reasonData = null): ?Rule
{
$literals = array(-$package->id);
@ -85,7 +85,7 @@ class RuleSetGenerator
*
* @phpstan-param ReasonData $reasonData
*/
protected function createInstallOneOfRule(array $packages, $reason, $reasonData)
protected function createInstallOneOfRule(array $packages, $reason, $reasonData): Rule
{
$literals = array();
foreach ($packages as $package) {
@ -109,7 +109,7 @@ class RuleSetGenerator
*
* @phpstan-param ReasonData $reasonData
*/
protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData = null)
protected function createRule2Literals(BasePackage $issuer, BasePackage $provider, $reason, $reasonData = null): ?Rule
{
// ignore self conflict
if ($issuer === $provider) {
@ -127,7 +127,7 @@ class RuleSetGenerator
*
* @phpstan-param ReasonData $reasonData
*/
protected function createMultiConflictRule(array $packages, $reason, $reasonData)
protected function createMultiConflictRule(array $packages, $reason, $reasonData): Rule
{
$literals = array();
foreach ($packages as $package) {
@ -152,7 +152,7 @@ class RuleSetGenerator
*
* @return void
*/
private function addRule($type, Rule $newRule = null)
private function addRule($type, Rule $newRule = null): void
{
if (!$newRule) {
return;
@ -164,7 +164,7 @@ class RuleSetGenerator
/**
* @return void
*/
protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter)
protected function addRulesForPackage(BasePackage $package, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var \SplQueue<BasePackage> */
$workQueue = new \SplQueue;
@ -218,7 +218,7 @@ class RuleSetGenerator
/**
* @return void
*/
protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter)
protected function addConflictRules(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
/** @var BasePackage $package */
foreach ($this->addedMap as $package) {
@ -259,7 +259,7 @@ class RuleSetGenerator
/**
* @return void
*/
protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter)
protected function addRulesForRequest(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($request->getFixedPackages() as $package) {
if ($package->id == -1) {
@ -305,7 +305,7 @@ class RuleSetGenerator
/**
* @return void
*/
protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter)
protected function addRulesForRootAliases(PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($this->pool->getPackages() as $package) {
// ensure that rules for root alias packages and aliases of packages which were loaded are also loaded
@ -323,7 +323,7 @@ class RuleSetGenerator
/**
* @return RuleSet
*/
public function getRulesFor(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null)
public function getRulesFor(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null): RuleSet
{
$platformRequirementFilter = $platformRequirementFilter ?: PlatformRequirementFilterFactory::ignoreNothing();

View File

@ -29,7 +29,7 @@ class RuleWatchChain extends \SplDoublyLinkedList
* @param int $offset The offset to seek to.
* @return void
*/
public function seek($offset)
public function seek($offset): void
{
$this->rewind();
for ($i = 0; $i < $offset; $i++, $this->next());
@ -45,7 +45,7 @@ class RuleWatchChain extends \SplDoublyLinkedList
*
* @return void
*/
public function remove()
public function remove(): void
{
$offset = $this->key();
$this->offsetUnset($offset);

View File

@ -40,7 +40,7 @@ class RuleWatchGraph
* @param RuleWatchNode $node The rule node to be inserted into the graph
* @return void
*/
public function insert(RuleWatchNode $node)
public function insert(RuleWatchNode $node): void
{
if ($node->getRule()->isAssertion()) {
return;
@ -88,7 +88,7 @@ class RuleWatchGraph
* register decisions resulting from propagation
* @return Rule|null If a conflict is found the conflicting rule is returned
*/
public function propagateLiteral($decidedLiteral, $level, Decisions $decisions)
public function propagateLiteral($decidedLiteral, $level, Decisions $decisions): ?Rule
{
// we invert the decided literal here, example:
// A was decided => (-A|B) now requires B to be true, so we look for
@ -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) {
$alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions): bool {
return $literal !== $ruleLiteral &&
$otherWatch !== $ruleLiteral &&
!$decisions->conflict($ruleLiteral);
@ -156,7 +156,7 @@ class RuleWatchGraph
* @param RuleWatchNode $node The rule node to be moved
* @return void
*/
protected function moveWatch($fromLiteral, $toLiteral, RuleWatchNode $node)
protected function moveWatch($fromLiteral, $toLiteral, RuleWatchNode $node): void
{
if (!isset($this->watchChains[$toLiteral])) {
$this->watchChains[$toLiteral] = new RuleWatchChain;

View File

@ -54,7 +54,7 @@ class RuleWatchNode
* @param Decisions $decisions The decisions made so far by the solver
* @return void
*/
public function watch2OnHighest(Decisions $decisions)
public function watch2OnHighest(Decisions $decisions): void
{
$literals = $this->rule->getLiterals();
@ -80,7 +80,7 @@ class RuleWatchNode
*
* @return Rule
*/
public function getRule()
public function getRule(): Rule
{
return $this->rule;
}
@ -91,7 +91,7 @@ class RuleWatchNode
* @param int $literal The watched literal that should not be returned
* @return int A literal
*/
public function getOtherWatch($literal)
public function getOtherWatch($literal): int
{
if ($this->watch1 == $literal) {
return $this->watch2;
@ -107,7 +107,7 @@ class RuleWatchNode
* @param int $to The literal to be watched now
* @return void
*/
public function moveWatch($from, $to)
public function moveWatch($from, $to): void
{
if ($this->watch1 == $from) {
$this->watch1 = $to;

View File

@ -68,7 +68,7 @@ class Solver
/**
* @return int
*/
public function getRuleSetSize()
public function getRuleSetSize(): int
{
return \count($this->rules);
}
@ -76,7 +76,7 @@ class Solver
/**
* @return Pool
*/
public function getPool()
public function getPool(): Pool
{
return $this->pool;
}
@ -86,7 +86,7 @@ class Solver
/**
* @return void
*/
private function makeAssertionRuleDecisions()
private function makeAssertionRuleDecisions(): void
{
$decisionStart = \count($this->decisions) - 1;
@ -159,7 +159,7 @@ class Solver
/**
* @return void
*/
protected function setupFixedMap(Request $request)
protected function setupFixedMap(Request $request): void
{
$this->fixedMap = array();
foreach ($request->getFixedPackages() as $package) {
@ -170,7 +170,7 @@ class Solver
/**
* @return void
*/
protected function checkForRootRequireProblems(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter)
protected function checkForRootRequireProblems(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter): void
{
foreach ($request->getRequires() as $packageName => $constraint) {
if ($platformRequirementFilter->isIgnored($packageName)) {
@ -190,7 +190,7 @@ class Solver
/**
* @return LockTransaction
*/
public function solve(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null)
public function solve(Request $request, PlatformRequirementFilterInterface $platformRequirementFilter = null): LockTransaction
{
$platformRequirementFilter = $platformRequirementFilter ?: PlatformRequirementFilterFactory::ignoreNothing();
@ -233,7 +233,7 @@ class Solver
* @param int $level
* @return Rule|null A rule on conflict, otherwise null.
*/
protected function propagate($level)
protected function propagate($level): ?Rule
{
while ($this->decisions->validOffset($this->propagateIndex)) {
$decision = $this->decisions->atOffset($this->propagateIndex);
@ -261,7 +261,7 @@ class Solver
*
* @return void
*/
private function revert($level)
private function revert($level): void
{
while (!$this->decisions->isEmpty()) {
$literal = $this->decisions->lastLiteral();
@ -302,7 +302,7 @@ class Solver
* @param string|int $literal
* @return int
*/
private function setPropagateLearn($level, $literal, Rule $rule)
private function setPropagateLearn($level, $literal, Rule $rule): int
{
$level++;
@ -351,7 +351,7 @@ class Solver
* @param int[] $decisionQueue
* @return int
*/
private function selectAndInstall($level, array $decisionQueue, Rule $rule)
private function selectAndInstall($level, array $decisionQueue, Rule $rule): int
{
// choose best package to install from decisionQueue
$literals = $this->policy->selectPreferredPackages($this->pool, $decisionQueue, $rule->getRequiredPackage());
@ -370,7 +370,7 @@ class Solver
* @param int $level
* @return array{int, int, GenericRule, int}
*/
protected function analyze($level, Rule $rule)
protected function analyze($level, Rule $rule): array
{
$analyzedRule = $rule;
$ruleLevel = 1;
@ -518,7 +518,7 @@ class Solver
* @param array<string, true> $ruleSeen
* @return void
*/
private function analyzeUnsolvableRule(Problem $problem, Rule $conflictRule, array &$ruleSeen)
private function analyzeUnsolvableRule(Problem $problem, Rule $conflictRule, array &$ruleSeen): void
{
$why = spl_object_hash($conflictRule);
$ruleSeen[$why] = true;
@ -548,7 +548,7 @@ class Solver
/**
* @return int
*/
private function analyzeUnsolvable(Rule $conflictRule)
private function analyzeUnsolvable(Rule $conflictRule): int
{
$problem = new Problem();
$problem->addRule($conflictRule);
@ -606,7 +606,7 @@ class Solver
*
* @return void
*/
private function enableDisableLearnedRules()
private function enableDisableLearnedRules(): void
{
foreach ($this->rules->getIteratorFor(RuleSet::TYPE_LEARNED) as $rule) {
$why = $this->learnedWhy[spl_object_hash($rule)];
@ -631,7 +631,7 @@ class Solver
/**
* @return void
*/
private function runSat()
private function runSat(): void
{
$this->propagateIndex = 0;

View File

@ -46,7 +46,7 @@ class SolverProblemsException extends \RuntimeException
* @param bool $isDevExtraction
* @return string
*/
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $isDevExtraction = false)
public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $isDevExtraction = false): string
{
$installedMap = $request->getPresentMap(true);
$missingExtensions = array();
@ -100,7 +100,7 @@ class SolverProblemsException extends \RuntimeException
/**
* @return Problem[]
*/
public function getProblems()
public function getProblems(): array
{
return $this->problems;
}
@ -109,7 +109,7 @@ class SolverProblemsException extends \RuntimeException
* @param string[] $missingExtensions
* @return string
*/
private function createExtensionHint(array $missingExtensions)
private function createExtensionHint(array $missingExtensions): string
{
$paths = IniHelper::getAll();
@ -133,7 +133,7 @@ class SolverProblemsException extends \RuntimeException
* @param Rule[][] $reasonSets
* @return string[]
*/
private function getExtensionProblems(array $reasonSets)
private function getExtensionProblems(array $reasonSets): array
{
$missingExtensions = array();
foreach ($reasonSets as $reasonSet) {

View File

@ -60,7 +60,7 @@ class Transaction
/**
* @return OperationInterface[]
*/
public function getOperations()
public function getOperations(): array
{
return $this->operations;
}
@ -69,9 +69,9 @@ class Transaction
* @param PackageInterface[] $resultPackages
* @return void
*/
private function setResultPackageMaps($resultPackages)
private function setResultPackageMaps($resultPackages): void
{
$packageSort = function (PackageInterface $a, PackageInterface $b) {
$packageSort = function (PackageInterface $a, PackageInterface $b): int {
// sort alias packages by the same name behind their non alias version
if ($a->getName() == $b->getName()) {
if ($a instanceof AliasPackage != $b instanceof AliasPackage) {
@ -101,7 +101,7 @@ class Transaction
/**
* @return OperationInterface[]
*/
protected function calculateOperations()
protected function calculateOperations(): array
{
$operations = array();
@ -218,7 +218,7 @@ class Transaction
*
* @return array<string, PackageInterface>
*/
protected function getRootPackages()
protected function getRootPackages(): array
{
$roots = $this->resultPackageMap;
@ -244,7 +244,7 @@ class Transaction
/**
* @return PackageInterface[]
*/
protected function getProvidersInResult(Link $link)
protected function getProvidersInResult(Link $link): array
{
if (!isset($this->resultPackagesByName[$link->getTarget()])) {
return array();
@ -266,7 +266,7 @@ class Transaction
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function movePluginsToFront(array $operations)
private function movePluginsToFront(array $operations): array
{
$dlModifyingPluginsNoDeps = array();
$dlModifyingPluginsWithDeps = array();
@ -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) {
$requires = array_filter(array_keys($package->getRequires()), 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) {
$requires = array_filter(array_keys($package->getRequires()), function ($req): bool {
return !PlatformRepository::isPlatformPackage($req);
});
@ -343,7 +343,7 @@ class Transaction
* @param OperationInterface[] $operations
* @return OperationInterface[] reordered operation list
*/
private function moveUninstallsToFront(array $operations)
private function moveUninstallsToFront(array $operations): array
{
$uninstOps = array();
foreach ($operations as $idx => $op) {

View File

@ -116,7 +116,7 @@ abstract class ArchiveDownloader extends FileDownloader
$promise = \React\Promise\resolve();
}
return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path) {
return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path): \React\Promise\PromiseInterface {
$filesystem->unlink($fileName);
/**
@ -125,7 +125,7 @@ abstract class ArchiveDownloader extends FileDownloader
* @param string $dir Directory
* @return \SplFileInfo[]
*/
$getFolderContent = function ($dir) {
$getFolderContent = function ($dir): array {
$finder = Finder::create()
->ignoreVCS(false)
->ignoreDotFiles(false)

View File

@ -59,7 +59,7 @@ class DownloadManager
* @param bool $preferSource prefer downloading from source
* @return DownloadManager
*/
public function setPreferSource($preferSource)
public function setPreferSource($preferSource): DownloadManager
{
$this->preferSource = $preferSource;
@ -72,7 +72,7 @@ class DownloadManager
* @param bool $preferDist prefer downloading from dist
* @return DownloadManager
*/
public function setPreferDist($preferDist)
public function setPreferDist($preferDist): DownloadManager
{
$this->preferDist = $preferDist;
@ -86,7 +86,7 @@ class DownloadManager
*
* @return DownloadManager
*/
public function setPreferences(array $preferences)
public function setPreferences(array $preferences): DownloadManager
{
$this->packagePreferences = $preferences;
@ -100,7 +100,7 @@ class DownloadManager
* @param DownloaderInterface $downloader downloader instance
* @return DownloadManager
*/
public function setDownloader($type, DownloaderInterface $downloader)
public function setDownloader($type, DownloaderInterface $downloader): DownloadManager
{
$type = strtolower($type);
$this->downloaders[$type] = $downloader;
@ -115,7 +115,7 @@ class DownloadManager
* @throws \InvalidArgumentException if downloader for provided type is not registered
* @return DownloaderInterface
*/
public function getDownloader($type)
public function getDownloader($type): DownloaderInterface
{
$type = strtolower($type);
if (!isset($this->downloaders[$type])) {
@ -134,7 +134,7 @@ class DownloadManager
* wrong type
* @return DownloaderInterface|null
*/
public function getDownloaderForPackage(PackageInterface $package)
public function getDownloaderForPackage(PackageInterface $package): ?DownloaderInterface
{
$installationSource = $package->getInstallationSource();
@ -168,7 +168,7 @@ class DownloadManager
/**
* @return string
*/
public function getDownloaderType(DownloaderInterface $downloader)
public function getDownloaderType(DownloaderInterface $downloader): string
{
return array_search($downloader, $this->downloaders);
}
@ -184,7 +184,7 @@ class DownloadManager
* @throws \RuntimeException
* @return PromiseInterface
*/
public function download(PackageInterface $package, $targetDir, PackageInterface $prevPackage = null)
public function download(PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$this->filesystem->ensureDirectoryExists(dirname($targetDir));
@ -253,7 +253,7 @@ class DownloadManager
*
* @return PromiseInterface|null
*/
public function prepare($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null)
public function prepare($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): ?PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
@ -274,7 +274,7 @@ class DownloadManager
* @throws \RuntimeException
* @return PromiseInterface|null
*/
public function install(PackageInterface $package, $targetDir)
public function install(PackageInterface $package, $targetDir): ?PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
@ -295,7 +295,7 @@ class DownloadManager
* @throws \InvalidArgumentException if initial package is not installed
* @return PromiseInterface|null
*/
public function update(PackageInterface $initial, PackageInterface $target, $targetDir)
public function update(PackageInterface $initial, PackageInterface $target, $targetDir): ?PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($target);
@ -330,9 +330,14 @@ class DownloadManager
// if downloader type changed, or update failed and user asks for reinstall,
// we wipe the dir and do a new install instead of updating it
$promise = $initialDownloader->remove($initial, $targetDir);
if ($promise) {
return $promise->then(function ($res) use ($target, $targetDir) {
return $this->install($target, $targetDir);
if ($promise instanceof PromiseInterface) {
return $promise->then(function ($res) use ($target, $targetDir): PromiseInterface {
$promise = $this->install($target, $targetDir);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve();
});
}
@ -347,7 +352,7 @@ class DownloadManager
*
* @return PromiseInterface|null
*/
public function remove(PackageInterface $package, $targetDir)
public function remove(PackageInterface $package, $targetDir): ?PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
@ -368,7 +373,7 @@ class DownloadManager
*
* @return PromiseInterface|null
*/
public function cleanup($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null)
public function cleanup($type, PackageInterface $package, $targetDir, PackageInterface $prevPackage = null): ?PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
@ -386,7 +391,7 @@ class DownloadManager
*
* @return string
*/
protected function resolvePackageInstallPreference(PackageInterface $package)
protected function resolvePackageInstallPreference(PackageInterface $package): string
{
foreach ($this->packagePreferences as $pattern => $preference) {
$pattern = '{^'.str_replace('\\*', '.*', preg_quote($pattern)).'$}i';
@ -406,7 +411,7 @@ class DownloadManager
* @return string[]
* @phpstan-return array<'dist'|'source'>&non-empty-array
*/
private function getAvailableSources(PackageInterface $package, PackageInterface $prevPackage = null)
private function getAvailableSources(PackageInterface $package, PackageInterface $prevPackage = null): array
{
$sourceType = $package->getSourceType();
$distType = $package->getDistType();
@ -432,7 +437,7 @@ class DownloadManager
&& !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev())
) {
$prevSource = $prevPackage->getInstallationSource();
usort($sources, function ($a, $b) use ($prevSource) {
usort($sources, function ($a, $b) use ($prevSource): int {
return $a === $prevSource ? -1 : 1;
});
@ -456,7 +461,7 @@ class DownloadManager
*
* @return string
*/
private function normalizeTargetDir($dir)
private function normalizeTargetDir($dir): string
{
if ($dir === '\\' || $dir === '/') {
return $dir;

View File

@ -118,7 +118,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
throw new \InvalidArgumentException('The given package is missing url information');
}
$cacheKeyGenerator = function (PackageInterface $package, $key) {
$cacheKeyGenerator = function (PackageInterface $package, $key): string {
$cacheKey = sha1($key);
return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
@ -195,7 +195,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
->then($accept, $reject);
}
return $result->then(function ($result) use ($fileName, $checksum, $url, $package, $eventDispatcher) {
return $result->then(function ($result) use ($fileName, $checksum, $url, $package, $eventDispatcher): string {
// in case of retry, the first call's Promise chain finally calls this twice at the end,
// once with $result being the returned $fileName from $accept, and then once for every
// failed request with a null result, which can be skipped.
@ -221,7 +221,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
});
};
$accept = function ($response) use ($cache, $package, $fileName, &$urls) {
$accept = function ($response) use ($cache, $package, $fileName, &$urls): string {
$url = reset($urls);
$cacheKey = $url['cacheKey'];
FileDownloader::$downloadMetadata[$package->getName()] = @filesize($fileName) ?: $response->getHeader('Content-Length') ?: '?';
@ -407,10 +407,13 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
$promise = \React\Promise\resolve();
}
return $promise->then(function () use ($target, $path) {
return $promise->then(function () use ($target, $path): PromiseInterface {
$promise = $this->install($target, $path, false);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve();
});
}
@ -426,7 +429,7 @@ class FileDownloader implements DownloaderInterface, ChangeReportInterface
}
$promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(function ($result) use ($path) {
return $promise->then(function ($result) use ($path): void {
if (!$result) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
}

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Util\ProcessExecutor;
@ -24,7 +25,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null)
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface
{
return \React\Promise\resolve();
}
@ -32,7 +33,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, $path, $url)
protected function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface
{
// Ensure we are allowed to use this URL by config
$this->config->prohibitUrlByConfig($url, $this->io);
@ -60,7 +61,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface
{
// Ensure we are allowed to use this URL by config
$this->config->prohibitUrlByConfig($url, $this->io);
@ -83,7 +84,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, $path)
public function getLocalChanges(PackageInterface $package, $path): ?string
{
if (!$this->hasMetadataRepository($path)) {
return null;
@ -97,7 +98,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function getCommitLogs($fromReference, $toReference, $path)
protected function getCommitLogs($fromReference, $toReference, $path): string
{
$command = sprintf('fossil timeline -t ci -W 0 -n 0 before %s', ProcessExecutor::escape($toReference));
@ -121,7 +122,7 @@ class FossilDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function hasMetadataRepository($path)
protected function hasMetadataRepository($path): bool
{
return is_file($path . '/.fslckout') || is_file($path . '/_FOSSIL_');
}

View File

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

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
@ -23,7 +24,7 @@ use Composer\Util\ProcessExecutor;
*/
class GzipDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, $file, $path)
protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface
{
$filename = pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_FILENAME);
$targetFilepath = $path . DIRECTORY_SEPARATOR . $filename;
@ -59,7 +60,7 @@ class GzipDownloader extends ArchiveDownloader
*
* @return void
*/
private function extractUsingExt($file, $targetFilepath)
private function extractUsingExt($file, $targetFilepath): void
{
$archiveFile = gzopen($file, 'rb');
$targetFile = fopen($targetFilepath, 'wb');

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Util\ProcessExecutor;
use Composer\Util\Hg as HgUtils;
@ -24,7 +25,7 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null)
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface
{
if (null === HgUtils::getVersion($this->process)) {
throw new \RuntimeException('hg was not found in your PATH, skipping source download');
@ -36,11 +37,11 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, $path, $url)
protected function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface
{
$hgUtils = new HgUtils($this->io, $this->config, $this->process);
$cloneCommand = function ($url) use ($path) {
$cloneCommand = function ($url) use ($path): string {
return sprintf('hg clone -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($path));
};
@ -58,7 +59,7 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface
{
$hgUtils = new HgUtils($this->io, $this->config, $this->process);
@ -69,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) {
$command = function ($url) use ($ref): string {
return sprintf('hg pull -- %s && hg up -- %s', ProcessExecutor::escape($url), ProcessExecutor::escape($ref));
};
@ -81,7 +82,7 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, $path)
public function getLocalChanges(PackageInterface $package, $path): ?string
{
if (!is_dir($path.'/.hg')) {
return null;
@ -95,7 +96,7 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function getCommitLogs($fromReference, $toReference, $path)
protected function getCommitLogs($fromReference, $toReference, $path): string
{
$command = sprintf('hg log -r %s:%s --style compact', ProcessExecutor::escape($fromReference), ProcessExecutor::escape($toReference));
@ -109,7 +110,7 @@ class HgDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function hasMetadataRepository($path)
protected function hasMetadataRepository($path): bool
{
return is_dir($path . '/.hg');
}

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\Archiver\ArchivableFilesFinder;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\PackageInterface;
@ -38,7 +39,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
/**
* @inheritDoc
*/
public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true)
public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true): ?PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
$url = $package->getDistUrl();
@ -74,7 +75,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
/**
* @inheritDoc
*/
public function install(PackageInterface $package, $path, $output = true)
public function install(PackageInterface $package, $path, $output = true): ?PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
$url = $package->getDistUrl();
@ -160,7 +161,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
/**
* @inheritDoc
*/
public function remove(PackageInterface $package, $path, $output = true)
public function remove(PackageInterface $package, $path, $output = true): ?PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
/**
@ -205,7 +206,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
/**
* @inheritDoc
*/
public function getVcsReference(PackageInterface $package, $path)
public function getVcsReference(PackageInterface $package, $path): ?string
{
$path = Filesystem::trimTrailingSlash($path);
$parser = new VersionParser;
@ -223,7 +224,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
/**
* @inheritDoc
*/
protected function getInstallOperationAppendix(PackageInterface $package, $path)
protected function getInstallOperationAppendix(PackageInterface $package, $path): string
{
$realUrl = realpath($package->getDistUrl());
@ -295,7 +296,7 @@ class PathDownloader extends FileDownloader implements VcsCapableDownloaderInter
*
* @return bool
*/
private function safeJunctions()
private function safeJunctions(): bool
{
// We need to call mklink, and rmdir on Windows 7 (version 6.1)
return function_exists('proc_open') &&

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Repository\VcsRepository;
use Composer\Util\Perforce;
@ -27,7 +28,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null)
protected function doDownload(PackageInterface $package, $path, $url, PackageInterface $prevPackage = null): ?PromiseInterface
{
return \React\Promise\resolve();
}
@ -35,7 +36,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
public function doInstall(PackageInterface $package, $path, $url)
public function doInstall(PackageInterface $package, $path, $url): ?PromiseInterface
{
$ref = $package->getSourceReference();
$label = $this->getLabelFromSourceReference((string) $ref);
@ -57,7 +58,7 @@ class PerforceDownloader extends VcsDownloader
*
* @return string|null
*/
private function getLabelFromSourceReference($ref)
private function getLabelFromSourceReference($ref): ?string
{
$pos = strpos($ref, '@');
if (false !== $pos) {
@ -73,7 +74,7 @@ class PerforceDownloader extends VcsDownloader
*
* @return void
*/
public function initPerforce(PackageInterface $package, $path, $url)
public function initPerforce(PackageInterface $package, $path, $url): void
{
if (!empty($this->perforce)) {
$this->perforce->initializePath($path);
@ -92,7 +93,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @return array<string, mixed>
*/
private function getRepoConfig(VcsRepository $repository)
private function getRepoConfig(VcsRepository $repository): array
{
return $repository->getRepoConfig();
}
@ -100,7 +101,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url): ?PromiseInterface
{
return $this->doInstall($target, $path, $url);
}
@ -108,7 +109,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, $path)
public function getLocalChanges(PackageInterface $package, $path): ?string
{
$this->io->writeError('Perforce driver does not check for local changes before overriding');
@ -118,7 +119,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function getCommitLogs($fromReference, $toReference, $path)
protected function getCommitLogs($fromReference, $toReference, $path): string
{
return $this->perforce->getCommitLogs($fromReference, $toReference);
}
@ -126,7 +127,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @return void
*/
public function setPerforce(Perforce $perforce)
public function setPerforce(Perforce $perforce): void
{
$this->perforce = $perforce;
}
@ -134,7 +135,7 @@ class PerforceDownloader extends VcsDownloader
/**
* @inheritDoc
*/
protected function hasMetadataRepository($path)
protected function hasMetadataRepository($path): bool
{
return true;
}

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
/**
@ -24,7 +25,7 @@ class PharDownloader extends ArchiveDownloader
/**
* @inheritDoc
*/
protected function extract(PackageInterface $package, $file, $path)
protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface
{
// Can throw an UnexpectedValueException
$archive = new \Phar($file);

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Util\IniHelper;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
@ -27,7 +28,7 @@ use RarArchive;
*/
class RarDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, $file, $path)
protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface
{
$processError = null;

View File

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

View File

@ -31,7 +31,7 @@ class TransportException extends \RuntimeException
*
* @return void
*/
public function setHeaders($headers)
public function setHeaders($headers): void
{
$this->headers = $headers;
}
@ -39,7 +39,7 @@ class TransportException extends \RuntimeException
/**
* @return ?array<string>
*/
public function getHeaders()
public function getHeaders(): ?array
{
return $this->headers;
}
@ -49,7 +49,7 @@ class TransportException extends \RuntimeException
*
* @return void
*/
public function setResponse($response)
public function setResponse($response): void
{
$this->response = $response;
}
@ -57,7 +57,7 @@ class TransportException extends \RuntimeException
/**
* @return ?string
*/
public function getResponse()
public function getResponse(): ?string
{
return $this->response;
}
@ -67,7 +67,7 @@ class TransportException extends \RuntimeException
*
* @return void
*/
public function setStatusCode($statusCode)
public function setStatusCode($statusCode): void
{
$this->statusCode = $statusCode;
}
@ -75,7 +75,7 @@ class TransportException extends \RuntimeException
/**
* @return ?int
*/
public function getStatusCode()
public function getStatusCode(): ?int
{
return $this->statusCode;
}
@ -83,7 +83,7 @@ class TransportException extends \RuntimeException
/**
* @return array<mixed>
*/
public function getResponseInfo()
public function getResponseInfo(): array
{
return $this->responseInfo;
}
@ -93,7 +93,7 @@ class TransportException extends \RuntimeException
*
* @return void
*/
public function setResponseInfo(array $responseInfo)
public function setResponseInfo(array $responseInfo): void
{
$this->responseInfo = $responseInfo;
}

View File

@ -200,7 +200,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa
}
if (trim($logs)) {
$logs = implode("\n", array_map(function ($line) {
$logs = implode("\n", array_map(function ($line): string {
return ' ' . $line;
}, explode("\n", $logs)));
@ -346,7 +346,7 @@ abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterfa
*
* @return string[]
*/
private function prepareUrls(array $urls)
private function prepareUrls(array $urls): array
{
foreach ($urls as $index => $url) {
if (Filesystem::isLocalPath($url)) {

View File

@ -12,6 +12,7 @@
namespace Composer\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Util\ProcessExecutor;
@ -23,7 +24,7 @@ use Composer\Util\ProcessExecutor;
*/
class XzDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, $file, $path)
protected function extract(PackageInterface $package, $file, $path): ?PromiseInterface
{
$command = 'tar -xJf ' . ProcessExecutor::escape($file) . ' -C ' . ProcessExecutor::escape($path);

View File

@ -105,7 +105,7 @@ class ZipDownloader extends ArchiveDownloader
* @param string $path Path where to extract file
* @return PromiseInterface
*/
private function extractWithSystemUnzip(PackageInterface $package, $file, $path)
private function extractWithSystemUnzip(PackageInterface $package, $file, $path): PromiseInterface
{
// Force Exception throwing if the other alternative extraction method is not available
$isLastChance = !self::$hasZipArchive;
@ -127,7 +127,7 @@ class ZipDownloader extends ArchiveDownloader
$executable = $commandSpec[0];
$io = $this->io;
$tryFallback = function ($processError) use ($isLastChance, $io, $file, $path, $package, $executable) {
$tryFallback = function ($processError) use ($isLastChance, $io, $file, $path, $package, $executable): \React\Promise\PromiseInterface {
if ($isLastChance) {
throw $processError;
}
@ -172,7 +172,7 @@ class ZipDownloader extends ArchiveDownloader
* @param string $path Path where to extract file
* @return PromiseInterface
*/
private function extractWithZipArchive(PackageInterface $package, $file, $path)
private function extractWithZipArchive(PackageInterface $package, $file, $path): PromiseInterface
{
$processError = null;
$zipArchive = $this->zipArchiveObject ?: new ZipArchive();

View File

@ -12,10 +12,12 @@
namespace Composer\EventDispatcher;
use Composer\Autoload\AutoloadGenerator;
use Composer\DependencyResolver\Transaction;
use Composer\Installer\InstallerEvent;
use Composer\IO\IOInterface;
use Composer\Composer;
use Composer\PartialComposer;
use Composer\Pcre\Preg;
use Composer\Util\Platform;
use Composer\DependencyResolver\Operation\OperationInterface;
@ -44,7 +46,7 @@ use Symfony\Component\Process\ExecutableFinder;
*/
class EventDispatcher
{
/** @var Composer */
/** @var PartialComposer */
protected $composer;
/** @var IOInterface */
protected $io;
@ -62,11 +64,11 @@ class EventDispatcher
/**
* Constructor.
*
* @param Composer $composer The composer instance
* @param PartialComposer $composer The composer instance
* @param IOInterface $io The IOInterface instance
* @param ProcessExecutor $process
*/
public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null)
public function __construct(PartialComposer $composer, IOInterface $io, ProcessExecutor $process = null)
{
$this->composer = $composer;
$this->io = $io;
@ -116,6 +118,8 @@ class EventDispatcher
*/
public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array())
{
assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer'));
return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags));
}
@ -133,6 +137,8 @@ class EventDispatcher
*/
public function dispatchPackageEvent($eventName, $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation)
{
assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer'));
return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $localRepo, $operations, $operation));
}
@ -149,6 +155,8 @@ class EventDispatcher
*/
public function dispatchInstallerEvent($eventName, $devMode, $executeOperations, Transaction $transaction)
{
assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer'));
return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $executeOperations, $transaction));
}
@ -486,6 +494,8 @@ class EventDispatcher
return array();
}
assert($this->composer instanceof Composer, new \LogicException('This should only be reached with a fully loaded Composer'));
if ($this->loader) {
$this->loader->unregister();
}
@ -556,7 +566,7 @@ class EventDispatcher
/**
* @return void
*/
private function ensureBinDirIsInPath()
private function ensureBinDirIsInPath(): void
{
$pathEnv = 'PATH';
if (false === Platform::getEnv('PATH') && false !== Platform::getEnv('Path')) {

View File

@ -28,6 +28,7 @@ use Composer\Util\Loop;
use Composer\Util\Silencer;
use Composer\Plugin\PluginEvents;
use Composer\EventDispatcher\Event;
use Phar;
use Seld\JsonLint\DuplicateKeyException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Formatter\OutputFormatterStyle;
@ -39,6 +40,7 @@ use Composer\Downloader\TransportException;
use Composer\Json\JsonValidationException;
use Composer\Repository\InstalledRepositoryInterface;
use Seld\JsonLint\JsonParser;
use ZipArchive;
/**
* Creates a configured instance of composer.
@ -52,9 +54,8 @@ class Factory
{
/**
* @throws \RuntimeException
* @return string
*/
protected static function getHomeDir()
protected static function getHomeDir(): string
{
$home = Platform::getEnv('COMPOSER_HOME');
if ($home) {
@ -95,11 +96,7 @@ class Factory
return $dirs[0];
}
/**
* @param string $home
* @return string
*/
protected static function getCacheDir($home)
protected static function getCacheDir(string $home): string
{
$cacheDir = Platform::getEnv('COMPOSER_CACHE_DIR');
if ($cacheDir) {
@ -144,11 +141,7 @@ class Factory
return $home . '/cache';
}
/**
* @param string $home
* @return string
*/
protected static function getDataDir($home)
protected static function getDataDir(string $home): string
{
$homeEnv = Platform::getEnv('COMPOSER_HOME');
if ($homeEnv) {
@ -169,12 +162,7 @@ class Factory
return $home;
}
/**
* @param string|null $cwd
*
* @return Config
*/
public static function createConfig(IOInterface $io = null, $cwd = null)
public static function createConfig(IOInterface $io = null, ?string $cwd = null): Config
{
$cwd = $cwd ?: (string) getcwd();
@ -243,20 +231,12 @@ class Factory
return $config;
}
/**
* @return string
*/
public static function getComposerFile()
public static function getComposerFile(): string
{
return trim((string) Platform::getEnv('COMPOSER')) ?: './composer.json';
}
/**
* @param string $composerFile
*
* @return string
*/
public static function getLockFile($composerFile)
public static function getLockFile(string $composerFile): string
{
return "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
? substr($composerFile, 0, -4).'lock'
@ -266,7 +246,7 @@ class Factory
/**
* @return array{highlight: OutputFormatterStyle, warning: OutputFormatterStyle}
*/
public static function createAdditionalStyles()
public static function createAdditionalStyles(): array
{
return array(
'highlight' => new OutputFormatterStyle('red'),
@ -274,12 +254,7 @@ class Factory
);
}
/**
* Creates a ConsoleOutput instance
*
* @return ConsoleOutput
*/
public static function createOutput()
public static function createOutput(): ConsoleOutput
{
$styles = self::createAdditionalStyles();
$formatter = new OutputFormatter(false, $styles);
@ -299,9 +274,9 @@ class Factory
* @param bool $fullLoad Whether to initialize everything or only main project stuff (used when loading the global composer)
* @throws \InvalidArgumentException
* @throws \UnexpectedValueException
* @return Composer
* @return Composer|PartialComposer Composer if $fullLoad is true, otherwise PartialComposer
*/
public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true, $disableScripts = false)
public function createComposer(IOInterface $io, $localConfig = null, bool $disablePlugins = false, ?string $cwd = null, bool $fullLoad = true, bool $disableScripts = false)
{
$cwd = $cwd ?: (string) getcwd();
@ -363,7 +338,7 @@ class Factory
$vendorDir = $config->get('vendor-dir');
// initialize composer
$composer = new Composer();
$composer = $fullLoad ? new Composer() : new PartialComposer();
$composer->setConfig($config);
if ($fullLoad) {
@ -410,7 +385,7 @@ class Factory
$im = $this->createInstallationManager($loop, $io, $dispatcher);
$composer->setInstallationManager($im);
if ($fullLoad) {
if ($composer instanceof Composer) {
// initialize download manager
$dm = $this->createDownloadManager($io, $config, $httpDownloader, $process, $dispatcher);
$composer->setDownloadManager($dm);
@ -427,7 +402,7 @@ class Factory
// add installers to the manager (must happen after download manager is created since they read it out of $composer)
$this->createDefaultInstallers($im, $composer, $io, $process);
if ($fullLoad) {
if ($composer instanceof Composer) {
$globalComposer = null;
if (realpath($config->get('home')) !== $cwd) {
$globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins, $disableScripts);
@ -440,7 +415,7 @@ class Factory
}
// init locker if possible
if ($fullLoad && isset($composerFile)) {
if ($composer instanceof Composer && isset($composerFile)) {
$lockFile = self::getLockFile($composerFile);
$locker = new Package\Locker($io, new JsonFile($lockFile, null, $io), $im, file_get_contents($composerFile), $process);
@ -460,16 +435,17 @@ class Factory
}
/**
* @param IOInterface $io IO instance
* @param bool $disablePlugins Whether plugins should not be loaded
* @param bool $disableScripts Whether scripts should not be executed
* @return Composer|null
*/
public static function createGlobal(IOInterface $io, $disablePlugins = false, $disableScripts = false)
public static function createGlobal(IOInterface $io, bool $disablePlugins = false, bool $disableScripts = false): ?Composer
{
$factory = new static();
return $factory->createGlobalComposer($io, static::createConfig($io), $disablePlugins, $disableScripts, true);
$composer = $factory->createGlobalComposer($io, static::createConfig($io), $disablePlugins, $disableScripts, true);
assert(null === $composer || $composer instanceof Composer);
return $composer;
}
/**
@ -478,7 +454,7 @@ class Factory
*
* @return void
*/
protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, $vendorDir, RootPackageInterface $rootPackage, ProcessExecutor $process = null)
protected function addLocalRepository(IOInterface $io, RepositoryManager $rm, $vendorDir, RootPackageInterface $rootPackage, ProcessExecutor $process = null): void
{
$fs = null;
if ($process) {
@ -489,13 +465,9 @@ class Factory
}
/**
* @param bool $disablePlugins
* @param bool $disableScripts
* @param bool $fullLoad
*
* @return Composer|null
* @return PartialComposer|Composer|null By default PartialComposer, but Composer if $fullLoad is set to true
*/
protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins, $disableScripts, $fullLoad = false)
protected function createGlobalComposer(IOInterface $io, Config $config, bool $disablePlugins, bool $disableScripts, bool $fullLoad = false): ?PartialComposer
{
$composer = null;
try {
@ -513,7 +485,7 @@ class Factory
* @param EventDispatcher $eventDispatcher
* @return Downloader\DownloadManager
*/
public function createDownloadManager(IOInterface $io, Config $config, HttpDownloader $httpDownloader, ProcessExecutor $process, EventDispatcher $eventDispatcher = null)
public function createDownloadManager(IOInterface $io, Config $config, HttpDownloader $httpDownloader, ProcessExecutor $process, EventDispatcher $eventDispatcher = null): Downloader\DownloadManager
{
$cache = null;
if ($config->get('cache-files-ttl') > 0) {
@ -566,20 +538,20 @@ class Factory
public function createArchiveManager(Config $config, Downloader\DownloadManager $dm, Loop $loop)
{
$am = new Archiver\ArchiveManager($dm, $loop);
if (class_exists(ZipArchive::class)) {
$am->addArchiver(new Archiver\ZipArchiver);
}
if (class_exists(Phar::class)) {
$am->addArchiver(new Archiver\PharArchiver);
}
return $am;
}
/**
* @param IOInterface $io
* @param Composer $composer
* @param Composer $globalComposer
* @param bool $disablePlugins
* @return Plugin\PluginManager
*/
protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false)
protected function createPluginManager(IOInterface $io, Composer $composer, PartialComposer $globalComposer = null, bool $disablePlugins = false): Plugin\PluginManager
{
return new Plugin\PluginManager($io, $composer, $globalComposer, $disablePlugins);
}
@ -587,7 +559,7 @@ class Factory
/**
* @return Installer\InstallationManager
*/
public function createInstallationManager(Loop $loop, IOInterface $io, EventDispatcher $eventDispatcher = null)
public function createInstallationManager(Loop $loop, IOInterface $io, EventDispatcher $eventDispatcher = null): Installer\InstallationManager
{
return new Installer\InstallationManager($loop, $io, $eventDispatcher);
}
@ -595,7 +567,7 @@ class Factory
/**
* @return void
*/
protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io, ProcessExecutor $process = null)
protected function createDefaultInstallers(Installer\InstallationManager $im, PartialComposer $composer, IOInterface $io, ProcessExecutor $process = null): void
{
$fs = new Filesystem($process);
$binaryInstaller = new Installer\BinaryInstaller($io, rtrim($composer->getConfig()->get('bin-dir'), '/'), $composer->getConfig()->get('bin-compat'), $fs, rtrim($composer->getConfig()->get('vendor-dir'), '/'));
@ -608,10 +580,8 @@ class Factory
/**
* @param InstalledRepositoryInterface $repo repository to purge packages from
* @param Installer\InstallationManager $im manager to check whether packages are still installed
*
* @return void
*/
protected function purgePackages(InstalledRepositoryInterface $repo, Installer\InstallationManager $im)
protected function purgePackages(InstalledRepositoryInterface $repo, Installer\InstallationManager $im): void
{
foreach ($repo->getPackages() as $package) {
if (!$im->isPackageInstalled($repo, $package)) {
@ -620,10 +590,7 @@ class Factory
}
}
/**
* @return Package\Loader\RootPackageLoader
*/
protected function loadRootPackage(RepositoryManager $rm, Config $config, VersionParser $parser, VersionGuesser $guesser, IOInterface $io)
protected function loadRootPackage(RepositoryManager $rm, Config $config, VersionParser $parser, VersionGuesser $guesser, IOInterface $io): Package\Loader\RootPackageLoader
{
return new Package\Loader\RootPackageLoader($rm, $config, $parser, $guesser, $io);
}
@ -636,11 +603,14 @@ class Factory
* @param bool $disableScripts Whether scripts should not be run
* @return Composer
*/
public static function create(IOInterface $io, $config = null, $disablePlugins = false, $disableScripts = false)
public static function create(IOInterface $io, $config = null, bool $disablePlugins = false, bool $disableScripts = false): Composer
{
$factory = new static();
return $factory->createComposer($io, $config, $disablePlugins, null, true, $disableScripts);
$composer = $factory->createComposer($io, $config, $disablePlugins, null, true, $disableScripts);
assert($composer instanceof Composer);
return $composer;
}
/**
@ -651,7 +621,7 @@ class Factory
* @param mixed[] $options Array of options passed directly to HttpDownloader constructor
* @return HttpDownloader
*/
public static function createHttpDownloader(IOInterface $io, Config $config, $options = array())
public static function createHttpDownloader(IOInterface $io, Config $config, $options = array()): HttpDownloader
{
static $warned = false;
$disableTls = false;
@ -693,10 +663,7 @@ class Factory
return $httpDownloader;
}
/**
* @return bool
*/
private static function useXdg()
private static function useXdg(): bool
{
foreach (array_keys($_SERVER) as $key) {
if (strpos($key, 'XDG_') === 0) {
@ -713,9 +680,8 @@ class Factory
/**
* @throws \RuntimeException
* @return string
*/
private static function getUserDir()
private static function getUserDir(): string
{
$home = Platform::getEnv('HOME');
if (!$home) {

View File

@ -20,7 +20,7 @@ final class IgnoreAllPlatformRequirementFilter implements PlatformRequirementFil
* @param string $req
* @return bool
*/
public function isIgnored($req)
public function isIgnored($req): bool
{
return PlatformRepository::isPlatformPackage($req);
}

View File

@ -55,7 +55,7 @@ final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFi
* @param string $req
* @return bool
*/
public function isIgnored($req)
public function isIgnored($req): bool
{
if (!PlatformRepository::isPlatformPackage($req)) {
return false;
@ -68,7 +68,7 @@ final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFi
* @param string $req
* @return ConstraintInterface
*/
public function filterConstraint($req, ConstraintInterface $constraint)
public function filterConstraint($req, ConstraintInterface $constraint): ConstraintInterface
{
if (!PlatformRepository::isPlatformPackage($req)) {
return $constraint;

View File

@ -18,7 +18,7 @@ final class IgnoreNothingPlatformRequirementFilter implements PlatformRequiremen
* @param string $req
* @return false
*/
public function isIgnored($req)
public function isIgnored($req): bool
{
return false;
}

View File

@ -19,7 +19,7 @@ final class PlatformRequirementFilterFactory
*
* @return PlatformRequirementFilterInterface
*/
public static function fromBoolOrList($boolOrList)
public static function fromBoolOrList($boolOrList): PlatformRequirementFilterInterface
{
if (is_bool($boolOrList)) {
return $boolOrList ? self::ignoreAll() : self::ignoreNothing();
@ -40,7 +40,7 @@ final class PlatformRequirementFilterFactory
/**
* @return PlatformRequirementFilterInterface
*/
public static function ignoreAll()
public static function ignoreAll(): PlatformRequirementFilterInterface
{
return new IgnoreAllPlatformRequirementFilter();
}
@ -48,7 +48,7 @@ final class PlatformRequirementFilterFactory
/**
* @return PlatformRequirementFilterInterface
*/
public static function ignoreNothing()
public static function ignoreNothing(): PlatformRequirementFilterInterface
{
return new IgnoreNothingPlatformRequirementFilter();
}

View File

@ -18,5 +18,5 @@ interface PlatformRequirementFilterInterface
* @param string $req
* @return bool
*/
public function isIgnored($req);
public function isIgnored($req): bool;
}

View File

@ -50,13 +50,13 @@ class BufferIO extends ConsoleIO
/**
* @return string output
*/
public function getOutput()
public function getOutput(): string
{
fseek($this->output->getStream(), 0);
$output = stream_get_contents($this->output->getStream());
$output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches) {
$output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches): string {
$pre = strip_tags($matches[1]);
if (strlen($pre) === strlen($matches[2])) {
@ -77,7 +77,7 @@ class BufferIO extends ConsoleIO
*
* @return void
*/
public function setUserInputs(array $inputs)
public function setUserInputs(array $inputs): void
{
if (!$this->input instanceof StreamableInputInterface) {
throw new \RuntimeException('Setting the user inputs requires at least the version 3.2 of the symfony/console component.');

View File

@ -157,7 +157,7 @@ class ConsoleIO extends BaseIO
*
* @return void
*/
private function doWrite($messages, $newline, $stderr, $verbosity, $raw = false)
private function doWrite($messages, $newline, $stderr, $verbosity, $raw = false): void
{
$sfVerbosity = $this->verbosityMap[$verbosity];
if ($sfVerbosity > $this->output->getVerbosity()) {
@ -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) {
$messages = array_map(function ($message) use ($memoryUsage, $timeSpent): string {
return sprintf('[%.1fMiB/%.2fs] %s', $memoryUsage, $timeSpent, $message);
}, (array) $messages);
}
@ -216,7 +216,7 @@ class ConsoleIO extends BaseIO
*
* @return void
*/
private function doOverwrite($messages, $newline, $size, $stderr, $verbosity)
private function doOverwrite($messages, $newline, $size, $stderr, $verbosity): void
{
// messages can be an array, let's convert it to string anyway
$messages = implode($newline ? "\n" : '', (array) $messages);
@ -345,7 +345,7 @@ class ConsoleIO extends BaseIO
/**
* @return OutputInterface
*/
private function getErrorOutput()
private function getErrorOutput(): OutputInterface
{
if ($this->output instanceof ConsoleOutputInterface) {
return $this->output->getErrorOutput();

View File

@ -22,7 +22,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function isInteractive()
public function isInteractive(): bool
{
return false;
}
@ -30,7 +30,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function isVerbose()
public function isVerbose(): bool
{
return false;
}
@ -38,7 +38,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function isVeryVerbose()
public function isVeryVerbose(): bool
{
return false;
}
@ -46,7 +46,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function isDebug()
public function isDebug(): bool
{
return false;
}
@ -54,7 +54,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function isDecorated()
public function isDecorated(): bool
{
return false;
}
@ -62,28 +62,28 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function write($messages, $newline = true, $verbosity = self::NORMAL)
public function write($messages, $newline = true, $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function writeError($messages, $newline = true, $verbosity = self::NORMAL)
public function writeError($messages, $newline = true, $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function overwrite($messages, $newline = true, $size = 80, $verbosity = self::NORMAL)
public function overwrite($messages, $newline = true, $size = 80, $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function overwriteError($messages, $newline = true, $size = 80, $verbosity = self::NORMAL)
public function overwriteError($messages, $newline = true, $size = 80, $verbosity = self::NORMAL): void
{
}
@ -98,7 +98,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function askConfirmation($question, $default = true)
public function askConfirmation($question, $default = true): bool
{
return $default;
}
@ -114,7 +114,7 @@ class NullIO extends BaseIO
/**
* @inheritDoc
*/
public function askAndHideAnswer($question)
public function askAndHideAnswer($question): ?string
{
return null;
}

View File

@ -226,7 +226,7 @@ class Installer
* @return int 0 on success or a positive error code on failure
* @phpstan-return self::ERROR_*
*/
public function run()
public function run(): int
{
// Disable GC to save CPU cycles, as the dependency solver can create hundreds of thousands
// of PHP objects, the GC can spend quite some time walking the tree of references looking
@ -386,7 +386,7 @@ class Installer
* @return int
* @phpstan-return self::ERROR_*
*/
protected function doUpdate(InstalledRepositoryInterface $localRepo, $doInstall)
protected function doUpdate(InstalledRepositoryInterface $localRepo, $doInstall): int
{
$platformRepo = $this->createPlatformRepo(true);
$aliases = $this->getRootAliases(true);
@ -522,7 +522,7 @@ class Installer
}
}
$sortByName = function ($a, $b) {
$sortByName = function ($a, $b): int {
if ($a instanceof UpdateOperation) {
$a = $a->getTargetPackage()->getName();
} else {
@ -597,7 +597,7 @@ class Installer
* @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
* @phpstan-return self::ERROR_*
*/
protected function extractDevPackages(LockTransaction $lockTransaction, PlatformRepository $platformRepo, array $aliases, PolicyInterface $policy, LockArrayRepository $lockedRepository = null)
protected function extractDevPackages(LockTransaction $lockTransaction, PlatformRepository $platformRepo, array $aliases, PolicyInterface $policy, LockArrayRepository $lockedRepository = null): int
{
if (!$this->package->getDevRequires()) {
return 0;
@ -648,7 +648,7 @@ class Installer
* @return int exit code
* @phpstan-return self::ERROR_*
*/
protected function doInstall(InstalledRepositoryInterface $localRepo, $alreadySolved = false)
protected function doInstall(InstalledRepositoryInterface $localRepo, $alreadySolved = false): int
{
$this->io->writeError('<info>Installing dependencies from lock file'.($this->devMode ? ' (including require-dev)' : '').'</info>');
@ -769,7 +769,7 @@ class Installer
*
* @return PlatformRepository
*/
protected function createPlatformRepo($forUpdate)
protected function createPlatformRepo($forUpdate): PlatformRepository
{
if ($forUpdate) {
$platformOverrides = $this->config->get('platform') ?: array();
@ -789,7 +789,7 @@ class Installer
*
* @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $rootAliases
*/
private function createRepositorySet($forUpdate, PlatformRepository $platformRepo, array $rootAliases = array(), $lockedRepository = null)
private function createRepositorySet($forUpdate, PlatformRepository $platformRepo, array $rootAliases = array(), $lockedRepository = null): RepositorySet
{
if ($forUpdate) {
$minimumStability = $this->package->getMinimumStability();
@ -858,7 +858,7 @@ class Installer
*
* @return DefaultPolicy
*/
private function createPolicy($forUpdate)
private function createPolicy($forUpdate): DefaultPolicy
{
$preferStable = null;
$preferLowest = null;
@ -882,7 +882,7 @@ class Installer
* @param RootPackageInterface&BasePackage $rootPackage
* @return Request
*/
private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo, LockArrayRepository $lockedRepository = null)
private function createRequest(RootPackageInterface $rootPackage, PlatformRepository $platformRepo, LockArrayRepository $lockedRepository = null): Request
{
$request = new Request($lockedRepository);
@ -919,7 +919,7 @@ class Installer
*
* @return void
*/
private function requirePackagesForUpdate(Request $request, LockArrayRepository $lockedRepository = null, $includeDevRequires = true)
private function requirePackagesForUpdate(Request $request, LockArrayRepository $lockedRepository = null, $includeDevRequires = true): void
{
// if we're updating mirrors we want to keep exactly the same versions installed which are in the lock file, but we want current remote metadata
if ($this->updateMirrors) {
@ -953,7 +953,7 @@ class Installer
*
* @phpstan-return list<array{package: string, version: string, alias: string, alias_normalized: string}>
*/
private function getRootAliases($forUpdate)
private function getRootAliases($forUpdate): array
{
if ($forUpdate) {
$aliases = $this->package->getAliases();
@ -969,7 +969,7 @@ class Installer
*
* @return array<string, string>
*/
private function extractPlatformRequirements(array $links)
private function extractPlatformRequirements(array $links): array
{
$platformReqs = array();
foreach ($links as $link) {
@ -988,7 +988,7 @@ class Installer
*
* @return void
*/
private function mockLocalRepositories(RepositoryManager $rm)
private function mockLocalRepositories(RepositoryManager $rm): void
{
$packages = array();
foreach ($rm->getLocalRepository()->getPackages() as $package) {
@ -1009,7 +1009,7 @@ class Installer
/**
* @return PoolOptimizer|null
*/
private function createPoolOptimizer(PolicyInterface $policy)
private function createPoolOptimizer(PolicyInterface $policy): ?PoolOptimizer
{
// Not the best architectural decision here, would need to be able
// to configure from the outside of Installer but this is only
@ -1030,7 +1030,7 @@ class Installer
* @param Composer $composer
* @return Installer
*/
public static function create(IOInterface $io, Composer $composer)
public static function create(IOInterface $io, Composer $composer): Installer
{
return new static(
$io,
@ -1062,7 +1062,7 @@ class Installer
* @param bool $dryRun
* @return Installer
*/
public function setDryRun($dryRun = true)
public function setDryRun($dryRun = true): Installer
{
$this->dryRun = (bool) $dryRun;
@ -1074,7 +1074,7 @@ class Installer
*
* @return bool
*/
public function isDryRun()
public function isDryRun(): bool
{
return $this->dryRun;
}
@ -1085,7 +1085,7 @@ class Installer
* @param bool $preferSource
* @return Installer
*/
public function setPreferSource($preferSource = true)
public function setPreferSource($preferSource = true): Installer
{
$this->preferSource = (bool) $preferSource;
@ -1098,7 +1098,7 @@ class Installer
* @param bool $preferDist
* @return Installer
*/
public function setPreferDist($preferDist = true)
public function setPreferDist($preferDist = true): Installer
{
$this->preferDist = (bool) $preferDist;
@ -1111,7 +1111,7 @@ class Installer
* @param bool $optimizeAutoloader
* @return Installer
*/
public function setOptimizeAutoloader($optimizeAutoloader)
public function setOptimizeAutoloader($optimizeAutoloader): Installer
{
$this->optimizeAutoloader = (bool) $optimizeAutoloader;
if (!$this->optimizeAutoloader) {
@ -1130,7 +1130,7 @@ class Installer
* @param bool $classMapAuthoritative
* @return Installer
*/
public function setClassMapAuthoritative($classMapAuthoritative)
public function setClassMapAuthoritative($classMapAuthoritative): Installer
{
$this->classMapAuthoritative = (bool) $classMapAuthoritative;
if ($this->classMapAuthoritative) {
@ -1148,7 +1148,7 @@ class Installer
* @param string|null $apcuAutoloaderPrefix
* @return Installer
*/
public function setApcuAutoloader($apcuAutoloader, $apcuAutoloaderPrefix = null)
public function setApcuAutoloader($apcuAutoloader, $apcuAutoloaderPrefix = null): Installer
{
$this->apcuAutoloader = $apcuAutoloader;
$this->apcuAutoloaderPrefix = $apcuAutoloaderPrefix;
@ -1162,7 +1162,7 @@ class Installer
* @param bool $update
* @return Installer
*/
public function setUpdate($update)
public function setUpdate($update): Installer
{
$this->update = (bool) $update;
@ -1175,7 +1175,7 @@ class Installer
* @param bool $install
* @return Installer
*/
public function setInstall($install)
public function setInstall($install): Installer
{
$this->install = (bool) $install;
@ -1188,7 +1188,7 @@ class Installer
* @param bool $devMode
* @return Installer
*/
public function setDevMode($devMode = true)
public function setDevMode($devMode = true): Installer
{
$this->devMode = (bool) $devMode;
@ -1203,7 +1203,7 @@ class Installer
* @param bool $dumpAutoloader
* @return Installer
*/
public function setDumpAutoloader($dumpAutoloader = true)
public function setDumpAutoloader($dumpAutoloader = true): Installer
{
$this->dumpAutoloader = (bool) $dumpAutoloader;
@ -1219,7 +1219,7 @@ class Installer
* @return Installer
* @deprecated Use setRunScripts(false) on the EventDispatcher instance being injected instead
*/
public function setRunScripts($runScripts = true)
public function setRunScripts($runScripts = true): Installer
{
$this->runScripts = (bool) $runScripts;
@ -1232,7 +1232,7 @@ class Installer
* @param Config $config
* @return Installer
*/
public function setConfig(Config $config)
public function setConfig(Config $config): Installer
{
$this->config = $config;
@ -1245,7 +1245,7 @@ class Installer
* @param bool $verbose
* @return Installer
*/
public function setVerbose($verbose = true)
public function setVerbose($verbose = true): Installer
{
$this->verbose = (bool) $verbose;
@ -1257,7 +1257,7 @@ class Installer
*
* @return bool
*/
public function isVerbose()
public function isVerbose(): bool
{
return $this->verbose;
}
@ -1275,7 +1275,7 @@ class Installer
*
* @deprecated use setPlatformRequirementFilter instead
*/
public function setIgnorePlatformRequirements($ignorePlatformReqs)
public function setIgnorePlatformRequirements($ignorePlatformReqs): Installer
{
trigger_error('Installer::setIgnorePlatformRequirements is deprecated since Composer 2.2, use setPlatformRequirementFilter instead.', E_USER_DEPRECATED);
@ -1286,7 +1286,7 @@ class Installer
* @param PlatformRequirementFilterInterface $platformRequirementFilter
* @return Installer
*/
public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter)
public function setPlatformRequirementFilter(PlatformRequirementFilterInterface $platformRequirementFilter): Installer
{
$this->platformRequirementFilter = $platformRequirementFilter;
@ -1299,7 +1299,7 @@ class Installer
* @param bool $updateMirrors
* @return Installer
*/
public function setUpdateMirrors($updateMirrors)
public function setUpdateMirrors($updateMirrors): Installer
{
$this->updateMirrors = $updateMirrors;
@ -1314,7 +1314,7 @@ class Installer
*
* @return Installer
*/
public function setUpdateAllowList(array $packages)
public function setUpdateAllowList(array $packages): Installer
{
$this->updateAllowList = array_flip(array_map('strtolower', $packages));
@ -1330,7 +1330,7 @@ class Installer
* @param int $updateAllowTransitiveDependencies One of the UPDATE_ constants on the Request class
* @return Installer
*/
public function setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies)
public function setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies): Installer
{
if (!in_array($updateAllowTransitiveDependencies, array(Request::UPDATE_ONLY_LISTED, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE, Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS), true)) {
throw new \RuntimeException("Invalid value for updateAllowTransitiveDependencies supplied");
@ -1347,7 +1347,7 @@ class Installer
* @param bool $preferStable
* @return Installer
*/
public function setPreferStable($preferStable = true)
public function setPreferStable($preferStable = true): Installer
{
$this->preferStable = (bool) $preferStable;
@ -1360,7 +1360,7 @@ class Installer
* @param bool $preferLowest
* @return Installer
*/
public function setPreferLowest($preferLowest = true)
public function setPreferLowest($preferLowest = true): Installer
{
$this->preferLowest = (bool) $preferLowest;
@ -1375,7 +1375,7 @@ class Installer
* @param bool $writeLock
* @return Installer
*/
public function setWriteLock($writeLock = true)
public function setWriteLock($writeLock = true): Installer
{
$this->writeLock = (bool) $writeLock;
@ -1390,7 +1390,7 @@ class Installer
* @param bool $executeOperations
* @return Installer
*/
public function setExecuteOperations($executeOperations = true)
public function setExecuteOperations($executeOperations = true): Installer
{
$this->executeOperations = (bool) $executeOperations;
@ -1406,7 +1406,7 @@ class Installer
*
* @return Installer
*/
public function disablePlugins()
public function disablePlugins(): Installer
{
$this->installationManager->disablePlugins();
@ -1417,7 +1417,7 @@ class Installer
* @param SuggestedPackagesReporter $suggestedPackagesReporter
* @return Installer
*/
public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter)
public function setSuggestedPackagesReporter(SuggestedPackagesReporter $suggestedPackagesReporter): Installer
{
$this->suggestedPackagesReporter = $suggestedPackagesReporter;

View File

@ -62,7 +62,7 @@ class BinaryInstaller
*
* @return void
*/
public function installBinaries(PackageInterface $package, $installPath, $warnOnOverwrite = true)
public function installBinaries(PackageInterface $package, $installPath, $warnOnOverwrite = true): void
{
$binaries = $this->getBinaries($package);
if (!$binaries) {
@ -120,7 +120,7 @@ class BinaryInstaller
/**
* @return void
*/
public function removeBinaries(PackageInterface $package)
public function removeBinaries(PackageInterface $package): void
{
$this->initializeBinDir();
@ -149,7 +149,7 @@ class BinaryInstaller
*
* @return string
*/
public static function determineBinaryCaller($bin)
public static function determineBinaryCaller($bin): string
{
if ('.bat' === substr($bin, -4) || '.exe' === substr($bin, -4)) {
return 'call';
@ -168,7 +168,7 @@ class BinaryInstaller
/**
* @return string[]
*/
protected function getBinaries(PackageInterface $package)
protected function getBinaries(PackageInterface $package): array
{
return $package->getBinaries();
}
@ -180,7 +180,7 @@ class BinaryInstaller
*
* @return void
*/
protected function installFullBinaries($binPath, $link, $bin, PackageInterface $package)
protected function installFullBinaries($binPath, $link, $bin, PackageInterface $package): void
{
// add unixy support for cygwin and similar environments
if ('.bat' !== substr($binPath, -4)) {
@ -202,7 +202,7 @@ class BinaryInstaller
*
* @return void
*/
protected function installUnixyProxyBinaries($binPath, $link)
protected function installUnixyProxyBinaries($binPath, $link): void
{
file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link));
Silencer::call('chmod', $link, 0777 & ~umask());
@ -211,7 +211,7 @@ class BinaryInstaller
/**
* @return void
*/
protected function initializeBinDir()
protected function initializeBinDir(): void
{
$this->filesystem->ensureDirectoryExists($this->binDir);
$this->binDir = realpath($this->binDir);
@ -223,7 +223,7 @@ class BinaryInstaller
*
* @return string
*/
protected function generateWindowsProxyCode($bin, $link)
protected function generateWindowsProxyCode($bin, $link): string
{
$binPath = $this->filesystem->findShortestPath($link, $bin);
$caller = self::determineBinaryCaller($bin);
@ -252,7 +252,7 @@ class BinaryInstaller
*
* @return string
*/
protected function generateUnixyProxyCode($bin, $link)
protected function generateUnixyProxyCode($bin, $link): string
{
$binPath = $this->filesystem->findShortestPath($link, $bin);

View File

@ -199,18 +199,18 @@ class InstallationManager
$loop = $this->loop;
$io = $this->io;
$runCleanup = function () use (&$cleanupPromises, $loop) {
$runCleanup = function () use (&$cleanupPromises, $loop): void {
$promises = array();
$loop->abortJobs();
foreach ($cleanupPromises as $cleanup) {
$promises[] = new \React\Promise\Promise(function ($resolve, $reject) use ($cleanup) {
$promises[] = new \React\Promise\Promise(function ($resolve, $reject) use ($cleanup): void {
$promise = $cleanup();
if (!$promise instanceof PromiseInterface) {
$resolve();
} else {
$promise->then(function () use ($resolve) {
$promise->then(function () use ($resolve): void {
$resolve();
});
}
@ -229,7 +229,7 @@ class InstallationManager
if ($handleInterruptsUnix) {
pcntl_async_signals(true);
$prevHandler = pcntl_signal_get_handler(SIGINT);
pcntl_signal(SIGINT, function ($sig) use ($runCleanup, $prevHandler, $io) {
pcntl_signal(SIGINT, function ($sig) use ($runCleanup, $prevHandler, $io): void {
$io->writeError('Received SIGINT, aborting', true, IOInterface::DEBUG);
$runCleanup();
@ -241,7 +241,7 @@ class InstallationManager
});
}
if ($handleInterruptsWindows) {
$windowsHandler = function ($event) use ($runCleanup, $io) {
$windowsHandler = function ($event) use ($runCleanup, $io): void {
if ($event !== PHP_WINDOWS_EVENT_CTRL_C) {
return;
}
@ -316,7 +316,7 @@ class InstallationManager
*
* @return void
*/
private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, array $operations, array &$cleanupPromises, $devMode, $runScripts, array $allOperations)
private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, array $operations, array &$cleanupPromises, $devMode, $runScripts, array $allOperations): void
{
$promises = array();
@ -400,7 +400,7 @@ class InstallationManager
*
* @return void
*/
private function executeBatch(InstalledRepositoryInterface $repo, array $operations, array $cleanupPromises, $devMode, $runScripts, array $allOperations)
private function executeBatch(InstalledRepositoryInterface $repo, array $operations, array $cleanupPromises, $devMode, $runScripts, array $allOperations): void
{
$promises = array();
$postExecCallbacks = array();
@ -446,15 +446,15 @@ class InstallationManager
$promise = $promise->then(function () use ($opType, $repo, $operation) {
return $this->$opType($repo, $operation);
})->then($cleanupPromises[$index])
->then(function () use ($devMode, $repo) {
->then(function () use ($devMode, $repo): void {
$repo->write($devMode, $this);
}, function ($e) use ($opType, $package, $io) {
}, function ($e) use ($opType, $package, $io): void {
$io->writeError(' <error>' . ucfirst($opType) .' of '.$package->getPrettyName().' failed</error>');
throw $e;
});
$postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation) {
$postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation): void {
$event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($opType);
if (defined($event) && $runScripts && $dispatcher) {
$dispatcher->dispatchPackageEvent(constant($event), $devMode, $repo, $allOperations, $operation);
@ -481,7 +481,7 @@ class InstallationManager
*
* @return void
*/
private function waitOnPromises(array $promises)
private function waitOnPromises(array $promises): void
{
$progress = null;
if (
@ -548,8 +548,13 @@ class InstallationManager
}
$installer = $this->getInstaller($targetType);
$promise = $promise->then(function () use ($installer, $repo, $target) {
return $installer->install($repo, $target);
$promise = $promise->then(function () use ($installer, $repo, $target): PromiseInterface {
$promise = $installer->install($repo, $target);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve();
});
}
@ -700,7 +705,7 @@ class InstallationManager
/**
* @return void
*/
private function markForNotification(PackageInterface $package)
private function markForNotification(PackageInterface $package): void
{
if ($package->getNotificationUrl()) {
$this->notifiablePackages[$package->getNotificationUrl()][$package->getName()] = $package;

View File

@ -14,6 +14,7 @@ namespace Composer\Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\PartialComposer;
use Composer\Pcre\Preg;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
@ -31,11 +32,11 @@ use Composer\Downloader\DownloadManager;
*/
class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
{
/** @var Composer */
/** @var PartialComposer */
protected $composer;
/** @var string */
protected $vendorDir;
/** @var DownloadManager */
/** @var DownloadManager|null */
protected $downloadManager;
/** @var IOInterface */
protected $io;
@ -50,15 +51,15 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
* Initializes library installer.
*
* @param IOInterface $io
* @param Composer $composer
* @param PartialComposer $composer
* @param string|null $type
* @param Filesystem $filesystem
* @param BinaryInstaller $binaryInstaller
*/
public function __construct(IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null)
public function __construct(IOInterface $io, PartialComposer $composer, $type = 'library', Filesystem $filesystem = null, BinaryInstaller $binaryInstaller = null)
{
$this->composer = $composer;
$this->downloadManager = $composer->getDownloadManager();
$this->downloadManager = $composer instanceof Composer ? $composer->getDownloadManager() : null;
$this->io = $io;
$this->type = $type;
@ -101,7 +102,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->downloadManager->download($package, $downloadPath, $prevPackage);
return $this->getDownloadManager()->download($package, $downloadPath, $prevPackage);
}
/**
@ -112,7 +113,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->downloadManager->prepare($type, $package, $downloadPath, $prevPackage);
return $this->getDownloadManager()->prepare($type, $package, $downloadPath, $prevPackage);
}
/**
@ -123,7 +124,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->downloadManager->cleanup($type, $package, $downloadPath, $prevPackage);
return $this->getDownloadManager()->cleanup($type, $package, $downloadPath, $prevPackage);
}
/**
@ -147,7 +148,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($package);
return $promise->then(function () use ($binaryInstaller, $installPath, $package, $repo) {
return $promise->then(function () use ($binaryInstaller, $installPath, $package, $repo): void {
$binaryInstaller->installBinaries($package, $installPath);
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
@ -175,7 +176,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($target);
return $promise->then(function () use ($binaryInstaller, $installPath, $target, $initial, $repo) {
return $promise->then(function () use ($binaryInstaller, $installPath, $target, $initial, $repo): void {
$binaryInstaller->installBinaries($target, $installPath);
$repo->removePackage($initial);
if (!$repo->hasPackage($target)) {
@ -202,7 +203,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$downloadPath = $this->getPackageBasePath($package);
$filesystem = $this->filesystem;
return $promise->then(function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo) {
return $promise->then(function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo): void {
$binaryInstaller->removeBinaries($package);
$repo->removePackage($package);
@ -266,7 +267,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
{
$downloadPath = $this->getInstallPath($package);
return $this->downloadManager->install($package, $downloadPath);
return $this->getDownloadManager()->install($package, $downloadPath);
}
/**
@ -287,15 +288,20 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$promise = \React\Promise\resolve();
}
return $promise->then(function () use ($target) {
return $this->installCode($target);
return $promise->then(function () use ($target): PromiseInterface {
$promise = $this->installCode($target);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve();
});
}
$this->filesystem->rename($initialDownloadPath, $targetDownloadPath);
}
return $this->downloadManager->update($initial, $target, $targetDownloadPath);
return $this->getDownloadManager()->update($initial, $target, $targetDownloadPath);
}
/**
@ -305,7 +311,7 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
{
$downloadPath = $this->getPackageBasePath($package);
return $this->downloadManager->remove($package, $downloadPath);
return $this->getDownloadManager()->remove($package, $downloadPath);
}
/**
@ -316,4 +322,11 @@ class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
$this->filesystem->ensureDirectoryExists($this->vendorDir);
$this->vendorDir = realpath($this->vendorDir);
}
protected function getDownloadManager(): DownloadManager
{
assert($this->downloadManager instanceof DownloadManager, new \LogicException(self::class.' should be initialized with a fully loaded Composer instance to be able to install/... packages'));
return $this->downloadManager;
}
}

View File

@ -14,8 +14,10 @@ namespace Composer\Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\PartialComposer;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\Plugin\PluginManager;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use React\Promise\PromiseInterface;
@ -28,13 +30,7 @@ use React\Promise\PromiseInterface;
*/
class PluginInstaller extends LibraryInstaller
{
/**
* Initializes Plugin installer.
*
* @param IOInterface $io
* @param Composer $composer
*/
public function __construct(IOInterface $io, Composer $composer, Filesystem $fs = null, BinaryInstaller $binaryInstaller = null)
public function __construct(IOInterface $io, PartialComposer $composer, Filesystem $fs = null, BinaryInstaller $binaryInstaller = null)
{
parent::__construct($io, $composer, 'composer-plugin', $fs, $binaryInstaller);
}
@ -70,10 +66,10 @@ class PluginInstaller extends LibraryInstaller
$promise = \React\Promise\resolve();
}
return $promise->then(function () use ($package, $repo) {
return $promise->then(function () use ($package, $repo): void {
try {
Platform::workaroundFilesystemIssues();
$this->composer->getPluginManager()->registerPackage($package, true);
$this->getPluginManager()->registerPackage($package, true);
} catch (\Exception $e) {
$this->rollbackInstall($e, $repo, $package);
}
@ -90,11 +86,11 @@ class PluginInstaller extends LibraryInstaller
$promise = \React\Promise\resolve();
}
return $promise->then(function () use ($initial, $target, $repo) {
return $promise->then(function () use ($initial, $target, $repo): void {
try {
Platform::workaroundFilesystemIssues();
$this->composer->getPluginManager()->deactivatePackage($initial);
$this->composer->getPluginManager()->registerPackage($target, true);
$this->getPluginManager()->deactivatePackage($initial);
$this->getPluginManager()->registerPackage($target, true);
} catch (\Exception $e) {
$this->rollbackInstall($e, $repo, $target);
}
@ -103,7 +99,7 @@ class PluginInstaller extends LibraryInstaller
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->composer->getPluginManager()->uninstallPackage($package);
$this->getPluginManager()->uninstallPackage($package);
return parent::uninstall($repo, $package);
}
@ -114,4 +110,12 @@ class PluginInstaller extends LibraryInstaller
parent::uninstall($repo, $package);
throw $e;
}
protected function getPluginManager(): PluginManager
{
assert($this->composer instanceof Composer, new \LogicException(self::class.' should be initialized with a fully loaded Composer instance.'));
$pluginManager = $this->composer->getPluginManager();
return $pluginManager;
}
}

View File

@ -12,6 +12,7 @@
namespace Composer\Installer;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Downloader\DownloadManager;
use Composer\Repository\InstalledRepositoryInterface;
@ -48,7 +49,7 @@ class ProjectInstaller implements InstallerInterface
* @param string $packageType
* @return bool
*/
public function supports($packageType)
public function supports($packageType): bool
{
return true;
}
@ -56,7 +57,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool
{
return false;
}
@ -64,7 +65,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function download(PackageInterface $package, PackageInterface $prevPackage = null)
public function download(PackageInterface $package, PackageInterface $prevPackage = null): ?PromiseInterface
{
$installPath = $this->installPath;
if (file_exists($installPath) && !$this->filesystem->isDirEmpty($installPath)) {
@ -80,7 +81,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, PackageInterface $prevPackage = null)
public function prepare($type, PackageInterface $package, PackageInterface $prevPackage = null): ?PromiseInterface
{
return $this->downloadManager->prepare($type, $package, $this->installPath, $prevPackage);
}
@ -88,7 +89,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function cleanup($type, PackageInterface $package, PackageInterface $prevPackage = null)
public function cleanup($type, PackageInterface $package, PackageInterface $prevPackage = null): ?PromiseInterface
{
return $this->downloadManager->cleanup($type, $package, $this->installPath, $prevPackage);
}
@ -96,7 +97,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
public function install(InstalledRepositoryInterface $repo, PackageInterface $package): ?PromiseInterface
{
return $this->downloadManager->install($package, $this->installPath);
}
@ -104,7 +105,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target): ?PromiseInterface
{
throw new \InvalidArgumentException("not supported");
}
@ -112,7 +113,7 @@ class ProjectInstaller implements InstallerInterface
/**
* @inheritDoc
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package): ?PromiseInterface
{
throw new \InvalidArgumentException("not supported");
}
@ -123,7 +124,7 @@ class ProjectInstaller implements InstallerInterface
* @param PackageInterface $package
* @return string path
*/
public function getInstallPath(PackageInterface $package)
public function getInstallPath(PackageInterface $package): string
{
return $this->installPath;
}

View File

@ -47,7 +47,7 @@ class SuggestedPackagesReporter
/**
* @return array<array{source: string, target: string, reason: string}> Suggested packages with source, target and reason keys.
*/
public function getPackages()
public function getPackages(): array
{
return $this->suggestedPackages;
}
@ -63,7 +63,7 @@ class SuggestedPackagesReporter
* @param string $reason Reason the target package to be suggested
* @return SuggestedPackagesReporter
*/
public function addPackage($source, $target, $reason)
public function addPackage($source, $target, $reason): SuggestedPackagesReporter
{
$this->suggestedPackages[] = array(
'source' => $source,
@ -80,7 +80,7 @@ class SuggestedPackagesReporter
* @param PackageInterface $package
* @return SuggestedPackagesReporter
*/
public function addSuggestionsFromPackage(PackageInterface $package)
public function addSuggestionsFromPackage(PackageInterface $package): SuggestedPackagesReporter
{
$source = $package->getPrettyName();
foreach ($package->getSuggests() as $target => $reason) {
@ -104,7 +104,7 @@ class SuggestedPackagesReporter
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
* @return void
*/
public function output($mode, InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null)
public function output($mode, InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null): void
{
$suggestedPackages = $this->getFilteredSuggestions($installedRepo, $onlyDependentsOf);
@ -170,7 +170,7 @@ class SuggestedPackagesReporter
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
* @return void
*/
public function outputMinimalistic(InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null)
public function outputMinimalistic(InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null): void
{
$suggestedPackages = $this->getFilteredSuggestions($installedRepo, $onlyDependentsOf);
if ($suggestedPackages) {
@ -183,7 +183,7 @@ class SuggestedPackagesReporter
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
* @return mixed[]
*/
private function getFilteredSuggestions(InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null)
private function getFilteredSuggestions(InstalledRepository $installedRepo = null, PackageInterface $onlyDependentsOf = null): array
{
$suggestedPackages = $this->getPackages();
$installedNames = array();
@ -198,7 +198,7 @@ class SuggestedPackagesReporter
$sourceFilter = array();
if ($onlyDependentsOf) {
$sourceFilter = array_map(function ($link) {
$sourceFilter = array_map(function ($link): string {
return $link->getTarget();
}, array_merge($onlyDependentsOf->getRequires(), $onlyDependentsOf->getDevRequires()));
$sourceFilter[] = $onlyDependentsOf->getName();
@ -220,7 +220,7 @@ class SuggestedPackagesReporter
* @param string $string
* @return string
*/
private function escapeOutput($string)
private function escapeOutput($string): string
{
return OutputFormatter::escape(
$this->removeControlCharacters($string)
@ -231,7 +231,7 @@ class SuggestedPackagesReporter
* @param string $string
* @return string
*/
private function removeControlCharacters($string)
private function removeControlCharacters($string): string
{
return Preg::replace(
'/[[:cntrl:]]/',

View File

@ -256,7 +256,7 @@ class JsonFile
* @throws \RuntimeException
* @return void
*/
private static function throwEncodeError($code)
private static function throwEncodeError($code): void
{
switch ($code) {
case JSON_ERROR_DEPTH:

Some files were not shown because too many files have changed in this diff Show More