diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index a5f4be066..e2c430166 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -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) diff --git a/phpstan/config.neon b/phpstan/config.neon index 210f3f75d..e5469b6a7 100644 --- a/phpstan/config.neon +++ b/phpstan/config.neon @@ -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+\(\)~' diff --git a/src/Composer/Autoload/AutoloadGenerator.php b/src/Composer/Autoload/AutoloadGenerator.php index 73ec3d5e7..d3560bfcf 100644 --- a/src/Composer/Autoload/AutoloadGenerator.php +++ b/src/Composer/Autoload/AutoloadGenerator.php @@ -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 $scannedFiles * @return array */ - 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 $scannedFiles * @return array */ - 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])) { diff --git a/src/Composer/Autoload/ClassMapGenerator.php b/src/Composer/Autoload/ClassMapGenerator.php index cb948945f..8a2db5681 100644 --- a/src/Composer/Autoload/ClassMapGenerator.php +++ b/src/Composer/Autoload/ClassMapGenerator.php @@ -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 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 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 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; diff --git a/src/Composer/Autoload/PhpFileCleaner.php b/src/Composer/Autoload/PhpFileCleaner.php index 7941f463c..8fc077418 100644 --- a/src/Composer/Autoload/PhpFileCleaner.php +++ b/src/Composer/Autoload/PhpFileCleaner.php @@ -51,7 +51,7 @@ class PhpFileCleaner * @param string[] $types * @return void */ - public static function setTypeConfig($types) + 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 $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); } diff --git a/src/Composer/Command/AboutCommand.php b/src/Composer/Command/AboutCommand.php index 18b0db279..80d9a9caa 100644 --- a/src/Composer/Command/AboutCommand.php +++ b/src/Composer/Command/AboutCommand.php @@ -24,7 +24,7 @@ class AboutCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('about') diff --git a/src/Composer/Command/ArchiveCommand.php b/src/Composer/Command/ArchiveCommand.php index beaa65a77..b785f4ea4 100644 --- a/src/Composer/Command/ArchiveCommand.php +++ b/src/Composer/Command/ArchiveCommand.php @@ -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('Found multiple matches, selected '.$package->getPrettyString().'.'); - $io->writeError('Alternatives were '.implode(', ', array_map(function ($p) { + $io->writeError('Alternatives were '.implode(', ', array_map(function ($p): string { return $p->getPrettyString(); }, $packages)).'.'); $io->writeError('Please use a more specific constraint to pick a different package.'); diff --git a/src/Composer/Command/BaseDependencyCommand.php b/src/Composer/Command/BaseDependencyCommand.php index 4b24202ed..224d2739e 100644 --- a/src/Composer/Command/BaseDependencyCommand.php +++ b/src/Composer/Command/BaseDependencyCommand.php @@ -50,7 +50,7 @@ class BaseDependencyCommand extends BaseCommand * @param bool $inverted Whether to invert matching process (why-not vs why behaviour) * @return int Exit code of the operation. */ - protected function doExecute(InputInterface $input, OutputInterface $output, $inverted = false) + 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()) { diff --git a/src/Composer/Command/CheckPlatformReqsCommand.php b/src/Composer/Command/CheckPlatformReqsCommand.php index d86dec5da..8e525e7bf 100644 --- a/src/Composer/Command/CheckPlatformReqsCommand.php +++ b/src/Composer/Command/CheckPlatformReqsCommand.php @@ -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) { diff --git a/src/Composer/Command/ClearCacheCommand.php b/src/Composer/Command/ClearCacheCommand.php index 015a49b6f..e7c15de31 100644 --- a/src/Composer/Command/ClearCacheCommand.php +++ b/src/Composer/Command/ClearCacheCommand.php @@ -25,7 +25,7 @@ class ClearCacheCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('clear-cache') diff --git a/src/Composer/Command/ConfigCommand.php b/src/Composer/Command/ConfigCommand.php index 8b67042fe..3e51a4599 100644 --- a/src/Composer/Command/ConfigCommand.php +++ b/src/Composer/Command/ConfigCommand.php @@ -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(); diff --git a/src/Composer/Command/CreateProjectCommand.php b/src/Composer/Command/CreateProjectCommand.php index 5a270a81c..d7dcaeaae 100644 --- a/src/Composer/Command/CreateProjectCommand.php +++ b/src/Composer/Command/CreateProjectCommand.php @@ -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); diff --git a/src/Composer/Command/DependsCommand.php b/src/Composer/Command/DependsCommand.php index dfd8d716b..54fda17a5 100644 --- a/src/Composer/Command/DependsCommand.php +++ b/src/Composer/Command/DependsCommand.php @@ -27,7 +27,7 @@ class DependsCommand extends BaseDependencyCommand * * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('depends') diff --git a/src/Composer/Command/DiagnoseCommand.php b/src/Composer/Command/DiagnoseCommand.php index a39ffd541..75bec936a 100644 --- a/src/Composer/Command/DiagnoseCommand.php +++ b/src/Composer/Command/DiagnoseCommand.php @@ -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.''.PHP_EOL; }; diff --git a/src/Composer/Command/FundCommand.php b/src/Composer/Command/FundCommand.php index 6e551a66a..c6287dac9 100644 --- a/src/Composer/Command/FundCommand.php +++ b/src/Composer/Command/FundCommand.php @@ -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()); diff --git a/src/Composer/Command/GlobalCommand.php b/src/Composer/Command/GlobalCommand.php index 91aae03f0..0b5f442cc 100644 --- a/src/Composer/Command/GlobalCommand.php +++ b/src/Composer/Command/GlobalCommand.php @@ -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; } diff --git a/src/Composer/Command/HomeCommand.php b/src/Composer/Command/HomeCommand.php index a44546c55..b83f31e03 100644 --- a/src/Composer/Command/HomeCommand.php +++ b/src/Composer/Command/HomeCommand.php @@ -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(); diff --git a/src/Composer/Command/InitCommand.php b/src/Composer/Command/InitCommand.php index 6869d4068..8b67c26ab 100644 --- a/src/Composer/Command/InitCommand.php +++ b/src/Composer/Command/InitCommand.php @@ -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> $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(); diff --git a/src/Composer/Command/InstallCommand.php b/src/Composer/Command/InstallCommand.php index b992758bb..df1edf062 100644 --- a/src/Composer/Command/InstallCommand.php +++ b/src/Composer/Command/InstallCommand.php @@ -98,7 +98,7 @@ EOT $composer = $this->requireComposer(); - if ((!$composer->getLocker() || !$composer->getLocker()->isLocked()) && !HttpDownloader::isCurlEnabled()) { + if (!$composer->getLocker()->isLocked() && !HttpDownloader::isCurlEnabled()) { $io->writeError('Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled.'); } diff --git a/src/Composer/Command/LicensesCommand.php b/src/Composer/Command/LicensesCommand.php index 5a9bfa16b..f59034282 100644 --- a/src/Composer/Command/LicensesCommand.php +++ b/src/Composer/Command/LicensesCommand.php @@ -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 $bucket * @return array */ - 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 $bucket the list to add packages to * @return array */ - public function appendPackages(array $packages, array $bucket) + public function appendPackages(array $packages, array $bucket): array { foreach ($packages as $package) { $bucket[$package->getName()] = $package; diff --git a/src/Composer/Command/OutdatedCommand.php b/src/Composer/Command/OutdatedCommand.php index bdf60f664..332a4c64e 100644 --- a/src/Composer/Command/OutdatedCommand.php +++ b/src/Composer/Command/OutdatedCommand.php @@ -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; } diff --git a/src/Composer/Command/PackageDiscoveryTrait.php b/src/Composer/Command/PackageDiscoveryTrait.php index c55e97612..a9685ae13 100644 --- a/src/Composer/Command/PackageDiscoveryTrait.php +++ b/src/Composer/Command/PackageDiscoveryTrait.php @@ -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( diff --git a/src/Composer/Command/ProhibitsCommand.php b/src/Composer/Command/ProhibitsCommand.php index 304b116e2..59165f4de 100644 --- a/src/Composer/Command/ProhibitsCommand.php +++ b/src/Composer/Command/ProhibitsCommand.php @@ -27,7 +27,7 @@ class ProhibitsCommand extends BaseDependencyCommand * * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('prohibits') diff --git a/src/Composer/Command/ReinstallCommand.php b/src/Composer/Command/ReinstallCommand.php index 7b8a00873..926ba9839 100644 --- a/src/Composer/Command/ReinstallCommand.php +++ b/src/Composer/Command/ReinstallCommand.php @@ -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()]; }); diff --git a/src/Composer/Command/RemoveCommand.php b/src/Composer/Command/RemoveCommand.php index e33675224..fdda37df1 100644 --- a/src/Composer/Command/RemoveCommand.php +++ b/src/Composer/Command/RemoveCommand.php @@ -116,7 +116,7 @@ EOT if (count($input->getArgument('packages')) === 0) { $this->getIO()->writeError('No unused packages to remove'); - $this->setCode(function () { + $this->setCode(function (): int { return 0; }); } diff --git a/src/Composer/Command/RequireCommand.php b/src/Composer/Command/RequireCommand.php index c46a96518..5ad66a794 100644 --- a/src/Composer/Command/RequireCommand.php +++ b/src/Composer/Command/RequireCommand.php @@ -296,7 +296,7 @@ EOT * @param string $requireKey * @return string[] */ - private function getInconsistentRequireKeys(array $newRequirements, $requireKey) + private function getInconsistentRequireKeys(array $newRequirements, $requireKey): array { $requireKeys = $this->getPackagesByRequireKey(); $inconsistentRequirements = array(); @@ -315,7 +315,7 @@ EOT /** * @return array */ - 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()); diff --git a/src/Composer/Command/RunScriptCommand.php b/src/Composer/Command/RunScriptCommand.php index f35688c15..fc66a9d04 100644 --- a/src/Composer/Command/RunScriptCommand.php +++ b/src/Composer/Command/RunScriptCommand.php @@ -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(); diff --git a/src/Composer/Command/ScriptAliasCommand.php b/src/Composer/Command/ScriptAliasCommand.php index 801068c9a..2c98c9a66 100644 --- a/src/Composer/Command/ScriptAliasCommand.php +++ b/src/Composer/Command/ScriptAliasCommand.php @@ -42,7 +42,7 @@ class ScriptAliasCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName($this->script) diff --git a/src/Composer/Command/SearchCommand.php b/src/Composer/Command/SearchCommand.php index 9a404482f..496394a30 100644 --- a/src/Composer/Command/SearchCommand.php +++ b/src/Composer/Command/SearchCommand.php @@ -33,7 +33,7 @@ class SearchCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('search') diff --git a/src/Composer/Command/SelfUpdateCommand.php b/src/Composer/Command/SelfUpdateCommand.php index af8d511e7..06b0d2d0d 100644 --- a/src/Composer/Command/SelfUpdateCommand.php +++ b/src/Composer/Command/SelfUpdateCommand.php @@ -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 https://composer.github.io/pubkeys.html to find the latest keys'); - $validator = function ($value) { + $validator = function ($value): string { if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { throw new \UnexpectedValueException('Invalid input'); } @@ -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(); diff --git a/src/Composer/Command/ShowCommand.php b/src/Composer/Command/ShowCommand.php index 5a80f1db9..ae9350f1e 100644 --- a/src/Composer/Command/ShowCommand.php +++ b/src/Composer/Command/ShowCommand.php @@ -223,7 +223,7 @@ EOT if ($input->getOption('no-dev')) { $packages = $this->filterRequiredPackages($installedRepo, $rootPkg); - $repos = $installedRepo = new InstalledRepository(array(new InstalledArrayRepository(array_map(function ($pkg) { + $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 $versions * @return array */ - 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 $json * @return array */ - 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 $json * @return array */ - 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 $json * @return array */ - 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 */ - 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 $bucket * @return array */ - private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()) + private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array()): array { $requires = $package->getRequires(); diff --git a/src/Composer/Command/StatusCommand.php b/src/Composer/Command/StatusCommand.php index eed32b623..8aec0e70d 100644 --- a/src/Composer/Command/StatusCommand.php +++ b/src/Composer/Command/StatusCommand.php @@ -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(''.$path.':'); @@ -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(''.$path.':'); diff --git a/src/Composer/Command/SuggestsCommand.php b/src/Composer/Command/SuggestsCommand.php index 8c72ba045..eae73a05c 100644 --- a/src/Composer/Command/SuggestsCommand.php +++ b/src/Composer/Command/SuggestsCommand.php @@ -26,7 +26,7 @@ class SuggestsCommand extends BaseCommand /** * @return void */ - protected function configure() + protected function configure(): void { $this ->setName('suggests') diff --git a/src/Composer/Command/UpdateCommand.php b/src/Composer/Command/UpdateCommand.php index c2efd014b..39decf788 100644 --- a/src/Composer/Command/UpdateCommand.php +++ b/src/Composer/Command/UpdateCommand.php @@ -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 $packages * @return array */ - 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(); diff --git a/src/Composer/Command/ValidateCommand.php b/src/Composer/Command/ValidateCommand.php index 700461bcf..8c5ad5aea 100644 --- a/src/Composer/Command/ValidateCommand.php +++ b/src/Composer/Command/ValidateCommand.php @@ -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); diff --git a/src/Composer/Compiler.php b/src/Composer/Compiler.php index 362deeb34..6bf250468 100644 --- a/src/Composer/Compiler.php +++ b/src/Composer/Compiler.php @@ -44,7 +44,7 @@ class Compiler * * @throws \RuntimeException */ - public function compile($pharFile = 'composer.phar') + 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 diff --git a/src/Composer/Composer.php b/src/Composer/Composer.php index 749c9e35d..8913397b6 100644 --- a/src/Composer/Composer.php +++ b/src/Composer/Composer.php @@ -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 * @author Nils Adermann */ -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; } diff --git a/src/Composer/Config.php b/src/Composer/Config.php index a83f70175..24423a0a4 100644 --- a/src/Composer/Config.php +++ b/src/Composer/Config.php @@ -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 */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -441,7 +441,7 @@ class Config * * @return array */ - 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 */ - 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); diff --git a/src/Composer/Config/JsonConfigSource.php b/src/Composer/Config/JsonConfigSource.php index 604c41f9a..84de4f32c 100644 --- a/src/Composer/Config/JsonConfigSource.php +++ b/src/Composer/Config/JsonConfigSource.php @@ -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; diff --git a/src/Composer/Console/Application.php b/src/Composer/Console/Application.php index 4762396af..5bf8f6ffc 100644 --- a/src/Composer/Console/Application.php +++ b/src/Composer/Console/Application.php @@ -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('PHP temp directory (%s) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini', sys_get_temp_dir())); @@ -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('Check https://getcomposer.org/doc/06-config.md#process-timeout for details', 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) { diff --git a/src/Composer/Console/GithubActionError.php b/src/Composer/Console/GithubActionError.php index 6cd49c20d..578ac8eca 100644 --- a/src/Composer/Console/GithubActionError.php +++ b/src/Composer/Console/GithubActionError.php @@ -34,7 +34,7 @@ final class GithubActionError * * @return void */ - public function emit($message, $file = null, $line = null) + 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); diff --git a/src/Composer/DependencyResolver/Decisions.php b/src/Composer/DependencyResolver/Decisions.php index 2df464bc1..8740cf7bf 100644 --- a/src/Composer/DependencyResolver/Decisions.php +++ b/src/Composer/DependencyResolver/Decisions.php @@ -43,7 +43,7 @@ class Decisions implements \Iterator, \Countable * @param int $level * @return void */ - public function decide($literal, $level, Rule $why) + 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); diff --git a/src/Composer/DependencyResolver/DefaultPolicy.php b/src/Composer/DependencyResolver/DefaultPolicy.php index 74e60d31a..e9add445f 100644 --- a/src/Composer/DependencyResolver/DefaultPolicy.php +++ b/src/Composer/DependencyResolver/DefaultPolicy.php @@ -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 */ - 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; diff --git a/src/Composer/DependencyResolver/GenericRule.php b/src/Composer/DependencyResolver/GenericRule.php index 00abfafd3..c86aa19cb 100644 --- a/src/Composer/DependencyResolver/GenericRule.php +++ b/src/Composer/DependencyResolver/GenericRule.php @@ -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); } diff --git a/src/Composer/DependencyResolver/LockTransaction.php b/src/Composer/DependencyResolver/LockTransaction.php index a3abe1e2a..4d04a5cd6 100644 --- a/src/Composer/DependencyResolver/LockTransaction.php +++ b/src/Composer/DependencyResolver/LockTransaction.php @@ -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 $aliases * @return array */ - 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']); }); diff --git a/src/Composer/DependencyResolver/MultiConflictRule.php b/src/Composer/DependencyResolver/MultiConflictRule.php index deda73010..a7fcb0036 100644 --- a/src/Composer/DependencyResolver/MultiConflictRule.php +++ b/src/Composer/DependencyResolver/MultiConflictRule.php @@ -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."); } diff --git a/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php b/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php index 320fc54c0..e1c21008b 100644 --- a/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php +++ b/src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.php @@ -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 '.$this->package->getPrettyName().' ('.$this->package->getFullPrettyVersion().') as installed, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->package->getAliasOf()->getFullPrettyVersion().')'; } diff --git a/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php b/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php index f447047d4..6cdd02837 100644 --- a/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php +++ b/src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.php @@ -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 '.$this->package->getPrettyName().' ('.$this->package->getFullPrettyVersion().') as uninstalled, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->package->getAliasOf()->getFullPrettyVersion().')'; } diff --git a/src/Composer/DependencyResolver/Operation/UninstallOperation.php b/src/Composer/DependencyResolver/Operation/UninstallOperation.php index ebfe98df8..35e7ed753 100644 --- a/src/Composer/DependencyResolver/Operation/UninstallOperation.php +++ b/src/Composer/DependencyResolver/Operation/UninstallOperation.php @@ -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 '.$package->getPrettyName().' ('.$package->getFullPrettyVersion().')'; } diff --git a/src/Composer/DependencyResolver/Operation/UpdateOperation.php b/src/Composer/DependencyResolver/Operation/UpdateOperation.php index be9a49c22..dbfb3d310 100644 --- a/src/Composer/DependencyResolver/Operation/UpdateOperation.php +++ b/src/Composer/DependencyResolver/Operation/UpdateOperation.php @@ -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(); diff --git a/src/Composer/DependencyResolver/PolicyInterface.php b/src/Composer/DependencyResolver/PolicyInterface.php index 48ce24e16..4651ceb4d 100644 --- a/src/Composer/DependencyResolver/PolicyInterface.php +++ b/src/Composer/DependencyResolver/PolicyInterface.php @@ -26,12 +26,12 @@ interface PolicyInterface * * @phpstan-param Constraint::STR_OP_* $operator */ - public function versionCompare(PackageInterface $a, PackageInterface $b, $operator); + 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; } diff --git a/src/Composer/DependencyResolver/Pool.php b/src/Composer/DependencyResolver/Pool.php index 0fa5783e4..9a1a73b3c 100644 --- a/src/Composer/DependencyResolver/Pool.php +++ b/src/Composer/DependencyResolver/Pool.php @@ -60,7 +60,7 @@ class Pool implements \Countable * @param string $name * @return array */ - public function getRemovedVersions($name, ConstraintInterface $constraint) + 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 */ - 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 $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; } diff --git a/src/Composer/DependencyResolver/PoolBuilder.php b/src/Composer/DependencyResolver/PoolBuilder.php index 69769ca7f..9766557e6 100644 --- a/src/Composer/DependencyResolver/PoolBuilder.php +++ b/src/Composer/DependencyResolver/PoolBuilder.php @@ -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; diff --git a/src/Composer/DependencyResolver/PoolOptimizer.php b/src/Composer/DependencyResolver/PoolOptimizer.php index 7e1e32fdc..5c77eda79 100644 --- a/src/Composer/DependencyResolver/PoolOptimizer.php +++ b/src/Composer/DependencyResolver/PoolOptimizer.php @@ -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> $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; diff --git a/src/Composer/DependencyResolver/Problem.php b/src/Composer/DependencyResolver/Problem.php index 124a544cb..77e2975c8 100644 --- a/src/Composer/DependencyResolver/Problem.php +++ b/src/Composer/DependencyResolver/Problem.php @@ -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> The problem's reasons */ - public function getReasons() + public function getReasons(): array { return $this->reasons; } @@ -77,7 +77,7 @@ class Problem * @param array $learnedPool * @return string */ - public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, array $installedMap = array(), array $learnedPool = array()) + 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 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() : ''; } diff --git a/src/Composer/DependencyResolver/Request.php b/src/Composer/DependencyResolver/Request.php index 3b680ad0b..508a8f0b2 100644 --- a/src/Composer/DependencyResolver/Request.php +++ b/src/Composer/DependencyResolver/Request.php @@ -64,7 +64,7 @@ class Request * @param string $packageName * @return void */ - public function requireName($packageName, ConstraintInterface $constraint = null) + 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 */ - public function getRequires() + public function getRequires(): array { return $this->requires; } @@ -176,7 +176,7 @@ class Request /** * @return array */ - 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 */ - 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 */ - 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; } diff --git a/src/Composer/DependencyResolver/Rule.php b/src/Composer/DependencyResolver/Rule.php index 133e7f7a0..1e2d08daa 100644 --- a/src/Composer/DependencyResolver/Rule.php +++ b/src/Composer/DependencyResolver/Rule.php @@ -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 $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(); diff --git a/src/Composer/DependencyResolver/Rule2Literals.php b/src/Composer/DependencyResolver/Rule2Literals.php index cf5e20792..f07d011fc 100644 --- a/src/Composer/DependencyResolver/Rule2Literals.php +++ b/src/Composer/DependencyResolver/Rule2Literals.php @@ -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; } diff --git a/src/Composer/DependencyResolver/RuleSet.php b/src/Composer/DependencyResolver/RuleSet.php index d83320c52..68c2b7905 100644 --- a/src/Composer/DependencyResolver/RuleSet.php +++ b/src/Composer/DependencyResolver/RuleSet.php @@ -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 */ - public function getRules() + public function getRules(): array { return $this->rules; } @@ -132,7 +132,7 @@ class RuleSet implements \IteratorAggregate, \Countable * @param self::TYPE_*|array $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_* $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) { diff --git a/src/Composer/DependencyResolver/RuleSetGenerator.php b/src/Composer/DependencyResolver/RuleSetGenerator.php index fef50b0eb..71f86864b 100644 --- a/src/Composer/DependencyResolver/RuleSetGenerator.php +++ b/src/Composer/DependencyResolver/RuleSetGenerator.php @@ -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 */ $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(); diff --git a/src/Composer/DependencyResolver/RuleWatchChain.php b/src/Composer/DependencyResolver/RuleWatchChain.php index a03aaf2f6..a54032686 100644 --- a/src/Composer/DependencyResolver/RuleWatchChain.php +++ b/src/Composer/DependencyResolver/RuleWatchChain.php @@ -29,7 +29,7 @@ class RuleWatchChain extends \SplDoublyLinkedList * @param int $offset The offset to seek to. * @return void */ - public function seek($offset) + 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); diff --git a/src/Composer/DependencyResolver/RuleWatchGraph.php b/src/Composer/DependencyResolver/RuleWatchGraph.php index e9e3caa17..03da05ce2 100644 --- a/src/Composer/DependencyResolver/RuleWatchGraph.php +++ b/src/Composer/DependencyResolver/RuleWatchGraph.php @@ -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; diff --git a/src/Composer/DependencyResolver/RuleWatchNode.php b/src/Composer/DependencyResolver/RuleWatchNode.php index a0abf254d..136ac4a86 100644 --- a/src/Composer/DependencyResolver/RuleWatchNode.php +++ b/src/Composer/DependencyResolver/RuleWatchNode.php @@ -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; diff --git a/src/Composer/DependencyResolver/Solver.php b/src/Composer/DependencyResolver/Solver.php index b0a3eb00f..43f253969 100644 --- a/src/Composer/DependencyResolver/Solver.php +++ b/src/Composer/DependencyResolver/Solver.php @@ -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 $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; diff --git a/src/Composer/DependencyResolver/SolverProblemsException.php b/src/Composer/DependencyResolver/SolverProblemsException.php index deaec7d24..fb5dfdde8 100644 --- a/src/Composer/DependencyResolver/SolverProblemsException.php +++ b/src/Composer/DependencyResolver/SolverProblemsException.php @@ -46,7 +46,7 @@ class SolverProblemsException extends \RuntimeException * @param bool $isDevExtraction * @return string */ - public function getPrettyString(RepositorySet $repositorySet, Request $request, Pool $pool, $isVerbose, $isDevExtraction = false) + 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) { diff --git a/src/Composer/DependencyResolver/Transaction.php b/src/Composer/DependencyResolver/Transaction.php index ef9c74174..2d3272c51 100644 --- a/src/Composer/DependencyResolver/Transaction.php +++ b/src/Composer/DependencyResolver/Transaction.php @@ -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 */ - 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) { diff --git a/src/Composer/Downloader/ArchiveDownloader.php b/src/Composer/Downloader/ArchiveDownloader.php index ddbea79c0..152dfb9c4 100644 --- a/src/Composer/Downloader/ArchiveDownloader.php +++ b/src/Composer/Downloader/ArchiveDownloader.php @@ -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) diff --git a/src/Composer/Downloader/DownloadManager.php b/src/Composer/Downloader/DownloadManager.php index 71eb87ee6..41e61e0ad 100644 --- a/src/Composer/Downloader/DownloadManager.php +++ b/src/Composer/Downloader/DownloadManager.php @@ -59,7 +59,7 @@ class DownloadManager * @param bool $preferSource prefer downloading from source * @return DownloadManager */ - public function setPreferSource($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; diff --git a/src/Composer/Downloader/FileDownloader.php b/src/Composer/Downloader/FileDownloader.php index f4bd777df..ab347d23d 100644 --- a/src/Composer/Downloader/FileDownloader.php +++ b/src/Composer/Downloader/FileDownloader.php @@ -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 $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.'); } diff --git a/src/Composer/Downloader/FossilDownloader.php b/src/Composer/Downloader/FossilDownloader.php index f5215d966..662828b84 100644 --- a/src/Composer/Downloader/FossilDownloader.php +++ b/src/Composer/Downloader/FossilDownloader.php @@ -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_'); } diff --git a/src/Composer/Downloader/GitDownloader.php b/src/Composer/Downloader/GitDownloader.php index 33ff7922a..7f7d74c9f 100644 --- a/src/Composer/Downloader/GitDownloader.php +++ b/src/Composer/Downloader/GitDownloader.php @@ -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(' '.$package->getPrettyName().' has modified files:'); diff --git a/src/Composer/Downloader/GzipDownloader.php b/src/Composer/Downloader/GzipDownloader.php index 8b5caf474..5826078a0 100644 --- a/src/Composer/Downloader/GzipDownloader.php +++ b/src/Composer/Downloader/GzipDownloader.php @@ -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'); diff --git a/src/Composer/Downloader/HgDownloader.php b/src/Composer/Downloader/HgDownloader.php index 45b0e2874..d7db15a23 100644 --- a/src/Composer/Downloader/HgDownloader.php +++ b/src/Composer/Downloader/HgDownloader.php @@ -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'); } diff --git a/src/Composer/Downloader/PathDownloader.php b/src/Composer/Downloader/PathDownloader.php index 74c36f136..9c24383c7 100644 --- a/src/Composer/Downloader/PathDownloader.php +++ b/src/Composer/Downloader/PathDownloader.php @@ -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') && diff --git a/src/Composer/Downloader/PerforceDownloader.php b/src/Composer/Downloader/PerforceDownloader.php index c7d0e7985..ae603a832 100644 --- a/src/Composer/Downloader/PerforceDownloader.php +++ b/src/Composer/Downloader/PerforceDownloader.php @@ -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 */ - 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; } diff --git a/src/Composer/Downloader/PharDownloader.php b/src/Composer/Downloader/PharDownloader.php index 2bfd70a72..b91b2ec1e 100644 --- a/src/Composer/Downloader/PharDownloader.php +++ b/src/Composer/Downloader/PharDownloader.php @@ -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); diff --git a/src/Composer/Downloader/RarDownloader.php b/src/Composer/Downloader/RarDownloader.php index e11366421..ea9c63604 100644 --- a/src/Composer/Downloader/RarDownloader.php +++ b/src/Composer/Downloader/RarDownloader.php @@ -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; diff --git a/src/Composer/Downloader/SvnDownloader.php b/src/Composer/Downloader/SvnDownloader.php index 0d269121c..7dd58493e 100644 --- a/src/Composer/Downloader/SvnDownloader.php +++ b/src/Composer/Downloader/SvnDownloader.php @@ -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); diff --git a/src/Composer/Downloader/TransportException.php b/src/Composer/Downloader/TransportException.php index 92be261a6..e36028670 100644 --- a/src/Composer/Downloader/TransportException.php +++ b/src/Composer/Downloader/TransportException.php @@ -31,7 +31,7 @@ class TransportException extends \RuntimeException * * @return void */ - public function setHeaders($headers) + public function setHeaders($headers): void { $this->headers = $headers; } @@ -39,7 +39,7 @@ class TransportException extends \RuntimeException /** * @return ?array */ - 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 */ - 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; } diff --git a/src/Composer/Downloader/VcsDownloader.php b/src/Composer/Downloader/VcsDownloader.php index eaea3d9da..836925b66 100644 --- a/src/Composer/Downloader/VcsDownloader.php +++ b/src/Composer/Downloader/VcsDownloader.php @@ -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)) { diff --git a/src/Composer/Downloader/XzDownloader.php b/src/Composer/Downloader/XzDownloader.php index 7e69a52bc..2072b05e3 100644 --- a/src/Composer/Downloader/XzDownloader.php +++ b/src/Composer/Downloader/XzDownloader.php @@ -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); diff --git a/src/Composer/Downloader/ZipDownloader.php b/src/Composer/Downloader/ZipDownloader.php index 23ad6db76..a1f297a9d 100644 --- a/src/Composer/Downloader/ZipDownloader.php +++ b/src/Composer/Downloader/ZipDownloader.php @@ -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(); diff --git a/src/Composer/EventDispatcher/EventDispatcher.php b/src/Composer/EventDispatcher/EventDispatcher.php index 29b1f5de7..ea6d51792 100644 --- a/src/Composer/EventDispatcher/EventDispatcher.php +++ b/src/Composer/EventDispatcher/EventDispatcher.php @@ -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')) { diff --git a/src/Composer/Factory.php b/src/Composer/Factory.php index 5911b6633..e6ef47563 100644 --- a/src/Composer/Factory.php +++ b/src/Composer/Factory.php @@ -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); - $am->addArchiver(new Archiver\ZipArchiver); - $am->addArchiver(new Archiver\PharArchiver); + 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) { diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php index d1fb51b8f..ca37baea4 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilter.php @@ -20,7 +20,7 @@ final class IgnoreAllPlatformRequirementFilter implements PlatformRequirementFil * @param string $req * @return bool */ - public function isIgnored($req) + public function isIgnored($req): bool { return PlatformRepository::isPlatformPackage($req); } diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php index 6c3adf14b..e51d59b39 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilter.php @@ -55,7 +55,7 @@ final class IgnoreListPlatformRequirementFilter implements PlatformRequirementFi * @param string $req * @return bool */ - public function isIgnored($req) + 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; diff --git a/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php b/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php index 7c4bddbab..2262326c3 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php +++ b/src/Composer/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilter.php @@ -18,7 +18,7 @@ final class IgnoreNothingPlatformRequirementFilter implements PlatformRequiremen * @param string $req * @return false */ - public function isIgnored($req) + public function isIgnored($req): bool { return false; } diff --git a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.php b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.php index ac8a83cd7..302bdd915 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.php +++ b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactory.php @@ -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(); } diff --git a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php index 89e858152..52cf83e16 100644 --- a/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php +++ b/src/Composer/Filter/PlatformRequirementFilter/PlatformRequirementFilterInterface.php @@ -18,5 +18,5 @@ interface PlatformRequirementFilterInterface * @param string $req * @return bool */ - public function isIgnored($req); + public function isIgnored($req): bool; } diff --git a/src/Composer/IO/BufferIO.php b/src/Composer/IO/BufferIO.php index 627abec9d..4d7242120 100644 --- a/src/Composer/IO/BufferIO.php +++ b/src/Composer/IO/BufferIO.php @@ -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.'); diff --git a/src/Composer/IO/ConsoleIO.php b/src/Composer/IO/ConsoleIO.php index 63337ec93..2fd2cb178 100644 --- a/src/Composer/IO/ConsoleIO.php +++ b/src/Composer/IO/ConsoleIO.php @@ -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(); diff --git a/src/Composer/IO/NullIO.php b/src/Composer/IO/NullIO.php index 89c574e43..278b945b3 100644 --- a/src/Composer/IO/NullIO.php +++ b/src/Composer/IO/NullIO.php @@ -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; } diff --git a/src/Composer/Installer.php b/src/Composer/Installer.php index 8bd88e5b9..18b798d7b 100644 --- a/src/Composer/Installer.php +++ b/src/Composer/Installer.php @@ -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 $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('Installing dependencies from lock file'.($this->devMode ? ' (including require-dev)' : '').''); @@ -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 $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 */ - private function getRootAliases($forUpdate) + private function getRootAliases($forUpdate): array { if ($forUpdate) { $aliases = $this->package->getAliases(); @@ -969,7 +969,7 @@ class Installer * * @return array */ - 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; diff --git a/src/Composer/Installer/BinaryInstaller.php b/src/Composer/Installer/BinaryInstaller.php index 417e9be2b..4af59ad23 100644 --- a/src/Composer/Installer/BinaryInstaller.php +++ b/src/Composer/Installer/BinaryInstaller.php @@ -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); diff --git a/src/Composer/Installer/InstallationManager.php b/src/Composer/Installer/InstallationManager.php index 71aa3d986..788d367e7 100644 --- a/src/Composer/Installer/InstallationManager.php +++ b/src/Composer/Installer/InstallationManager.php @@ -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(' ' . ucfirst($opType) .' of '.$package->getPrettyName().' failed'); throw $e; }); - $postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation) { + $postExecCallbacks[] = function () use ($opType, $runScripts, $dispatcher, $devMode, $repo, $allOperations, $operation): void { $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($opType); if (defined($event) && $runScripts && $dispatcher) { $dispatcher->dispatchPackageEvent(constant($event), $devMode, $repo, $allOperations, $operation); @@ -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; diff --git a/src/Composer/Installer/LibraryInstaller.php b/src/Composer/Installer/LibraryInstaller.php index 7490e11a5..f5525341d 100644 --- a/src/Composer/Installer/LibraryInstaller.php +++ b/src/Composer/Installer/LibraryInstaller.php @@ -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; + } } diff --git a/src/Composer/Installer/PluginInstaller.php b/src/Composer/Installer/PluginInstaller.php index e4d0f0404..2dded4eac 100644 --- a/src/Composer/Installer/PluginInstaller.php +++ b/src/Composer/Installer/PluginInstaller.php @@ -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; + } } diff --git a/src/Composer/Installer/ProjectInstaller.php b/src/Composer/Installer/ProjectInstaller.php index 42bb77aca..7e31fdaf9 100644 --- a/src/Composer/Installer/ProjectInstaller.php +++ b/src/Composer/Installer/ProjectInstaller.php @@ -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; } diff --git a/src/Composer/Installer/SuggestedPackagesReporter.php b/src/Composer/Installer/SuggestedPackagesReporter.php index f8fb9d887..17e51b5f6 100644 --- a/src/Composer/Installer/SuggestedPackagesReporter.php +++ b/src/Composer/Installer/SuggestedPackagesReporter.php @@ -47,7 +47,7 @@ class SuggestedPackagesReporter /** * @return array 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:]]/', diff --git a/src/Composer/Json/JsonFile.php b/src/Composer/Json/JsonFile.php index 35661c925..aa81fb61a 100644 --- a/src/Composer/Json/JsonFile.php +++ b/src/Composer/Json/JsonFile.php @@ -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: diff --git a/src/Composer/Json/JsonFormatter.php b/src/Composer/Json/JsonFormatter.php index a85357f87..dd705db78 100644 --- a/src/Composer/Json/JsonFormatter.php +++ b/src/Composer/Json/JsonFormatter.php @@ -38,7 +38,7 @@ class JsonFormatter * @param bool $unescapeSlashes Un escape slashes * @return string */ - public static function format($json, $unescapeUnicode, $unescapeSlashes) + public static function format($json, $unescapeUnicode, $unescapeSlashes): string { $result = ''; $pos = 0; diff --git a/src/Composer/Json/JsonManipulator.php b/src/Composer/Json/JsonManipulator.php index 1e51f4dcc..8a309086d 100644 --- a/src/Composer/Json/JsonManipulator.php +++ b/src/Composer/Json/JsonManipulator.php @@ -94,7 +94,7 @@ class JsonManipulator // update existing link $existingPackage = $packageMatches['package']; $packageRegex = str_replace('/', '\\\\?/', preg_quote($existingPackage)); - $links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint) { + $links = Preg::replaceCallback('{'.self::$DEFINES.'"'.$packageRegex.'"(?P\s*:\s*)(?&string)}ix', function ($m) use ($existingPackage, $constraint): string { return JsonFile::encode(str_replace('\\/', '/', $existingPackage)) . $m['separator'] . '"' . $constraint . '"'; }, $links); } else { @@ -133,9 +133,9 @@ class JsonManipulator * @param array $packages * @return void */ - private function sortPackages(array &$packages = array()) + private function sortPackages(array &$packages = array()): void { - $prefix = function ($requirement) { + $prefix = function ($requirement): string { if (PlatformRepository::isPlatformPackage($requirement)) { return Preg::replace( array( @@ -159,7 +159,7 @@ class JsonManipulator return '5-'.$requirement; }; - uksort($packages, function ($a, $b) use ($prefix) { + uksort($packages, function ($a, $b) use ($prefix): int { return strnatcmp($prefix($a), $prefix($b)); }); } @@ -297,7 +297,7 @@ class JsonManipulator // child exists $childRegex = '{'.self::$DEFINES.'(?P"'.preg_quote($name).'"\s*:\s*)(?P(?&json))(?P,?)}x'; if (Preg::isMatch($childRegex, $children, $matches)) { - $children = Preg::replaceCallback($childRegex, function ($matches) use ($subName, $value) { + $children = Preg::replaceCallback($childRegex, function ($matches) use ($subName, $value): string { if ($subName !== null) { $curVal = json_decode($matches['content'], true); if (!is_array($curVal)) { @@ -351,7 +351,7 @@ class JsonManipulator } } - $this->contents = Preg::replaceCallback($nodeRegex, function ($m) use ($children) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($m) use ($children): string { return $m['start'] . $children . $m['end']; }, $this->contents); @@ -436,7 +436,7 @@ class JsonManipulator $newline = $this->newline; $indent = $this->indent; - $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($indent, $newline) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($indent, $newline): string { return $matches['start'] . '{' . $newline . $indent . '}' . $matches['end']; }, $this->contents); @@ -450,7 +450,7 @@ class JsonManipulator return true; } - $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($name, $subName, $childrenClean) { + $this->contents = Preg::replaceCallback($nodeRegex, function ($matches) use ($name, $subName, $childrenClean): string { if ($subName !== null) { $curVal = json_decode($matches['content'], true); unset($curVal[$name][$subName]); diff --git a/src/Composer/Json/JsonValidationException.php b/src/Composer/Json/JsonValidationException.php index e4533f672..35f61d32d 100644 --- a/src/Composer/Json/JsonValidationException.php +++ b/src/Composer/Json/JsonValidationException.php @@ -28,7 +28,7 @@ class JsonValidationException extends Exception * @param string $message * @param string[] $errors */ - public function __construct($message, $errors = array(), Exception $previous = null) + public function __construct($message, array $errors = array(), Exception $previous = null) { $this->errors = $errors; parent::__construct((string) $message, 0, $previous); @@ -37,7 +37,7 @@ class JsonValidationException extends Exception /** * @return string[] */ - public function getErrors() + public function getErrors(): array { return $this->errors; } diff --git a/src/Composer/Package/AliasPackage.php b/src/Composer/Package/AliasPackage.php index 4dd2bd9aa..5c2645eb1 100644 --- a/src/Composer/Package/AliasPackage.php +++ b/src/Composer/Package/AliasPackage.php @@ -83,7 +83,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function getVersion() + public function getVersion(): string { return $this->version; } @@ -91,7 +91,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function getStability() + public function getStability(): string { return $this->stability; } @@ -99,7 +99,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function getPrettyVersion() + public function getPrettyVersion(): string { return $this->prettyVersion; } @@ -107,7 +107,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function isDev() + public function isDev(): bool { return $this->dev; } @@ -115,7 +115,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function getRequires() + public function getRequires(): array { return $this->requires; } @@ -124,7 +124,7 @@ class AliasPackage extends BasePackage * @inheritDoc * @return array */ - public function getConflicts() + public function getConflicts(): array { return $this->conflicts; } @@ -133,7 +133,7 @@ class AliasPackage extends BasePackage * @inheritDoc * @return array */ - public function getProvides() + public function getProvides(): array { return $this->provides; } @@ -142,7 +142,7 @@ class AliasPackage extends BasePackage * @inheritDoc * @return array */ - public function getReplaces() + public function getReplaces(): array { return $this->replaces; } @@ -150,7 +150,7 @@ class AliasPackage extends BasePackage /** * @inheritDoc */ - public function getDevRequires() + public function getDevRequires(): array { return $this->devRequires; } @@ -173,7 +173,7 @@ class AliasPackage extends BasePackage * @see setRootPackageAlias * @return bool */ - public function isRootPackageAlias() + public function isRootPackageAlias(): bool { return $this->rootPackageAlias; } @@ -184,7 +184,7 @@ class AliasPackage extends BasePackage * * @return Link[] */ - protected function replaceSelfVersionDependencies(array $links, $linkType) + protected function replaceSelfVersionDependencies(array $links, $linkType): array { // for self.version requirements, we use the original package's branch name instead, to avoid leaking the magic dev-master-alias to users $prettyVersion = $this->prettyVersion; @@ -220,7 +220,7 @@ class AliasPackage extends BasePackage /** * @return bool */ - public function hasSelfVersionRequires() + public function hasSelfVersionRequires(): bool { return $this->hasSelfVersionRequires; } @@ -234,167 +234,167 @@ class AliasPackage extends BasePackage * Wrappers around the aliased package * ***************************************/ - public function getType() + public function getType(): string { return $this->aliasOf->getType(); } - public function getTargetDir() + public function getTargetDir(): ?string { return $this->aliasOf->getTargetDir(); } - public function getExtra() + public function getExtra(): array { return $this->aliasOf->getExtra(); } - public function setInstallationSource($type) + public function setInstallationSource($type): void { $this->aliasOf->setInstallationSource($type); } - public function getInstallationSource() + public function getInstallationSource(): ?string { return $this->aliasOf->getInstallationSource(); } - public function getSourceType() + public function getSourceType(): ?string { return $this->aliasOf->getSourceType(); } - public function getSourceUrl() + public function getSourceUrl(): ?string { return $this->aliasOf->getSourceUrl(); } - public function getSourceUrls() + public function getSourceUrls(): array { return $this->aliasOf->getSourceUrls(); } - public function getSourceReference() + public function getSourceReference(): ?string { return $this->aliasOf->getSourceReference(); } - public function setSourceReference($reference) + public function setSourceReference($reference): void { $this->aliasOf->setSourceReference($reference); } - public function setSourceMirrors($mirrors) + public function setSourceMirrors($mirrors): void { $this->aliasOf->setSourceMirrors($mirrors); } - public function getSourceMirrors() + public function getSourceMirrors(): ?array { return $this->aliasOf->getSourceMirrors(); } - public function getDistType() + public function getDistType(): ?string { return $this->aliasOf->getDistType(); } - public function getDistUrl() + public function getDistUrl(): ?string { return $this->aliasOf->getDistUrl(); } - public function getDistUrls() + public function getDistUrls(): array { return $this->aliasOf->getDistUrls(); } - public function getDistReference() + public function getDistReference(): ?string { return $this->aliasOf->getDistReference(); } - public function setDistReference($reference) + public function setDistReference($reference): void { $this->aliasOf->setDistReference($reference); } - public function getDistSha1Checksum() + public function getDistSha1Checksum(): ?string { return $this->aliasOf->getDistSha1Checksum(); } - public function setTransportOptions(array $options) + public function setTransportOptions(array $options): void { $this->aliasOf->setTransportOptions($options); } - public function getTransportOptions() + public function getTransportOptions(): array { return $this->aliasOf->getTransportOptions(); } - public function setDistMirrors($mirrors) + public function setDistMirrors($mirrors): void { $this->aliasOf->setDistMirrors($mirrors); } - public function getDistMirrors() + public function getDistMirrors(): ?array { return $this->aliasOf->getDistMirrors(); } - public function getAutoload() + public function getAutoload(): array { return $this->aliasOf->getAutoload(); } - public function getDevAutoload() + public function getDevAutoload(): array { return $this->aliasOf->getDevAutoload(); } - public function getIncludePaths() + public function getIncludePaths(): array { return $this->aliasOf->getIncludePaths(); } - public function getReleaseDate() + public function getReleaseDate(): ?\DateTime { return $this->aliasOf->getReleaseDate(); } - public function getBinaries() + public function getBinaries(): array { return $this->aliasOf->getBinaries(); } - public function getSuggests() + public function getSuggests(): array { return $this->aliasOf->getSuggests(); } - public function getNotificationUrl() + public function getNotificationUrl(): ?string { return $this->aliasOf->getNotificationUrl(); } - public function isDefaultBranch() + public function isDefaultBranch(): bool { return $this->aliasOf->isDefaultBranch(); } - public function setDistUrl($url) + public function setDistUrl($url): void { $this->aliasOf->setDistUrl($url); } - public function setDistType($type) + public function setDistType($type): void { $this->aliasOf->setDistType($type); } - public function setSourceDistReferences($reference) + public function setSourceDistReferences($reference): void { $this->aliasOf->setSourceDistReferences($reference); } diff --git a/src/Composer/Package/Archiver/ArchivableFilesFilter.php b/src/Composer/Package/Archiver/ArchivableFilesFilter.php index 3242df7e8..9a5be1a19 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFilter.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFilter.php @@ -40,7 +40,7 @@ class ArchivableFilesFilter extends FilterIterator * * @return void */ - public function addEmptyDir(PharData $phar, $sources) + public function addEmptyDir(PharData $phar, $sources): void { foreach ($this->dirs as $filepath) { $localname = str_replace($sources . "/", '', $filepath); diff --git a/src/Composer/Package/Archiver/ArchivableFilesFinder.php b/src/Composer/Package/Archiver/ArchivableFilesFinder.php index b1d5650ed..31e81e295 100644 --- a/src/Composer/Package/Archiver/ArchivableFilesFinder.php +++ b/src/Composer/Package/Archiver/ArchivableFilesFinder.php @@ -57,7 +57,7 @@ class ArchivableFilesFinder extends \FilterIterator $this->finder = new Finder(); - $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs) { + $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs): bool { if ($file->isLink() && strpos($file->getRealPath(), $sources) !== 0) { return false; } diff --git a/src/Composer/Package/Archiver/ArchiveManager.php b/src/Composer/Package/Archiver/ArchiveManager.php index a6682fb3b..de8ff52e8 100644 --- a/src/Composer/Package/Archiver/ArchiveManager.php +++ b/src/Composer/Package/Archiver/ArchiveManager.php @@ -56,7 +56,7 @@ class ArchiveManager * * @return void */ - public function addArchiver(ArchiverInterface $archiver) + public function addArchiver(ArchiverInterface $archiver): void { $this->archivers[] = $archiver; } @@ -82,7 +82,7 @@ class ArchiveManager * * @return string A filename without an extension */ - public function getPackageFilename(CompletePackageInterface $package) + public function getPackageFilename(CompletePackageInterface $package): string { if ($package->getArchiveName()) { $baseName = $package->getArchiveName(); @@ -101,7 +101,7 @@ class ArchiveManager $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6); } - $name = implode('-', array_filter($nameParts, function ($p) { + $name = implode('-', array_filter($nameParts, function ($p): bool { return !empty($p); })); @@ -121,7 +121,7 @@ class ArchiveManager * @throws \RuntimeException * @return string The path of the created archive */ - public function archive(CompletePackageInterface $package, $format, $targetDir, $fileName = null, $ignoreFilters = false) + public function archive(CompletePackageInterface $package, $format, $targetDir, $fileName = null, $ignoreFilters = false): string { if (empty($format)) { throw new \InvalidArgumentException('Format must be specified'); diff --git a/src/Composer/Package/Archiver/ArchiverInterface.php b/src/Composer/Package/Archiver/ArchiverInterface.php index 4ea8dc485..a9038ca76 100644 --- a/src/Composer/Package/Archiver/ArchiverInterface.php +++ b/src/Composer/Package/Archiver/ArchiverInterface.php @@ -30,7 +30,7 @@ interface ArchiverInterface * * @return string The path to the written archive file */ - public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false); + public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false): string; /** * Format supported by the archiver. @@ -40,5 +40,5 @@ interface ArchiverInterface * * @return bool true if the format is supported by the archiver */ - public function supports($format, $sourceType); + public function supports($format, $sourceType): bool; } diff --git a/src/Composer/Package/Archiver/BaseExcludeFilter.php b/src/Composer/Package/Archiver/BaseExcludeFilter.php index 9a9c3b8c2..2fbd22796 100644 --- a/src/Composer/Package/Archiver/BaseExcludeFilter.php +++ b/src/Composer/Package/Archiver/BaseExcludeFilter.php @@ -49,7 +49,7 @@ abstract class BaseExcludeFilter * * @return bool Whether the file should be excluded */ - public function filter($relativePath, $exclude) + public function filter($relativePath, $exclude): bool { foreach ($this->excludePatterns as $patternData) { list($pattern, $negate, $stripLeadingSlash) = $patternData; @@ -80,7 +80,7 @@ abstract class BaseExcludeFilter * * @return array Exclude patterns to be used in filter() */ - protected function parseLines(array $lines, $lineParser) + protected function parseLines(array $lines, $lineParser): array { return array_filter( array_map( @@ -95,7 +95,7 @@ abstract class BaseExcludeFilter }, $lines ), - function ($pattern) { + function ($pattern): bool { return $pattern !== null; } ); @@ -108,7 +108,7 @@ abstract class BaseExcludeFilter * * @return array Exclude patterns */ - protected function generatePatterns($rules) + protected function generatePatterns($rules): array { $patterns = array(); foreach ($rules as $rule) { @@ -125,7 +125,7 @@ abstract class BaseExcludeFilter * * @return array{0: non-empty-string, 1: bool, 2: bool} An exclude pattern */ - protected function generatePattern($rule) + protected function generatePattern($rule): array { $negate = false; $pattern = ''; diff --git a/src/Composer/Package/Archiver/GitExcludeFilter.php b/src/Composer/Package/Archiver/GitExcludeFilter.php index 6a9294529..351ca4e7d 100644 --- a/src/Composer/Package/Archiver/GitExcludeFilter.php +++ b/src/Composer/Package/Archiver/GitExcludeFilter.php @@ -50,7 +50,7 @@ class GitExcludeFilter extends BaseExcludeFilter * * @return array{0: string, 1: bool, 2: bool}|null An exclude pattern for filter() */ - public function parseGitAttributesLine($line) + public function parseGitAttributesLine($line): ?array { $parts = Preg::split('#\s+#', $line); diff --git a/src/Composer/Package/Archiver/PharArchiver.php b/src/Composer/Package/Archiver/PharArchiver.php index 582e4537e..f0d3abaf5 100644 --- a/src/Composer/Package/Archiver/PharArchiver.php +++ b/src/Composer/Package/Archiver/PharArchiver.php @@ -36,7 +36,7 @@ class PharArchiver implements ArchiverInterface /** * @inheritDoc */ - public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false) + public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false): string { $sources = realpath($sources); @@ -97,7 +97,7 @@ class PharArchiver implements ArchiverInterface /** * @inheritDoc */ - public function supports($format, $sourceType) + public function supports($format, $sourceType): bool { return isset(static::$formats[$format]); } diff --git a/src/Composer/Package/Archiver/ZipArchiver.php b/src/Composer/Package/Archiver/ZipArchiver.php index 4e83a2f4d..8c7a4e59c 100644 --- a/src/Composer/Package/Archiver/ZipArchiver.php +++ b/src/Composer/Package/Archiver/ZipArchiver.php @@ -28,7 +28,7 @@ class ZipArchiver implements ArchiverInterface /** * @inheritDoc */ - public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false) + public function archive($sources, $target, $format, array $excludes = array(), $ignoreFilters = false): string { $fs = new Filesystem(); $sources = $fs->normalizePath($sources); @@ -78,7 +78,7 @@ class ZipArchiver implements ArchiverInterface /** * @inheritDoc */ - public function supports($format, $sourceType) + public function supports($format, $sourceType): bool { return isset(static::$formats[$format]) && $this->compressionAvailable(); } @@ -86,7 +86,7 @@ class ZipArchiver implements ArchiverInterface /** * @return bool */ - private function compressionAvailable() + private function compressionAvailable(): bool { return class_exists('ZipArchive'); } diff --git a/src/Composer/Package/BasePackage.php b/src/Composer/Package/BasePackage.php index a3ec9c570..f46cec9fd 100644 --- a/src/Composer/Package/BasePackage.php +++ b/src/Composer/Package/BasePackage.php @@ -274,7 +274,7 @@ abstract class BasePackage implements PackageInterface public static function packageNamesToRegexp(array $packageNames, $wrap = '{^(?:%s)$}iD') { $packageNames = array_map( - function ($packageName) { + function ($packageName): string { return BasePackage::packageNameToRegexp($packageName, '%s'); }, $packageNames diff --git a/src/Composer/Package/Comparer/Comparer.php b/src/Composer/Package/Comparer/Comparer.php index b24661ad3..d7c2a5fc7 100644 --- a/src/Composer/Package/Comparer/Comparer.php +++ b/src/Composer/Package/Comparer/Comparer.php @@ -31,7 +31,7 @@ class Comparer * * @return void */ - public function setSource($source) + public function setSource($source): void { $this->source = $source; } @@ -41,7 +41,7 @@ class Comparer * * @return void */ - public function setUpdate($update) + public function setUpdate($update): void { $this->update = $update; } @@ -82,7 +82,7 @@ class Comparer /** * @return void */ - public function doCompare() + public function doCompare(): void { $source = array(); $destination = array(); diff --git a/src/Composer/Package/CompleteAliasPackage.php b/src/Composer/Package/CompleteAliasPackage.php index 5c9e340f3..ea2dfad45 100644 --- a/src/Composer/Package/CompleteAliasPackage.php +++ b/src/Composer/Package/CompleteAliasPackage.php @@ -40,127 +40,127 @@ class CompleteAliasPackage extends AliasPackage implements CompletePackageInterf return $this->aliasOf; } - public function getScripts() + public function getScripts(): array { return $this->aliasOf->getScripts(); } - public function setScripts(array $scripts) + public function setScripts(array $scripts): void { $this->aliasOf->setScripts($scripts); } - public function getRepositories() + public function getRepositories(): array { return $this->aliasOf->getRepositories(); } - public function setRepositories(array $repositories) + public function setRepositories(array $repositories): void { $this->aliasOf->setRepositories($repositories); } - public function getLicense() + public function getLicense(): array { return $this->aliasOf->getLicense(); } - public function setLicense(array $license) + public function setLicense(array $license): void { $this->aliasOf->setLicense($license); } - public function getKeywords() + public function getKeywords(): array { return $this->aliasOf->getKeywords(); } - public function setKeywords(array $keywords) + public function setKeywords(array $keywords): void { $this->aliasOf->setKeywords($keywords); } - public function getDescription() + public function getDescription(): ?string { return $this->aliasOf->getDescription(); } - public function setDescription($description) + public function setDescription($description): void { $this->aliasOf->setDescription($description); } - public function getHomepage() + public function getHomepage(): ?string { return $this->aliasOf->getHomepage(); } - public function setHomepage($homepage) + public function setHomepage($homepage): void { $this->aliasOf->setHomepage($homepage); } - public function getAuthors() + public function getAuthors(): array { return $this->aliasOf->getAuthors(); } - public function setAuthors(array $authors) + public function setAuthors(array $authors): void { $this->aliasOf->setAuthors($authors); } - public function getSupport() + public function getSupport(): array { return $this->aliasOf->getSupport(); } - public function setSupport(array $support) + public function setSupport(array $support): void { $this->aliasOf->setSupport($support); } - public function getFunding() + public function getFunding(): array { return $this->aliasOf->getFunding(); } - public function setFunding(array $funding) + public function setFunding(array $funding): void { $this->aliasOf->setFunding($funding); } - public function isAbandoned() + public function isAbandoned(): bool { return $this->aliasOf->isAbandoned(); } - public function getReplacementPackage() + public function getReplacementPackage(): ?string { return $this->aliasOf->getReplacementPackage(); } - public function setAbandoned($abandoned) + public function setAbandoned($abandoned): void { $this->aliasOf->setAbandoned($abandoned); } - public function getArchiveName() + public function getArchiveName(): ?string { return $this->aliasOf->getArchiveName(); } - public function setArchiveName($name) + public function setArchiveName($name): void { $this->aliasOf->setArchiveName($name); } - public function getArchiveExcludes() + public function getArchiveExcludes(): array { return $this->aliasOf->getArchiveExcludes(); } - public function setArchiveExcludes(array $excludes) + public function setArchiveExcludes(array $excludes): void { $this->aliasOf->setArchiveExcludes($excludes); } diff --git a/src/Composer/Package/Dumper/ArrayDumper.php b/src/Composer/Package/Dumper/ArrayDumper.php index 9b6e40946..fd54a516f 100644 --- a/src/Composer/Package/Dumper/ArrayDumper.php +++ b/src/Composer/Package/Dumper/ArrayDumper.php @@ -26,7 +26,7 @@ class ArrayDumper /** * @return array */ - public function dump(PackageInterface $package) + public function dump(PackageInterface $package): array { $keys = array( 'binaries' => 'bin', @@ -148,7 +148,7 @@ class ArrayDumper * * @return array */ - private function dumpValues(PackageInterface $package, array $keys, array $data) + private function dumpValues(PackageInterface $package, array $keys, array $data): array { foreach ($keys as $method => $key) { if (is_numeric($method)) { diff --git a/src/Composer/Package/Link.php b/src/Composer/Package/Link.php index af08705df..8e613a565 100644 --- a/src/Composer/Package/Link.php +++ b/src/Composer/Package/Link.php @@ -105,7 +105,7 @@ class Link /** * @return string */ - public function getDescription() + public function getDescription(): string { return $this->description; } @@ -113,7 +113,7 @@ class Link /** * @return string */ - public function getSource() + public function getSource(): string { return $this->source; } @@ -121,7 +121,7 @@ class Link /** * @return string */ - public function getTarget() + public function getTarget(): string { return $this->target; } @@ -129,7 +129,7 @@ class Link /** * @return ConstraintInterface */ - public function getConstraint() + public function getConstraint(): ConstraintInterface { return $this->constraint; } @@ -138,7 +138,7 @@ class Link * @throws \UnexpectedValueException If no pretty constraint was provided * @return string */ - public function getPrettyConstraint() + public function getPrettyConstraint(): string { if (null === $this->prettyConstraint) { throw new \UnexpectedValueException(sprintf('Link %s has been misconfigured and had no prettyConstraint given.', $this)); @@ -159,7 +159,7 @@ class Link * @param PackageInterface $sourcePackage * @return string */ - public function getPrettyString(PackageInterface $sourcePackage) + public function getPrettyString(PackageInterface $sourcePackage): string { return $sourcePackage->getPrettyString().' '.$this->description.' '.$this->target.' '.$this->constraint->getPrettyString(); } diff --git a/src/Composer/Package/Loader/ArrayLoader.php b/src/Composer/Package/Loader/ArrayLoader.php index 403da9a45..16cede400 100644 --- a/src/Composer/Package/Loader/ArrayLoader.php +++ b/src/Composer/Package/Loader/ArrayLoader.php @@ -321,7 +321,7 @@ class ArrayLoader implements LoaderInterface * * @return void */ - private function configureCachedLinks(&$linkCache, $package, array $config) + private function configureCachedLinks(&$linkCache, $package, array $config): void { $name = $package->getName(); $prettyVersion = $package->getPrettyVersion(); @@ -385,7 +385,7 @@ class ArrayLoader implements LoaderInterface * @param string $prettyConstraint constraint string * @return Link */ - private function createLink($source, $sourceVersion, $description, $target, $prettyConstraint) + private function createLink($source, $sourceVersion, $description, $target, $prettyConstraint): Link { if (!\is_string($prettyConstraint)) { throw new \UnexpectedValueException('Link constraint in '.$source.' '.$description.' > '.$target.' should be a string, got '.\gettype($prettyConstraint) . ' (' . var_export($prettyConstraint, true) . ')'); diff --git a/src/Composer/Package/Loader/InvalidPackageException.php b/src/Composer/Package/Loader/InvalidPackageException.php index 25141de25..80c713544 100644 --- a/src/Composer/Package/Loader/InvalidPackageException.php +++ b/src/Composer/Package/Loader/InvalidPackageException.php @@ -40,7 +40,7 @@ class InvalidPackageException extends \Exception /** * @return mixed[] */ - public function getData() + public function getData(): array { return $this->data; } @@ -48,7 +48,7 @@ class InvalidPackageException extends \Exception /** * @return string[] */ - public function getErrors() + public function getErrors(): array { return $this->errors; } @@ -56,7 +56,7 @@ class InvalidPackageException extends \Exception /** * @return string[] */ - public function getWarnings() + public function getWarnings(): array { return $this->warnings; } diff --git a/src/Composer/Package/Loader/RootPackageLoader.php b/src/Composer/Package/Loader/RootPackageLoader.php index cd061941c..9c0c47c8f 100644 --- a/src/Composer/Package/Loader/RootPackageLoader.php +++ b/src/Composer/Package/Loader/RootPackageLoader.php @@ -194,7 +194,7 @@ class RootPackageLoader extends ArrayLoader * * @return list */ - private function extractAliases(array $requires, array $aliases) + private function extractAliases(array $requires, array $aliases): array { foreach ($requires as $reqName => $reqVersion) { if (Preg::isMatch('{^([^,\s#]+)(?:#[^ ]+)? +as +([^,\s]+)$}', $reqVersion, $match)) { @@ -224,7 +224,7 @@ class RootPackageLoader extends ArrayLoader * @phpstan-param array $stabilityFlags * @phpstan-return array */ - public static function extractStabilityFlags(array $requires, $minimumStability, array $stabilityFlags) + public static function extractStabilityFlags(array $requires, $minimumStability, array $stabilityFlags): array { $stabilities = BasePackage::$stabilities; /** @var int $minimumStability */ @@ -286,7 +286,7 @@ class RootPackageLoader extends ArrayLoader * * @return array */ - public static function extractReferences(array $requires, array $references) + public static function extractReferences(array $requires, array $references): array { foreach ($requires as $reqName => $reqVersion) { $reqVersion = Preg::replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion); diff --git a/src/Composer/Package/Loader/ValidatingArrayLoader.php b/src/Composer/Package/Loader/ValidatingArrayLoader.php index 7fb2c3b79..2a1278448 100644 --- a/src/Composer/Package/Loader/ValidatingArrayLoader.php +++ b/src/Composer/Package/Loader/ValidatingArrayLoader.php @@ -431,7 +431,7 @@ class ValidatingArrayLoader implements LoaderInterface /** * @return string[] */ - public function getWarnings() + public function getWarnings(): array { return $this->warnings; } @@ -439,7 +439,7 @@ class ValidatingArrayLoader implements LoaderInterface /** * @return string[] */ - public function getErrors() + public function getErrors(): array { return $this->errors; } @@ -450,7 +450,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @return string|null */ - public static function hasPackageNamingError($name, $isLink = false) + public static function hasPackageNamingError($name, $isLink = false): ?string { if (PlatformRepository::isPlatformPackage($name)) { return null; @@ -494,7 +494,7 @@ class ValidatingArrayLoader implements LoaderInterface * @phpstan-param non-empty-string $property * @phpstan-param non-empty-string $regex */ - private function validateRegex($property, $regex, $mandatory = false) + private function validateRegex($property, $regex, $mandatory = false): bool { if (!$this->validateString($property, $mandatory)) { return false; @@ -523,7 +523,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @phpstan-param non-empty-string $property */ - private function validateString($property, $mandatory = false) + private function validateString($property, $mandatory = false): bool { if (isset($this->config[$property]) && !is_string($this->config[$property])) { $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given'; @@ -552,7 +552,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @phpstan-param non-empty-string $property */ - private function validateArray($property, $mandatory = false) + private function validateArray($property, $mandatory = false): bool { if (isset($this->config[$property]) && !is_array($this->config[$property])) { $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given'; @@ -583,7 +583,7 @@ class ValidatingArrayLoader implements LoaderInterface * @phpstan-param non-empty-string $property * @phpstan-param non-empty-string|null $regex */ - private function validateFlatArray($property, $regex = null, $mandatory = false) + private function validateFlatArray($property, $regex = null, $mandatory = false): bool { if (!$this->validateArray($property, $mandatory)) { return false; @@ -617,7 +617,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @phpstan-param non-empty-string $property */ - private function validateUrl($property, $mandatory = false) + private function validateUrl($property, $mandatory = false): bool { if (!$this->validateString($property, $mandatory)) { return false; @@ -639,7 +639,7 @@ class ValidatingArrayLoader implements LoaderInterface * * @return bool */ - private function filterUrl($value, array $schemes = array('http', 'https')) + private function filterUrl($value, array $schemes = array('http', 'https')): bool { if ($value === '') { return true; diff --git a/src/Composer/Package/Locker.php b/src/Composer/Package/Locker.php index 5a306d14d..1702d2ba9 100644 --- a/src/Composer/Package/Locker.php +++ b/src/Composer/Package/Locker.php @@ -78,7 +78,7 @@ class Locker * * @return string */ - public static function getContentHash($composerFileContents) + public static function getContentHash($composerFileContents): string { $content = JsonFile::parseJson($composerFileContents, 'composer.json'); @@ -115,7 +115,7 @@ class Locker * * @return bool */ - public function isLocked() + public function isLocked(): bool { if (!$this->virtualFileWritten && !$this->lockFile->exists()) { return false; @@ -131,7 +131,7 @@ class Locker * * @return bool */ - public function isFresh() + public function isFresh(): bool { $lock = $this->lockFile->read(); @@ -156,7 +156,7 @@ class Locker * @throws \RuntimeException * @return \Composer\Repository\LockArrayRepository */ - public function getLockedRepository($withDevReqs = false) + public function getLockedRepository($withDevReqs = false): \Composer\Repository\LockArrayRepository { $lockData = $this->getLockData(); $packages = new LockArrayRepository(); @@ -205,7 +205,7 @@ class Locker /** * @return string[] Names of dependencies installed through require-dev */ - public function getDevPackageNames() + public function getDevPackageNames(): array { $names = array(); $lockData = $this->getLockData(); @@ -224,7 +224,7 @@ class Locker * @param bool $withDevReqs if true, the platform requirements from the require-dev block are also returned * @return \Composer\Package\Link[] */ - public function getPlatformRequirements($withDevReqs = false) + public function getPlatformRequirements($withDevReqs = false): array { $lockData = $this->getLockData(); $requirements = array(); @@ -255,7 +255,7 @@ class Locker /** * @return string */ - public function getMinimumStability() + public function getMinimumStability(): string { $lockData = $this->getLockData(); @@ -265,7 +265,7 @@ class Locker /** * @return array */ - public function getStabilityFlags() + public function getStabilityFlags(): array { $lockData = $this->getLockData(); @@ -275,7 +275,7 @@ class Locker /** * @return bool|null */ - public function getPreferStable() + public function getPreferStable(): ?bool { $lockData = $this->getLockData(); @@ -287,7 +287,7 @@ class Locker /** * @return bool|null */ - public function getPreferLowest() + public function getPreferLowest(): ?bool { $lockData = $this->getLockData(); @@ -299,7 +299,7 @@ class Locker /** * @return array */ - public function getPlatformOverrides() + public function getPlatformOverrides(): array { $lockData = $this->getLockData(); @@ -311,7 +311,7 @@ class Locker * * @phpstan-return list */ - public function getAliases() + public function getAliases(): array { $lockData = $this->getLockData(); @@ -321,7 +321,7 @@ class Locker /** * @return array */ - public function getLockData() + public function getLockData(): array { if (null !== $this->lockDataCache) { return $this->lockDataCache; @@ -353,11 +353,11 @@ class Locker * * @phpstan-param list $aliases */ - public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest, array $platformOverrides, $write = true) + public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest, array $platformOverrides, $write = true): bool { // keep old default branch names normalized to DEFAULT_BRANCH_ALIAS for BC as that is how Composer 1 outputs the lock file // when loading the lock file the version is anyway ignored in Composer 2, so it has no adverse effect - $aliases = array_map(function ($alias) { + $aliases = array_map(function ($alias): array { if (in_array($alias['version'], array('dev-master', 'dev-trunk', 'dev-default'), true)) { $alias['version'] = VersionParser::DEFAULT_BRANCH_ALIAS; } @@ -419,7 +419,7 @@ class Locker * * @phpstan-return list> */ - private function lockPackages(array $packages) + private function lockPackages(array $packages): array { $locked = array(); @@ -477,7 +477,7 @@ class Locker * @param PackageInterface $package The package to scan. * @return string|null The formatted datetime or null if none was found. */ - private function getPackageTime(PackageInterface $package) + private function getPackageTime(PackageInterface $package): ?string { if (!function_exists('proc_open')) { return null; diff --git a/src/Composer/Package/Package.php b/src/Composer/Package/Package.php index a0be96f3d..7549c4008 100644 --- a/src/Composer/Package/Package.php +++ b/src/Composer/Package/Package.php @@ -788,7 +788,7 @@ class Package extends BasePackage * @param string $source * @return array */ - private function convertLinksToMap(array $links, $source) + private function convertLinksToMap(array $links, $source): array { trigger_error('Package::'.$source.' must be called with a map of lowercased package name => Link object, got a indexed array, this is deprecated and you should fix your usage.'); $newLinks = array(); diff --git a/src/Composer/Package/RootAliasPackage.php b/src/Composer/Package/RootAliasPackage.php index 4817653dc..adf69b6b0 100644 --- a/src/Composer/Package/RootAliasPackage.php +++ b/src/Composer/Package/RootAliasPackage.php @@ -43,7 +43,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getAliases() + public function getAliases(): array { return $this->aliasOf->getAliases(); } @@ -51,7 +51,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getMinimumStability() + public function getMinimumStability(): string { return $this->aliasOf->getMinimumStability(); } @@ -59,7 +59,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getStabilityFlags() + public function getStabilityFlags(): array { return $this->aliasOf->getStabilityFlags(); } @@ -67,7 +67,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getReferences() + public function getReferences(): array { return $this->aliasOf->getReferences(); } @@ -75,7 +75,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getPreferStable() + public function getPreferStable(): bool { return $this->aliasOf->getPreferStable(); } @@ -83,7 +83,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function getConfig() + public function getConfig(): array { return $this->aliasOf->getConfig(); } @@ -91,7 +91,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setRequires(array $require) + public function setRequires(array $require): void { $this->requires = $this->replaceSelfVersionDependencies($require, Link::TYPE_REQUIRE); @@ -101,7 +101,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setDevRequires(array $devRequire) + public function setDevRequires(array $devRequire): void { $this->devRequires = $this->replaceSelfVersionDependencies($devRequire, Link::TYPE_DEV_REQUIRE); @@ -111,7 +111,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setConflicts(array $conflicts) + public function setConflicts(array $conflicts): void { $this->conflicts = $this->replaceSelfVersionDependencies($conflicts, Link::TYPE_CONFLICT); $this->aliasOf->setConflicts($conflicts); @@ -120,7 +120,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setProvides(array $provides) + public function setProvides(array $provides): void { $this->provides = $this->replaceSelfVersionDependencies($provides, Link::TYPE_PROVIDE); $this->aliasOf->setProvides($provides); @@ -129,7 +129,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setReplaces(array $replaces) + public function setReplaces(array $replaces): void { $this->replaces = $this->replaceSelfVersionDependencies($replaces, Link::TYPE_REPLACE); $this->aliasOf->setReplaces($replaces); @@ -138,7 +138,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setAutoload(array $autoload) + public function setAutoload(array $autoload): void { $this->aliasOf->setAutoload($autoload); } @@ -146,7 +146,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setDevAutoload(array $devAutoload) + public function setDevAutoload(array $devAutoload): void { $this->aliasOf->setDevAutoload($devAutoload); } @@ -154,7 +154,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setStabilityFlags(array $stabilityFlags) + public function setStabilityFlags(array $stabilityFlags): void { $this->aliasOf->setStabilityFlags($stabilityFlags); } @@ -162,7 +162,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setMinimumStability($minimumStability) + public function setMinimumStability($minimumStability): void { $this->aliasOf->setMinimumStability($minimumStability); } @@ -170,7 +170,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setPreferStable($preferStable) + public function setPreferStable($preferStable): void { $this->aliasOf->setPreferStable($preferStable); } @@ -178,7 +178,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setConfig(array $config) + public function setConfig(array $config): void { $this->aliasOf->setConfig($config); } @@ -186,7 +186,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setReferences(array $references) + public function setReferences(array $references): void { $this->aliasOf->setReferences($references); } @@ -194,7 +194,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setAliases(array $aliases) + public function setAliases(array $aliases): void { $this->aliasOf->setAliases($aliases); } @@ -202,7 +202,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setSuggests(array $suggests) + public function setSuggests(array $suggests): void { $this->aliasOf->setSuggests($suggests); } @@ -210,7 +210,7 @@ class RootAliasPackage extends CompleteAliasPackage implements RootPackageInterf /** * @inheritDoc */ - public function setExtra(array $extra) + public function setExtra(array $extra): void { $this->aliasOf->setExtra($extra); } diff --git a/src/Composer/Package/RootPackage.php b/src/Composer/Package/RootPackage.php index 070e7b6c9..38375dc73 100644 --- a/src/Composer/Package/RootPackage.php +++ b/src/Composer/Package/RootPackage.php @@ -37,7 +37,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * {@inerhitDoc} */ - public function setMinimumStability($minimumStability) + public function setMinimumStability($minimumStability): void { $this->minimumStability = $minimumStability; } @@ -45,7 +45,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getMinimumStability() + public function getMinimumStability(): string { return $this->minimumStability; } @@ -53,7 +53,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function setStabilityFlags(array $stabilityFlags) + public function setStabilityFlags(array $stabilityFlags): void { $this->stabilityFlags = $stabilityFlags; } @@ -61,7 +61,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getStabilityFlags() + public function getStabilityFlags(): array { return $this->stabilityFlags; } @@ -69,7 +69,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * {@inerhitDoc} */ - public function setPreferStable($preferStable) + public function setPreferStable($preferStable): void { $this->preferStable = $preferStable; } @@ -77,7 +77,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getPreferStable() + public function getPreferStable(): bool { return $this->preferStable; } @@ -85,7 +85,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * {@inerhitDoc} */ - public function setConfig(array $config) + public function setConfig(array $config): void { $this->config = $config; } @@ -93,7 +93,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getConfig() + public function getConfig(): array { return $this->config; } @@ -101,7 +101,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * {@inerhitDoc} */ - public function setReferences(array $references) + public function setReferences(array $references): void { $this->references = $references; } @@ -109,7 +109,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getReferences() + public function getReferences(): array { return $this->references; } @@ -117,7 +117,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * {@inerhitDoc} */ - public function setAliases(array $aliases) + public function setAliases(array $aliases): void { $this->aliases = $aliases; } @@ -125,7 +125,7 @@ class RootPackage extends CompletePackage implements RootPackageInterface /** * @inheritDoc */ - public function getAliases() + public function getAliases(): array { return $this->aliases; } diff --git a/src/Composer/Package/Version/StabilityFilter.php b/src/Composer/Package/Version/StabilityFilter.php index 8eda2033b..81f4ec063 100644 --- a/src/Composer/Package/Version/StabilityFilter.php +++ b/src/Composer/Package/Version/StabilityFilter.php @@ -30,7 +30,7 @@ class StabilityFilter * @param string $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev' * @return bool true if any package name is acceptable */ - public static function isPackageAcceptable(array $acceptableStabilities, array $stabilityFlags, array $names, $stability) + public static function isPackageAcceptable(array $acceptableStabilities, array $stabilityFlags, array $names, $stability): bool { foreach ($names as $name) { // allow if package matches the package-specific stability flag diff --git a/src/Composer/Package/Version/VersionGuesser.php b/src/Composer/Package/Version/VersionGuesser.php index 7927fa726..d5b0bf907 100644 --- a/src/Composer/Package/Version/VersionGuesser.php +++ b/src/Composer/Package/Version/VersionGuesser.php @@ -66,7 +66,7 @@ class VersionGuesser * @return array|null * @phpstan-return Version|null */ - public function guessVersion(array $packageConfig, $path) + public function guessVersion(array $packageConfig, $path): ?array { if (!function_exists('proc_open')) { return null; @@ -103,7 +103,7 @@ class VersionGuesser * @return array * @phpstan-return Version */ - private function postprocess(array $versionData) + private function postprocess(array $versionData): array { if (!empty($versionData['feature_version']) && $versionData['feature_version'] === $versionData['version'] && $versionData['feature_pretty_version'] === $versionData['pretty_version']) { unset($versionData['feature_version'], $versionData['feature_pretty_version']); @@ -126,7 +126,7 @@ class VersionGuesser * * @return array{version: string|null, commit: string|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null} */ - private function guessGitVersion(array $packageConfig, $path) + private function guessGitVersion(array $packageConfig, $path): array { GitUtil::cleanEnv(); $commit = null; @@ -211,7 +211,7 @@ class VersionGuesser * * @return array{version: string, pretty_version: string}|null */ - private function versionFromGitTags($path) + private function versionFromGitTags($path): ?array { // try to fetch current version from git tags if (0 === $this->process->execute('git describe --exact-match --tags', $output, $path)) { @@ -232,7 +232,7 @@ class VersionGuesser * * @return array{version: string|null, commit: ''|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null}|null */ - private function guessHgVersion(array $packageConfig, $path) + private function guessHgVersion(array $packageConfig, $path): ?array { // try to fetch current version from hg branch if (0 === $this->process->execute('hg branch', $output, $path)) { @@ -276,7 +276,7 @@ class VersionGuesser * * @return array{version: string|null, pretty_version: string|null} */ - private function guessFeatureVersion(array $packageConfig, $version, array $branches, $scmCmdline, $path) + private function guessFeatureVersion(array $packageConfig, $version, array $branches, $scmCmdline, $path): array { $prettyVersion = $version; @@ -296,7 +296,7 @@ class VersionGuesser // sort local branches first then remote ones // and sort numeric branches below named ones, to make sure if the branch has the same distance from main and 1.10 and 1.9 for example, main is picked // and sort using natural sort so that 1.10 will appear before 1.9 - usort($branches, function ($a, $b) { + usort($branches, function ($a, $b): int { $aRemote = 0 === strpos($a, 'remotes/'); $bRemote = 0 === strpos($b, 'remotes/'); @@ -340,7 +340,7 @@ class VersionGuesser * * @return bool */ - private function isFeatureBranch(array $packageConfig, $branchName) + private function isFeatureBranch(array $packageConfig, $branchName): bool { $nonFeatureBranches = ''; if (!empty($packageConfig['non-feature-branches'])) { @@ -355,7 +355,7 @@ class VersionGuesser * * @return array{version: string|null, commit: '', pretty_version: string|null} */ - private function guessFossilVersion($path) + private function guessFossilVersion($path): array { $version = null; $prettyVersion = null; @@ -385,7 +385,7 @@ class VersionGuesser * * @return array{version: string, commit: '', pretty_version: string}|null */ - private function guessSvnVersion(array $packageConfig, $path) + private function guessSvnVersion(array $packageConfig, $path): ?array { SvnUtil::cleanEnv(); diff --git a/src/Composer/Package/Version/VersionSelector.php b/src/Composer/Package/Version/VersionSelector.php index 8e4b45faa..431bdb851 100644 --- a/src/Composer/Package/Version/VersionSelector.php +++ b/src/Composer/Package/Version/VersionSelector.php @@ -87,7 +87,7 @@ class VersionSelector if ($this->platformConstraints && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) { $platformConstraints = $this->platformConstraints; - $candidates = array_filter($candidates, function ($pkg) use ($platformConstraints, $platformRequirementFilter) { + $candidates = array_filter($candidates, function ($pkg) use ($platformConstraints, $platformRequirementFilter): bool { $reqs = $pkg->getRequires(); foreach ($reqs as $name => $link) { @@ -172,7 +172,7 @@ class VersionSelector * @param PackageInterface $package * @return string */ - public function findRecommendedRequireVersion(PackageInterface $package) + public function findRecommendedRequireVersion(PackageInterface $package): string { // Extensions which are versioned in sync with PHP should rather be required as "*" to simplify // the requires and have only one required version to change when bumping the php requirement @@ -211,7 +211,7 @@ class VersionSelector * * @return string */ - private function transformVersion($version, $prettyVersion, $stability) + private function transformVersion($version, $prettyVersion, $stability): string { // attempt to transform 2.1.1 to 2.1 // this allows you to upgrade through minor versions @@ -242,7 +242,7 @@ class VersionSelector /** * @return VersionParser */ - private function getParser() + private function getParser(): VersionParser { if ($this->parser === null) { $this->parser = new VersionParser(); diff --git a/src/Composer/PartialComposer.php b/src/Composer/PartialComposer.php new file mode 100644 index 000000000..891175066 --- /dev/null +++ b/src/Composer/PartialComposer.php @@ -0,0 +1,151 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer; + +use Composer\Package\RootPackageInterface; +use Composer\Util\Loop; +use Composer\Repository\RepositoryManager; +use Composer\Installer\InstallationManager; +use Composer\EventDispatcher\EventDispatcher; + +/** + * @author Jordi Boggiano + */ +class PartialComposer +{ + /** + * @var RootPackageInterface + */ + private $package; + + /** + * @var Loop + */ + private $loop; + + /** + * @var Repository\RepositoryManager + */ + private $repositoryManager; + + /** + * @var Installer\InstallationManager + */ + private $installationManager; + + /** + * @var Config + */ + private $config; + + /** + * @var EventDispatcher + */ + private $eventDispatcher; + + /** + * @return void + */ + public function setPackage(RootPackageInterface $package): void + { + $this->package = $package; + } + + /** + * @return RootPackageInterface + */ + public function getPackage(): RootPackageInterface + { + return $this->package; + } + + /** + * @return void + */ + public function setConfig(Config $config): void + { + $this->config = $config; + } + + /** + * @return Config + */ + public function getConfig(): Config + { + return $this->config; + } + + /** + * @return void + */ + public function setLoop(Loop $loop): void + { + $this->loop = $loop; + } + + /** + * @return Loop + */ + public function getLoop(): Loop + { + return $this->loop; + } + + /** + * @return void + */ + public function setRepositoryManager(RepositoryManager $manager): void + { + $this->repositoryManager = $manager; + } + + /** + * @return RepositoryManager + */ + public function getRepositoryManager(): RepositoryManager + { + return $this->repositoryManager; + } + + /** + * @return void + */ + public function setInstallationManager(InstallationManager $manager): void + { + $this->installationManager = $manager; + } + + /** + * @return InstallationManager + */ + public function getInstallationManager(): InstallationManager + { + return $this->installationManager; + } + + /** + * @return void + */ + public function setEventDispatcher(EventDispatcher $eventDispatcher): void + { + $this->eventDispatcher = $eventDispatcher; + } + + /** + * @return EventDispatcher + */ + public function getEventDispatcher(): EventDispatcher + { + return $this->eventDispatcher; + } +} diff --git a/src/Composer/Platform/HhvmDetector.php b/src/Composer/Platform/HhvmDetector.php index 7fee999a6..2785d26c4 100644 --- a/src/Composer/Platform/HhvmDetector.php +++ b/src/Composer/Platform/HhvmDetector.php @@ -34,7 +34,7 @@ class HhvmDetector /** * @return void */ - public function reset() + public function reset(): void { self::$hhvmVersion = null; } @@ -42,7 +42,7 @@ class HhvmDetector /** * @return string|null */ - public function getVersion() + public function getVersion(): ?string { if (null !== self::$hhvmVersion) { return self::$hhvmVersion ?: null; diff --git a/src/Composer/Platform/Runtime.php b/src/Composer/Platform/Runtime.php index 250a21aa7..a5d228027 100644 --- a/src/Composer/Platform/Runtime.php +++ b/src/Composer/Platform/Runtime.php @@ -20,7 +20,7 @@ class Runtime * * @return bool */ - public function hasConstant($constant, $class = null) + public function hasConstant($constant, $class = null): bool { return defined(ltrim($class.'::'.$constant, ':')); } @@ -41,7 +41,7 @@ class Runtime * * @return bool */ - public function hasFunction($fn) + public function hasFunction($fn): bool { return function_exists($fn); } @@ -62,7 +62,7 @@ class Runtime * * @return bool */ - public function hasClass($class) + public function hasClass($class): bool { return class_exists($class, false); } @@ -74,7 +74,7 @@ class Runtime * @return object * @throws \ReflectionException */ - public function construct($class, array $arguments = array()) + public function construct($class, array $arguments = array()): object { if (empty($arguments)) { return new $class; @@ -86,7 +86,7 @@ class Runtime } /** @return string[] */ - public function getExtensions() + public function getExtensions(): array { return get_loaded_extensions(); } @@ -96,7 +96,7 @@ class Runtime * * @return string */ - public function getExtensionVersion($extension) + public function getExtensionVersion($extension): string { return phpversion($extension); } @@ -107,7 +107,7 @@ class Runtime * @return string * @throws \ReflectionException */ - public function getExtensionInfo($extension) + public function getExtensionInfo($extension): string { $reflector = new \ReflectionExtension($extension); diff --git a/src/Composer/Platform/Version.php b/src/Composer/Platform/Version.php index 6c9cd8fa5..d2b4d1171 100644 --- a/src/Composer/Platform/Version.php +++ b/src/Composer/Platform/Version.php @@ -24,7 +24,7 @@ class Version * @param bool $isFips * @return string|null */ - public static function parseOpenssl($opensslVersion, &$isFips) + public static function parseOpenssl($opensslVersion, &$isFips): ?string { $isFips = false; @@ -43,7 +43,7 @@ class Version * @param string $libjpegVersion * @return string|null */ - public static function parseLibjpeg($libjpegVersion) + public static function parseLibjpeg($libjpegVersion): ?string { if (!Preg::isMatch('/^(?\d+)(?[a-z]*)$/', $libjpegVersion, $matches)) { return null; @@ -56,7 +56,7 @@ class Version * @param string $zoneinfoVersion * @return string|null */ - public static function parseZoneinfoVersion($zoneinfoVersion) + public static function parseZoneinfoVersion($zoneinfoVersion): ?string { if (!Preg::isMatch('/^(?\d{4})(?[a-z]*)$/', $zoneinfoVersion, $matches)) { return null; @@ -71,7 +71,7 @@ class Version * @param string $alpha * @return int */ - private static function convertAlphaVersionToIntVersion($alpha) + private static function convertAlphaVersionToIntVersion($alpha): int { return strlen($alpha) * (-ord('a') + 1) + array_sum(array_map('ord', str_split($alpha))); } @@ -80,7 +80,7 @@ class Version * @param int $versionId * @return string */ - public static function convertLibxpmVersionId($versionId) + public static function convertLibxpmVersionId($versionId): string { return self::convertVersionId($versionId, 100); } @@ -89,7 +89,7 @@ class Version * @param int $versionId * @return string */ - public static function convertOpenldapVersionId($versionId) + public static function convertOpenldapVersionId($versionId): string { return self::convertVersionId($versionId, 100); } @@ -100,7 +100,7 @@ class Version * * @return string */ - private static function convertVersionId($versionId, $base) + private static function convertVersionId($versionId, $base): string { return sprintf( '%d.%d.%d', diff --git a/src/Composer/Plugin/CommandEvent.php b/src/Composer/Plugin/CommandEvent.php index 6d81ee2cb..650757ff9 100644 --- a/src/Composer/Plugin/CommandEvent.php +++ b/src/Composer/Plugin/CommandEvent.php @@ -61,7 +61,7 @@ class CommandEvent extends Event * * @return InputInterface */ - public function getInput() + public function getInput(): InputInterface { return $this->input; } @@ -71,7 +71,7 @@ class CommandEvent extends Event * * @return OutputInterface */ - public function getOutput() + public function getOutput(): OutputInterface { return $this->output; } @@ -81,7 +81,7 @@ class CommandEvent extends Event * * @return string */ - public function getCommandName() + public function getCommandName(): string { return $this->commandName; } diff --git a/src/Composer/Plugin/PluginManager.php b/src/Composer/Plugin/PluginManager.php index 4f974d9f8..b849de107 100644 --- a/src/Composer/Plugin/PluginManager.php +++ b/src/Composer/Plugin/PluginManager.php @@ -13,6 +13,7 @@ namespace Composer\Plugin; use Composer\Composer; +use Composer\Autoload\AutoloadGenerator; use Composer\EventDispatcher\EventSubscriberInterface; use Composer\Installer\InstallerInterface; use Composer\IO\IOInterface; @@ -20,6 +21,7 @@ use Composer\Package\BasePackage; use Composer\Package\CompletePackage; use Composer\Package\Package; use Composer\Package\Version\VersionParser; +use Composer\PartialComposer; use Composer\Pcre\Preg; use Composer\Repository\RepositoryInterface; use Composer\Repository\InstalledRepository; @@ -42,7 +44,7 @@ class PluginManager protected $composer; /** @var IOInterface */ protected $io; - /** @var ?Composer */ + /** @var PartialComposer|null */ protected $globalComposer; /** @var VersionParser */ protected $versionParser; @@ -67,15 +69,7 @@ class PluginManager /** @var int */ private static $classCounter = 0; - /** - * Initializes plugin manager - * - * @param IOInterface $io - * @param Composer $composer - * @param Composer $globalComposer - * @param bool $disablePlugins - */ - public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null, $disablePlugins = false) + public function __construct(IOInterface $io, Composer $composer, PartialComposer $globalComposer = null, bool $disablePlugins = false) { $this->io = $io; $this->composer = $composer; @@ -92,7 +86,7 @@ class PluginManager * * @return void */ - public function loadInstalledPlugins() + public function loadInstalledPlugins(): void { if ($this->disablePlugins) { return; @@ -111,17 +105,16 @@ class PluginManager * * @return void */ - public function deactivateInstalledPlugins() + public function deactivateInstalledPlugins(): void { if ($this->disablePlugins) { return; } $repo = $this->composer->getRepositoryManager()->getLocalRepository(); - $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null; $this->deactivateRepository($repo, false); - if ($globalRepo) { - $this->deactivateRepository($globalRepo, true); + if ($this->globalComposer !== null) { + $this->deactivateRepository($this->globalComposer->getRepositoryManager()->getLocalRepository(), true); } } @@ -130,17 +123,15 @@ class PluginManager * * @return array plugins */ - public function getPlugins() + public function getPlugins(): array { return $this->plugins; } /** * Gets global composer or null when main composer is not fully loaded - * - * @return Composer|null */ - public function getGlobalComposer() + public function getGlobalComposer(): ?PartialComposer { return $this->globalComposer; } @@ -159,7 +150,7 @@ class PluginManager * * @throws \UnexpectedValueException */ - public function registerPackage(PackageInterface $package, $failOnMissingClasses = false, $isGlobalPlugin = false) + public function registerPackage(PackageInterface $package, $failOnMissingClasses = false, $isGlobalPlugin = false): void { if ($this->disablePlugins) { return; @@ -318,7 +309,7 @@ class PluginManager * * @throws \UnexpectedValueException */ - public function deactivatePackage(PackageInterface $package) + public function deactivatePackage(PackageInterface $package): void { if ($this->disablePlugins) { return; @@ -349,7 +340,7 @@ class PluginManager * * @throws \UnexpectedValueException */ - public function uninstallPackage(PackageInterface $package) + public function uninstallPackage(PackageInterface $package): void { if ($this->disablePlugins) { return; @@ -374,7 +365,7 @@ class PluginManager * * @return string */ - protected function getPluginApiVersion() + protected function getPluginApiVersion(): string { return PluginInterface::PLUGIN_API_VERSION; } @@ -392,7 +383,7 @@ class PluginManager * * @return void */ - public function addPlugin(PluginInterface $plugin, $isGlobalPlugin = false, PackageInterface $sourcePackage = null) + public function addPlugin(PluginInterface $plugin, $isGlobalPlugin = false, PackageInterface $sourcePackage = null): void { if ($sourcePackage === null) { trigger_error('Calling PluginManager::addPlugin without $sourcePackage is deprecated, if you are using this please get in touch with us to explain the use case', E_USER_DEPRECATED); @@ -429,7 +420,7 @@ class PluginManager * * @return void */ - public function removePlugin(PluginInterface $plugin) + public function removePlugin(PluginInterface $plugin): void { $index = array_search($plugin, $this->plugins, true); if ($index === false) { @@ -454,7 +445,7 @@ class PluginManager * * @return void */ - public function uninstallPlugin(PluginInterface $plugin) + public function uninstallPlugin(PluginInterface $plugin): void { $this->io->writeError('Uninstalling plugin '.get_class($plugin), true, IOInterface::DEBUG); $plugin->uninstall($this->composer, $this->io); @@ -476,7 +467,7 @@ class PluginManager * * @throws \RuntimeException */ - private function loadRepository(RepositoryInterface $repo, $isGlobalRepo) + private function loadRepository(RepositoryInterface $repo, $isGlobalRepo): void { $packages = $repo->getPackages(); $sortedPackages = PackageSorter::sortPackages($packages); @@ -503,7 +494,7 @@ class PluginManager * * @return void */ - private function deactivateRepository(RepositoryInterface $repo, $isGlobalRepo) + private function deactivateRepository(RepositoryInterface $repo, $isGlobalRepo): void { $packages = $repo->getPackages(); $sortedPackages = array_reverse(PackageSorter::sortPackages($packages)); @@ -530,7 +521,7 @@ class PluginManager * * @return array Map of package names to packages */ - private function collectDependencies(InstalledRepository $installedRepo, array $collected, PackageInterface $package) + private function collectDependencies(InstalledRepository $installedRepo, array $collected, PackageInterface $package): array { foreach ($package->getRequires() as $requireLink) { foreach ($installedRepo->findPackagesWithReplacersAndProviders($requireLink->getTarget()) as $requiredPackage) { @@ -552,12 +543,13 @@ class PluginManager * * @return string Install path */ - private function getInstallPath(PackageInterface $package, $global = false) + private function getInstallPath(PackageInterface $package, $global = false): string { if (!$global) { return $this->composer->getInstallationManager()->getInstallPath($package); } + assert(null !== $this->globalComposer); return $this->globalComposer->getInstallationManager()->getInstallPath($package); } @@ -567,7 +559,7 @@ class PluginManager * @throws \RuntimeException On empty or non-string implementation class name value * @return null|string The fully qualified class of the implementation or null if Plugin is not of Capable type or does not provide it */ - protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability) + protected function getCapabilityImplementationClassName(PluginInterface $plugin, $capability): ?string { if (!($plugin instanceof Capable)) { return null; @@ -600,7 +592,7 @@ class PluginManager * @phpstan-param class-string $capabilityClassName * @phpstan-return null|CapabilityClass */ - public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = array()) + public function getPluginCapability(PluginInterface $plugin, $capabilityClassName, array $ctorArgs = array()): ?Capability { if ($capabilityClass = $this->getCapabilityImplementationClassName($plugin, $capabilityClassName)) { if (!class_exists($capabilityClass)) { @@ -631,7 +623,7 @@ class PluginManager * Keeping it an array will allow future values to be passed w\o changing the signature. * @return CapabilityClass[] */ - public function getPluginCapabilities($capabilityClassName, array $ctorArgs = array()) + public function getPluginCapabilities($capabilityClassName, array $ctorArgs = array()): array { $capabilities = array(); foreach ($this->getPlugins() as $plugin) { @@ -647,7 +639,7 @@ class PluginManager * @param array|bool|null $allowPluginsConfig * @return array|null */ - private function parseAllowedPlugins($allowPluginsConfig) + private function parseAllowedPlugins($allowPluginsConfig): ?array { if (null === $allowPluginsConfig) { return null; @@ -674,7 +666,7 @@ class PluginManager * @param bool $isGlobalPlugin * @return bool */ - private function isPluginAllowed($package, $isGlobalPlugin) + private function isPluginAllowed($package, $isGlobalPlugin): bool { static $warned = array(); $rules = $isGlobalPlugin ? $this->allowGlobalPluginRules : $this->allowPluginRules; diff --git a/src/Composer/Plugin/PostFileDownloadEvent.php b/src/Composer/Plugin/PostFileDownloadEvent.php index 7be34d728..80489af9d 100644 --- a/src/Composer/Plugin/PostFileDownloadEvent.php +++ b/src/Composer/Plugin/PostFileDownloadEvent.php @@ -81,7 +81,7 @@ class PostFileDownloadEvent extends Event * * @return string|null */ - public function getFileName() + public function getFileName(): ?string { return $this->fileName; } @@ -91,7 +91,7 @@ class PostFileDownloadEvent extends Event * * @return string|null */ - public function getChecksum() + public function getChecksum(): ?string { return $this->checksum; } @@ -101,7 +101,7 @@ class PostFileDownloadEvent extends Event * * @return string */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -127,7 +127,7 @@ class PostFileDownloadEvent extends Event * @return \Composer\Package\PackageInterface|null The package. * @deprecated Use getContext instead */ - public function getPackage() + public function getPackage(): ?\Composer\Package\PackageInterface { trigger_error('PostFileDownloadEvent::getPackage is deprecated since Composer 2.1, use getContext instead.', E_USER_DEPRECATED); $context = $this->getContext(); @@ -140,7 +140,7 @@ class PostFileDownloadEvent extends Event * * @return string */ - public function getType() + public function getType(): string { return $this->type; } diff --git a/src/Composer/Plugin/PreCommandRunEvent.php b/src/Composer/Plugin/PreCommandRunEvent.php index 60ad05b4a..2c534a68e 100644 --- a/src/Composer/Plugin/PreCommandRunEvent.php +++ b/src/Composer/Plugin/PreCommandRunEvent.php @@ -51,7 +51,7 @@ class PreCommandRunEvent extends Event * * @return InputInterface */ - public function getInput() + public function getInput(): InputInterface { return $this->input; } @@ -61,7 +61,7 @@ class PreCommandRunEvent extends Event * * @return string */ - public function getCommand() + public function getCommand(): string { return $this->command; } diff --git a/src/Composer/Plugin/PreFileDownloadEvent.php b/src/Composer/Plugin/PreFileDownloadEvent.php index 9e675d438..5b9b0307a 100644 --- a/src/Composer/Plugin/PreFileDownloadEvent.php +++ b/src/Composer/Plugin/PreFileDownloadEvent.php @@ -73,7 +73,7 @@ class PreFileDownloadEvent extends Event /** * @return HttpDownloader */ - public function getHttpDownloader() + public function getHttpDownloader(): HttpDownloader { return $this->httpDownloader; } @@ -83,7 +83,7 @@ class PreFileDownloadEvent extends Event * * @return string */ - public function getProcessedUrl() + public function getProcessedUrl(): string { return $this->processedUrl; } @@ -95,7 +95,7 @@ class PreFileDownloadEvent extends Event * * @return void */ - public function setProcessedUrl($processedUrl) + public function setProcessedUrl($processedUrl): void { $this->processedUrl = $processedUrl; } @@ -105,7 +105,7 @@ class PreFileDownloadEvent extends Event * * @return string|null */ - public function getCustomCacheKey() + public function getCustomCacheKey(): ?string { return $this->customCacheKey; } @@ -117,7 +117,7 @@ class PreFileDownloadEvent extends Event * * @return void */ - public function setCustomCacheKey($customCacheKey) + public function setCustomCacheKey($customCacheKey): void { $this->customCacheKey = $customCacheKey; } @@ -127,7 +127,7 @@ class PreFileDownloadEvent extends Event * * @return string */ - public function getType() + public function getType(): string { return $this->type; } @@ -152,7 +152,7 @@ class PreFileDownloadEvent extends Event * * @return mixed[] */ - public function getTransportOptions() + public function getTransportOptions(): array { return $this->transportOptions; } @@ -166,7 +166,7 @@ class PreFileDownloadEvent extends Event * * @return void */ - public function setTransportOptions(array $options) + public function setTransportOptions(array $options): void { $this->transportOptions = $options; } diff --git a/src/Composer/Plugin/PrePoolCreateEvent.php b/src/Composer/Plugin/PrePoolCreateEvent.php index ff7702553..d64e96d95 100644 --- a/src/Composer/Plugin/PrePoolCreateEvent.php +++ b/src/Composer/Plugin/PrePoolCreateEvent.php @@ -93,7 +93,7 @@ class PrePoolCreateEvent extends Event /** * @return RepositoryInterface[] */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -101,7 +101,7 @@ class PrePoolCreateEvent extends Event /** * @return Request */ - public function getRequest() + public function getRequest(): Request { return $this->request; } @@ -110,7 +110,7 @@ class PrePoolCreateEvent extends Event * @return int[] array of stability => BasePackage::STABILITY_* value * @phpstan-return array */ - public function getAcceptableStabilities() + public function getAcceptableStabilities(): array { return $this->acceptableStabilities; } @@ -119,7 +119,7 @@ class PrePoolCreateEvent extends Event * @return int[] array of package name => BasePackage::STABILITY_* value * @phpstan-return array */ - public function getStabilityFlags() + public function getStabilityFlags(): array { return $this->stabilityFlags; } @@ -128,7 +128,7 @@ class PrePoolCreateEvent extends Event * @return array[] of package => version => [alias, alias_normalized] * @phpstan-return array> */ - public function getRootAliases() + public function getRootAliases(): array { return $this->rootAliases; } @@ -137,7 +137,7 @@ class PrePoolCreateEvent extends Event * @return string[] * @phpstan-return array */ - public function getRootReferences() + public function getRootReferences(): array { return $this->rootReferences; } @@ -145,7 +145,7 @@ class PrePoolCreateEvent extends Event /** * @return BasePackage[] */ - public function getPackages() + public function getPackages(): array { return $this->packages; } @@ -153,7 +153,7 @@ class PrePoolCreateEvent extends Event /** * @return BasePackage[] */ - public function getUnacceptableFixedPackages() + public function getUnacceptableFixedPackages(): array { return $this->unacceptableFixedPackages; } @@ -163,7 +163,7 @@ class PrePoolCreateEvent extends Event * * @return void */ - public function setPackages(array $packages) + public function setPackages(array $packages): void { $this->packages = $packages; } @@ -173,7 +173,7 @@ class PrePoolCreateEvent extends Event * * @return void */ - public function setUnacceptableFixedPackages(array $packages) + public function setUnacceptableFixedPackages(array $packages): void { $this->unacceptableFixedPackages = $packages; } diff --git a/src/Composer/Question/StrictConfirmationQuestion.php b/src/Composer/Question/StrictConfirmationQuestion.php index 301bb91b0..bcb339bda 100644 --- a/src/Composer/Question/StrictConfirmationQuestion.php +++ b/src/Composer/Question/StrictConfirmationQuestion.php @@ -53,7 +53,7 @@ class StrictConfirmationQuestion extends Question * * @return callable */ - private function getDefaultNormalizer() + private function getDefaultNormalizer(): callable { $default = $this->getDefault(); $trueRegex = $this->trueAnswerRegex; @@ -84,9 +84,9 @@ class StrictConfirmationQuestion extends Question * * @return callable */ - private function getDefaultValidator() + private function getDefaultValidator(): callable { - return function ($answer) { + return function ($answer): bool { if (!is_bool($answer)) { throw new InvalidArgumentException('Please answer yes, y, no, or n.'); } diff --git a/src/Composer/Repository/ArtifactRepository.php b/src/Composer/Repository/ArtifactRepository.php index e8140162c..7db28bcab 100644 --- a/src/Composer/Repository/ArtifactRepository.php +++ b/src/Composer/Repository/ArtifactRepository.php @@ -73,7 +73,7 @@ class ArtifactRepository extends ArrayRepository implements ConfigurableReposito * * @return void */ - private function scanDirectory($path) + private function scanDirectory($path): void { $io = $this->io; @@ -102,7 +102,7 @@ class ArtifactRepository extends ArrayRepository implements ConfigurableReposito /** * @return ?BasePackage */ - private function getComposerInformation(\SplFileInfo $file) + private function getComposerInformation(\SplFileInfo $file): ?BasePackage { $json = null; $fileType = null; diff --git a/src/Composer/Repository/ComposerRepository.php b/src/Composer/Repository/ComposerRepository.php index 8fa6bf03b..9e6adbaf6 100644 --- a/src/Composer/Repository/ComposerRepository.php +++ b/src/Composer/Repository/ComposerRepository.php @@ -39,6 +39,7 @@ use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Util\Http\Response; use Composer\MetadataMinifier\MetadataMinifier; use Composer\Util\Url; +use React\Promise\PromiseInterface; /** * @author Jordi Boggiano @@ -349,7 +350,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @param list $results * @return list */ - function (array $results) { + function (array $results): array { return $results; } ; @@ -360,7 +361,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @param list $results * @return list */ - function (array $results) use ($packageFilterRegex) { + function (array $results) use ($packageFilterRegex): array { /** @var list $results */ return Preg::grep($packageFilterRegex, $results); } @@ -399,7 +400,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return list */ - private function getVendorNames() + private function getVendorNames(): array { $cacheKey = 'vendor-list.txt'; $cacheAge = $this->cache->getAge($cacheKey); @@ -430,7 +431,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @param string|null $packageFilter * @return list */ - private function loadPackageList($packageFilter = null) + private function loadPackageList($packageFilter = null): array { if (null === $this->listUrl) { throw new \LogicException('Make sure to call loadRootServerFile before loadPackageList'); @@ -640,7 +641,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return string[] */ - private function getProviderNames() + private function getProviderNames(): array { $this->loadRootServerFile(); @@ -677,7 +678,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return bool */ - private function hasProviders() + private function hasProviders(): bool { $this->loadRootServerFile(); @@ -694,7 +695,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return array */ - private function whatProvides($name, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()) + private function whatProvides($name, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()): array { $packagesSource = null; if (!$this->hasPartialPackages() || !isset($this->partialPackagesByName[$name])) { @@ -862,7 +863,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return array{namesFound: array, packages: array} */ - private function loadAsyncPackages(array $packageNames, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()) + private function loadAsyncPackages(array $packageNames, array $acceptableStabilities = null, array $stabilityFlags = null, array $alreadyLoaded = array()): array { $this->loadRootServerFile(); @@ -904,7 +905,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito } $promises[] = $this->asyncFetchFile($url, $cacheKey, $lastModified) - ->then(function ($response) use (&$packages, &$namesFound, $url, $cacheKey, $contents, $realName, $constraint, $acceptableStabilities, $stabilityFlags, $alreadyLoaded) { + ->then(function ($response) use (&$packages, &$namesFound, $url, $cacheKey, $contents, $realName, $constraint, $acceptableStabilities, $stabilityFlags, $alreadyLoaded): void { $packagesSource = 'downloaded file ('.Url::sanitize($url).')'; if (true === $response) { @@ -972,7 +973,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return bool */ - private function isVersionAcceptable($constraint, $name, $versionData, array $acceptableStabilities = null, array $stabilityFlags = null) + private function isVersionAcceptable($constraint, $name, $versionData, array $acceptableStabilities = null, array $stabilityFlags = null): bool { $versions = array($versionData['version_normalized']); @@ -998,7 +999,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return string */ - private function getPackagesJsonUrl() + private function getPackagesJsonUrl(): string { $jsonUrlParts = parse_url($this->url); @@ -1094,7 +1095,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito // Disables lazy-provider behavior as with available-packages, but may allow much more compact expression of packages covered by this repository. // Over-specifying covered packages is safe, but may result in increased traffic to your repository. if (!empty($data['available-package-patterns'])) { - $this->availablePackagePatterns = array_map(function ($pattern) { + $this->availablePackagePatterns = array_map(function ($pattern): string { return BasePackage::packageNameToRegexp($pattern); }, $data['available-package-patterns']); $this->hasAvailablePackageList = true; @@ -1135,7 +1136,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return string */ - private function canonicalizeUrl($url) + private function canonicalizeUrl($url): string { if ('/' === $url[0]) { if (Preg::isMatch('{^[^:]++://[^/]*+}', $this->url, $matches)) { @@ -1151,7 +1152,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return mixed[] */ - private function loadDataFromServer() + private function loadDataFromServer(): array { $data = $this->loadRootServerFile(); @@ -1161,7 +1162,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito /** * @return bool */ - private function hasPartialPackages() + private function hasPartialPackages(): bool { if ($this->hasPartialPackages && null === $this->partialPackagesByName) { $this->initializePartialPackages(); @@ -1175,7 +1176,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return void */ - private function loadProviderListings($data) + private function loadProviderListings($data): void { if (isset($data['providers'])) { if (!is_array($this->providerListing)) { @@ -1205,7 +1206,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return mixed[] */ - private function loadIncludes($data) + private function loadIncludes($data): array { $packages = array(); @@ -1250,7 +1251,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return list */ - private function createPackages(array $packages, $source = null) + private function createPackages(array $packages, $source = null): array { if (!$packages) { return array(); @@ -1457,10 +1458,8 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * @param string $filename * @param string $cacheKey * @param string|null $lastModifiedTime - * - * @return \React\Promise\PromiseInterface */ - private function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null) + private function asyncFetchFile($filename, $cacheKey, $lastModifiedTime = null): PromiseInterface { if (isset($this->packagesNotFoundCache[$filename])) { return \React\Promise\resolve(array('packages' => array())); @@ -1494,6 +1493,9 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito $degradedMode = &$this->degradedMode; $eventDispatcher = $this->eventDispatcher; + /** + * @return array|true true if the response was a 304 and the cache is fresh + */ $accept = function ($response) use ($io, $url, $filename, $cache, $cacheKey, $eventDispatcher) { // package not found is acceptable for a v2 protocol repository if ($response->getStatusCode() === 404) { @@ -1566,7 +1568,7 @@ class ComposerRepository extends ArrayRepository implements ConfigurableReposito * * @return void */ - private function initializePartialPackages() + private function initializePartialPackages(): void { $rootData = $this->loadRootServerFile(); diff --git a/src/Composer/Repository/CompositeRepository.php b/src/Composer/Repository/CompositeRepository.php index 83603081c..e34ce7357 100644 --- a/src/Composer/Repository/CompositeRepository.php +++ b/src/Composer/Repository/CompositeRepository.php @@ -12,6 +12,7 @@ namespace Composer\Repository; +use Composer\Package\BasePackage; use Composer\Package\PackageInterface; /** @@ -39,9 +40,9 @@ class CompositeRepository implements RepositoryInterface } } - public function getRepoName() + public function getRepoName(): string { - return 'composite repo ('.implode(', ', array_map(function ($repo) { + return 'composite repo ('.implode(', ', array_map(function ($repo): string { return $repo->getRepoName(); }, $this->repositories)).')'; } @@ -51,7 +52,7 @@ class CompositeRepository implements RepositoryInterface * * @return RepositoryInterface[] */ - public function getRepositories() + public function getRepositories(): array { return $this->repositories; } @@ -59,7 +60,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function hasPackage(PackageInterface $package) + public function hasPackage(PackageInterface $package): bool { foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ @@ -74,7 +75,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackage($name, $constraint) + public function findPackage($name, $constraint): ?BasePackage { foreach ($this->repositories as $repository) { /* @var $repository RepositoryInterface */ @@ -90,7 +91,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackages($name, $constraint = null) + public function findPackages($name, $constraint = null): array { $packages = array(); foreach ($this->repositories as $repository) { @@ -104,7 +105,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function loadPackages(array $packageMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = array()) + public function loadPackages(array $packageMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = array()): array { $packages = array(); $namesFound = array(); @@ -124,7 +125,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null) + public function search($query, $mode = 0, $type = null): array { $matches = array(); foreach ($this->repositories as $repository) { @@ -138,7 +139,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function getPackages() + public function getPackages(): array { $packages = array(); foreach ($this->repositories as $repository) { @@ -152,7 +153,7 @@ class CompositeRepository implements RepositoryInterface /** * @inheritDoc */ - public function getProviders($packageName) + public function getProviders($packageName): array { $results = array(); foreach ($this->repositories as $repository) { @@ -166,7 +167,7 @@ class CompositeRepository implements RepositoryInterface /** * @return void */ - public function removePackage(PackageInterface $package) + public function removePackage(PackageInterface $package): void { foreach ($this->repositories as $repository) { if ($repository instanceof WritableRepositoryInterface) { @@ -195,7 +196,7 @@ class CompositeRepository implements RepositoryInterface * * @return void */ - public function addRepository(RepositoryInterface $repository) + public function addRepository(RepositoryInterface $repository): void { if ($repository instanceof self) { foreach ($repository->getRepositories() as $repo) { diff --git a/src/Composer/Repository/FilesystemRepository.php b/src/Composer/Repository/FilesystemRepository.php index 6138514fc..ea9a0eeb1 100644 --- a/src/Composer/Repository/FilesystemRepository.php +++ b/src/Composer/Repository/FilesystemRepository.php @@ -150,7 +150,7 @@ class FilesystemRepository extends WritableArrayRepository } sort($data['dev-package-names']); - usort($data['packages'], function ($a, $b) { + usort($data['packages'], function ($a, $b): int { return strcmp($a['name'], $b['name']); }); @@ -173,7 +173,7 @@ class FilesystemRepository extends WritableArrayRepository * * @return string */ - private function dumpToPhpCode(array $array = array(), $level = 0) + private function dumpToPhpCode(array $array = array(), $level = 0): string { $lines = "array(\n"; $level++; @@ -211,7 +211,7 @@ class FilesystemRepository extends WritableArrayRepository * * @return ?array */ - private function generateInstalledVersions(InstallationManager $installationManager, array $installPaths, $devMode, $repoDir) + private function generateInstalledVersions(InstallationManager $installationManager, array $installPaths, $devMode, $repoDir): ?array { if (!$this->dumpVersions) { return null; diff --git a/src/Composer/Repository/FilterRepository.php b/src/Composer/Repository/FilterRepository.php index 078f66f8f..fc5acd776 100644 --- a/src/Composer/Repository/FilterRepository.php +++ b/src/Composer/Repository/FilterRepository.php @@ -62,7 +62,7 @@ class FilterRepository implements RepositoryInterface $this->repo = $repo; } - public function getRepoName() + public function getRepoName(): string { return $this->repo->getRepoName(); } @@ -72,7 +72,7 @@ class FilterRepository implements RepositoryInterface * * @return RepositoryInterface */ - public function getRepository() + public function getRepository(): RepositoryInterface { return $this->repo; } @@ -80,7 +80,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function hasPackage(PackageInterface $package) + public function hasPackage(PackageInterface $package): bool { return $this->repo->hasPackage($package); } @@ -88,7 +88,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackage($name, $constraint) + public function findPackage($name, $constraint): ?BasePackage { if (!$this->isAllowed($name)) { return null; @@ -100,7 +100,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function findPackages($name, $constraint = null) + public function findPackages($name, $constraint = null): array { if (!$this->isAllowed($name)) { return array(); @@ -112,7 +112,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function loadPackages(array $packageMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = array()) + public function loadPackages(array $packageMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = array()): array { foreach ($packageMap as $name => $constraint) { if (!$this->isAllowed($name)) { @@ -135,7 +135,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function search($query, $mode = 0, $type = null) + public function search($query, $mode = 0, $type = null): array { $result = array(); @@ -151,7 +151,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function getPackages() + public function getPackages(): array { $result = array(); foreach ($this->repo->getPackages() as $package) { @@ -166,7 +166,7 @@ class FilterRepository implements RepositoryInterface /** * @inheritDoc */ - public function getProviders($packageName) + public function getProviders($packageName): array { $result = array(); foreach ($this->repo->getProviders($packageName) as $name => $provider) { @@ -195,7 +195,7 @@ class FilterRepository implements RepositoryInterface * * @return bool */ - private function isAllowed($name) + private function isAllowed($name): bool { if (!$this->only && !$this->exclude) { return true; diff --git a/src/Composer/Repository/InstalledArrayRepository.php b/src/Composer/Repository/InstalledArrayRepository.php index 40673e7f7..d046a9973 100644 --- a/src/Composer/Repository/InstalledArrayRepository.php +++ b/src/Composer/Repository/InstalledArrayRepository.php @@ -21,7 +21,7 @@ namespace Composer\Repository; */ class InstalledArrayRepository extends WritableArrayRepository implements InstalledRepositoryInterface { - public function getRepoName() + public function getRepoName(): string { return 'installed '.parent::getRepoName(); } @@ -29,7 +29,7 @@ class InstalledArrayRepository extends WritableArrayRepository implements Instal /** * @inheritDoc */ - public function isFresh() + public function isFresh(): bool { // this is not a completely correct implementation but there is no way to // distinguish an empty repo and a newly created one given this is all in-memory diff --git a/src/Composer/Repository/InstalledRepository.php b/src/Composer/Repository/InstalledRepository.php index db0967ba7..e99ed95db 100644 --- a/src/Composer/Repository/InstalledRepository.php +++ b/src/Composer/Repository/InstalledRepository.php @@ -38,7 +38,7 @@ class InstalledRepository extends CompositeRepository * * @return BasePackage[] */ - public function findPackagesWithReplacersAndProviders($name, $constraint = null) + public function findPackagesWithReplacersAndProviders($name, $constraint = null): array { $name = strtolower($name); @@ -87,7 +87,7 @@ class InstalledRepository extends CompositeRepository * @return array[] An associative array of arrays as described above. * @phpstan-return array */ - public function getDependents($needle, $constraint = null, $invert = false, $recurse = true, $packagesFound = null) + public function getDependents($needle, $constraint = null, $invert = false, $recurse = true, $packagesFound = null): array { $needles = array_map('strtolower', (array) $needle); $results = array(); @@ -249,9 +249,9 @@ class InstalledRepository extends CompositeRepository return $results; } - public function getRepoName() + public function getRepoName(): string { - return 'installed repo ('.implode(', ', array_map(function ($repo) { + return 'installed repo ('.implode(', ', array_map(function ($repo): string { return $repo->getRepoName(); }, $this->getRepositories())).')'; } @@ -259,7 +259,7 @@ class InstalledRepository extends CompositeRepository /** * @inheritDoc */ - public function addRepository(RepositoryInterface $repository) + public function addRepository(RepositoryInterface $repository): void { if ( $repository instanceof LockArrayRepository diff --git a/src/Composer/Repository/LockArrayRepository.php b/src/Composer/Repository/LockArrayRepository.php index 7e3b92b03..ddccdd0b1 100644 --- a/src/Composer/Repository/LockArrayRepository.php +++ b/src/Composer/Repository/LockArrayRepository.php @@ -21,7 +21,7 @@ namespace Composer\Repository; */ class LockArrayRepository extends ArrayRepository { - public function getRepoName() + public function getRepoName(): string { return 'lock repo'; } diff --git a/src/Composer/Repository/PackageRepository.php b/src/Composer/Repository/PackageRepository.php index b787931ca..f0ed385ee 100644 --- a/src/Composer/Repository/PackageRepository.php +++ b/src/Composer/Repository/PackageRepository.php @@ -45,7 +45,7 @@ class PackageRepository extends ArrayRepository /** * Initializes repository (reads file, or remote address). */ - protected function initialize() + protected function initialize(): void { parent::initialize(); @@ -61,7 +61,7 @@ class PackageRepository extends ArrayRepository } } - public function getRepoName() + public function getRepoName(): string { return Preg::replace('{^array }', 'package ', parent::getRepoName()); } diff --git a/src/Composer/Repository/PathRepository.php b/src/Composer/Repository/PathRepository.php index 725a50360..dcb9c82d5 100644 --- a/src/Composer/Repository/PathRepository.php +++ b/src/Composer/Repository/PathRepository.php @@ -129,12 +129,12 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn parent::__construct(); } - public function getRepoName() + public function getRepoName(): string { return 'path repo ('.Url::sanitize($this->repoConfig['url']).')'; } - public function getRepoConfig() + public function getRepoConfig(): array { return $this->repoConfig; } @@ -144,7 +144,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn * * This method will basically read the folder and add the found package. */ - protected function initialize() + protected function initialize(): void { parent::initialize(); @@ -240,7 +240,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn * * @return string[] */ - private function getUrlMatches() + private function getUrlMatches(): array { $flags = GLOB_MARK | GLOB_ONLYDIR; @@ -251,7 +251,7 @@ class PathRepository extends ArrayRepository implements ConfigurableRepositoryIn } // Ensure environment-specific path separators are normalized to URL separators - return array_map(function ($val) { + return array_map(function ($val): string { return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/'); }, glob($this->url, $flags)); } diff --git a/src/Composer/Repository/PlatformRepository.php b/src/Composer/Repository/PlatformRepository.php index b1c98b61c..4722f9899 100644 --- a/src/Composer/Repository/PlatformRepository.php +++ b/src/Composer/Repository/PlatformRepository.php @@ -84,7 +84,7 @@ class PlatformRepository extends ArrayRepository parent::__construct($packages); } - public function getRepoName() + public function getRepoName(): string { return 'platform repo'; } @@ -93,7 +93,7 @@ class PlatformRepository extends ArrayRepository * @param string $name * @return bool */ - public function isPlatformPackageDisabled($name) + public function isPlatformPackageDisabled($name): bool { return isset($this->disabledPackages[$name]); } @@ -101,12 +101,12 @@ class PlatformRepository extends ArrayRepository /** * @return array */ - public function getDisabledPackages() + public function getDisabledPackages(): array { return $this->disabledPackages; } - protected function initialize() + protected function initialize(): void { parent::initialize(); @@ -365,7 +365,7 @@ class PlatformRepository extends ArrayRepository case 'libxml': // ext/dom, ext/simplexml, ext/xmlreader and ext/xmlwriter use the same libxml as the ext/libxml - $libxmlProvides = array_map(function ($extension) { + $libxmlProvides = array_map(function ($extension): string { return $extension . '-libxml'; }, array_intersect($loadedExtensions, array('dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter'))); $this->addLibrary($name, $this->runtime->getConstant('LIBXML_DOTTED_VERSION'), 'libxml library version', array(), $libxmlProvides); @@ -531,7 +531,7 @@ class PlatformRepository extends ArrayRepository /** * @inheritDoc */ - public function addPackage(PackageInterface $package) + public function addPackage(PackageInterface $package): void { if (!$package instanceof CompletePackage) { throw new \UnexpectedValueException('Expected CompletePackage but got '.get_class($package)); @@ -586,7 +586,7 @@ class PlatformRepository extends ArrayRepository * * @return CompletePackage */ - private function addOverriddenPackage(array $override, $name = null) + private function addOverriddenPackage(array $override, $name = null): CompletePackage { $version = $this->versionParser->normalize($override['version']); $package = new CompletePackage($name ?: $override['name'], $version, $override['version']); @@ -604,7 +604,7 @@ class PlatformRepository extends ArrayRepository /** * @return void */ - private function addDisabledPackage(CompletePackage $package) + private function addDisabledPackage(CompletePackage $package): void { $package->setDescription($package->getDescription().'. Package disabled via config.platform'); $package->setExtra(array('config.platform' => true)); @@ -620,7 +620,7 @@ class PlatformRepository extends ArrayRepository * * @return void */ - private function addExtension($name, $prettyVersion) + private function addExtension($name, $prettyVersion): void { $extraDescription = null; @@ -653,7 +653,7 @@ class PlatformRepository extends ArrayRepository * @param string $name * @return string */ - private function buildPackageName($name) + private function buildPackageName($name): string { return 'ext-' . str_replace(' ', '-', strtolower($name)); } @@ -667,7 +667,7 @@ class PlatformRepository extends ArrayRepository * * @return void */ - private function addLibrary($name, $prettyVersion, $description = null, array $replaces = array(), array $provides = array()) + private function addLibrary($name, $prettyVersion, $description = null, array $replaces = array(), array $provides = array()): void { try { $version = $this->versionParser->normalize($prettyVersion); @@ -704,7 +704,7 @@ class PlatformRepository extends ArrayRepository * @param string $name * @return bool */ - public static function isPlatformPackage($name) + public static function isPlatformPackage($name): bool { static $cache = array(); @@ -725,12 +725,12 @@ class PlatformRepository extends ArrayRepository * @internal * @return string|null */ - public static function getPlatformPhpVersion() + public static function getPlatformPhpVersion(): ?string { return self::$lastSeenPlatformPhp; } - public function search($query, $mode = 0, $type = null) + public function search($query, $mode = 0, $type = null): array { // suppress vendor search as there are no vendors to match in platform packages if ($mode === self::SEARCH_VENDOR) { diff --git a/src/Composer/Repository/RepositoryFactory.php b/src/Composer/Repository/RepositoryFactory.php index 5891d0f7a..9dbfcb1bb 100644 --- a/src/Composer/Repository/RepositoryFactory.php +++ b/src/Composer/Repository/RepositoryFactory.php @@ -64,7 +64,7 @@ class RepositoryFactory * @param bool $allowFilesystem * @return RepositoryInterface */ - public static function fromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false, RepositoryManager $rm = null) + public static function fromString(IOInterface $io, Config $config, $repository, $allowFilesystem = false, RepositoryManager $rm = null): RepositoryInterface { $repoConfig = static::configFromString($io, $config, $repository, $allowFilesystem); @@ -77,7 +77,7 @@ class RepositoryFactory * @param array $repoConfig * @return RepositoryInterface */ - public static function createRepo(IOInterface $io, Config $config, array $repoConfig, RepositoryManager $rm = null) + public static function createRepo(IOInterface $io, Config $config, array $repoConfig, RepositoryManager $rm = null): RepositoryInterface { if (!$rm) { $rm = static::manager($io, $config, Factory::createHttpDownloader($io, $config)); @@ -93,7 +93,7 @@ class RepositoryFactory * @param RepositoryManager|null $rm * @return RepositoryInterface[] */ - public static function defaultRepos(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null) + public static function defaultRepos(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null): array { if (!$config) { $config = Factory::createConfig($io); @@ -118,7 +118,7 @@ class RepositoryFactory * @param HttpDownloader $httpDownloader * @return RepositoryManager */ - public static function manager(IOInterface $io, Config $config, HttpDownloader $httpDownloader, EventDispatcher $eventDispatcher = null, ProcessExecutor $process = null) + public static function manager(IOInterface $io, Config $config, HttpDownloader $httpDownloader, EventDispatcher $eventDispatcher = null, ProcessExecutor $process = null): RepositoryManager { $rm = new RepositoryManager($io, $config, $httpDownloader, $eventDispatcher, $process); $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository'); @@ -145,7 +145,7 @@ class RepositoryFactory * * @return RepositoryInterface[] */ - private static function createRepos(RepositoryManager $rm, array $repoConfigs) + private static function createRepos(RepositoryManager $rm, array $repoConfigs): array { $repos = array(); @@ -178,9 +178,9 @@ class RepositoryFactory * * @return string */ - public static function generateRepositoryName($index, array $repo, array $existingRepos) + public static function generateRepositoryName($index, array $repo, array $existingRepos): string { - $name = is_int($index) && isset($repo['url']) ? Preg::replace('{^https?://}i', '', $repo['url']) : $index; + $name = is_int($index) && isset($repo['url']) ? Preg::replace('{^https?://}i', '', $repo['url']) : (string) $index; while (isset($existingRepos[$name])) { $name .= '2'; } diff --git a/src/Composer/Repository/RepositorySet.php b/src/Composer/Repository/RepositorySet.php index eb640df2b..b01ce59f9 100644 --- a/src/Composer/Repository/RepositorySet.php +++ b/src/Composer/Repository/RepositorySet.php @@ -118,7 +118,7 @@ class RepositorySet * * @return void */ - public function allowInstalledRepositories($allow = true) + public function allowInstalledRepositories($allow = true): void { $this->allowInstalledRepositories = $allow; } @@ -127,7 +127,7 @@ class RepositorySet * @return ConstraintInterface[] an array of package name => constraint from the root package, platform requirements excluded * @phpstan-return array */ - public function getRootRequires() + public function getRootRequires(): array { return $this->rootRequires; } @@ -142,7 +142,7 @@ class RepositorySet * * @return void */ - public function addRepository(RepositoryInterface $repo) + public function addRepository(RepositoryInterface $repo): void { if ($this->locked) { throw new \RuntimeException("Pool has already been created from this repository set, it cannot be modified anymore."); @@ -169,7 +169,7 @@ class RepositorySet * @param int $flags any of the ALLOW_* constants from this class to tweak what is returned * @return BasePackage[] */ - public function findPackages($name, ConstraintInterface $constraint = null, $flags = 0) + public function findPackages($name, ConstraintInterface $constraint = null, $flags = 0): array { $ignoreStability = ($flags & self::ALLOW_UNACCEPTABLE_STABILITIES) !== 0; $loadFromAllRepos = ($flags & self::ALLOW_SHADOWED_REPOSITORIES) !== 0; @@ -216,7 +216,7 @@ class RepositorySet * @return array[] an array with the provider name as key and value of array('name' => '...', 'description' => '...', 'type' => '...') * @phpstan-return array */ - public function getProviders($packageName) + public function getProviders($packageName): array { $providers = array(); foreach ($this->repositories as $repository) { @@ -235,7 +235,7 @@ class RepositorySet * @param string $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev' * @return bool */ - public function isPackageAcceptable($names, $stability) + public function isPackageAcceptable($names, $stability): bool { return StabilityFilter::isPackageAcceptable($this->acceptableStabilities, $this->stabilityFlags, $names, $stability); } @@ -245,7 +245,7 @@ class RepositorySet * * @return Pool */ - public function createPool(Request $request, IOInterface $io, EventDispatcher $eventDispatcher = null, PoolOptimizer $poolOptimizer = null) + public function createPool(Request $request, IOInterface $io, EventDispatcher $eventDispatcher = null, PoolOptimizer $poolOptimizer = null): Pool { $poolBuilder = new PoolBuilder($this->acceptableStabilities, $this->stabilityFlags, $this->rootAliases, $this->rootReferences, $io, $eventDispatcher, $poolOptimizer); @@ -265,7 +265,7 @@ class RepositorySet * * @return Pool */ - public function createPoolWithAllPackages() + public function createPoolWithAllPackages(): Pool { foreach ($this->repositories as $repo) { if (($repo instanceof InstalledRepositoryInterface || $repo instanceof InstalledRepository) && !$this->allowInstalledRepositories) { @@ -304,7 +304,7 @@ class RepositorySet * * @return Pool */ - public function createPoolForPackage($packageName, LockArrayRepository $lockedRepo = null) + public function createPoolForPackage($packageName, LockArrayRepository $lockedRepo = null): Pool { // TODO unify this with above in some simpler version without "request"? return $this->createPoolForPackages(array($packageName), $lockedRepo); @@ -315,7 +315,7 @@ class RepositorySet * * @return Pool */ - public function createPoolForPackages($packageNames, LockArrayRepository $lockedRepo = null) + public function createPoolForPackages($packageNames, LockArrayRepository $lockedRepo = null): Pool { $request = new Request($lockedRepo); @@ -336,7 +336,7 @@ class RepositorySet * * @return array> */ - private static function getRootAliasesPerPackage(array $aliases) + private static function getRootAliasesPerPackage(array $aliases): array { $normalizedAliases = array(); diff --git a/src/Composer/Repository/RootPackageRepository.php b/src/Composer/Repository/RootPackageRepository.php index 9652282f7..e1aa37443 100644 --- a/src/Composer/Repository/RootPackageRepository.php +++ b/src/Composer/Repository/RootPackageRepository.php @@ -28,7 +28,7 @@ class RootPackageRepository extends ArrayRepository parent::__construct(array($package)); } - public function getRepoName() + public function getRepoName(): string { return 'root package repo'; } diff --git a/src/Composer/Repository/Vcs/FossilDriver.php b/src/Composer/Repository/Vcs/FossilDriver.php index 66a50bdff..8304c61c8 100644 --- a/src/Composer/Repository/Vcs/FossilDriver.php +++ b/src/Composer/Repository/Vcs/FossilDriver.php @@ -38,7 +38,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function initialize() + public function initialize(): void { // Make sure fossil is installed and reachable. $this->checkFossil(); @@ -71,7 +71,7 @@ class FossilDriver extends VcsDriver * * @return void */ - protected function checkFossil() + protected function checkFossil(): void { if (0 !== $this->process->execute('fossil version', $ignoredOutput)) { throw new \RuntimeException("fossil was not found, check that it is installed and in your PATH env.\n\n" . $this->process->getErrorOutput()); @@ -83,7 +83,7 @@ class FossilDriver extends VcsDriver * * @return void */ - protected function updateLocalRepo() + protected function updateLocalRepo(): void { $fs = new Filesystem(); $fs->ensureDirectoryExists($this->checkoutDir); @@ -121,7 +121,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'trunk'; @@ -133,7 +133,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -141,7 +141,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource($identifier): array { return array('type' => 'fossil', 'url' => $this->getUrl(), 'reference' => $identifier); } @@ -149,7 +149,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist($identifier): ?array { return null; } @@ -157,7 +157,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent($file, $identifier): ?string { $command = sprintf('fossil cat -r %s -- %s', ProcessExecutor::escape($identifier), ProcessExecutor::escape($file)); $this->process->execute($command, $content, $this->checkoutDir); @@ -172,7 +172,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate($identifier): ?\DateTime { $this->process->execute('fossil finfo -b -n 1 composer.json', $output, $this->checkoutDir); list(, $date) = explode(' ', trim($output), 3); @@ -183,7 +183,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if (null === $this->tags) { $tags = array(); @@ -202,7 +202,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if (null === $this->branches) { $branches = array(); @@ -222,7 +222,7 @@ class FossilDriver extends VcsDriver /** * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, $url, $deep = false): bool { if (Preg::isMatch('#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i', $url)) { return true; diff --git a/src/Composer/Repository/Vcs/GitDriver.php b/src/Composer/Repository/Vcs/GitDriver.php index b91508acd..cd69d5743 100644 --- a/src/Composer/Repository/Vcs/GitDriver.php +++ b/src/Composer/Repository/Vcs/GitDriver.php @@ -234,7 +234,7 @@ class GitDriver extends VcsDriver GitUtil::cleanEnv(); try { - $gitUtil->runCommand(function ($url) { + $gitUtil->runCommand(function ($url): string { return 'git ls-remote --heads -- ' . ProcessExecutor::escape($url); }, $url, sys_get_temp_dir()); } catch (\RuntimeException $e) { diff --git a/src/Composer/Repository/Vcs/GitLabDriver.php b/src/Composer/Repository/Vcs/GitLabDriver.php index 2e7d36cc2..85ac75049 100644 --- a/src/Composer/Repository/Vcs/GitLabDriver.php +++ b/src/Composer/Repository/Vcs/GitLabDriver.php @@ -91,7 +91,7 @@ class GitLabDriver extends VcsDriver * * @inheritDoc */ - public function initialize() + public function initialize(): void { if (!Preg::isMatch(self::URL_REGEX, $this->url, $match)) { throw new \InvalidArgumentException(sprintf('The GitLab repository URL %s is invalid. It must be the HTTP URL of a GitLab project.', $this->url)); @@ -136,7 +136,7 @@ class GitLabDriver extends VcsDriver * * @return void */ - public function setHttpDownloader(HttpDownloader $httpDownloader) + public function setHttpDownloader(HttpDownloader $httpDownloader): void { $this->httpDownloader = $httpDownloader; } @@ -144,7 +144,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getComposerInformation($identifier) + public function getComposerInformation($identifier): array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); @@ -184,7 +184,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getFileContent($file, $identifier) + public function getFileContent($file, $identifier): ?string { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); @@ -216,7 +216,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getChangeDate($identifier) + public function getChangeDate($identifier): ?\DateTime { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); @@ -232,7 +232,7 @@ class GitLabDriver extends VcsDriver /** * @return string */ - public function getRepositoryUrl() + public function getRepositoryUrl(): string { if ($this->protocol) { return $this->project["{$this->protocol}_url_to_repo"]; @@ -244,7 +244,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getUrl() + public function getUrl(): string { if ($this->gitDriver) { return $this->gitDriver->getUrl(); @@ -256,7 +256,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getDist($identifier) + public function getDist($identifier): ?array { $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier; @@ -266,7 +266,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getSource($identifier) + public function getSource($identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); @@ -278,7 +278,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getRootIdentifier() + public function getRootIdentifier(): string { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); @@ -290,7 +290,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getBranches() + public function getBranches(): array { if ($this->gitDriver) { return $this->gitDriver->getBranches(); @@ -306,7 +306,7 @@ class GitLabDriver extends VcsDriver /** * @inheritDoc */ - public function getTags() + public function getTags(): array { if ($this->gitDriver) { return $this->gitDriver->getTags(); @@ -322,7 +322,7 @@ class GitLabDriver extends VcsDriver /** * @return string Base URL for GitLab API v3 */ - public function getApiUrl() + public function getApiUrl(): string { return $this->scheme.'://'.$this->originUrl.'/api/v4/projects/'.$this->urlEncodeAll($this->namespace).'%2F'.$this->urlEncodeAll($this->repository); } @@ -333,7 +333,7 @@ class GitLabDriver extends VcsDriver * @param string $string * @return string */ - private function urlEncodeAll($string) + private function urlEncodeAll($string): string { $encoded = ''; for ($i = 0; isset($string[$i]); $i++) { @@ -352,7 +352,7 @@ class GitLabDriver extends VcsDriver * * @return string[] where keys are named references like tags or branches and the value a sha */ - protected function getReferences($type) + protected function getReferences($type): array { $perPage = 100; $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage; @@ -383,7 +383,7 @@ class GitLabDriver extends VcsDriver /** * @return void */ - protected function fetchProject() + protected function fetchProject(): void { // we need to fetch the default branch from the api $resource = $this->getApiUrl(); @@ -402,7 +402,7 @@ class GitLabDriver extends VcsDriver * @return true * @throws \RuntimeException */ - protected function attemptCloneFallback() + protected function attemptCloneFallback(): bool { if ($this->isPrivate === false) { $url = $this->generatePublicUrl(); @@ -430,7 +430,7 @@ class GitLabDriver extends VcsDriver * * @return string */ - protected function generateSshUrl() + protected function generateSshUrl(): string { if ($this->hasNonstandardOrigin) { return 'ssh://git@'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository.'.git'; @@ -442,7 +442,7 @@ class GitLabDriver extends VcsDriver /** * @return string */ - protected function generatePublicUrl() + protected function generatePublicUrl(): string { return $this->scheme . '://' . $this->originUrl . '/'.$this->namespace.'/'.$this->repository.'.git'; } @@ -452,7 +452,7 @@ class GitLabDriver extends VcsDriver * * @return void */ - protected function setupGitDriver($url) + protected function setupGitDriver($url): void { $this->gitDriver = new GitDriver( array('url' => $url), @@ -469,7 +469,7 @@ class GitLabDriver extends VcsDriver * * @param bool $fetchingRepoData */ - protected function getContents($url, $fetchingRepoData = false) + protected function getContents($url, $fetchingRepoData = false): Response { try { $response = parent::getContents($url); @@ -568,7 +568,7 @@ class GitLabDriver extends VcsDriver * * @inheritDoc */ - public static function supports(IOInterface $io, Config $config, $url, $deep = false) + public static function supports(IOInterface $io, Config $config, $url, $deep = false): bool { if (!Preg::isMatch(self::URL_REGEX, $url, $match)) { return false; @@ -594,7 +594,7 @@ class GitLabDriver extends VcsDriver /** * @return string|null */ - protected function getNextPage(Response $response) + protected function getNextPage(Response $response): ?string { $header = $response->getHeader('link'); diff --git a/src/Composer/Repository/Vcs/HgDriver.php b/src/Composer/Repository/Vcs/HgDriver.php index 73bc426e5..e9b83d6c5 100644 --- a/src/Composer/Repository/Vcs/HgDriver.php +++ b/src/Composer/Repository/Vcs/HgDriver.php @@ -71,7 +71,7 @@ class HgDriver extends VcsDriver $fs->removeDirectory($this->repoDir); $repoDir = $this->repoDir; - $command = function ($url) use ($repoDir) { + $command = function ($url) use ($repoDir): string { return sprintf('hg clone --noupdate -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir)); }; diff --git a/src/Composer/Repository/Vcs/PerforceDriver.php b/src/Composer/Repository/Vcs/PerforceDriver.php index 75a61037c..b178257f2 100644 --- a/src/Composer/Repository/Vcs/PerforceDriver.php +++ b/src/Composer/Repository/Vcs/PerforceDriver.php @@ -55,7 +55,7 @@ class PerforceDriver extends VcsDriver * * @return void */ - private function initPerforce($repoConfig) + private function initPerforce($repoConfig): void { if (!empty($this->perforce)) { return; diff --git a/src/Composer/Repository/VcsRepository.php b/src/Composer/Repository/VcsRepository.php index b5b85cd14..11d8df0e9 100644 --- a/src/Composer/Repository/VcsRepository.php +++ b/src/Composer/Repository/VcsRepository.php @@ -542,7 +542,7 @@ class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInt /** * @return bool */ - private function shouldRethrowTransportException(TransportException $e) + private function shouldRethrowTransportException(TransportException $e): bool { return in_array($e->getCode(), array(401, 403, 429), true) || $e->getCode() >= 500; } diff --git a/src/Composer/Repository/WritableArrayRepository.php b/src/Composer/Repository/WritableArrayRepository.php index 722cc68f1..eb6b595db 100644 --- a/src/Composer/Repository/WritableArrayRepository.php +++ b/src/Composer/Repository/WritableArrayRepository.php @@ -12,6 +12,7 @@ namespace Composer\Repository; +use Composer\Package\PackageInterface; use Composer\Package\AliasPackage; use Composer\Installer\InstallationManager; diff --git a/src/Composer/Script/Event.php b/src/Composer/Script/Event.php index 83aef267a..3ddf2eae0 100644 --- a/src/Composer/Script/Event.php +++ b/src/Composer/Script/Event.php @@ -121,7 +121,7 @@ class Event extends BaseEvent * @param BaseEvent $event * @return BaseEvent */ - private function calculateOriginatingEvent(BaseEvent $event) + private function calculateOriginatingEvent(BaseEvent $event): BaseEvent { if ($event instanceof Event && $event->getOriginatingEvent()) { return $this->calculateOriginatingEvent($event->getOriginatingEvent()); diff --git a/src/Composer/SelfUpdate/Keys.php b/src/Composer/SelfUpdate/Keys.php index 64666f251..8c33a436f 100644 --- a/src/Composer/SelfUpdate/Keys.php +++ b/src/Composer/SelfUpdate/Keys.php @@ -24,7 +24,7 @@ class Keys * * @return string */ - public static function fingerprint($path) + public static function fingerprint($path): string { $hash = strtoupper(hash('sha256', Preg::replace('{\s}', '', file_get_contents($path)))); diff --git a/src/Composer/SelfUpdate/Versions.php b/src/Composer/SelfUpdate/Versions.php index 9e617fb13..ce959479d 100644 --- a/src/Composer/SelfUpdate/Versions.php +++ b/src/Composer/SelfUpdate/Versions.php @@ -41,7 +41,7 @@ class Versions /** * @return string */ - public function getChannel() + public function getChannel(): string { if ($this->channel) { return $this->channel; @@ -63,7 +63,7 @@ class Versions * * @return void */ - public function setChannel($channel) + public function setChannel($channel): void { if (!in_array($channel, self::$channels, true)) { throw new \InvalidArgumentException('Invalid channel '.$channel.', must be one of: ' . implode(', ', self::$channels)); @@ -79,7 +79,7 @@ class Versions * * @return array{path: string, version: string, min-php: int} */ - public function getLatest($channel = null) + public function getLatest($channel = null): array { $versions = $this->getVersionsData(); @@ -95,7 +95,7 @@ class Versions /** * @return array> */ - private function getVersionsData() + private function getVersionsData(): array { if (!$this->versionsData) { if ($this->config->get('disable-tls') === true) { diff --git a/src/Composer/Util/AuthHelper.php b/src/Composer/Util/AuthHelper.php index 28c4aba68..26eab08b2 100644 --- a/src/Composer/Util/AuthHelper.php +++ b/src/Composer/Util/AuthHelper.php @@ -41,7 +41,7 @@ class AuthHelper * * @return void */ - public function storeAuth($origin, $storeAuth) + public function storeAuth($origin, $storeAuth): void { $store = false; $configSource = $this->config->getAuthConfigSource(); @@ -50,7 +50,7 @@ class AuthHelper } elseif ($storeAuth === 'prompt') { $answer = $this->io->askAndValidate( 'Do you want to store credentials for '.$origin.' in '.$configSource->getName().' ? [Yn] ', - function ($value) { + function ($value): string { $input = strtolower(substr(trim($value), 0, 1)); if (in_array($input, array('y','n'))) { return $input; @@ -83,7 +83,7 @@ class AuthHelper * retried, if storeAuth is true then on a successful retry the authentication should be persisted to auth.json * @phpstan-return ?array{retry: bool, storeAuth: string|bool} */ - public function promptAuthIfNeeded($url, $origin, $statusCode, $reason = null, $headers = array()) + public function promptAuthIfNeeded($url, $origin, $statusCode, $reason = null, $headers = array()): ?array { $storeAuth = false; @@ -215,7 +215,7 @@ class AuthHelper * * @return string[] updated headers array */ - public function addAuthenticationHeader(array $headers, $origin, $url) + public function addAuthenticationHeader(array $headers, $origin, $url): array { if ($this->io->hasAuthentication($origin)) { $authenticationDisplayMessage = null; @@ -272,7 +272,7 @@ class AuthHelper * * @return bool Whether the given URL is a public BitBucket download which requires no authentication. */ - public function isPublicBitBucketDownload($urlToBitBucketFile) + public function isPublicBitBucketDownload($urlToBitBucketFile): bool { $domain = parse_url($urlToBitBucketFile, PHP_URL_HOST); if (strpos($domain, 'bitbucket.org') === false) { diff --git a/src/Composer/Util/Bitbucket.php b/src/Composer/Util/Bitbucket.php index 62a46c1c5..5eb6b8fe6 100644 --- a/src/Composer/Util/Bitbucket.php +++ b/src/Composer/Util/Bitbucket.php @@ -58,7 +58,7 @@ class Bitbucket /** * @return string */ - public function getToken() + public function getToken(): string { if (!isset($this->token['access_token'])) { return ''; @@ -73,7 +73,7 @@ class Bitbucket * @param string $originUrl The host this Bitbucket instance is located at * @return bool true on success */ - public function authorizeOAuth($originUrl) + public function authorizeOAuth($originUrl): bool { if ($originUrl !== 'bitbucket.org') { return false; @@ -92,7 +92,7 @@ class Bitbucket /** * @return bool */ - private function requestAccessToken() + private function requestAccessToken(): bool { try { $response = $this->httpDownloader->get(self::OAUTH2_ACCESS_TOKEN_URL, array( @@ -140,7 +140,7 @@ class Bitbucket * @throws TransportException|\Exception * @return bool true on success */ - public function authorizeOAuthInteractively($originUrl, $message = null) + public function authorizeOAuthInteractively($originUrl, $message = null): bool { if ($message) { $this->io->writeError($message); @@ -194,7 +194,7 @@ class Bitbucket * @param string $consumerSecret * @return string */ - public function requestToken($originUrl, $consumerKey, $consumerSecret) + public function requestToken($originUrl, $consumerKey, $consumerSecret): string { if ($this->token !== null || $this->getTokenFromConfig($originUrl)) { return $this->token['access_token']; @@ -223,7 +223,7 @@ class Bitbucket * * @return void */ - private function storeInAuthConfig($originUrl, $consumerKey, $consumerSecret) + private function storeInAuthConfig($originUrl, $consumerKey, $consumerSecret): void { $this->config->getConfigSource()->removeConfigSetting('bitbucket-oauth.'.$originUrl); @@ -246,7 +246,7 @@ class Bitbucket * @param string $originUrl * @return bool */ - private function getTokenFromConfig($originUrl) + private function getTokenFromConfig($originUrl): bool { $authConfig = $this->config->get('bitbucket-oauth'); diff --git a/src/Composer/Util/ComposerMirror.php b/src/Composer/Util/ComposerMirror.php index f06668518..948bccee3 100644 --- a/src/Composer/Util/ComposerMirror.php +++ b/src/Composer/Util/ComposerMirror.php @@ -31,7 +31,7 @@ class ComposerMirror * * @return string */ - public static function processUrl($mirrorUrl, $packageName, $version, $reference, $type, $prettyVersion = null) + public static function processUrl($mirrorUrl, $packageName, $version, $reference, $type, $prettyVersion = null): string { if ($reference) { $reference = Preg::isMatch('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : md5($reference); @@ -56,7 +56,7 @@ class ComposerMirror * * @return string */ - public static function processGitUrl($mirrorUrl, $packageName, $url, $type) + public static function processGitUrl($mirrorUrl, $packageName, $url, $type): string { if (Preg::isMatch('#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#', $url, $match)) { $url = 'gh-'.$match[1].'/'.$match[2]; @@ -81,7 +81,7 @@ class ComposerMirror * * @return string */ - public static function processHgUrl($mirrorUrl, $packageName, $url, $type) + public static function processHgUrl($mirrorUrl, $packageName, $url, $type): string { return self::processGitUrl($mirrorUrl, $packageName, $url, $type); } diff --git a/src/Composer/Util/ConfigValidator.php b/src/Composer/Util/ConfigValidator.php index c7447a2a8..b0dd79fad 100644 --- a/src/Composer/Util/ConfigValidator.php +++ b/src/Composer/Util/ConfigValidator.php @@ -48,7 +48,7 @@ class ConfigValidator * * @return array{list, list, list} a triple containing the errors, publishable errors, and warnings */ - public function validate($file, $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL, $flags = self::CHECK_VERSION) + public function validate($file, $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL, $flags = self::CHECK_VERSION): array { $errors = array(); $publishErrors = array(); diff --git a/src/Composer/Util/ErrorHandler.php b/src/Composer/Util/ErrorHandler.php index 5e2bc1790..257f7ce29 100644 --- a/src/Composer/Util/ErrorHandler.php +++ b/src/Composer/Util/ErrorHandler.php @@ -36,7 +36,7 @@ class ErrorHandler * @throws \ErrorException * @return bool */ - public static function handle($level, $message, $file, $line) + public static function handle($level, $message, $file, $line): bool { // error code is not included in error_reporting if (!(error_reporting() & $level)) { @@ -56,7 +56,7 @@ class ErrorHandler self::$io->writeError('Deprecation Notice: '.$message.' in '.$file.':'.$line.''); if (self::$io->isVerbose()) { self::$io->writeError('Stack trace:'); - self::$io->writeError(array_filter(array_map(function ($a) { + self::$io->writeError(array_filter(array_map(function ($a): ?string { if (isset($a['line'], $a['file'])) { return ' '.$a['file'].':'.$a['line'].''; } @@ -76,7 +76,7 @@ class ErrorHandler * * @return void */ - public static function register(IOInterface $io = null) + public static function register(IOInterface $io = null): void { set_error_handler(array(__CLASS__, 'handle')); error_reporting(E_ALL | E_STRICT); diff --git a/src/Composer/Util/Filesystem.php b/src/Composer/Util/Filesystem.php index 3bd1c86fa..99aa803c9 100644 --- a/src/Composer/Util/Filesystem.php +++ b/src/Composer/Util/Filesystem.php @@ -177,7 +177,7 @@ class Filesystem * * @return bool|null Returns null, when no edge case was hit. Otherwise a bool whether removal was successful */ - private function removeEdgeCases($directory, $fallbackToPhp = true) + private function removeEdgeCases($directory, $fallbackToPhp = true): ?bool { if ($this->isSymlinkedDirectory($directory)) { return $this->unlinkSymlinkedDirectory($directory); @@ -711,7 +711,7 @@ class Filesystem * * @return bool */ - private function unlinkImplementation($path) + private function unlinkImplementation($path): bool { if (Platform::isWindows() && is_dir($path) && is_link($path)) { return rmdir($path); @@ -767,7 +767,7 @@ class Filesystem * * @return bool */ - private function unlinkSymlinkedDirectory($directory) + private function unlinkSymlinkedDirectory($directory): bool { $resolved = $this->resolveSymlinkedDirectorySymlink($directory); @@ -781,7 +781,7 @@ class Filesystem * * @return string resolved path to symbolic link or original pathname (unresolved) */ - private function resolveSymlinkedDirectorySymlink($pathname) + private function resolveSymlinkedDirectorySymlink($pathname): string { if (!is_dir($pathname)) { return $pathname; @@ -926,7 +926,7 @@ class Filesystem * * @return bool */ - private function filesAreEqual($a, $b) + private function filesAreEqual($a, $b): bool { // Check if filesize is different if (filesize($a) !== filesize($b)) { diff --git a/src/Composer/Util/Git.php b/src/Composer/Util/Git.php index f2ea4dc24..27dc75a0d 100644 --- a/src/Composer/Util/Git.php +++ b/src/Composer/Util/Git.php @@ -283,7 +283,7 @@ class Git // update the repo if it is a valid git repository if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { try { - $commandCallable = function ($url) { + $commandCallable = function ($url): string { $sanitizedUrl = Preg::replace('{://([^@]+?):(.+?)@}', '://', $url); return sprintf('git remote set-url origin -- %s && git remote update --prune origin && git remote set-url origin -- %s && git gc --auto', ProcessExecutor::escape($url), ProcessExecutor::escape($sanitizedUrl)); @@ -301,7 +301,7 @@ class Git // clean up directory and do a fresh clone into it $this->filesystem->removeDirectory($dir); - $commandCallable = function ($url) use ($dir) { + $commandCallable = function ($url) use ($dir): string { return sprintf('git clone --mirror -- %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($dir)); }; @@ -349,7 +349,7 @@ class Git * * @return bool */ - private function checkRefIsInMirror($dir, $ref) + private function checkRefIsInMirror($dir, $ref): bool { if (is_dir($dir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $dir) && trim($output) === '.') { $escapedRef = ProcessExecutor::escape($ref.'^{commit}'); @@ -368,7 +368,7 @@ class Git * * @return bool */ - private function isAuthenticationFailure($url, &$match) + private function isAuthenticationFailure($url, &$match): bool { if (!Preg::isMatch('{^(https?://)([^/]+)(.*)$}i', $url, $match)) { return false; @@ -441,7 +441,7 @@ class Git * * @return never */ - private function throwException($message, $url) + private function throwException($message, $url): void { // git might delete a directory when it fails and php will not know clearstatcache(); @@ -476,7 +476,7 @@ class Git * * @return string */ - private function maskCredentials($error, array $credentials) + private function maskCredentials($error, array $credentials): string { $maskedCredentials = array(); diff --git a/src/Composer/Util/GitHub.php b/src/Composer/Util/GitHub.php index 2dd53e350..f20cb2376 100644 --- a/src/Composer/Util/GitHub.php +++ b/src/Composer/Util/GitHub.php @@ -54,7 +54,7 @@ class GitHub * @param string $originUrl The host this GitHub instance is located at * @return bool true on success */ - public function authorizeOAuth($originUrl) + public function authorizeOAuth($originUrl): bool { if (!in_array($originUrl, $this->config->get('github-domains'))) { return false; @@ -79,7 +79,7 @@ class GitHub * @throws TransportException|\Exception * @return bool true on success */ - public function authorizeOAuthInteractively($originUrl, $message = null) + public function authorizeOAuthInteractively($originUrl, $message = null): bool { if ($message) { $this->io->writeError($message); @@ -145,7 +145,7 @@ class GitHub * * @return array{limit: int|'?', reset: string} */ - public function getRateLimit(array $headers) + public function getRateLimit(array $headers): array { $rateLimit = array( 'limit' => '?', @@ -178,7 +178,7 @@ class GitHub * * @return string|null */ - public function getSsoUrl(array $headers) + public function getSsoUrl(array $headers): ?string { foreach ($headers as $header) { $header = trim($header); @@ -200,7 +200,7 @@ class GitHub * * @return bool */ - public function isRateLimited(array $headers) + public function isRateLimited(array $headers): bool { foreach ($headers as $header) { if (Preg::isMatch('{^X-RateLimit-Remaining: *0$}i', trim($header))) { @@ -220,7 +220,7 @@ class GitHub * * @return bool */ - public function requiresSso(array $headers) + public function requiresSso(array $headers): bool { foreach ($headers as $header) { if (Preg::isMatch('{^X-GitHub-SSO: required}i', trim($header))) { diff --git a/src/Composer/Util/GitLab.php b/src/Composer/Util/GitLab.php index 4c1376ad4..4bd61d792 100644 --- a/src/Composer/Util/GitLab.php +++ b/src/Composer/Util/GitLab.php @@ -55,7 +55,7 @@ class GitLab * * @return bool true on success */ - public function authorizeOAuth($originUrl) + public function authorizeOAuth($originUrl): bool { // before composer 1.9, origin URLs had no port number in them $bcOriginUrl = Preg::replace('{:\d+}', '', $originUrl); @@ -112,7 +112,7 @@ class GitLab * * @return bool true on success */ - public function authorizeOAuthInteractively($scheme, $originUrl, $message = null) + public function authorizeOAuthInteractively($scheme, $originUrl, $message = null): bool { if ($message) { $this->io->writeError($message); @@ -169,7 +169,7 @@ class GitLab * * @see https://docs.gitlab.com/ee/api/oauth2.html#resource-owner-password-credentials-flow */ - private function createToken($scheme, $originUrl) + private function createToken($scheme, $originUrl): array { $username = $this->io->ask('Username: '); $password = $this->io->askAndHideAnswer('Password: '); diff --git a/src/Composer/Util/Hg.php b/src/Composer/Util/Hg.php index 73e3a8e52..da8c3329a 100644 --- a/src/Composer/Util/Hg.php +++ b/src/Composer/Util/Hg.php @@ -53,7 +53,7 @@ class Hg * * @return void */ - public function runCommand($commandCallable, $url, $cwd) + public function runCommand($commandCallable, $url, $cwd): void { $this->config->prohibitUrlByConfig($url, $this->io); @@ -89,7 +89,7 @@ class Hg * * @return never */ - private function throwException($message, $url) + private function throwException($message, $url): void { if (null === self::getVersion($this->process)) { throw new \RuntimeException(Url::sanitize('Failed to clone ' . $url . ', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput())); @@ -103,7 +103,7 @@ class Hg * * @return string|null The hg version number, if present. */ - public static function getVersion(ProcessExecutor $process) + public static function getVersion(ProcessExecutor $process): ?string { if (false === self::$version) { self::$version = null; diff --git a/src/Composer/Util/Http/CurlDownloader.php b/src/Composer/Util/Http/CurlDownloader.php index a53fd7fb7..eeff04e1f 100644 --- a/src/Composer/Util/Http/CurlDownloader.php +++ b/src/Composer/Util/Http/CurlDownloader.php @@ -133,7 +133,7 @@ class CurlDownloader * * @return int internal job id */ - public function download($resolve, $reject, $origin, $url, $options, $copyTo = null) + public function download($resolve, $reject, $origin, $url, $options, $copyTo = null): int { $attributes = array(); if (isset($options['retry-auth-failure'])) { @@ -156,7 +156,7 @@ class CurlDownloader * * @return int internal job id */ - private function initDownload($resolve, $reject, $origin, $url, $options, $copyTo = null, array $attributes = array()) + private function initDownload($resolve, $reject, $origin, $url, $options, $copyTo = null, array $attributes = array()): int { // set defaults in a PHPStan-happy way (array_merge is not well supported) $attributes['retryAuthFailure'] = $attributes['retryAuthFailure'] ?? true; @@ -180,7 +180,7 @@ class CurlDownloader if ($copyTo) { $errorMessage = ''; // @phpstan-ignore-next-line - set_error_handler(function ($code, $msg) use (&$errorMessage) { + set_error_handler(function ($code, $msg) use (&$errorMessage): void { if ($errorMessage) { $errorMessage .= "\n"; } @@ -287,7 +287,7 @@ class CurlDownloader * @param int $id * @return void */ - public function abortRequest($id) + public function abortRequest($id): void { if (isset($this->jobs[$id], $this->jobs[$id]['curlHandle'])) { $job = $this->jobs[$id]; @@ -309,7 +309,7 @@ class CurlDownloader /** * @return void */ - public function tick() + public function tick(): void { static $timeoutWarning = false; @@ -489,7 +489,7 @@ class CurlDownloader * @param Job $job * @return string */ - private function handleRedirect(array $job, Response $response) + private function handleRedirect(array $job, Response $response): string { if ($locationHeader = $response->getHeader('location')) { if (parse_url($locationHeader, PHP_URL_SCHEME)) { @@ -524,7 +524,7 @@ class CurlDownloader * @param Job $job * @return array{retry: bool, storeAuth: string|bool} */ - private function isAuthenticatedRetryNeeded(array $job, Response $response) + private function isAuthenticatedRetryNeeded(array $job, Response $response): array { if (in_array($response->getStatusCode(), array(401, 403)) && $job['attributes']['retryAuthFailure']) { $result = $this->authHelper->promptAuthIfNeeded($job['url'], $job['origin'], $response->getStatusCode(), $response->getStatusMessage(), $response->getHeaders()); @@ -579,7 +579,7 @@ class CurlDownloader * * @return void */ - private function restartJob(array $job, $url, array $attributes = array()) + private function restartJob(array $job, $url, array $attributes = array()): void { if (null !== $job['filename']) { @unlink($job['filename'].'~'); @@ -596,7 +596,7 @@ class CurlDownloader * @param string $errorMessage * @return TransportException */ - private function failResponse(array $job, Response $response, $errorMessage) + private function failResponse(array $job, Response $response, $errorMessage): TransportException { if (null !== $job['filename']) { @unlink($job['filename'].'~'); @@ -614,7 +614,7 @@ class CurlDownloader * @param Job $job * @return void */ - private function rejectJob(array $job, \Exception $e) + private function rejectJob(array $job, \Exception $e): void { if (is_resource($job['headerHandle'])) { fclose($job['headerHandle']); @@ -632,7 +632,7 @@ class CurlDownloader * @param int $code * @return void */ - private function checkCurlResult($code) + private function checkCurlResult($code): void { if ($code != CURLM_OK && $code != CURLM_CALL_MULTI_PERFORM) { throw new \RuntimeException( diff --git a/src/Composer/Util/Http/CurlResponse.php b/src/Composer/Util/Http/CurlResponse.php index 495a73b85..c51ff5069 100644 --- a/src/Composer/Util/Http/CurlResponse.php +++ b/src/Composer/Util/Http/CurlResponse.php @@ -19,12 +19,13 @@ class CurlResponse extends Response { /** * @see https://www.php.net/curl_getinfo - * @var CurlInfo + * @var array + * @phpstan-var CurlInfo */ private $curlInfo; /** - * @param CurlInfo $curlInfo + * @phpstan-param CurlInfo $curlInfo */ public function __construct(array $request, $code, array $headers, $body, array $curlInfo) { @@ -33,9 +34,9 @@ class CurlResponse extends Response } /** - * @return CurlInfo + * @phpstan-return CurlInfo */ - public function getCurlInfo() + public function getCurlInfo(): array { return $this->curlInfo; } diff --git a/src/Composer/Util/Http/ProxyHelper.php b/src/Composer/Util/Http/ProxyHelper.php index febcfc73d..db19db62d 100644 --- a/src/Composer/Util/Http/ProxyHelper.php +++ b/src/Composer/Util/Http/ProxyHelper.php @@ -27,7 +27,7 @@ class ProxyHelper * * @throws \RuntimeException on malformed url */ - public static function getProxyData() + public static function getProxyData(): array { $httpProxy = null; $httpsProxy = null; @@ -64,7 +64,7 @@ class ProxyHelper * * @return array{http: array{proxy: string, header?: string}} */ - public static function getContextOptions($proxyUrl) + public static function getContextOptions($proxyUrl): array { $proxy = parse_url($proxyUrl); @@ -97,7 +97,7 @@ class ProxyHelper * * @return void */ - public static function setRequestFullUri($requestUrl, array &$options) + public static function setRequestFullUri($requestUrl, array &$options): void { if ('http' === parse_url($requestUrl, PHP_URL_SCHEME)) { $options['http']['request_fulluri'] = true; @@ -114,7 +114,7 @@ class ProxyHelper * * @return string|null The found value */ - private static function getProxyEnv(array $names, &$name) + private static function getProxyEnv(array $names, &$name): ?string { foreach ($names as $name) { if (!empty($_SERVER[$name])) { @@ -133,7 +133,7 @@ class ProxyHelper * @throws \RuntimeException on malformed url * @return string The formatted proxy url */ - private static function checkProxy($proxyUrl, $envName) + private static function checkProxy($proxyUrl, $envName): string { $error = sprintf('malformed %s url', $envName); $proxy = parse_url($proxyUrl); @@ -161,7 +161,7 @@ class ProxyHelper * * @return string The formatted value */ - private static function formatParsedUrl(array $proxy, $includeAuth) + private static function formatParsedUrl(array $proxy, $includeAuth): string { $proxyUrl = isset($proxy['scheme']) ? strtolower($proxy['scheme']) . '://' : ''; diff --git a/src/Composer/Util/Http/ProxyManager.php b/src/Composer/Util/Http/ProxyManager.php index 352ab8d35..5f11c8242 100644 --- a/src/Composer/Util/Http/ProxyManager.php +++ b/src/Composer/Util/Http/ProxyManager.php @@ -58,7 +58,7 @@ class ProxyManager /** * @return ProxyManager */ - public static function getInstance() + public static function getInstance(): ProxyManager { if (!self::$instance) { self::$instance = new self(); @@ -72,7 +72,7 @@ class ProxyManager * * @return void */ - public static function reset() + public static function reset(): void { self::$instance = null; } @@ -83,7 +83,7 @@ class ProxyManager * @param string $requestUrl * @return RequestProxy */ - public function getProxyForRequest($requestUrl) + public function getProxyForRequest($requestUrl): RequestProxy { if ($this->error) { throw new TransportException('Unable to use a proxy: '.$this->error); @@ -113,7 +113,7 @@ class ProxyManager * * @return bool If false any error will be in $message */ - public function isProxying() + public function isProxying(): bool { return $this->hasProxy; } @@ -123,7 +123,7 @@ class ProxyManager * * @return string|null Safe proxy URL or an error message if setting up proxy failed or null if no proxy was configured */ - public function getFormattedProxy() + public function getFormattedProxy(): ?string { return $this->hasProxy ? $this->info : $this->error; } @@ -133,7 +133,7 @@ class ProxyManager * * @return void */ - private function initProxyData() + private function initProxyData(): void { try { list($httpProxy, $httpsProxy, $noProxy) = ProxyHelper::getProxyData(); @@ -167,7 +167,7 @@ class ProxyManager * * @return non-empty-string */ - private function setData($url, $scheme) + private function setData($url, $scheme): string { $safeProxy = Url::sanitize($url); $this->fullProxy[$scheme] = $url; @@ -184,7 +184,7 @@ class ProxyManager * @param string $requestUrl * @return bool */ - private function noProxy($requestUrl) + private function noProxy($requestUrl): bool { return $this->noProxyHandler && $this->noProxyHandler->test($requestUrl); } diff --git a/src/Composer/Util/Http/RequestProxy.php b/src/Composer/Util/Http/RequestProxy.php index 5a832706f..e60c1a19c 100644 --- a/src/Composer/Util/Http/RequestProxy.php +++ b/src/Composer/Util/Http/RequestProxy.php @@ -47,7 +47,7 @@ class RequestProxy * * @return mixed[] */ - public function getContextOptions() + public function getContextOptions(): array { return $this->contextOptions; } @@ -58,7 +58,7 @@ class RequestProxy * @param string|null $format Output format specifier * @return string Safe proxy, no proxy or empty */ - public function getFormattedUrl($format = '') + public function getFormattedUrl($format = ''): string { $result = ''; if ($this->formattedUrl) { @@ -74,7 +74,7 @@ class RequestProxy * * @return string Proxy url or empty */ - public function getUrl() + public function getUrl(): string { return $this->url; } @@ -84,7 +84,7 @@ class RequestProxy * * @return bool False if not secure or there is no proxy */ - public function isSecure() + public function isSecure(): bool { return $this->isSecure; } diff --git a/src/Composer/Util/Http/Response.php b/src/Composer/Util/Http/Response.php index 39c68d6f2..4c9072fac 100644 --- a/src/Composer/Util/Http/Response.php +++ b/src/Composer/Util/Http/Response.php @@ -50,7 +50,7 @@ class Response /** * @return int */ - public function getStatusCode() + public function getStatusCode(): int { return $this->code; } @@ -58,7 +58,7 @@ class Response /** * @return string|null */ - public function getStatusMessage() + public function getStatusMessage(): ?string { $value = null; foreach ($this->headers as $header) { @@ -75,7 +75,7 @@ class Response /** * @return string[] */ - public function getHeaders() + public function getHeaders(): array { return $this->headers; } @@ -84,7 +84,7 @@ class Response * @param string $name * @return ?string */ - public function getHeader($name) + public function getHeader($name): ?string { return self::findHeaderValue($this->headers, $name); } @@ -92,7 +92,7 @@ class Response /** * @return ?string */ - public function getBody() + public function getBody(): ?string { return $this->body; } @@ -109,7 +109,7 @@ class Response * @return void * @phpstan-impure */ - public function collect() + public function collect(): void { /** @phpstan-ignore-next-line */ $this->request = $this->code = $this->headers = $this->body = null; @@ -120,7 +120,7 @@ class Response * @param string $name header name (case insensitive) * @return string|null */ - public static function findHeaderValue(array $headers, $name) + public static function findHeaderValue(array $headers, $name): ?string { $value = null; foreach ($headers as $header) { diff --git a/src/Composer/Util/HttpDownloader.php b/src/Composer/Util/HttpDownloader.php index d1c8c1fbd..b919680f2 100644 --- a/src/Composer/Util/HttpDownloader.php +++ b/src/Composer/Util/HttpDownloader.php @@ -191,7 +191,7 @@ class HttpDownloader * * @return array{Job, PromiseInterface} */ - private function addJob($request, $sync = false) + private function addJob($request, $sync = false): array { $request['options'] = array_replace_recursive($this->options, $request['options']); @@ -216,13 +216,13 @@ class HttpDownloader $rfs = $this->rfs; if ($this->canUseCurl($job)) { - $resolver = function ($resolve, $reject) use (&$job) { + $resolver = function ($resolve, $reject) use (&$job): void { $job['status'] = HttpDownloader::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; } else { - $resolver = function ($resolve, $reject) use (&$job, $rfs) { + $resolver = function ($resolve, $reject) use (&$job, $rfs): void { // start job $url = $job['request']['url']; $options = $job['request']['options']; @@ -248,7 +248,7 @@ class HttpDownloader $curl = $this->curl; - $canceler = function () use (&$job, $curl) { + $canceler = function () use (&$job, $curl): void { if ($job['status'] === HttpDownloader::STATUS_QUEUED) { $job['status'] = HttpDownloader::STATUS_ABORTED; } @@ -270,7 +270,7 @@ class HttpDownloader $this->markJobDone(); return $response; - }, function ($e) use (&$job) { + }, function ($e) use (&$job): void { $job['status'] = HttpDownloader::STATUS_FAILED; $job['exception'] = $e; @@ -291,7 +291,7 @@ class HttpDownloader * @param int $id * @return void */ - private function startJob($id) + private function startJob($id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { @@ -355,7 +355,7 @@ class HttpDownloader * * @return void */ - public function enableAsync() + public function enableAsync(): void { $this->allowAsync = true; } @@ -366,7 +366,7 @@ class HttpDownloader * @param int|null $index For internal use only, the job id * @return int number of active (queued or started) jobs */ - public function countActiveJobs($index = null) + public function countActiveJobs($index = null): int { if ($this->runningJobs < $this->maxJobs) { foreach ($this->jobs as $job) { @@ -400,7 +400,7 @@ class HttpDownloader * @param int $index Job id * @return Response */ - private function getResponse($index) + private function getResponse($index): Response { if (!isset($this->jobs[$index])) { throw new \LogicException('Invalid request id'); @@ -428,7 +428,7 @@ class HttpDownloader * @param array{warning?: string, info?: string, warning-versions?: string, info-versions?: string, warnings?: array, infos?: array} $data * @return void */ - public static function outputWarnings(IOInterface $io, $url, $data) + public static function outputWarnings(IOInterface $io, $url, $data): void { // legacy warning/info keys foreach (array('warning', 'info') as $type) { @@ -473,7 +473,7 @@ class HttpDownloader * * @return ?string[] */ - public static function getExceptionHints(\Exception $e) + public static function getExceptionHints(\Exception $e): ?array { if (!$e instanceof TransportException) { return null; @@ -507,7 +507,7 @@ class HttpDownloader * @param Job $job * @return bool */ - private function canUseCurl(array $job) + private function canUseCurl(array $job): bool { if (!$this->curl) { return false; @@ -528,7 +528,7 @@ class HttpDownloader * @internal * @return bool */ - public static function isCurlEnabled() + public static function isCurlEnabled(): bool { return \extension_loaded('curl') && \function_exists('curl_multi_exec') && \function_exists('curl_multi_init'); } diff --git a/src/Composer/Util/IniHelper.php b/src/Composer/Util/IniHelper.php index 8076f82ed..699f22513 100644 --- a/src/Composer/Util/IniHelper.php +++ b/src/Composer/Util/IniHelper.php @@ -31,7 +31,7 @@ class IniHelper * * @return string[] */ - public static function getAll() + public static function getAll(): array { return XdebugHandler::getAllIniFiles(); } @@ -41,7 +41,7 @@ class IniHelper * * @return string */ - public static function getMessage() + public static function getMessage(): string { $paths = self::getAll(); diff --git a/src/Composer/Util/Loop.php b/src/Composer/Util/Loop.php index b103011a4..48edc1e16 100644 --- a/src/Composer/Util/Loop.php +++ b/src/Composer/Util/Loop.php @@ -44,7 +44,7 @@ class Loop /** * @return HttpDownloader */ - public function getHttpDownloader() + public function getHttpDownloader(): HttpDownloader { return $this->httpDownloader; } @@ -52,7 +52,7 @@ class Loop /** * @return ProcessExecutor|null */ - public function getProcessExecutor() + public function getProcessExecutor(): ?ProcessExecutor { return $this->processExecutor; } @@ -62,15 +62,15 @@ class Loop * @param ?ProgressBar $progress * @return void */ - public function wait(array $promises, ProgressBar $progress = null) + public function wait(array $promises, ProgressBar $progress = null): void { /** @var \Exception|null */ $uncaught = null; \React\Promise\all($promises)->then( - function () { + function (): void { }, - function ($e) use (&$uncaught) { + function ($e) use (&$uncaught): void { $uncaught = $e; } ); @@ -122,7 +122,7 @@ class Loop /** * @return void */ - public function abortJobs() + public function abortJobs(): void { foreach ($this->currentPromises as $promiseGroup) { foreach ($promiseGroup as $promise) { diff --git a/src/Composer/Util/NoProxyPattern.php b/src/Composer/Util/NoProxyPattern.php index e8f14997b..a81a88a5b 100644 --- a/src/Composer/Util/NoProxyPattern.php +++ b/src/Composer/Util/NoProxyPattern.php @@ -51,7 +51,7 @@ class NoProxyPattern * * @return bool */ - public function test($url) + public function test($url): bool { if ($this->noproxy) { return true; @@ -115,7 +115,7 @@ class NoProxyPattern * * @return bool */ - protected function match($index, $hostName, $url) + protected function match($index, $hostName, $url): bool { if (!$rule = $this->getRule($index, $hostName)) { // Data must have been misformatted @@ -154,7 +154,7 @@ class NoProxyPattern * * @return bool */ - protected function matchRange(stdClass $network, stdClass $target) + protected function matchRange(stdClass $network, stdClass $target): bool { $net = unpack('C*', $network->ip); $mask = unpack('C*', $network->netmask); @@ -186,7 +186,7 @@ class NoProxyPattern * * @return null|stdClass Null if the hostname is invalid */ - private function getRule($index, $hostName) + private function getRule($index, $hostName): ?stdClass { if (array_key_exists($index, $this->rules)) { return $this->rules[$index]; @@ -213,7 +213,7 @@ class NoProxyPattern * * @return bool False if the host contains invalid data */ - private function ipCheckData($host, &$ipdata, $allowPrefix = false) + private function ipCheckData($host, &$ipdata, $allowPrefix = false): bool { $ipdata = null; $netmask = null; @@ -262,7 +262,7 @@ class NoProxyPattern * * @return mixed[] in_addr, size */ - private function ipGetAddr($host) + private function ipGetAddr($host): array { $ip = inet_pton($host); $size = strlen($ip); @@ -279,7 +279,7 @@ class NoProxyPattern * * @return string */ - private function ipGetMask($prefix, $size) + private function ipGetMask($prefix, $size): string { $mask = ''; @@ -305,7 +305,7 @@ class NoProxyPattern * * @return string[] network in_addr, binary mask */ - private function ipGetNetwork($rangeIp, $size, $prefix) + private function ipGetNetwork($rangeIp, $size, $prefix): array { $netmask = $this->ipGetMask($prefix, $size); @@ -335,7 +335,7 @@ class NoProxyPattern * * @return string Mapped or existing in_addr */ - private function ipMapTo6($binary, $size) + private function ipMapTo6($binary, $size): string { if ($size === 4) { $prefix = str_repeat(chr(0), 10) . str_repeat(chr(255), 2); @@ -354,7 +354,7 @@ class NoProxyPattern * * @return stdClass */ - private function makeData($host, $port, $ipdata) + private function makeData($host, $port, $ipdata): stdClass { return (object) array( 'host' => $host, @@ -373,7 +373,7 @@ class NoProxyPattern * * @return stdClass */ - private function makeIpData($ip, $size, $netmask) + private function makeIpData($ip, $size, $netmask): stdClass { return (object) array( 'ip' => $ip, @@ -389,7 +389,7 @@ class NoProxyPattern * * @return mixed[] host, port, if there was error */ - private function splitHostPort($hostName) + private function splitHostPort($hostName): array { // host, port, err $error = array('', '', true); @@ -439,7 +439,7 @@ class NoProxyPattern * * @return bool */ - private function validateInt($int, $min, $max) + private function validateInt($int, $min, $max): bool { $options = array( 'options' => array( diff --git a/src/Composer/Util/PackageSorter.php b/src/Composer/Util/PackageSorter.php index df2d89a4b..62889961a 100644 --- a/src/Composer/Util/PackageSorter.php +++ b/src/Composer/Util/PackageSorter.php @@ -24,7 +24,7 @@ class PackageSorter * @param PackageInterface[] $packages * @return PackageInterface[] sorted array */ - public static function sortPackages(array $packages) + public static function sortPackages(array $packages): array { $usageList = array(); @@ -69,17 +69,17 @@ class PackageSorter $weightList[$index] = $weight; } - $stable_sort = function (&$array) { + $stable_sort = function (&$array): void { static $transform, $restore; $i = 0; if (!$transform) { - $transform = function (&$v, $k) use (&$i) { + $transform = function (&$v, $k) use (&$i): void { $v = array($v, ++$i, $k, $v); }; - $restore = function (&$v) { + $restore = function (&$v): void { $v = $v[3]; }; } diff --git a/src/Composer/Util/Platform.php b/src/Composer/Util/Platform.php index 756c11506..d237f8ea1 100644 --- a/src/Composer/Util/Platform.php +++ b/src/Composer/Util/Platform.php @@ -51,7 +51,7 @@ class Platform * @param string $value * @return void */ - public static function putEnv($name, $value) + public static function putEnv($name, $value): void { $value = (string) $value; putenv($name . '=' . $value); @@ -64,7 +64,7 @@ class Platform * @param string $name * @return void */ - public static function clearEnv($name) + public static function clearEnv($name): void { putenv($name); unset($_SERVER[$name], $_ENV[$name]); @@ -76,13 +76,13 @@ class Platform * @param string $path * @return string */ - public static function expandPath($path) + public static function expandPath($path): string { if (Preg::isMatch('#^~[\\/]#', $path)) { return self::getUserDirectory() . substr($path, 1); } - return Preg::replaceCallback('#^(\$|(?P%))(?P\w++)(?(percent)%)(?P.*)#', function ($matches) { + return Preg::replaceCallback('#^(\$|(?P%))(?P\w++)(?(percent)%)(?P.*)#', function ($matches): string { // Treat HOME as an alias for USERPROFILE on Windows for legacy reasons if (Platform::isWindows() && $matches['var'] == 'HOME') { return (Platform::getEnv('HOME') ?: Platform::getEnv('USERPROFILE')) . $matches['path']; @@ -96,7 +96,7 @@ class Platform * @throws \RuntimeException If the user home could not reliably be determined * @return string The formal user home as detected from environment parameters */ - public static function getUserDirectory() + public static function getUserDirectory(): string { if (false !== ($home = self::getEnv('HOME'))) { return $home; @@ -118,7 +118,7 @@ class Platform /** * @return bool Whether the host machine is running on the Windows Subsystem for Linux (WSL) */ - public static function isWindowsSubsystemForLinux() + public static function isWindowsSubsystemForLinux(): bool { if (null === self::$isWindowsSubsystemForLinux) { self::$isWindowsSubsystemForLinux = false; @@ -144,7 +144,7 @@ class Platform /** * @return bool Whether the host machine is running a Windows OS */ - public static function isWindows() + public static function isWindows(): bool { return \defined('PHP_WINDOWS_VERSION_BUILD'); } @@ -153,7 +153,7 @@ class Platform * @param string $str * @return int return a guaranteed binary length of the string, regardless of silly mbstring configs */ - public static function strlen($str) + public static function strlen($str): int { static $useMbString = null; if (null === $useMbString) { @@ -171,7 +171,7 @@ class Platform * @param ?resource $fd Open file descriptor or null to default to STDOUT * @return bool */ - public static function isTty($fd = null) + public static function isTty($fd = null): bool { if ($fd === null) { $fd = defined('STDOUT') ? STDOUT : fopen('php://stdout', 'w'); @@ -202,7 +202,7 @@ class Platform /** * @return void */ - public static function workaroundFilesystemIssues() + public static function workaroundFilesystemIssues(): void { if (self::isVirtualBoxGuest()) { usleep(200000); @@ -216,7 +216,7 @@ class Platform * * @return bool */ - private static function isVirtualBoxGuest() + private static function isVirtualBoxGuest(): bool { if (null === self::$isVirtualBoxGuest) { self::$isVirtualBoxGuest = false; diff --git a/src/Composer/Util/ProcessExecutor.php b/src/Composer/Util/ProcessExecutor.php index cb9cdd225..fb661bac4 100644 --- a/src/Composer/Util/ProcessExecutor.php +++ b/src/Composer/Util/ProcessExecutor.php @@ -100,7 +100,7 @@ class ProcessExecutor * @param mixed $output * @return int */ - private function doExecute($command, $cwd, $tty, &$output = null) + private function doExecute($command, $cwd, $tty, &$output = null): int { $this->outputCommandRun($command, $cwd, false); @@ -153,13 +153,13 @@ class ProcessExecutor 'cwd' => $cwd, ); - $resolver = function ($resolve, $reject) use (&$job) { + $resolver = function ($resolve, $reject) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_QUEUED; $job['resolve'] = $resolve; $job['reject'] = $reject; }; - $canceler = function () use (&$job) { + $canceler = function () use (&$job): void { if ($job['status'] === ProcessExecutor::STATUS_QUEUED) { $job['status'] = ProcessExecutor::STATUS_ABORTED; } @@ -190,7 +190,7 @@ class ProcessExecutor $this->markJobDone(); return $job['process']; - }, function ($e) use (&$job) { + }, function ($e) use (&$job): void { $job['status'] = ProcessExecutor::STATUS_FAILED; $this->markJobDone(); @@ -210,7 +210,7 @@ class ProcessExecutor * @param int $id * @return void */ - private function startJob($id) + private function startJob($id): void { $job = &$this->jobs[$id]; if ($job['status'] !== self::STATUS_QUEUED) { @@ -269,7 +269,7 @@ class ProcessExecutor * * @return void */ - public function enableAsync() + public function enableAsync(): void { $this->allowAsync = true; } @@ -280,7 +280,7 @@ class ProcessExecutor * @param ?int $index job id * @return int number of active (queued or started) jobs */ - public function countActiveJobs($index = null) + public function countActiveJobs($index = null): int { // tick foreach ($this->jobs as $job) { @@ -407,7 +407,7 @@ class ProcessExecutor } $commandString = is_string($command) ? $command : implode(' ', array_map(self::class.'::escape', $command)); - $safeCommand = Preg::replaceCallback('{://(?P[^:/\s]+):(?P[^@\s/]+)@}i', function ($m) { + $safeCommand = Preg::replaceCallback('{://(?P[^:/\s]+):(?P[^@\s/]+)@}i', function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx) we obfuscate that if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) { return '://***:***@'; @@ -437,7 +437,7 @@ class ProcessExecutor * * @return string */ - private static function escapeArgument($argument) + private static function escapeArgument($argument): string { if ('' === ($argument = (string) $argument)) { return escapeshellarg($argument); diff --git a/src/Composer/Util/RemoteFilesystem.php b/src/Composer/Util/RemoteFilesystem.php index 28982a8e9..1d6866f7a 100644 --- a/src/Composer/Util/RemoteFilesystem.php +++ b/src/Composer/Util/RemoteFilesystem.php @@ -106,7 +106,7 @@ class RemoteFilesystem * * @return bool true */ - public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array()) + public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array()): bool { return $this->get($originUrl, $fileUrl, $options, $fileName, $progress); } @@ -131,7 +131,7 @@ class RemoteFilesystem * * @return mixed[] Options */ - public function getOptions() + public function getOptions(): array { return $this->options; } @@ -142,7 +142,7 @@ class RemoteFilesystem * @param mixed[] $options * @return void */ - public function setOptions(array $options) + public function setOptions(array $options): void { $this->options = array_replace_recursive($this->options, $options); } @@ -152,7 +152,7 @@ class RemoteFilesystem * * @return bool */ - public function isTlsDisabled() + public function isTlsDisabled(): bool { return $this->disableTls === true; } @@ -162,7 +162,7 @@ class RemoteFilesystem * * @return string[] */ - public function getLastHeaders() + public function getLastHeaders(): array { return $this->lastHeaders; } @@ -171,7 +171,7 @@ class RemoteFilesystem * @param string[] $headers array of returned headers like from getLastHeaders() * @return int|null */ - public static function findStatusCode(array $headers) + public static function findStatusCode(array $headers): ?int { $value = null; foreach ($headers as $header) { @@ -189,7 +189,7 @@ class RemoteFilesystem * @param string[] $headers array of returned headers like from getLastHeaders() * @return string|null */ - public function findStatusMessage(array $headers) + public function findStatusMessage(array $headers): ?string { $value = null; foreach ($headers as $header) { @@ -290,7 +290,7 @@ class RemoteFilesystem $errorMessage = ''; $errorCode = 0; $result = false; - set_error_handler(function ($code, $msg) use (&$errorMessage) { + set_error_handler(function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } @@ -445,7 +445,7 @@ class RemoteFilesystem } $errorMessage = ''; - set_error_handler(function ($code, $msg) use (&$errorMessage) { + set_error_handler(function ($code, $msg) use (&$errorMessage): bool { if ($errorMessage) { $errorMessage .= "\n"; } @@ -554,7 +554,7 @@ class RemoteFilesystem * * @throws TransportException */ - protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) + protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax): void { switch ($notificationCode) { case STREAM_NOTIFY_FAILURE: @@ -592,7 +592,7 @@ class RemoteFilesystem * * @return void */ - protected function promptAuthAndRetry($httpStatus, $reason = null, $headers = array()) + protected function promptAuthAndRetry($httpStatus, $reason = null, $headers = array()): void { $result = $this->authHelper->promptAuthIfNeeded($this->fileUrl, $this->originUrl, $httpStatus, $reason, $headers); @@ -610,7 +610,7 @@ class RemoteFilesystem * * @return mixed[] */ - protected function getOptionsForUrl($originUrl, $additionalOptions) + protected function getOptionsForUrl($originUrl, $additionalOptions): array { $tlsOptions = array(); $headers = array(); @@ -698,7 +698,7 @@ class RemoteFilesystem * * @return string|null */ - private function decodeResult($result, $http_response_header) + private function decodeResult($result, $http_response_header): ?string { // decode gzip if ($result && extension_loaded('zlib')) { @@ -722,7 +722,7 @@ class RemoteFilesystem * * @return string|null */ - private function normalizeResult($result) + private function normalizeResult($result): ?string { if ($result === false) { return null; diff --git a/src/Composer/Util/Silencer.php b/src/Composer/Util/Silencer.php index 361ef41f6..75a97575b 100644 --- a/src/Composer/Util/Silencer.php +++ b/src/Composer/Util/Silencer.php @@ -30,7 +30,7 @@ class Silencer * @param int|null $mask Error levels to suppress, default value NULL indicates all warnings and below. * @return int The old error reporting level. */ - public static function suppress($mask = null) + public static function suppress($mask = null): int { if (!isset($mask)) { $mask = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_DEPRECATED | E_USER_DEPRECATED | E_STRICT; @@ -47,7 +47,7 @@ class Silencer * * @return void */ - public static function restore() + public static function restore(): void { if (!empty(self::$stack)) { error_reporting(array_pop(self::$stack)); diff --git a/src/Composer/Util/StreamContextFactory.php b/src/Composer/Util/StreamContextFactory.php index 852d72946..7448990d3 100644 --- a/src/Composer/Util/StreamContextFactory.php +++ b/src/Composer/Util/StreamContextFactory.php @@ -63,7 +63,7 @@ final class StreamContextFactory * @phpstan-return array{http: array{header: string[], proxy?: string, request_fulluri: bool}, ssl?: mixed[]} * @return array formatted as a stream context array */ - public static function initOptions($url, array $options, $forCurl = false) + public static function initOptions($url, array $options, $forCurl = false): array { // Make sure the headers are in an array form if (!isset($options['http']['header'])) { @@ -134,7 +134,7 @@ final class StreamContextFactory * * @return mixed[] */ - public static function getTlsDefaults(array $options, LoggerInterface $logger = null) + public static function getTlsDefaults(array $options, LoggerInterface $logger = null): array { $ciphers = implode(':', array( 'ECDHE-RSA-AES128-GCM-SHA256', @@ -240,12 +240,12 @@ final class StreamContextFactory * @param string|string[] $header * @return string[] */ - private static function fixHttpHeaderField($header) + private static function fixHttpHeaderField($header): array { if (!is_array($header)) { $header = explode("\r\n", $header); } - uasort($header, function ($el) { + uasort($header, function ($el): int { return stripos($el, 'content-type') === 0 ? 1 : -1; }); diff --git a/src/Composer/Util/Svn.php b/src/Composer/Util/Svn.php index 865479e9a..5c47d408c 100644 --- a/src/Composer/Util/Svn.php +++ b/src/Composer/Util/Svn.php @@ -86,7 +86,7 @@ class Svn /** * @return void */ - public static function cleanEnv() + public static function cleanEnv(): void { // clean up env for OSX, see https://github.com/composer/composer/issues/2146#issuecomment-35478940 Platform::clearEnv('DYLD_LIBRARY_PATH'); @@ -105,7 +105,7 @@ class Svn * @throws \RuntimeException * @return string */ - public function execute($command, $url, $cwd = null, $path = null, $verbose = false) + public function execute($command, $url, $cwd = null, $path = null, $verbose = false): string { // Ensure we are allowed to use this URL by config $this->config->prohibitUrlByConfig($url, $this->io); @@ -125,7 +125,7 @@ class Svn * @throws \RuntimeException * @return string */ - public function executeLocal($command, $path, $cwd = null, $verbose = false) + public function executeLocal($command, $path, $cwd = null, $verbose = false): string { // A local command has no remote url return $this->executeWithAuthRetry($command, $cwd, '', $path, $verbose); @@ -140,7 +140,7 @@ class Svn * * @return ?string */ - private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose) + private function executeWithAuthRetry($svnCommand, $cwd, $url, $path, $verbose): ?string { // Regenerate the command at each try, to use the newly user-provided credentials $command = $this->getCommand($svnCommand, $url, $path); @@ -194,7 +194,7 @@ class Svn * @param bool $cacheCredentials * @return void */ - public function setCacheCredentials($cacheCredentials) + public function setCacheCredentials($cacheCredentials): void { $this->cacheCredentials = $cacheCredentials; } @@ -205,7 +205,7 @@ class Svn * @throws \RuntimeException * @return \Composer\Util\Svn */ - protected function doAuthDance() + protected function doAuthDance(): \Composer\Util\Svn { // cannot ask for credentials in non interactive mode if (!$this->io->isInteractive()) { @@ -236,7 +236,7 @@ class Svn * * @return string */ - protected function getCommand($cmd, $url, $path = null) + protected function getCommand($cmd, $url, $path = null): string { $cmd = sprintf( '%s %s%s -- %s', @@ -260,7 +260,7 @@ class Svn * * @return string */ - protected function getCredentialString() + protected function getCredentialString(): string { if (!$this->hasAuth()) { return ''; @@ -280,7 +280,7 @@ class Svn * @throws \LogicException * @return string */ - protected function getPassword() + protected function getPassword(): string { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); @@ -295,7 +295,7 @@ class Svn * @throws \LogicException * @return string */ - protected function getUsername() + protected function getUsername(): string { if ($this->credentials === null) { throw new \LogicException("No svn auth detected."); @@ -309,7 +309,7 @@ class Svn * * @return bool */ - protected function hasAuth() + protected function hasAuth(): bool { if (null !== $this->hasAuth) { return $this->hasAuth; @@ -327,7 +327,7 @@ class Svn * * @return string */ - protected function getAuthCache() + protected function getAuthCache(): string { return $this->cacheCredentials ? '' : '--no-auth-cache '; } @@ -337,7 +337,7 @@ class Svn * * @return bool */ - private function createAuthFromConfig() + private function createAuthFromConfig(): bool { if (!$this->config->has('http-basic')) { return $this->hasAuth = false; @@ -363,7 +363,7 @@ class Svn * * @return bool */ - private function createAuthFromUrl() + private function createAuthFromUrl(): bool { $uri = parse_url($this->url); if (empty($uri['user'])) { @@ -383,7 +383,7 @@ class Svn * * @return string|null */ - public function binaryVersion() + public function binaryVersion(): ?string { if (!self::$version) { if (0 === $this->process->execute('svn --version', $output)) { diff --git a/src/Composer/Util/SyncHelper.php b/src/Composer/Util/SyncHelper.php index 9e8c5d710..f61d02dbe 100644 --- a/src/Composer/Util/SyncHelper.php +++ b/src/Composer/Util/SyncHelper.php @@ -31,7 +31,7 @@ class SyncHelper * * @return void */ - public static function downloadAndInstallPackageSync(Loop $loop, DownloaderInterface $downloader, $path, PackageInterface $package, PackageInterface $prevPackage = null) + public static function downloadAndInstallPackageSync(Loop $loop, DownloaderInterface $downloader, $path, PackageInterface $package, PackageInterface $prevPackage = null): void { $type = $prevPackage ? 'update' : 'install'; @@ -61,7 +61,7 @@ class SyncHelper * * @return void */ - public static function await(Loop $loop, PromiseInterface $promise = null) + public static function await(Loop $loop, PromiseInterface $promise = null): void { if ($promise) { $loop->wait(array($promise)); diff --git a/src/Composer/Util/Tar.php b/src/Composer/Util/Tar.php index cae69c906..9d4f7f112 100644 --- a/src/Composer/Util/Tar.php +++ b/src/Composer/Util/Tar.php @@ -22,7 +22,7 @@ class Tar * * @return string|null */ - public static function getComposerJson($pathToArchive) + public static function getComposerJson($pathToArchive): ?string { $phar = new \PharData($pathToArchive); @@ -40,7 +40,7 @@ class Tar * * @return string */ - private static function extractComposerJsonFromFolder(\PharData $phar) + private static function extractComposerJsonFromFolder(\PharData $phar): string { if (isset($phar['composer.json'])) { return $phar['composer.json']->getContent(); diff --git a/src/Composer/Util/TlsHelper.php b/src/Composer/Util/TlsHelper.php index 3fe329d4a..697a66b17 100644 --- a/src/Composer/Util/TlsHelper.php +++ b/src/Composer/Util/TlsHelper.php @@ -30,7 +30,7 @@ final class TlsHelper * * @return bool */ - public static function checkCertificateHost($certificate, $hostname, &$cn = null) + public static function checkCertificateHost($certificate, $hostname, &$cn = null): bool { $names = self::getCertificateNames($certificate); @@ -61,7 +61,7 @@ final class TlsHelper * * @return array{cn: string, san: string[]}|null */ - public static function getCertificateNames($certificate) + public static function getCertificateNames($certificate): ?array { if (is_array($certificate)) { $info = $certificate; @@ -78,7 +78,7 @@ final class TlsHelper if (isset($info['extensions']['subjectAltName'])) { $subjectAltNames = Preg::split('{\s*,\s*}', $info['extensions']['subjectAltName']); - $subjectAltNames = array_filter(array_map(function ($name) { + $subjectAltNames = array_filter(array_map(function ($name): ?string { if (0 === strpos($name, 'DNS:')) { return strtolower(ltrim(substr($name, 4))); } @@ -136,7 +136,7 @@ final class TlsHelper * @param string $certificate * @return string */ - public static function getCertificateFingerprint($certificate) + public static function getCertificateFingerprint($certificate): string { $pubkey = openssl_get_publickey($certificate); if ($pubkey === false) { @@ -161,7 +161,7 @@ final class TlsHelper * * @return bool */ - public static function isOpensslParseSafe() + public static function isOpensslParseSafe(): bool { return CaBundle::isOpensslParseSafe(); } @@ -173,13 +173,13 @@ final class TlsHelper * * @return callable|null */ - private static function certNameMatcher($certName) + private static function certNameMatcher($certName): ?callable { $wildcards = substr_count($certName, '*'); if (0 === $wildcards) { // Literal match. - return function ($hostname) use ($certName) { + return function ($hostname) use ($certName): bool { return $hostname === $certName; }; } @@ -203,7 +203,7 @@ final class TlsHelper $wildcardRegex = str_replace('\\*', '[a-z0-9-]+', $wildcardRegex); $wildcardRegex = "{^{$wildcardRegex}$}"; - return function ($hostname) use ($wildcardRegex) { + return function ($hostname) use ($wildcardRegex): bool { return Preg::isMatch($wildcardRegex, $hostname); }; } diff --git a/src/Composer/Util/Url.php b/src/Composer/Util/Url.php index c2ee92465..d118054d2 100644 --- a/src/Composer/Util/Url.php +++ b/src/Composer/Util/Url.php @@ -26,7 +26,7 @@ class Url * @param string $ref * @return string the updated URL */ - public static function updateDistReference(Config $config, $url, $ref) + public static function updateDistReference(Config $config, $url, $ref): string { $host = parse_url($url, PHP_URL_HOST); @@ -64,7 +64,7 @@ class Url * @param string $url * @return string */ - public static function getOrigin(Config $config, $url) + public static function getOrigin(Config $config, $url): string { if (0 === strpos($url, 'file://')) { return $url; @@ -108,13 +108,13 @@ class Url * @param string $url * @return string */ - public static function sanitize($url) + public static function sanitize($url): string { // GitHub repository rename result in redirect locations containing the access_token as GET parameter // e.g. https://api.github.com/repositories/9999999999?access_token=github_token $url = Preg::replace('{([&?]access_token=)[^&]+}', '$1***', $url); - $url = Preg::replaceCallback('{^(?P[a-z0-9]+://)?(?P[^:/\s@]+):(?P[^@\s/]+)@}i', function ($m) { + $url = Preg::replaceCallback('{^(?P[a-z0-9]+://)?(?P[^:/\s@]+):(?P[^@\s/]+)@}i', function ($m): string { // if the username looks like a long (12char+) hex string, or a modern github token (e.g. ghp_xxx) we obfuscate that if (Preg::isMatch('{^([a-f0-9]{12,}|gh[a-z]_[a-zA-Z0-9_]+)$}', $m['user'])) { return $m['prefix'].'***:***@'; diff --git a/src/Composer/Util/Zip.php b/src/Composer/Util/Zip.php index 7b1f6285c..3e448048d 100644 --- a/src/Composer/Util/Zip.php +++ b/src/Composer/Util/Zip.php @@ -24,7 +24,7 @@ class Zip * * @return string|null */ - public static function getComposerJson($pathToZip) + public static function getComposerJson($pathToZip): ?string { if (!extension_loaded('zip')) { throw new \RuntimeException('The Zip Util requires PHP\'s zip extension'); @@ -65,7 +65,7 @@ class Zip * * @return int */ - private static function locateFile(\ZipArchive $zip, $filename) + private static function locateFile(\ZipArchive $zip, $filename): int { // return root composer.json if it is there and is a file if (false !== ($index = $zip->locateName($filename)) && $zip->getFromIndex($index) !== false) { diff --git a/tests/Composer/Test/AllFunctionalTest.php b/tests/Composer/Test/AllFunctionalTest.php index d1f6394e4..12bd95e3d 100644 --- a/tests/Composer/Test/AllFunctionalTest.php +++ b/tests/Composer/Test/AllFunctionalTest.php @@ -63,7 +63,7 @@ class AllFunctionalTest extends TestCase $fs->removeDirectory(dirname(self::$pharPath)); } - public function testBuildPhar() + public function testBuildPhar(): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped('Building the phar does not work on HHVM.'); @@ -100,7 +100,7 @@ class AllFunctionalTest extends TestCase * @depends testBuildPhar * @param string $testFile */ - public function testIntegration($testFile) + public function testIntegration($testFile): void { $testData = $this->parseTestFile($testFile); $this->testDir = self::getUniqueTmpDirectory(); @@ -121,7 +121,7 @@ class AllFunctionalTest extends TestCase $proc = Process::fromShellCommandline(escapeshellcmd(PHP_BINARY).' '.escapeshellarg(self::$pharPath).' --no-ansi '.$testData['RUN'], $this->testDir, $env, null, 300); $output = ''; - $exitCode = $proc->run(function ($type, $buffer) use (&$output) { + $exitCode = $proc->run(function ($type, $buffer) use (&$output): void { $output .= $buffer; }); @@ -179,7 +179,7 @@ class AllFunctionalTest extends TestCase /** * @return array> */ - public function getTestFiles() + public function getTestFiles(): array { $tests = array(); foreach (Finder::create()->in(__DIR__.'/Fixtures/functional')->name('*.test')->files() as $file) { @@ -193,7 +193,7 @@ class AllFunctionalTest extends TestCase * @param string $file * @return array{RUN: string, EXPECT?: string, EXPECT-EXIT-CODE?: int, EXPECT-REGEX?: string, EXPECT-REGEXES?: string, TEST?: string} */ - private function parseTestFile($file) + private function parseTestFile($file): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); $data = array(); @@ -255,7 +255,7 @@ class AllFunctionalTest extends TestCase * @param string $output * @return string */ - private function cleanOutput($output) + private function cleanOutput($output): string { $processed = ''; diff --git a/tests/Composer/Test/ApplicationTest.php b/tests/Composer/Test/ApplicationTest.php index ed182360e..30aab4988 100644 --- a/tests/Composer/Test/ApplicationTest.php +++ b/tests/Composer/Test/ApplicationTest.php @@ -25,7 +25,7 @@ class ApplicationTest extends TestCase putenv('COMPOSER_NO_INTERACTION'); } - public function testDevWarning() + public function testDevWarning(): void { $application = new Application; @@ -84,7 +84,7 @@ class ApplicationTest extends TestCase * @param string $command * @return void */ - public function ensureNoDevWarning($command) + public function ensureNoDevWarning($command): void { $application = new Application; @@ -133,12 +133,12 @@ class ApplicationTest extends TestCase $application->doRun($inputMock, $outputMock); } - public function testDevWarningPrevented() + public function testDevWarningPrevented(): void { $this->ensureNoDevWarning('self-update'); } - public function testDevWarningPreventedAlias() + public function testDevWarningPreventedAlias(): void { $this->ensureNoDevWarning('self-up'); } diff --git a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php index 96f8d4584..06c12cfb5 100644 --- a/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php +++ b/tests/Composer/Test/Autoload/AutoloadGeneratorTest.php @@ -100,10 +100,10 @@ class AutoloadGeneratorTest extends TestCase $this->config = $this->getMockBuilder('Composer\Config')->getMock(); $this->configValueMap = array( - 'vendor-dir' => function () { + 'vendor-dir' => function (): string { return $this->vendorDir; }, - 'platform-check' => function () { + 'platform-check' => function (): bool { return true; }, ); @@ -130,7 +130,7 @@ class AutoloadGeneratorTest extends TestCase ->getMock(); $this->im->expects($this->any()) ->method('getInstallPath') - ->will($this->returnCallback(function ($package) { + ->will($this->returnCallback(function ($package): string { $targetDir = $package->getTargetDir(); return $this->vendorDir.'/'.$package->getName() . ($targetDir ? '/'.$targetDir : ''); @@ -161,7 +161,7 @@ class AutoloadGeneratorTest extends TestCase } } - public function testRootPackageAutoloading() + public function testRootPackageAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -206,7 +206,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('classmap', $this->vendorDir.'/composer', 'classmap'); } - public function testRootPackageDevAutoloading() + public function testRootPackageDevAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -244,7 +244,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('files2', $this->vendorDir.'/composer', 'files'); } - public function testRootPackageDevAutoloadingDisabledByDefault() + public function testRootPackageDevAutoloadingDisabledByDefault(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -277,7 +277,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertFalse(is_file($this->vendorDir.'/composer/autoload_files.php')); } - public function testVendorDirSameAsWorkingDir() + public function testVendorDirSameAsWorkingDir(): void { $this->vendorDir = $this->workingDir; @@ -308,7 +308,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('classmap3', $this->vendorDir.'/composer', 'classmap'); } - public function testRootPackageAutoloadingAlternativeVendorDir() + public function testRootPackageAutoloadingAlternativeVendorDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -337,7 +337,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('classmap2', $this->vendorDir.'/composer', 'classmap'); } - public function testRootPackageAutoloadingWithTargetDir() + public function testRootPackageAutoloadingWithTargetDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -368,7 +368,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('classmap6', $this->vendorDir.'/composer', 'classmap'); } - public function testVendorsAutoloading() + public function testVendorsAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -397,7 +397,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } - public function testNonDevAutoloadExclusionWithRecursion() + public function testNonDevAutoloadExclusionWithRecursion(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -430,7 +430,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } - public function testNonDevAutoloadShouldIncludeReplacedPackages() + public function testNonDevAutoloadShouldIncludeReplacedPackages(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array('a/a' => new Link('a', 'a/a', new MatchAllConstraint()))); @@ -464,7 +464,7 @@ class AutoloadGeneratorTest extends TestCase ); } - public function testNonDevAutoloadExclusionWithRecursionReplace() + public function testNonDevAutoloadExclusionWithRecursionReplace(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -497,7 +497,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertFileExists($this->vendorDir.'/composer/autoload_classmap.php', "ClassMap file needs to be generated, even if empty."); } - public function testNonDevAutoloadReplacesNestedRequirements() + public function testNonDevAutoloadReplacesNestedRequirements(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -549,7 +549,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('classmap9', $this->vendorDir.'/composer', 'classmap'); } - public function testPharAutoload() + public function testPharAutoload(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -590,7 +590,7 @@ class AutoloadGeneratorTest extends TestCase $this->assertAutoloadFiles('phar_static', $this->vendorDir . '/composer', 'static'); } - public function testPSRToClassMapIgnoresNonExistingDir() + public function testPSRToClassMapIgnoresNonExistingDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); @@ -613,7 +613,7 @@ class AutoloadGeneratorTest extends TestCase ); } - public function testPSRToClassMapIgnoresNonPSRClasses() + public function testPSRToClassMapIgnoresNonPSRClasses(): void { $package = new RootPackage('root/a', '1.0', '1.0'); @@ -654,7 +654,7 @@ EOF; $this->assertStringEqualsFile($this->vendorDir.'/composer/autoload_classmap.php', $expectedClassmap); } - public function testVendorsClassMapAutoloading() + public function testVendorsClassMapAutoloading(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -694,7 +694,7 @@ EOF; $this->assertAutoloadFiles('classmap4', $this->vendorDir.'/composer', 'classmap'); } - public function testVendorsClassMapAutoloadingWithTargetDir() + public function testVendorsClassMapAutoloadingWithTargetDir(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -734,7 +734,7 @@ EOF; ); } - public function testClassMapAutoloadingEmptyDirAndExactFile() + public function testClassMapAutoloadingEmptyDirAndExactFile(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -779,7 +779,7 @@ EOF; $this->assertStringNotContainsString('$loader->setApcuPrefix(', file_get_contents($this->vendorDir.'/composer/autoload_real.php')); } - public function testClassMapAutoloadingAuthoritativeAndApcu() + public function testClassMapAutoloadingAuthoritativeAndApcu(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -828,7 +828,7 @@ EOF; $this->assertStringContainsString('$loader->setApcuPrefix(', file_get_contents($this->vendorDir.'/composer/autoload_real.php')); } - public function testClassMapAutoloadingAuthoritativeAndApcuPrefix() + public function testClassMapAutoloadingAuthoritativeAndApcuPrefix(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires(array( @@ -877,7 +877,7 @@ EOF; $this->assertStringContainsString('$loader->setApcuPrefix(\'custom\\\'Prefix\');', file_get_contents($this->vendorDir.'/composer/autoload_real.php')); } - public function testFilesAutoloadGeneration() + public function testFilesAutoloadGeneration(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array('files' => array('root.php'))); @@ -924,7 +924,7 @@ EOF; $this->assertTrue(function_exists('testFilesAutoloadGenerationRoot')); } - public function testFilesAutoloadGenerationRemoveExtraEntitiesFromAutoloadFiles() + public function testFilesAutoloadGenerationRemoveExtraEntitiesFromAutoloadFiles(): void { $autoloadPackage = new RootPackage('root/a', '1.0', '1.0'); $autoloadPackage->setAutoload(array('files' => array('root.php'))); @@ -995,7 +995,7 @@ EOF; $this->assertFileDoesNotExist($this->vendorDir.'/composer/include_paths.php'); } - public function testFilesAutoloadOrderByDependencies() + public function testFilesAutoloadOrderByDependencies(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array('files' => array('root2.php'))); @@ -1065,7 +1065,7 @@ EOF; * - The main package has priority over other packages. * - Longer namespaces have priority over shorter namespaces. */ - public function testOverrideVendorsAutoloading() + public function testOverrideVendorsAutoloading(): void { $rootPackage = new RootPackage('root/z', '1.0', '1.0'); $rootPackage->setAutoload(array( @@ -1160,7 +1160,7 @@ EOF; $this->assertStringEqualsFile($this->vendorDir.'/composer/autoload_classmap.php', $expectedClassmap); } - public function testIncludePathFileGeneration() + public function testIncludePathFileGeneration(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $packages = array(); @@ -1197,7 +1197,7 @@ EOF; ); } - public function testIncludePathsArePrependedInAutoloadFile() + public function testIncludePathsArePrependedInAutoloadFile(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $packages = array(); @@ -1228,7 +1228,7 @@ EOF; set_include_path($oldIncludePath); } - public function testIncludePathsInRootPackage() + public function testIncludePathsInRootPackage(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setIncludePaths(array('/lib', '/src')); @@ -1257,7 +1257,7 @@ EOF; set_include_path($oldIncludePath); } - public function testIncludePathFileWithoutPathsIsSkipped() + public function testIncludePathFileWithoutPathsIsSkipped(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $packages = array(); @@ -1276,7 +1276,7 @@ EOF; $this->assertFileDoesNotExist($this->vendorDir."/composer/include_paths.php"); } - public function testPreAndPostEventsAreDispatchedDuringAutoloadDump() + public function testPreAndPostEventsAreDispatchedDuringAutoloadDump(): void { $this->eventDispatcher ->expects($this->exactly(2)) @@ -1297,7 +1297,7 @@ EOF; $this->generator->dump($this->config, $this->repository, $package, $this->im, 'composer', true, '_8'); } - public function testUseGlobalIncludePath() + public function testUseGlobalIncludePath(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -1318,7 +1318,7 @@ EOF; $this->assertFileContentEquals(__DIR__.'/Fixtures/autoload_static_include_path.php', $this->vendorDir.'/composer/autoload_static.php'); } - public function testVendorDirExcludedFromWorkingDir() + public function testVendorDirExcludedFromWorkingDir(): void { $workingDir = $this->vendorDir.'/working-dir'; $vendorDir = $workingDir.'/../vendor'; @@ -1354,7 +1354,7 @@ EOF; ->getMock(); $im->expects($this->any()) ->method('getInstallPath') - ->will($this->returnCallback(function ($package) use ($vendorDir) { + ->will($this->returnCallback(function ($package) use ($vendorDir): string { $targetDir = $package->getTargetDir(); return $vendorDir.'/'.$package->getName() . ($targetDir ? '/'.$targetDir : ''); @@ -1432,7 +1432,7 @@ EOF; $this->assertStringContainsString("\$baseDir . '/test.php',\n", file_get_contents($vendorDir.'/composer/autoload_files.php')); } - public function testUpLevelRelativePaths() + public function testUpLevelRelativePaths(): void { $workingDir = $this->workingDir.'/working-dir'; mkdir($workingDir, 0777, true); @@ -1516,7 +1516,7 @@ EOF; $this->assertStringContainsString("\$baseDir . '/../test.php',\n", file_get_contents($this->vendorDir.'/composer/autoload_files.php')); } - public function testEmptyPaths() + public function testEmptyPaths(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -1584,7 +1584,7 @@ EOF; $this->assertStringEqualsFile($this->vendorDir.'/composer/autoload_classmap.php', $expectedClassmap); } - public function testVendorSubstringPath() + public function testVendorSubstringPath(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -1631,7 +1631,7 @@ EOF; $this->assertStringEqualsFile($this->vendorDir.'/composer/autoload_psr4.php', $expectedPsr4); } - public function testExcludeFromClassmap() + public function testExcludeFromClassmap(): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setAutoload(array( @@ -1709,7 +1709,7 @@ EOF; * * @dataProvider platformCheckProvider */ - public function testGeneratesPlatformCheck(array $requires, $expectedFixture, array $provides = array(), array $replaces = array(), $ignorePlatformReqs = false) + public function testGeneratesPlatformCheck(array $requires, $expectedFixture, array $provides = array(), array $replaces = array(), $ignorePlatformReqs = false): void { $package = new RootPackage('root/a', '1.0', '1.0'); $package->setRequires($requires); @@ -1741,7 +1741,7 @@ EOF; /** * @return array */ - public function platformCheckProvider() + public function platformCheckProvider(): array { $versionParser = new VersionParser(); @@ -1850,7 +1850,7 @@ EOF; * * @return void */ - private function assertAutoloadFiles($name, $dir, $type = 'namespaces') + private function assertAutoloadFiles($name, $dir, $type = 'namespaces'): void { $a = __DIR__.'/Fixtures/autoload_'.$name.'.php'; $b = $dir.'/autoload_'.$type.'.php'; @@ -1864,7 +1864,7 @@ EOF; * * @return void */ - public static function assertFileContentEquals(string $expected, string $actual, ?string $message = null) + public static function assertFileContentEquals(string $expected, string $actual, ?string $message = null): void { self::assertSame( str_replace("\r", '', (string) file_get_contents($expected)), diff --git a/tests/Composer/Test/Autoload/ClassLoaderTest.php b/tests/Composer/Test/Autoload/ClassLoaderTest.php index f20c764d2..d11c522a9 100644 --- a/tests/Composer/Test/Autoload/ClassLoaderTest.php +++ b/tests/Composer/Test/Autoload/ClassLoaderTest.php @@ -27,7 +27,7 @@ class ClassLoaderTest extends TestCase * * @param string $class The fully-qualified class name to test, without preceding namespace separator. */ - public function testLoadClass($class) + public function testLoadClass($class): void { $loader = new ClassLoader(); $loader->add('Namespaced\\', __DIR__ . '/Fixtures'); @@ -42,7 +42,7 @@ class ClassLoaderTest extends TestCase * * @return array> Array of parameter sets to test with. */ - public function getLoadClassTests() + public function getLoadClassTests(): array { return array( array('Namespaced\\Foo'), @@ -54,7 +54,7 @@ class ClassLoaderTest extends TestCase /** * getPrefixes method should return empty array if ClassLoader does not have any psr-0 configuration */ - public function testGetPrefixesWithNoPSR0Configuration() + public function testGetPrefixesWithNoPSR0Configuration(): void { $loader = new ClassLoader(); $this->assertEmpty($loader->getPrefixes()); diff --git a/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php b/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php index 6316ceb26..5315c4b33 100644 --- a/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php +++ b/tests/Composer/Test/Autoload/ClassMapGeneratorTest.php @@ -30,7 +30,7 @@ class ClassMapGeneratorTest extends TestCase * @param string $directory * @param array $expected */ - public function testCreateMap($directory, $expected) + public function testCreateMap($directory, $expected): void { $this->assertEqualsNormalized($expected, ClassMapGenerator::createMap($directory)); } @@ -38,7 +38,7 @@ class ClassMapGeneratorTest extends TestCase /** * @return array>> */ - public function getTestCreateMapTests() + public function getTestCreateMapTests(): array { $classmap = array( 'Foo\\Bar\\A' => realpath(__DIR__) . '/Fixtures/classmap/sameNsMultipleClasses.php', @@ -120,7 +120,7 @@ class ClassMapGeneratorTest extends TestCase return $data; } - public function testCreateMapFinderSupport() + public function testCreateMapFinderSupport(): void { $this->checkIfFinderIsAvailable(); @@ -133,7 +133,7 @@ class ClassMapGeneratorTest extends TestCase ), ClassMapGenerator::createMap($finder)); } - public function testFindClassesThrowsWhenFileDoesNotExist() + public function testFindClassesThrowsWhenFileDoesNotExist(): void { $r = new \ReflectionClass('Composer\\Autoload\\ClassMapGenerator'); $find = $r->getMethod('findClasses'); @@ -144,7 +144,7 @@ class ClassMapGeneratorTest extends TestCase $find->invoke(null, __DIR__ . '/no-file'); } - public function testAmbiguousReference() + public function testAmbiguousReference(): void { $this->checkIfFinderIsAvailable(); @@ -167,7 +167,7 @@ class ClassMapGeneratorTest extends TestCase $io->expects($this->once()) ->method('writeError') - ->will($this->returnCallback(function ($text) use (&$msg) { + ->will($this->returnCallback(function ($text) use (&$msg): void { $msg = $text; })); @@ -188,7 +188,7 @@ class ClassMapGeneratorTest extends TestCase * If one file has a class or interface defined more than once, * an ambiguous reference warning should not be produced */ - public function testUnambiguousReference() + public function testUnambiguousReference(): void { $tempDir = $this->getUniqueTmpDirectory(); @@ -224,14 +224,14 @@ class ClassMapGeneratorTest extends TestCase $fs->removeDirectory($tempDir); } - public function testCreateMapThrowsWhenDirectoryDoesNotExist() + public function testCreateMapThrowsWhenDirectoryDoesNotExist(): void { self::expectException('RuntimeException'); self::expectExceptionMessage('Could not scan for classes inside'); ClassMapGenerator::createMap(__DIR__ . '/no-file.no-foler'); } - public function testDump() + public function testDump(): void { $tempDir = self::getUniqueTmpDirectory(); @@ -249,7 +249,7 @@ class ClassMapGeneratorTest extends TestCase $fs->removeDirectory($tempDir); } - public function testCreateMapDoesNotHitRegexBacktraceLimit() + public function testCreateMapDoesNotHitRegexBacktraceLimit(): void { $expected = array( 'Foo\\StripNoise' => realpath(__DIR__) . '/Fixtures/pcrebacktracelimit/StripNoise.php', @@ -274,7 +274,7 @@ class ClassMapGeneratorTest extends TestCase * @param string $message * @return void */ - protected function assertEqualsNormalized($expected, $actual, $message = '') + protected function assertEqualsNormalized($expected, $actual, $message = ''): void { foreach ($expected as $ns => $path) { $expected[$ns] = strtr($path, '\\', '/'); @@ -286,7 +286,7 @@ class ClassMapGeneratorTest extends TestCase } /** @return void */ - private function checkIfFinderIsAvailable() + private function checkIfFinderIsAvailable(): void { if (!class_exists('Symfony\\Component\\Finder\\Finder')) { $this->markTestSkipped('Finder component is not available'); diff --git a/tests/Composer/Test/CacheTest.php b/tests/Composer/Test/CacheTest.php index 4bc0c3994..6b83ac961 100644 --- a/tests/Composer/Test/CacheTest.php +++ b/tests/Composer/Test/CacheTest.php @@ -62,7 +62,7 @@ class CacheTest extends TestCase } } - public function testRemoveOutdatedFiles() + public function testRemoveOutdatedFiles(): void { $outdated = array_slice($this->files, 1); $this->finder @@ -82,7 +82,7 @@ class CacheTest extends TestCase $this->assertFileExists("{$this->root}/cached.file0.zip"); } - public function testRemoveFilesWhenCacheIsTooLarge() + public function testRemoveFilesWhenCacheIsTooLarge(): void { $emptyFinder = $this->getMockBuilder('Symfony\Component\Finder\Finder')->disableOriginalConstructor()->getMock(); $emptyFinder @@ -111,7 +111,7 @@ class CacheTest extends TestCase $this->assertFileExists("{$this->root}/cached.file3.zip"); } - public function testClearCache() + public function testClearCache(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $cache = new Cache($io, $this->root, 'a-z0-9.', $this->filesystem); diff --git a/tests/Composer/Test/Command/ArchiveCommandTest.php b/tests/Composer/Test/Command/ArchiveCommandTest.php index fda64ba7a..88cc15fe1 100644 --- a/tests/Composer/Test/Command/ArchiveCommandTest.php +++ b/tests/Composer/Test/Command/ArchiveCommandTest.php @@ -20,7 +20,7 @@ use Symfony\Component\Console\Input\ArrayInput; class ArchiveCommandTest extends TestCase { - public function testUsesConfigFromComposerObject() + public function testUsesConfigFromComposerObject(): void { $input = new ArrayInput(array()); @@ -64,7 +64,7 @@ class ArchiveCommandTest extends TestCase $command->run($input, $output); } - public function testUsesConfigFromFactoryWhenComposerIsNotDefined() + public function testUsesConfigFromFactoryWhenComposerIsNotDefined(): void { $input = new ArrayInput(array()); diff --git a/tests/Composer/Test/Command/InitCommandTest.php b/tests/Composer/Test/Command/InitCommandTest.php index 22950158e..69af6cfbc 100644 --- a/tests/Composer/Test/Command/InitCommandTest.php +++ b/tests/Composer/Test/Command/InitCommandTest.php @@ -17,7 +17,7 @@ use Composer\Test\TestCase; class InitCommandTest extends TestCase { - public function testParseValidAuthorString() + public function testParseValidAuthorString(): void { $command = new InitCommand; $author = $command->parseAuthorString('John Smith '); @@ -25,7 +25,7 @@ class InitCommandTest extends TestCase $this->assertEquals('john@example.com', $author['email']); } - public function testParseValidAuthorStringWithoutEmail() + public function testParseValidAuthorStringWithoutEmail(): void { $command = new InitCommand; $author = $command->parseAuthorString('John Smith'); @@ -33,7 +33,7 @@ class InitCommandTest extends TestCase $this->assertNull($author['email']); } - public function testParseValidUtf8AuthorString() + public function testParseValidUtf8AuthorString(): void { $command = new InitCommand; $author = $command->parseAuthorString('Matti Meikäläinen '); @@ -41,7 +41,7 @@ class InitCommandTest extends TestCase $this->assertEquals('matti@example.com', $author['email']); } - public function testParseValidUtf8AuthorStringWithNonSpacingMarks() + public function testParseValidUtf8AuthorStringWithNonSpacingMarks(): void { // \xCC\x88 is UTF-8 for U+0308 diaeresis (umlaut) combining mark $utf8_expected = "Matti Meika\xCC\x88la\xCC\x88inen"; @@ -51,7 +51,7 @@ class InitCommandTest extends TestCase $this->assertEquals('matti@example.com', $author['email']); } - public function testParseNumericAuthorString() + public function testParseNumericAuthorString(): void { $command = new InitCommand; $author = $command->parseAuthorString('h4x0r '); @@ -63,7 +63,7 @@ class InitCommandTest extends TestCase * Test scenario for issue #5631 * @link https://github.com/composer/composer/issues/5631 Issue #5631 */ - public function testParseValidAlias1AuthorString() + public function testParseValidAlias1AuthorString(): void { $command = new InitCommand; $author = $command->parseAuthorString( @@ -77,7 +77,7 @@ class InitCommandTest extends TestCase * Test scenario for issue #5631 * @link https://github.com/composer/composer/issues/5631 Issue #5631 */ - public function testParseValidAlias2AuthorString() + public function testParseValidAlias2AuthorString(): void { $command = new InitCommand; $author = $command->parseAuthorString( @@ -87,35 +87,35 @@ class InitCommandTest extends TestCase $this->assertEquals('john@example.com', $author['email']); } - public function testParseEmptyAuthorString() + public function testParseEmptyAuthorString(): void { $command = new InitCommand; self::expectException('InvalidArgumentException'); $command->parseAuthorString(''); } - public function testParseAuthorStringWithInvalidEmail() + public function testParseAuthorStringWithInvalidEmail(): void { $command = new InitCommand; self::expectException('InvalidArgumentException'); $command->parseAuthorString('John Smith '); } - public function testNamespaceFromValidPackageName() + public function testNamespaceFromValidPackageName(): void { $command = new InitCommand; $namespace = $command->namespaceFromPackageName('new_projects.acme-extra/package-name'); $this->assertEquals('NewProjectsAcmeExtra\PackageName', $namespace); } - public function testNamespaceFromInvalidPackageName() + public function testNamespaceFromInvalidPackageName(): void { $command = new InitCommand; $namespace = $command->namespaceFromPackageName('invalid-package-name'); $this->assertNull($namespace); } - public function testNamespaceFromMissingPackageName() + public function testNamespaceFromMissingPackageName(): void { $command = new InitCommand; $namespace = $command->namespaceFromPackageName(''); diff --git a/tests/Composer/Test/Command/RunScriptCommandTest.php b/tests/Composer/Test/Command/RunScriptCommandTest.php index eaffdbd92..7a9d7aef8 100644 --- a/tests/Composer/Test/Command/RunScriptCommandTest.php +++ b/tests/Composer/Test/Command/RunScriptCommandTest.php @@ -24,7 +24,7 @@ class RunScriptCommandTest extends TestCase * @param bool $dev * @param bool $noDev */ - public function testDetectAndPassDevModeToEventAndToDispatching($dev, $noDev) + public function testDetectAndPassDevModeToEventAndToDispatching($dev, $noDev): void { $scriptName = 'testScript'; @@ -61,7 +61,7 @@ class RunScriptCommandTest extends TestCase $ed->expects($this->once()) ->method('hasEventListeners') - ->with($this->callback(function (ScriptEvent $event) use ($scriptName, $expectedDevMode) { + ->with($this->callback(function (ScriptEvent $event) use ($scriptName, $expectedDevMode): bool { return $event->getName() === $scriptName && $event->isDevMode() === $expectedDevMode; })) @@ -89,7 +89,7 @@ class RunScriptCommandTest extends TestCase } /** @return bool[][] **/ - public function getDevOptions() + public function getDevOptions(): array { return array( array(true, true), @@ -100,7 +100,7 @@ class RunScriptCommandTest extends TestCase } /** @return Composer **/ - private function createComposerInstance() + private function createComposerInstance(): Composer { $composer = new Composer; $config = new Config; diff --git a/tests/Composer/Test/ComposerTest.php b/tests/Composer/Test/ComposerTest.php index 1ba78abea..216245a49 100644 --- a/tests/Composer/Test/ComposerTest.php +++ b/tests/Composer/Test/ComposerTest.php @@ -16,7 +16,7 @@ use Composer\Composer; class ComposerTest extends TestCase { - public function testSetGetPackage() + public function testSetGetPackage(): void { $composer = new Composer(); $package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); @@ -25,7 +25,7 @@ class ComposerTest extends TestCase $this->assertSame($package, $composer->getPackage()); } - public function testSetGetLocker() + public function testSetGetLocker(): void { $composer = new Composer(); $locker = $this->getMockBuilder('Composer\Package\Locker')->disableOriginalConstructor()->getMock(); @@ -34,7 +34,7 @@ class ComposerTest extends TestCase $this->assertSame($locker, $composer->getLocker()); } - public function testSetGetRepositoryManager() + public function testSetGetRepositoryManager(): void { $composer = new Composer(); $manager = $this->getMockBuilder('Composer\Repository\RepositoryManager')->disableOriginalConstructor()->getMock(); @@ -43,7 +43,7 @@ class ComposerTest extends TestCase $this->assertSame($manager, $composer->getRepositoryManager()); } - public function testSetGetDownloadManager() + public function testSetGetDownloadManager(): void { $composer = new Composer(); $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); @@ -53,7 +53,7 @@ class ComposerTest extends TestCase $this->assertSame($manager, $composer->getDownloadManager()); } - public function testSetGetInstallationManager() + public function testSetGetInstallationManager(): void { $composer = new Composer(); $manager = $this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock(); diff --git a/tests/Composer/Test/Config/JsonConfigSourceTest.php b/tests/Composer/Test/Config/JsonConfigSourceTest.php index 3d9e68980..fd0e1f3e4 100644 --- a/tests/Composer/Test/Config/JsonConfigSourceTest.php +++ b/tests/Composer/Test/Config/JsonConfigSourceTest.php @@ -29,7 +29,7 @@ class JsonConfigSourceTest extends TestCase * * @return string */ - protected function fixturePath($name) + protected function fixturePath($name): string { return __DIR__.'/Fixtures/'.$name; } @@ -48,7 +48,7 @@ class JsonConfigSourceTest extends TestCase } } - public function testAddRepository() + public function testAddRepository(): void { $config = $this->workingDir.'/composer.json'; copy($this->fixturePath('composer-repositories.json'), $config); @@ -58,7 +58,7 @@ class JsonConfigSourceTest extends TestCase $this->assertFileEquals($this->fixturePath('config/config-with-exampletld-repository.json'), $config); } - public function testAddRepositoryWithOptions() + public function testAddRepositoryWithOptions(): void { $config = $this->workingDir.'/composer.json'; copy($this->fixturePath('composer-repositories.json'), $config); @@ -76,7 +76,7 @@ class JsonConfigSourceTest extends TestCase $this->assertFileEquals($this->fixturePath('config/config-with-exampletld-repository-and-options.json'), $config); } - public function testRemoveRepository() + public function testRemoveRepository(): void { $config = $this->workingDir.'/composer.json'; copy($this->fixturePath('config/config-with-exampletld-repository.json'), $config); @@ -86,7 +86,7 @@ class JsonConfigSourceTest extends TestCase $this->assertFileEquals($this->fixturePath('composer-repositories.json'), $config); } - public function testAddPackagistRepositoryWithFalseValue() + public function testAddPackagistRepositoryWithFalseValue(): void { $config = $this->workingDir.'/composer.json'; copy($this->fixturePath('composer-repositories.json'), $config); @@ -96,7 +96,7 @@ class JsonConfigSourceTest extends TestCase $this->assertFileEquals($this->fixturePath('config/config-with-packagist-false.json'), $config); } - public function testRemovePackagist() + public function testRemovePackagist(): void { $config = $this->workingDir.'/composer.json'; copy($this->fixturePath('config/config-with-packagist-false.json'), $config); @@ -117,7 +117,7 @@ class JsonConfigSourceTest extends TestCase * * @dataProvider provideAddLinkData */ - public function testAddLink($sourceFile, $type, $name, $value, $compareAgainst) + public function testAddLink($sourceFile, $type, $name, $value, $compareAgainst): void { $composerJson = $this->workingDir.'/composer.json'; copy($sourceFile, $composerJson); @@ -138,7 +138,7 @@ class JsonConfigSourceTest extends TestCase * * @dataProvider provideRemoveLinkData */ - public function testRemoveLink($sourceFile, $type, $name, $compareAgainst) + public function testRemoveLink($sourceFile, $type, $name, $compareAgainst): void { $composerJson = $this->workingDir.'/composer.json'; copy($sourceFile, $composerJson); @@ -160,7 +160,7 @@ class JsonConfigSourceTest extends TestCase * * @phpstan-return array{string, string, string, string, string} */ - protected function addLinkDataArguments($type, $name, $value, $fixtureBasename, $before) + protected function addLinkDataArguments($type, $name, $value, $fixtureBasename, $before): array { return array( $before, @@ -174,7 +174,7 @@ class JsonConfigSourceTest extends TestCase /** * Provide data for testAddLink */ - public function provideAddLinkData() + public function provideAddLinkData(): array { $empty = $this->fixturePath('composer-empty.json'); $oneOfEverything = $this->fixturePath('composer-one-of-everything.json'); @@ -217,7 +217,7 @@ class JsonConfigSourceTest extends TestCase * * @phpstan-return array{string, string, string, string} */ - protected function removeLinkDataArguments($type, $name, $fixtureBasename, $after = null) + protected function removeLinkDataArguments($type, $name, $fixtureBasename, $after = null): array { return array( $this->fixturePath('removeLink/'.$fixtureBasename.'.json'), @@ -230,7 +230,7 @@ class JsonConfigSourceTest extends TestCase /** * Provide data for testRemoveLink */ - public function provideRemoveLinkData() + public function provideRemoveLinkData(): array { $oneOfEverything = $this->fixturePath('composer-one-of-everything.json'); $twoOfEverything = $this->fixturePath('composer-two-of-everything.json'); diff --git a/tests/Composer/Test/ConfigTest.php b/tests/Composer/Test/ConfigTest.php index fc829c159..17f4384c2 100644 --- a/tests/Composer/Test/ConfigTest.php +++ b/tests/Composer/Test/ConfigTest.php @@ -23,7 +23,7 @@ class ConfigTest extends TestCase * @param mixed[] $localConfig * @param ?mixed[] $systemConfig */ - public function testAddPackagistRepository($expected, $localConfig, $systemConfig = null) + public function testAddPackagistRepository($expected, $localConfig, $systemConfig = null): void { $config = new Config(false); if ($systemConfig) { @@ -34,7 +34,7 @@ class ConfigTest extends TestCase $this->assertEquals($expected, $config->getRepositories()); } - public function dataAddPackagistRepository() + public function dataAddPackagistRepository(): array { $data = array(); $data['local config inherits system defaults'] = array( @@ -141,7 +141,7 @@ class ConfigTest extends TestCase return $data; } - public function testPreferredInstallAsString() + public function testPreferredInstallAsString(): void { $config = new Config(false); $config->merge(array('config' => array('preferred-install' => 'source'))); @@ -150,7 +150,7 @@ class ConfigTest extends TestCase $this->assertEquals('dist', $config->get('preferred-install')); } - public function testMergePreferredInstall() + public function testMergePreferredInstall(): void { $config = new Config(false); $config->merge(array('config' => array('preferred-install' => 'dist'))); @@ -162,7 +162,7 @@ class ConfigTest extends TestCase $this->assertEquals(array('foo/*' => 'source', '*' => 'dist'), $config->get('preferred-install')); } - public function testMergeGithubOauth() + public function testMergeGithubOauth(): void { $config = new Config(false); $config->merge(array('config' => array('github-oauth' => array('foo' => 'bar')))); @@ -171,7 +171,7 @@ class ConfigTest extends TestCase $this->assertEquals(array('foo' => 'bar', 'bar' => 'baz'), $config->get('github-oauth')); } - public function testVarReplacement() + public function testVarReplacement(): void { $config = new Config(false); $config->merge(array('config' => array('a' => 'b', 'c' => '{$a}'))); @@ -183,7 +183,7 @@ class ConfigTest extends TestCase $this->assertEquals($home.'/foo', $config->get('cache-dir')); } - public function testRealpathReplacement() + public function testRealpathReplacement(): void { $config = new Config(false, '/foo/bar'); $config->merge(array('config' => array( @@ -198,7 +198,7 @@ class ConfigTest extends TestCase $this->assertEquals('/baz', $config->get('cache-dir')); } - public function testStreamWrapperDirs() + public function testStreamWrapperDirs(): void { $config = new Config(false, '/foo/bar'); $config->merge(array('config' => array( @@ -208,7 +208,7 @@ class ConfigTest extends TestCase $this->assertEquals('s3://baz', $config->get('cache-dir')); } - public function testFetchingRelativePaths() + public function testFetchingRelativePaths(): void { $config = new Config(false, '/foo/bar'); $config->merge(array('config' => array( @@ -222,7 +222,7 @@ class ConfigTest extends TestCase $this->assertEquals('vendor/foo', $config->get('bin-dir', Config::RELATIVE_PATHS)); } - public function testOverrideGithubProtocols() + public function testOverrideGithubProtocols(): void { $config = new Config(false); $config->merge(array('config' => array('github-protocols' => array('https', 'ssh')))); @@ -231,7 +231,7 @@ class ConfigTest extends TestCase $this->assertEquals(array('https'), $config->get('github-protocols')); } - public function testGitDisabledByDefaultInGithubProtocols() + public function testGitDisabledByDefaultInGithubProtocols(): void { $config = new Config(false); $config->merge(array('config' => array('github-protocols' => array('https', 'git')))); @@ -247,7 +247,7 @@ class ConfigTest extends TestCase * * @param string $url */ - public function testAllowedUrlsPass($url) + public function testAllowedUrlsPass($url): void { $config = new Config(false); $config->prohibitUrlByConfig($url); @@ -258,7 +258,7 @@ class ConfigTest extends TestCase * * @param string $url */ - public function testProhibitedUrlsThrowException($url) + public function testProhibitedUrlsThrowException($url): void { self::expectException('Composer\Downloader\TransportException'); self::expectExceptionMessage('Your configuration does not allow connections to ' . $url); @@ -269,7 +269,7 @@ class ConfigTest extends TestCase /** * @return string[][] List of test URLs that should pass strict security */ - public function allowedUrlProvider() + public function allowedUrlProvider(): array { $urls = array( 'https://packagist.org', @@ -282,7 +282,7 @@ class ConfigTest extends TestCase 'ssh://[user@]host.xz[:port]/path/to/repo.git/', ); - return array_combine($urls, array_map(function ($e) { + return array_combine($urls, array_map(function ($e): array { return array($e); }, $urls)); } @@ -290,7 +290,7 @@ class ConfigTest extends TestCase /** * @return string[][] List of test URLs that should not pass strict security */ - public function prohibitedUrlProvider() + public function prohibitedUrlProvider(): array { $urls = array( 'http://packagist.org', @@ -303,7 +303,7 @@ class ConfigTest extends TestCase 'git://5.6.7.8/git.git', ); - return array_combine($urls, array_map(function ($e) { + return array_combine($urls, array_map(function ($e): array { return array($e); }, $urls)); } @@ -311,7 +311,7 @@ class ConfigTest extends TestCase /** * @group TLS */ - public function testDisableTlsCanBeOverridden() + public function testDisableTlsCanBeOverridden(): void { $config = new Config; $config->merge( @@ -324,7 +324,7 @@ class ConfigTest extends TestCase $this->assertTrue($config->get('disable-tls')); } - public function testProcessTimeout() + public function testProcessTimeout(): void { Platform::putEnv('COMPOSER_PROCESS_TIMEOUT', '0'); $config = new Config(true); @@ -334,7 +334,7 @@ class ConfigTest extends TestCase $this->assertEquals(0, $result); } - public function testHtaccessProtect() + public function testHtaccessProtect(): void { Platform::putEnv('COMPOSER_HTACCESS_PROTECT', '0'); $config = new Config(true); @@ -344,7 +344,7 @@ class ConfigTest extends TestCase $this->assertEquals(0, $result); } - public function testGetSourceOfValue() + public function testGetSourceOfValue(): void { Platform::clearEnv('COMPOSER_PROCESS_TIMEOUT'); @@ -360,7 +360,7 @@ class ConfigTest extends TestCase $this->assertSame('phpunit-test', $config->getSourceOfValue('process-timeout')); } - public function testGetSourceOfValueEnvVariables() + public function testGetSourceOfValueEnvVariables(): void { Platform::putEnv('COMPOSER_HTACCESS_PROTECT', '0'); $config = new Config; diff --git a/tests/Composer/Test/Console/HtmlOutputFormatterTest.php b/tests/Composer/Test/Console/HtmlOutputFormatterTest.php index a105eec0d..60865f726 100644 --- a/tests/Composer/Test/Console/HtmlOutputFormatterTest.php +++ b/tests/Composer/Test/Console/HtmlOutputFormatterTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Console\Formatter\OutputFormatterStyle; class HtmlOutputFormatterTest extends TestCase { - public function testFormatting() + public function testFormatting(): void { $formatter = new HtmlOutputFormatter(array( 'warning' => new OutputFormatterStyle('black', 'yellow'), diff --git a/tests/Composer/Test/DefaultConfigTest.php b/tests/Composer/Test/DefaultConfigTest.php index 2aeeb783e..0b5f694ea 100644 --- a/tests/Composer/Test/DefaultConfigTest.php +++ b/tests/Composer/Test/DefaultConfigTest.php @@ -19,7 +19,7 @@ class DefaultConfigTest extends TestCase /** * @group TLS */ - public function testDefaultValuesAreAsExpected() + public function testDefaultValuesAreAsExpected(): void { $config = new Config; $this->assertFalse($config->get('disable-tls')); diff --git a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php index 9703706d5..27569baee 100644 --- a/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php +++ b/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php @@ -41,7 +41,7 @@ class DefaultPolicyTest extends TestCase $this->policy = new DefaultPolicy; } - public function testSelectSingle() + public function testSelectSingle(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repositorySet->addRepository($this->repo); @@ -56,7 +56,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectNewest() + public function testSelectNewest(): void { $this->repo->addPackage($packageA1 = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageA2 = $this->getPackage('A', '2.0')); @@ -72,7 +72,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectNewestPicksLatest() + public function testSelectNewestPicksLatest(): void { $this->repo->addPackage($packageA1 = $this->getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = $this->getPackage('A', '1.0.1-alpha')); @@ -88,7 +88,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectNewestPicksLatestStableWithPreferStable() + public function testSelectNewestPicksLatestStableWithPreferStable(): void { $this->repo->addPackage($packageA1 = $this->getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = $this->getPackage('A', '1.0.1-alpha')); @@ -105,7 +105,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectNewestWithDevPicksNonDev() + public function testSelectNewestWithDevPicksNonDev(): void { $this->repo->addPackage($packageA1 = $this->getPackage('A', 'dev-foo')); $this->repo->addPackage($packageA2 = $this->getPackage('A', '1.0.0')); @@ -121,7 +121,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testRepositoryOrderingAffectsPriority() + public function testRepositoryOrderingAffectsPriority(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; @@ -154,7 +154,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectLocalReposFirst() + public function testSelectLocalReposFirst(): void { $repoImportant = new ArrayRepository; @@ -185,7 +185,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectAllProviders() + public function testSelectAllProviders(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '2.0')); @@ -205,7 +205,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testPreferNonReplacingFromSameRepo() + public function testPreferNonReplacingFromSameRepo(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '2.0')); @@ -224,7 +224,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testPreferReplacingPackageFromSameVendor() + public function testPreferReplacingPackageFromSameVendor(): void { // test with default order $this->repo->addPackage($packageB = $this->getPackage('vendor-b/replacer', '1.0')); @@ -260,7 +260,7 @@ class DefaultPolicyTest extends TestCase $this->assertSame($expected, $selected); } - public function testSelectLowest() + public function testSelectLowest(): void { $policy = new DefaultPolicy(false, true); diff --git a/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php b/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php index a3a911e46..92b9840a8 100644 --- a/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php @@ -44,13 +44,13 @@ class PoolBuilderTest extends TestCase * @param mixed[] $packageRepos * @param mixed[] $fixed */ - public function testPoolBuilder($file, $message, $expect, $expectOptimized, $root, $requestData, $packageRepos, $fixed) + public function testPoolBuilder($file, $message, $expect, $expectOptimized, $root, $requestData, $packageRepos, $fixed): void { $rootAliases = !empty($root['aliases']) ? $root['aliases'] : array(); $minimumStability = !empty($root['minimum-stability']) ? $root['minimum-stability'] : 'stable'; $stabilityFlags = !empty($root['stability-flags']) ? $root['stability-flags'] : array(); $rootReferences = !empty($root['references']) ? $root['references'] : array(); - $stabilityFlags = array_map(function ($stability) { + $stabilityFlags = array_map(function ($stability): int { return BasePackage::$stabilities[$stability]; }, $stabilityFlags); @@ -62,7 +62,7 @@ class PoolBuilderTest extends TestCase $loader = new ArrayLoader(null, true); $packageIds = array(); - $loadPackage = function ($data) use ($loader, &$packageIds) { + $loadPackage = function ($data) use ($loader, &$packageIds): \Composer\Package\PackageInterface { /** @var ?int $id */ $id = null; if (!empty($data['id'])) { @@ -149,7 +149,7 @@ class PoolBuilderTest extends TestCase * @param array $packageIds * @return string[] */ - private function getPackageResultSet(Pool $pool, $packageIds) + private function getPackageResultSet(Pool $pool, $packageIds): array { $result = array(); for ($i = 1, $count = count($pool); $i <= $count; $i++) { @@ -184,7 +184,7 @@ class PoolBuilderTest extends TestCase /** * @return array> */ - public function getIntegrationTests() + public function getIntegrationTests(): array { $fixturesDir = realpath(__DIR__.'/Fixtures/poolbuilder/'); $tests = array(); @@ -223,7 +223,7 @@ class PoolBuilderTest extends TestCase * @param string $fixturesDir * @return array */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir) + protected function readTestFile(\SplFileInfo $file, $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); diff --git a/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php b/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php index 442b156ef..1f78a4013 100644 --- a/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php @@ -34,7 +34,7 @@ class PoolOptimizerTest extends TestCase * @param BasePackage[] $expectedPackages * @param string $message */ - public function testPoolOptimizer(array $requestData, array $packagesBefore, array $expectedPackages, $message) + public function testPoolOptimizer(array $requestData, array $packagesBefore, array $expectedPackages, $message): void { $lockedRepo = new LockArrayRepository(); @@ -71,7 +71,7 @@ class PoolOptimizerTest extends TestCase ); } - public function provideIntegrationTests() + public function provideIntegrationTests(): array { $fixturesDir = realpath(__DIR__.'/Fixtures/pooloptimizer/'); $tests = array(); @@ -100,7 +100,7 @@ class PoolOptimizerTest extends TestCase * @param string $fixturesDir * @return mixed[] */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir) + protected function readTestFile(\SplFileInfo $file, $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); @@ -154,7 +154,7 @@ class PoolOptimizerTest extends TestCase * @param BasePackage[] $packages * @return string[] */ - private function reducePackagesInfoForComparison(array $packages) + private function reducePackagesInfoForComparison(array $packages): array { $packagesInfo = array(); @@ -171,7 +171,7 @@ class PoolOptimizerTest extends TestCase * @param mixed[][] $packagesData * @return BasePackage[] */ - private function loadPackages(array $packagesData) + private function loadPackages(array $packagesData): array { $packages = array(); @@ -189,7 +189,7 @@ class PoolOptimizerTest extends TestCase * @param mixed[] $packageData * @return BasePackage */ - private function loadPackage(array $packageData) + private function loadPackage(array $packageData): BasePackage { $loader = new ArrayLoader(); diff --git a/tests/Composer/Test/DependencyResolver/PoolTest.php b/tests/Composer/Test/DependencyResolver/PoolTest.php index 350a5cab8..c4c5185ae 100644 --- a/tests/Composer/Test/DependencyResolver/PoolTest.php +++ b/tests/Composer/Test/DependencyResolver/PoolTest.php @@ -17,7 +17,7 @@ use Composer\Test\TestCase; class PoolTest extends TestCase { - public function testPool() + public function testPool(): void { $package = $this->getPackage('foo', '1'); @@ -27,7 +27,7 @@ class PoolTest extends TestCase $this->assertEquals(array($package), $pool->whatProvides('foo')); } - public function testWhatProvidesPackageWithConstraint() + public function testWhatProvidesPackageWithConstraint(): void { $firstPackage = $this->getPackage('foo', '1'); $secondPackage = $this->getPackage('foo', '2'); @@ -41,7 +41,7 @@ class PoolTest extends TestCase $this->assertEquals(array($secondPackage), $pool->whatProvides('foo', $this->getVersionConstraint('==', '2'))); } - public function testPackageById() + public function testPackageById(): void { $package = $this->getPackage('foo', '1'); @@ -50,7 +50,7 @@ class PoolTest extends TestCase $this->assertSame($package, $pool->packageById(1)); } - public function testWhatProvidesWhenPackageCannotBeFound() + public function testWhatProvidesWhenPackageCannotBeFound(): void { $pool = $this->createPool(); @@ -61,7 +61,7 @@ class PoolTest extends TestCase * @param array<\Composer\Package\BasePackage>|null $packages * @return \Composer\DependencyResolver\Pool */ - protected function createPool($packages = array()) + protected function createPool($packages = array()): \Composer\DependencyResolver\Pool { return new Pool($packages); } diff --git a/tests/Composer/Test/DependencyResolver/RequestTest.php b/tests/Composer/Test/DependencyResolver/RequestTest.php index a93bc404b..c3fff4a0e 100644 --- a/tests/Composer/Test/DependencyResolver/RequestTest.php +++ b/tests/Composer/Test/DependencyResolver/RequestTest.php @@ -19,7 +19,7 @@ use Composer\Test\TestCase; class RequestTest extends TestCase { - public function testRequestInstall() + public function testRequestInstall(): void { $repo = new ArrayRepository; $foo = $this->getPackage('foo', '1'); @@ -41,7 +41,7 @@ class RequestTest extends TestCase ); } - public function testRequestInstallSamePackageFromDifferentRepositories() + public function testRequestInstallSamePackageFromDifferentRepositories(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; diff --git a/tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php b/tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php index 3f2429024..807311882 100644 --- a/tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php +++ b/tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php @@ -43,7 +43,7 @@ class RuleSetIteratorTest extends TestCase ); } - public function testForeach() + public function testForeach(): void { $ruleSetIterator = new RuleSetIterator($this->rules); @@ -61,7 +61,7 @@ class RuleSetIteratorTest extends TestCase $this->assertEquals($expected, $result); } - public function testKeys() + public function testKeys(): void { $ruleSetIterator = new RuleSetIterator($this->rules); diff --git a/tests/Composer/Test/DependencyResolver/RuleSetTest.php b/tests/Composer/Test/DependencyResolver/RuleSetTest.php index f25e3df4f..c891cb936 100644 --- a/tests/Composer/Test/DependencyResolver/RuleSetTest.php +++ b/tests/Composer/Test/DependencyResolver/RuleSetTest.php @@ -22,7 +22,7 @@ use Composer\Test\TestCase; class RuleSetTest extends TestCase { - public function testAdd() + public function testAdd(): void { $rules = array( RuleSet::TYPE_PACKAGE => array(), @@ -44,7 +44,7 @@ class RuleSetTest extends TestCase $this->assertEquals($rules, $ruleSet->getRules()); } - public function testAddIgnoresDuplicates() + public function testAddIgnoresDuplicates(): void { $rules = array( RuleSet::TYPE_REQUEST => array( @@ -63,7 +63,7 @@ class RuleSetTest extends TestCase $this->assertCount(1, $ruleSet->getIteratorFor(array(RuleSet::TYPE_REQUEST))); } - public function testAddWhenTypeIsNotRecognized() + public function testAddWhenTypeIsNotRecognized(): void { $ruleSet = new RuleSet; @@ -72,7 +72,7 @@ class RuleSetTest extends TestCase $ruleSet->add(new GenericRule(array(), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)), 7); } - public function testCount() + public function testCount(): void { $ruleSet = new RuleSet; @@ -82,7 +82,7 @@ class RuleSetTest extends TestCase $this->assertEquals(2, $ruleSet->count()); } - public function testRuleById() + public function testRuleById(): void { $ruleSet = new RuleSet; @@ -92,7 +92,7 @@ class RuleSetTest extends TestCase $this->assertSame($rule, $ruleSet->ruleById[0]); } - public function testGetIterator() + public function testGetIterator(): void { $ruleSet = new RuleSet; @@ -108,7 +108,7 @@ class RuleSetTest extends TestCase $this->assertSame($rule2, $iterator->current()); } - public function testGetIteratorFor() + public function testGetIteratorFor(): void { $ruleSet = new RuleSet; $rule1 = new GenericRule(array(1), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -122,7 +122,7 @@ class RuleSetTest extends TestCase $this->assertSame($rule2, $iterator->current()); } - public function testGetIteratorWithout() + public function testGetIteratorWithout(): void { $ruleSet = new RuleSet; $rule1 = new GenericRule(array(1), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -136,7 +136,7 @@ class RuleSetTest extends TestCase $this->assertSame($rule2, $iterator->current()); } - public function testPrettyString() + public function testPrettyString(): void { $pool = new Pool(array( $p = $this->getPackage('foo', '2.1'), diff --git a/tests/Composer/Test/DependencyResolver/RuleTest.php b/tests/Composer/Test/DependencyResolver/RuleTest.php index 18f57c685..ed1401936 100644 --- a/tests/Composer/Test/DependencyResolver/RuleTest.php +++ b/tests/Composer/Test/DependencyResolver/RuleTest.php @@ -22,7 +22,7 @@ use Composer\Test\TestCase; class RuleTest extends TestCase { - public function testGetHash() + public function testGetHash(): void { $rule = new GenericRule(array(123), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -30,7 +30,7 @@ class RuleTest extends TestCase $this->assertEquals($hash['hash'], $rule->getHash()); } - public function testEqualsForRulesWithDifferentHashes() + public function testEqualsForRulesWithDifferentHashes(): void { $rule = new GenericRule(array(1, 2), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule2 = new GenericRule(array(1, 3), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -38,7 +38,7 @@ class RuleTest extends TestCase $this->assertFalse($rule->equals($rule2)); } - public function testEqualsForRulesWithDifferLiteralsQuantity() + public function testEqualsForRulesWithDifferLiteralsQuantity(): void { $rule = new GenericRule(array(1, 12), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule2 = new GenericRule(array(1), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -46,7 +46,7 @@ class RuleTest extends TestCase $this->assertFalse($rule->equals($rule2)); } - public function testEqualsForRulesWithSameLiterals() + public function testEqualsForRulesWithSameLiterals(): void { $rule = new GenericRule(array(1, 12), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule2 = new GenericRule(array(1, 12), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -54,7 +54,7 @@ class RuleTest extends TestCase $this->assertTrue($rule->equals($rule2)); } - public function testSetAndGetType() + public function testSetAndGetType(): void { $rule = new GenericRule(array(), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule->setType(RuleSet::TYPE_REQUEST); @@ -62,7 +62,7 @@ class RuleTest extends TestCase $this->assertEquals(RuleSet::TYPE_REQUEST, $rule->getType()); } - public function testEnable() + public function testEnable(): void { $rule = new GenericRule(array(), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule->disable(); @@ -72,7 +72,7 @@ class RuleTest extends TestCase $this->assertFalse($rule->isDisabled()); } - public function testDisable() + public function testDisable(): void { $rule = new GenericRule(array(), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule->enable(); @@ -82,7 +82,7 @@ class RuleTest extends TestCase $this->assertFalse($rule->isEnabled()); } - public function testIsAssertions() + public function testIsAssertions(): void { $rule = new GenericRule(array(1, 12), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); $rule2 = new GenericRule(array(1), Rule::RULE_ROOT_REQUIRE, array('packageName' => '', 'constraint' => new MatchAllConstraint)); @@ -91,7 +91,7 @@ class RuleTest extends TestCase $this->assertTrue($rule2->isAssertion()); } - public function testPrettyString() + public function testPrettyString(): void { $pool = new Pool(array( $p1 = $this->getPackage('foo', '2.1'), diff --git a/tests/Composer/Test/DependencyResolver/SolverTest.php b/tests/Composer/Test/DependencyResolver/SolverTest.php index e6e51c2fb..f63e5167e 100644 --- a/tests/Composer/Test/DependencyResolver/SolverTest.php +++ b/tests/Composer/Test/DependencyResolver/SolverTest.php @@ -58,7 +58,7 @@ class SolverTest extends TestCase $this->policy = new DefaultPolicy; } - public function testSolverInstallSingle() + public function testSolverInstallSingle(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->reposComplete(); @@ -70,7 +70,7 @@ class SolverTest extends TestCase )); } - public function testSolverRemoveIfNotRequested() + public function testSolverRemoveIfNotRequested(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->reposComplete(); @@ -80,7 +80,7 @@ class SolverTest extends TestCase )); } - public function testInstallNonExistingPackageFails() + public function testInstallNonExistingPackageFails(): void { $this->repo->addPackage($this->getPackage('A', '1.0')); $this->reposComplete(); @@ -99,7 +99,7 @@ class SolverTest extends TestCase } } - public function testSolverInstallSamePackageFromDifferentRepositories() + public function testSolverInstallSamePackageFromDifferentRepositories(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; @@ -117,7 +117,7 @@ class SolverTest extends TestCase )); } - public function testSolverInstallWithDeps() + public function testSolverInstallWithDeps(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -135,7 +135,7 @@ class SolverTest extends TestCase )); } - public function testSolverInstallHonoursNotEqualOperator() + public function testSolverInstallHonoursNotEqualOperator(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -161,7 +161,7 @@ class SolverTest extends TestCase )); } - public function testSolverInstallWithDepsInOrder() + public function testSolverInstallWithDepsInOrder(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -207,7 +207,7 @@ class SolverTest extends TestCase * * CAUTION: IF THIS TEST EVER FAILS, SOLVER BEHAVIOR HAS CHANGED AND MAY BREAK DOWNSTREAM USERS */ - public function testSolverMultiPackageNameVersionResolutionDependsOnRequireOrder() + public function testSolverMultiPackageNameVersionResolutionDependsOnRequireOrder(): void { $this->repo->addPackage($php74 = $this->getPackage('ourcustom/PHP', '7.4.23')); $this->repo->addPackage($php80 = $this->getPackage('ourcustom/PHP', '8.0.10')); @@ -256,7 +256,7 @@ class SolverTest extends TestCase * * CAUTION: IF THIS TEST EVER FAILS, SOLVER BEHAVIOR HAS CHANGED AND MAY BREAK DOWNSTREAM USERS */ - public function testSolverMultiPackageNameVersionResolutionIsIndependentOfRequireOrderIfOrderedDescendingByRequirement() + public function testSolverMultiPackageNameVersionResolutionIsIndependentOfRequireOrderIfOrderedDescendingByRequirement(): void { $this->repo->addPackage($php74 = $this->getPackage('ourcustom/PHP', '7.4')); $this->repo->addPackage($php80 = $this->getPackage('ourcustom/PHP', '8.0')); @@ -297,7 +297,7 @@ class SolverTest extends TestCase )); } - public function testSolverFixLocked() + public function testSolverFixLocked(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->reposComplete(); @@ -307,7 +307,7 @@ class SolverTest extends TestCase $this->checkSolverResult(array()); } - public function testSolverFixLockedWithAlternative() + public function testSolverFixLockedWithAlternative(): void { $this->repo->addPackage($this->getPackage('A', '1.0')); $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); @@ -318,7 +318,7 @@ class SolverTest extends TestCase $this->checkSolverResult(array()); } - public function testSolverUpdateDoesOnlyUpdate() + public function testSolverUpdateDoesOnlyUpdate(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -335,7 +335,7 @@ class SolverTest extends TestCase )); } - public function testSolverUpdateSingle() + public function testSolverUpdateSingle(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = $this->getPackage('A', '1.1')); @@ -348,7 +348,7 @@ class SolverTest extends TestCase )); } - public function testSolverUpdateAll() + public function testSolverUpdateAll(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -368,7 +368,7 @@ class SolverTest extends TestCase )); } - public function testSolverUpdateCurrent() + public function testSolverUpdateCurrent(): void { $this->repoLocked->addPackage($this->getPackage('A', '1.0')); $this->repo->addPackage($this->getPackage('A', '1.0')); @@ -379,7 +379,7 @@ class SolverTest extends TestCase $this->checkSolverResult(array()); } - public function testSolverUpdateOnlyUpdatesSelectedPackage() + public function testSolverUpdateOnlyUpdatesSelectedPackage(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -396,7 +396,7 @@ class SolverTest extends TestCase )); } - public function testSolverUpdateConstrained() + public function testSolverUpdateConstrained(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = $this->getPackage('A', '1.2')); @@ -412,7 +412,7 @@ class SolverTest extends TestCase ))); } - public function testSolverUpdateFullyConstrained() + public function testSolverUpdateFullyConstrained(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = $this->getPackage('A', '1.2')); @@ -428,7 +428,7 @@ class SolverTest extends TestCase ))); } - public function testSolverUpdateFullyConstrainedPrunesInstalledPackages() + public function testSolverUpdateFullyConstrainedPrunesInstalledPackages(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -451,7 +451,7 @@ class SolverTest extends TestCase )); } - public function testSolverAllJobs() + public function testSolverAllJobs(): void { $this->repoLocked->addPackage($packageD = $this->getPackage('D', '1.0')); $this->repoLocked->addPackage($oldPackageC = $this->getPackage('C', '1.0')); @@ -476,7 +476,7 @@ class SolverTest extends TestCase )); } - public function testSolverThreeAlternativeRequireAndConflict() + public function testSolverThreeAlternativeRequireAndConflict(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '2.0')); $this->repo->addPackage($middlePackageB = $this->getPackage('B', '1.0')); @@ -495,7 +495,7 @@ class SolverTest extends TestCase )); } - public function testSolverObsolete() + public function testSolverObsolete(): void { $this->repoLocked->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -511,7 +511,7 @@ class SolverTest extends TestCase )); } - public function testInstallOneOfTwoAlternatives() + public function testInstallOneOfTwoAlternatives(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('A', '1.0')); @@ -525,7 +525,7 @@ class SolverTest extends TestCase )); } - public function testInstallProvider() + public function testInstallProvider(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageQ = $this->getPackage('Q', '1.0')); @@ -542,7 +542,7 @@ class SolverTest extends TestCase $this->solver->solve($this->request); } - public function testSkipReplacerOfExistingPackage() + public function testSkipReplacerOfExistingPackage(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageQ = $this->getPackage('Q', '1.0')); @@ -560,7 +560,7 @@ class SolverTest extends TestCase )); } - public function testNoInstallReplacerOfMissingPackage() + public function testNoInstallReplacerOfMissingPackage(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageQ = $this->getPackage('Q', '1.0')); @@ -576,7 +576,7 @@ class SolverTest extends TestCase $this->solver->solve($this->request); } - public function testSkipReplacedPackageIfReplacerIsSelected() + public function testSkipReplacedPackageIfReplacerIsSelected(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageQ = $this->getPackage('Q', '1.0')); @@ -595,7 +595,7 @@ class SolverTest extends TestCase )); } - public function testPickOlderIfNewerConflicts() + public function testPickOlderIfNewerConflicts(): void { $this->repo->addPackage($packageX = $this->getPackage('X', '1.0')); $packageX->setRequires(array( @@ -633,7 +633,7 @@ class SolverTest extends TestCase )); } - public function testInstallCircularRequire() + public function testInstallCircularRequire(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB1 = $this->getPackage('B', '0.9')); @@ -651,7 +651,7 @@ class SolverTest extends TestCase )); } - public function testInstallAlternativeWithCircularRequire() + public function testInstallAlternativeWithCircularRequire(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -681,7 +681,7 @@ class SolverTest extends TestCase * If a replacer D replaces B and C with C not otherwise available, * D must be installed instead of the original B. */ - public function testUseReplacerIfNecessary() + public function testUseReplacerIfNecessary(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -714,7 +714,7 @@ class SolverTest extends TestCase )); } - public function testIssue265() + public function testIssue265(): void { $this->repo->addPackage($packageA1 = $this->getPackage('A', '2.0.999999-dev')); $this->repo->addPackage($packageA2 = $this->getPackage('A', '2.1-dev')); @@ -749,7 +749,7 @@ class SolverTest extends TestCase $this->solver->solve($this->request); } - public function testConflictResultEmpty() + public function testConflictResultEmpty(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -782,7 +782,7 @@ class SolverTest extends TestCase } } - public function testUnsatisfiableRequires() + public function testUnsatisfiableRequires(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -812,7 +812,7 @@ class SolverTest extends TestCase } } - public function testRequireMismatchException() + public function testRequireMismatchException(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -860,7 +860,7 @@ class SolverTest extends TestCase } } - public function testLearnLiteralsWithSortedRuleLiterals() + public function testLearnLiteralsWithSortedRuleLiterals(): void { $this->repo->addPackage($packageTwig2 = $this->getPackage('twig/twig', '2.0')); $this->repo->addPackage($packageTwig16 = $this->getPackage('twig/twig', '1.6')); @@ -887,7 +887,7 @@ class SolverTest extends TestCase )); } - public function testInstallRecursiveAliasDependencies() + public function testInstallRecursiveAliasDependencies(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '2.0')); @@ -913,7 +913,7 @@ class SolverTest extends TestCase )); } - public function testInstallDevAlias() + public function testInstallDevAlias(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '2.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -936,7 +936,7 @@ class SolverTest extends TestCase )); } - public function testInstallRootAliasesIfAliasOfIsInstalled() + public function testInstallRootAliasesIfAliasOfIsInstalled(): void { // root aliased, required $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); @@ -975,7 +975,7 @@ class SolverTest extends TestCase * In particular in this case the goal is to first have the solver decide X 2.0 should not be installed to later * decide to learn that X 2.0 must be installed and revert decisions to retry solving with this new assumption. */ - public function testLearnPositiveLiteral() + public function testLearnPositiveLiteral(): void { $this->repo->addPackage($packageA = $this->getPackage('A', '1.0')); $this->repo->addPackage($packageB = $this->getPackage('B', '1.0')); @@ -1042,7 +1042,7 @@ class SolverTest extends TestCase /** * @return void */ - protected function reposComplete() + protected function reposComplete(): void { $this->repoSet->addRepository($this->repo); $this->repoSet->addRepository($this->repoLocked); @@ -1051,7 +1051,7 @@ class SolverTest extends TestCase /** * @return void */ - protected function createSolver() + protected function createSolver(): void { $io = new NullIO(); $this->pool = $this->repoSet->createPool($this->request, $io); @@ -1062,7 +1062,7 @@ class SolverTest extends TestCase * @param array> $expected * @return void */ - protected function checkSolverResult(array $expected) + protected function checkSolverResult(array $expected): void { $this->createSolver(); $transaction = $this->solver->solve($this->request); diff --git a/tests/Composer/Test/DependencyResolver/TransactionTest.php b/tests/Composer/Test/DependencyResolver/TransactionTest.php index 4c19a6098..703fecf56 100644 --- a/tests/Composer/Test/DependencyResolver/TransactionTest.php +++ b/tests/Composer/Test/DependencyResolver/TransactionTest.php @@ -27,7 +27,7 @@ class TransactionTest extends TestCase { } - public function testTransactionGenerationAndSorting() + public function testTransactionGenerationAndSorting(): void { $presentPackages = array( $packageA = $this->getPackage('a/a', 'dev-master'), @@ -103,7 +103,7 @@ class TransactionTest extends TestCase * @param array> $expected * @return void */ - protected function checkTransactionOperations(Transaction $transaction, array $expected) + protected function checkTransactionOperations(Transaction $transaction, array $expected): void { $result = array(); foreach ($transaction->getOperations() as $operation) { diff --git a/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php b/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php index 9537e462a..00e31a3cb 100644 --- a/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ArchiveDownloaderTest.php @@ -19,7 +19,7 @@ class ArchiveDownloaderTest extends TestCase /** @var \Composer\Config&\PHPUnit\Framework\MockObject\MockObject */ protected $config; - public function testGetFileName() + public function testGetFileName(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -41,7 +41,7 @@ class ArchiveDownloaderTest extends TestCase $this->assertSame($first, $method->invoke($downloader, $packageMock, '/path')); } - public function testProcessUrl() + public function testProcessUrl(): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -57,7 +57,7 @@ class ArchiveDownloaderTest extends TestCase $this->assertEquals($expected, $url); } - public function testProcessUrl2() + public function testProcessUrl2(): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -73,7 +73,7 @@ class ArchiveDownloaderTest extends TestCase $this->assertEquals($expected, $url); } - public function testProcessUrl3() + public function testProcessUrl3(): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -93,7 +93,7 @@ class ArchiveDownloaderTest extends TestCase * @dataProvider provideUrls * @param string $url */ - public function testProcessUrlRewriteDist($url) + public function testProcessUrlRewriteDist($url): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -115,7 +115,7 @@ class ArchiveDownloaderTest extends TestCase $this->assertEquals($expected, $url); } - public function provideUrls() + public function provideUrls(): array { return array( array('https://api.github.com/repos/composer/composer/zipball/master'), @@ -132,7 +132,7 @@ class ArchiveDownloaderTest extends TestCase * @param string $url * @param string $extension */ - public function testProcessUrlRewriteBitbucketDist($url, $extension) + public function testProcessUrlRewriteBitbucketDist($url, $extension): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -154,7 +154,7 @@ class ArchiveDownloaderTest extends TestCase $this->assertEquals($expected, $url); } - public function provideBitbucketUrls() + public function provideBitbucketUrls(): array { return array( array('https://bitbucket.org/davereid/drush-virtualhost/get/77ca490c26ac818e024d1138aa8bd3677d1ef21f', 'zip'), diff --git a/tests/Composer/Test/Downloader/DownloadManagerTest.php b/tests/Composer/Test/Downloader/DownloadManagerTest.php index 7c84a1c9b..b3eb77c26 100644 --- a/tests/Composer/Test/Downloader/DownloadManagerTest.php +++ b/tests/Composer/Test/Downloader/DownloadManagerTest.php @@ -30,7 +30,7 @@ class DownloadManagerTest extends TestCase $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); } - public function testSetGetDownloader() + public function testSetGetDownloader(): void { $downloader = $this->createDownloaderMock(); $manager = new DownloadManager($this->io, false, $this->filesystem); @@ -42,7 +42,7 @@ class DownloadManagerTest extends TestCase $manager->getDownloader('unregistered'); } - public function testGetDownloaderForIncorrectlyInstalledPackage() + public function testGetDownloaderForIncorrectlyInstalledPackage(): void { $package = $this->createPackageMock(); $package @@ -57,7 +57,7 @@ class DownloadManagerTest extends TestCase $manager->getDownloaderForPackage($package); } - public function testGetDownloaderForCorrectlyInstalledDistPackage() + public function testGetDownloaderForCorrectlyInstalledDistPackage(): void { $package = $this->createPackageMock(); $package @@ -89,7 +89,7 @@ class DownloadManagerTest extends TestCase $this->assertSame($downloader, $manager->getDownloaderForPackage($package)); } - public function testGetDownloaderForIncorrectlyInstalledDistPackage() + public function testGetDownloaderForIncorrectlyInstalledDistPackage(): void { $package = $this->createPackageMock(); $package @@ -123,7 +123,7 @@ class DownloadManagerTest extends TestCase $manager->getDownloaderForPackage($package); } - public function testGetDownloaderForCorrectlyInstalledSourcePackage() + public function testGetDownloaderForCorrectlyInstalledSourcePackage(): void { $package = $this->createPackageMock(); $package @@ -155,7 +155,7 @@ class DownloadManagerTest extends TestCase $this->assertSame($downloader, $manager->getDownloaderForPackage($package)); } - public function testGetDownloaderForIncorrectlyInstalledSourcePackage() + public function testGetDownloaderForIncorrectlyInstalledSourcePackage(): void { $package = $this->createPackageMock(); $package @@ -189,7 +189,7 @@ class DownloadManagerTest extends TestCase $manager->getDownloaderForPackage($package); } - public function testGetDownloaderForMetapackage() + public function testGetDownloaderForMetapackage(): void { $package = $this->createPackageMock(); $package @@ -202,7 +202,7 @@ class DownloadManagerTest extends TestCase $this->assertNull($manager->getDownloaderForPackage($package)); } - public function testFullPackageDownload() + public function testFullPackageDownload(): void { $package = $this->createPackageMock(); $package @@ -238,7 +238,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testFullPackageDownloadFailover() + public function testFullPackageDownloadFailover(): void { $package = $this->createPackageMock(); $package @@ -291,7 +291,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testBadPackageDownload() + public function testBadPackageDownload(): void { $package = $this->createPackageMock(); $package @@ -309,7 +309,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testDistOnlyPackageDownload() + public function testDistOnlyPackageDownload(): void { $package = $this->createPackageMock(); $package @@ -345,7 +345,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testSourceOnlyPackageDownload() + public function testSourceOnlyPackageDownload(): void { $package = $this->createPackageMock(); $package @@ -381,7 +381,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testMetapackagePackageDownload() + public function testMetapackagePackageDownload(): void { $package = $this->createPackageMock(); $package @@ -411,7 +411,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testFullPackageDownloadWithSourcePreferred() + public function testFullPackageDownloadWithSourcePreferred(): void { $package = $this->createPackageMock(); $package @@ -448,7 +448,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testDistOnlyPackageDownloadWithSourcePreferred() + public function testDistOnlyPackageDownloadWithSourcePreferred(): void { $package = $this->createPackageMock(); $package @@ -485,7 +485,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testSourceOnlyPackageDownloadWithSourcePreferred() + public function testSourceOnlyPackageDownloadWithSourcePreferred(): void { $package = $this->createPackageMock(); $package @@ -522,7 +522,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testBadPackageDownloadWithSourcePreferred() + public function testBadPackageDownloadWithSourcePreferred(): void { $package = $this->createPackageMock(); $package @@ -541,7 +541,7 @@ class DownloadManagerTest extends TestCase $manager->download($package, 'target_dir'); } - public function testUpdateDistWithEqualTypes() + public function testUpdateDistWithEqualTypes(): void { $initial = $this->createPackageMock(); $initial @@ -579,7 +579,7 @@ class DownloadManagerTest extends TestCase $manager->update($initial, $target, 'vendor/bundles/FOS/UserBundle'); } - public function testUpdateDistWithNotEqualTypes() + public function testUpdateDistWithNotEqualTypes(): void { $initial = $this->createPackageMock(); $initial @@ -636,7 +636,7 @@ class DownloadManagerTest extends TestCase * @param bool $targetIsDev * @param string[] $expected */ - public function testGetAvailableSourcesUpdateSticksToSameSource($prevPkgSource, $prevPkgIsDev, $targetAvailable, $targetIsDev, $expected) + public function testGetAvailableSourcesUpdateSticksToSameSource($prevPkgSource, $prevPkgIsDev, $targetAvailable, $targetIsDev, $expected): void { $initial = null; if ($prevPkgSource) { @@ -666,7 +666,7 @@ class DownloadManagerTest extends TestCase $this->assertEquals($expected, $method->invoke($manager, $target, $initial ?? null)); } - public static function updatesProvider() + public static function updatesProvider(): array { return array( // prevPkg source, prevPkg isDev, pkg available, pkg isDev, expected @@ -689,7 +689,7 @@ class DownloadManagerTest extends TestCase ); } - public function testUpdateMetapackage() + public function testUpdateMetapackage(): void { $initial = $this->createPackageMock(); $target = $this->createPackageMock(); @@ -707,7 +707,7 @@ class DownloadManagerTest extends TestCase $manager->update($initial, $target, 'vendor/pkg'); } - public function testRemove() + public function testRemove(): void { $package = $this->createPackageMock(); @@ -730,7 +730,7 @@ class DownloadManagerTest extends TestCase $manager->remove($package, 'vendor/bundles/FOS/UserBundle'); } - public function testMetapackageRemove() + public function testMetapackageRemove(): void { $package = $this->createPackageMock(); @@ -750,7 +750,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithoutPreferenceDev() + public function testInstallPreferenceWithoutPreferenceDev(): void { $package = $this->createPackageMock(); $package @@ -793,7 +793,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithoutPreferenceNoDev() + public function testInstallPreferenceWithoutPreferenceNoDev(): void { $package = $this->createPackageMock(); $package @@ -836,7 +836,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithoutMatchDev() + public function testInstallPreferenceWithoutMatchDev(): void { $package = $this->createPackageMock(); $package @@ -883,7 +883,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithoutMatchNoDev() + public function testInstallPreferenceWithoutMatchNoDev(): void { $package = $this->createPackageMock(); $package @@ -930,7 +930,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithMatchAutoDev() + public function testInstallPreferenceWithMatchAutoDev(): void { $package = $this->createPackageMock(); $package @@ -977,7 +977,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithMatchAutoNoDev() + public function testInstallPreferenceWithMatchAutoNoDev(): void { $package = $this->createPackageMock(); $package @@ -1024,7 +1024,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithMatchSource() + public function testInstallPreferenceWithMatchSource(): void { $package = $this->createPackageMock(); $package @@ -1067,7 +1067,7 @@ class DownloadManagerTest extends TestCase /** * @covers Composer\Downloader\DownloadManager::resolvePackageInstallPreference */ - public function testInstallPreferenceWithMatchDist() + public function testInstallPreferenceWithMatchDist(): void { $package = $this->createPackageMock(); $package diff --git a/tests/Composer/Test/Downloader/FileDownloaderTest.php b/tests/Composer/Test/Downloader/FileDownloaderTest.php index 2ade50ce3..d3f9c0056 100644 --- a/tests/Composer/Test/Downloader/FileDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FileDownloaderTest.php @@ -43,7 +43,7 @@ class FileDownloaderTest extends TestCase * @param \Composer\Util\Filesystem $filesystem * @return \Composer\Downloader\FileDownloader */ - protected function getDownloader($io = null, $config = null, $eventDispatcher = null, $cache = null, $httpDownloader = null, $filesystem = null) + protected function getDownloader($io = null, $config = null, $eventDispatcher = null, $cache = null, $httpDownloader = null, $filesystem = null): \Composer\Downloader\FileDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->config; @@ -57,7 +57,7 @@ class FileDownloaderTest extends TestCase return new FileDownloader($io, $this->config, $httpDownloader, $eventDispatcher, $cache, $filesystem); } - public function testDownloadForPackageWithoutDistReference() + public function testDownloadForPackageWithoutDistReference(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->once()) @@ -71,7 +71,7 @@ class FileDownloaderTest extends TestCase $downloader->download($packageMock, '/path'); } - public function testDownloadToExistingFile() + public function testDownloadToExistingFile(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -101,7 +101,7 @@ class FileDownloaderTest extends TestCase } } - public function testGetFileName() + public function testGetFileName(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->once()) @@ -121,7 +121,7 @@ class FileDownloaderTest extends TestCase $this->assertMatchesRegularExpression('#/vendor/composer/tmp-[a-z0-9]+\.js#', $method->invoke($downloader, $packageMock, '/path')); } - public function testDownloadButFileIsUnsaved() + public function testDownloadButFileIsUnsaved(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -176,7 +176,7 @@ class FileDownloaderTest extends TestCase } } - public function testDownloadWithCustomProcessedUrl() + public function testDownloadWithCustomProcessedUrl(): void { $path = $this->getUniqueTmpDirectory(); @@ -218,7 +218,7 @@ class FileDownloaderTest extends TestCase $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getProcessExecutorMock() ); - $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($expectedUrl) { + $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($expectedUrl): void { $event->setProcessedUrl($expectedUrl); }); @@ -228,7 +228,7 @@ class FileDownloaderTest extends TestCase $cacheMock ->expects($this->any()) ->method('copyTo') - ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey) { + ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey): bool { $this->assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyTo method:'); return false; @@ -236,7 +236,7 @@ class FileDownloaderTest extends TestCase $cacheMock ->expects($this->any()) ->method('copyFrom') - ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey) { + ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey): bool { $this->assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyFrom method:'); return false; @@ -275,7 +275,7 @@ class FileDownloaderTest extends TestCase } } - public function testDownloadWithCustomCacheKey() + public function testDownloadWithCustomCacheKey(): void { $path = $this->getUniqueTmpDirectory(); @@ -318,7 +318,7 @@ class FileDownloaderTest extends TestCase $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $this->getProcessExecutorMock() ); - $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($customCacheKey) { + $dispatcher->addListener(PluginEvents::PRE_FILE_DOWNLOAD, function (PreFileDownloadEvent $event) use ($customCacheKey): void { $event->setCustomCacheKey($customCacheKey); }); @@ -328,7 +328,7 @@ class FileDownloaderTest extends TestCase $cacheMock ->expects($this->any()) ->method('copyTo') - ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey) { + ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey): bool { $this->assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyTo method:'); return false; @@ -336,7 +336,7 @@ class FileDownloaderTest extends TestCase $cacheMock ->expects($this->any()) ->method('copyFrom') - ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey) { + ->will($this->returnCallback(function ($cacheKey) use ($expectedCacheKey): bool { $this->assertEquals($expectedCacheKey, $cacheKey, 'Failed assertion on $cacheKey argument of Cache::copyFrom method:'); return false; @@ -375,7 +375,7 @@ class FileDownloaderTest extends TestCase } } - public function testCacheGarbageCollectionIsCalled() + public function testCacheGarbageCollectionIsCalled(): void { $expectedTtl = '99999999'; @@ -403,7 +403,7 @@ class FileDownloaderTest extends TestCase $downloader = $this->getDownloader(null, $this->config, null, $cacheMock, null, null); } - public function testDownloadFileWithInvalidChecksum() + public function testDownloadFileWithInvalidChecksum(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -458,7 +458,7 @@ class FileDownloaderTest extends TestCase } } - public function testDowngradeShowsAppropriateMessage() + public function testDowngradeShowsAppropriateMessage(): void { $oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $oldPackage->expects($this->once()) diff --git a/tests/Composer/Test/Downloader/FossilDownloaderTest.php b/tests/Composer/Test/Downloader/FossilDownloaderTest.php index 7a5e84e61..2ba0e33f0 100644 --- a/tests/Composer/Test/Downloader/FossilDownloaderTest.php +++ b/tests/Composer/Test/Downloader/FossilDownloaderTest.php @@ -42,7 +42,7 @@ class FossilDownloaderTest extends TestCase * @param \Composer\Util\Filesystem $filesystem * @return FossilDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null) + protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): FossilDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); @@ -52,7 +52,7 @@ class FossilDownloaderTest extends TestCase return new FossilDownloader($io, $config, $executor, $filesystem); } - public function testInstallForPackageWithoutSourceReference() + public function testInstallForPackageWithoutSourceReference(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->once()) @@ -65,7 +65,7 @@ class FossilDownloaderTest extends TestCase $downloader->install($packageMock, '/path'); } - public function testInstall() + public function testInstall(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -86,7 +86,7 @@ class FossilDownloaderTest extends TestCase $downloader->install($packageMock, 'repo'); } - public function testUpdateforPackageWithoutSourceReference() + public function testUpdateforPackageWithoutSourceReference(): void { $initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); @@ -102,7 +102,7 @@ class FossilDownloaderTest extends TestCase $downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock); } - public function testUpdate() + public function testUpdate(): void { // Ensure file exists $file = $this->workingDir . '/.fslckout'; @@ -134,7 +134,7 @@ class FossilDownloaderTest extends TestCase $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); } - public function testRemove() + public function testRemove(): void { // Ensure file exists $file = $this->workingDir . '/.fslckout'; @@ -159,7 +159,7 @@ class FossilDownloaderTest extends TestCase $downloader->cleanup('uninstall', $packageMock, $this->workingDir); } - public function testGetInstallationSource() + public function testGetInstallationSource(): void { $downloader = $this->getDownloaderMock(null); diff --git a/tests/Composer/Test/Downloader/GitDownloaderTest.php b/tests/Composer/Test/Downloader/GitDownloaderTest.php index 9791fd1ee..fce2ba033 100644 --- a/tests/Composer/Test/Downloader/GitDownloaderTest.php +++ b/tests/Composer/Test/Downloader/GitDownloaderTest.php @@ -50,7 +50,7 @@ class GitDownloaderTest extends TestCase * @param string|bool $version * @return void */ - private function initGitVersion($version) + private function initGitVersion($version): void { // reset the static version cache $refl = new \ReflectionProperty('Composer\Util\Git', 'version'); @@ -62,7 +62,7 @@ class GitDownloaderTest extends TestCase * @param ?\Composer\Config $config * @return \Composer\Config */ - protected function setupConfig($config = null) + protected function setupConfig($config = null): \Composer\Config { if (!$config) { $config = new Config(); @@ -82,7 +82,7 @@ class GitDownloaderTest extends TestCase * @param \Composer\Util\Filesystem $filesystem * @return GitDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null) + protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): GitDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $executor = $executor ?: $this->getProcessExecutorMock(); @@ -92,7 +92,7 @@ class GitDownloaderTest extends TestCase return new GitDownloader($io, $config, $executor, $filesystem); } - public function testDownloadForPackageWithoutSourceReference() + public function testDownloadForPackageWithoutSourceReference(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->once()) @@ -108,7 +108,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('install', $packageMock, '/path'); } - public function testDownload() + public function testDownload(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -138,7 +138,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('install', $packageMock, 'composerPath'); } - public function testDownloadWithCache() + public function testDownloadWithCache(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -165,7 +165,7 @@ class GitDownloaderTest extends TestCase $process = $this->getProcessExecutorMock(); $process->expects(array( - array('cmd' => $this->winCompat(sprintf("git clone --mirror -- 'https://example.com/composer/composer' '%s'", $cachePath)), 'callback' => function () use ($cachePath) { + array('cmd' => $this->winCompat(sprintf("git clone --mirror -- 'https://example.com/composer/composer' '%s'", $cachePath)), 'callback' => function () use ($cachePath): void { @mkdir($cachePath, 0777, true); }), array('cmd' => 'git rev-parse --git-dir', 'stdout' => '.'), @@ -183,7 +183,7 @@ class GitDownloaderTest extends TestCase @rmdir($cachePath); } - public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub() + public function testDownloadUsesVariousProtocolsAndSetsPushUrlForGithub(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -220,7 +220,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('install', $packageMock, 'composerPath'); } - public function pushUrlProvider() + public function pushUrlProvider(): array { return array( // ssh proto should use git@ all along @@ -238,7 +238,7 @@ class GitDownloaderTest extends TestCase * @param string $url * @param string $pushUrl */ - public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub($protocols, $url, $pushUrl) + public function testDownloadAndSetPushUrlUseCustomVariousProtocolsForGithub($protocols, $url, $pushUrl): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -272,7 +272,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('install', $packageMock, 'composerPath'); } - public function testDownloadThrowsRuntimeExceptionIfGitCommandFails() + public function testDownloadThrowsRuntimeExceptionIfGitCommandFails(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -313,7 +313,7 @@ class GitDownloaderTest extends TestCase } } - public function testUpdateforPackageWithoutSourceReference() + public function testUpdateforPackageWithoutSourceReference(): void { $initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); @@ -330,7 +330,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock); } - public function testUpdate() + public function testUpdate(): void { $expectedGitUpdateCommand = $this->winCompat("(git remote set-url composer -- 'https://github.com/composer/composer' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- 'https://github.com/composer/composer'"); @@ -367,7 +367,7 @@ class GitDownloaderTest extends TestCase $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); } - public function testUpdateWithNewRepoUrl() + public function testUpdateWithNewRepoUrl(): void { $expectedGitUpdateCommand = $this->winCompat("(git remote set-url composer -- 'https://github.com/composer/composer' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- 'https://github.com/composer/composer'"); @@ -419,7 +419,7 @@ composer https://github.com/old/url (push) /** * @group failing */ - public function testUpdateThrowsRuntimeExceptionIfGitCommandFails() + public function testUpdateThrowsRuntimeExceptionIfGitCommandFails(): void { $expectedGitUpdateCommand = $this->winCompat("(git remote set-url composer -- 'https://github.com/composer/composer' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- 'https://github.com/composer/composer'"); $expectedGitUpdateCommand2 = $this->winCompat("(git remote set-url composer -- 'git@github.com:composer/composer' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- 'git@github.com:composer/composer'"); @@ -470,7 +470,7 @@ composer https://github.com/old/url (push) } } - public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstButIsAbleToRecover() + public function testUpdateDoesntThrowsRuntimeExceptionIfGitCommandFailsAtFirstButIsAbleToRecover(): void { $expectedFirstGitUpdateCommand = $this->winCompat("(git remote set-url composer -- '".(Platform::isWindows() ? 'C:\\' : '/')."' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- '".(Platform::isWindows() ? 'C:\\' : '/')."'"); $expectedSecondGitUpdateCommand = $this->winCompat("(git remote set-url composer -- 'https://github.com/composer/composer' && git rev-parse --quiet --verify 'ref^{commit}' || (git fetch composer && git fetch --tags composer)) && git remote set-url composer -- 'https://github.com/composer/composer'"); @@ -517,7 +517,7 @@ composer https://github.com/old/url (push) $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); } - public function testDowngradeShowsAppropriateMessage() + public function testDowngradeShowsAppropriateMessage(): void { $oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $oldPackage->expects($this->any()) @@ -567,7 +567,7 @@ composer https://github.com/old/url (push) $downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage); } - public function testNotUsingDowngradingWithReferences() + public function testNotUsingDowngradingWithReferences(): void { $oldPackage = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $oldPackage->expects($this->any()) @@ -611,7 +611,7 @@ composer https://github.com/old/url (push) $downloader->cleanup('update', $newPackage, $this->workingDir, $oldPackage); } - public function testRemove() + public function testRemove(): void { $expectedGitResetCommand = $this->winCompat("git status --porcelain --untracked-files=no"); @@ -636,7 +636,7 @@ composer https://github.com/old/url (push) $downloader->cleanup('uninstall', $packageMock, $this->workingDir); } - public function testGetInstallationSource() + public function testGetInstallationSource(): void { $downloader = $this->getDownloaderMock(); @@ -647,7 +647,7 @@ composer https://github.com/old/url (push) * @param string $cmd * @return string */ - private function winCompat($cmd) + private function winCompat($cmd): string { if (Platform::isWindows()) { $cmd = str_replace('cd ', 'cd /D ', $cmd); diff --git a/tests/Composer/Test/Downloader/HgDownloaderTest.php b/tests/Composer/Test/Downloader/HgDownloaderTest.php index b2e555bab..81a039a24 100644 --- a/tests/Composer/Test/Downloader/HgDownloaderTest.php +++ b/tests/Composer/Test/Downloader/HgDownloaderTest.php @@ -42,7 +42,7 @@ class HgDownloaderTest extends TestCase * @param \Composer\Util\Filesystem $filesystem * @return HgDownloader */ - protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null) + protected function getDownloaderMock($io = null, $config = null, $executor = null, $filesystem = null): HgDownloader { $io = $io ?: $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $config = $config ?: $this->getMockBuilder('Composer\Config')->getMock(); @@ -52,7 +52,7 @@ class HgDownloaderTest extends TestCase return new HgDownloader($io, $config, $executor, $filesystem); } - public function testDownloadForPackageWithoutSourceReference() + public function testDownloadForPackageWithoutSourceReference(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->once()) @@ -65,7 +65,7 @@ class HgDownloaderTest extends TestCase $downloader->install($packageMock, '/path'); } - public function testDownload() + public function testDownload(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) @@ -85,7 +85,7 @@ class HgDownloaderTest extends TestCase $downloader->install($packageMock, 'composerPath'); } - public function testUpdateforPackageWithoutSourceReference() + public function testUpdateforPackageWithoutSourceReference(): void { $initialPackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $sourcePackageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); @@ -101,7 +101,7 @@ class HgDownloaderTest extends TestCase $downloader->cleanup('update', $sourcePackageMock, '/path', $initialPackageMock); } - public function testUpdate() + public function testUpdate(): void { $fs = new Filesystem; $fs->ensureDirectoryExists($this->workingDir.'/.hg'); @@ -128,7 +128,7 @@ class HgDownloaderTest extends TestCase $downloader->cleanup('update', $packageMock, $this->workingDir, $packageMock); } - public function testRemove() + public function testRemove(): void { $fs = new Filesystem; $fs->ensureDirectoryExists($this->workingDir.'/.hg'); @@ -151,7 +151,7 @@ class HgDownloaderTest extends TestCase $downloader->cleanup('uninstall', $packageMock, $this->workingDir); } - public function testGetInstallationSource() + public function testGetInstallationSource(): void { $downloader = $this->getDownloaderMock(null); diff --git a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php index ebcc0b662..16bd4d128 100644 --- a/tests/Composer/Test/Downloader/PerforceDownloaderTest.php +++ b/tests/Composer/Test/Downloader/PerforceDownloaderTest.php @@ -56,7 +56,7 @@ class PerforceDownloaderTest extends TestCase /** * @return \Composer\Config */ - protected function getConfig() + protected function getConfig(): \Composer\Config { $config = new Config(); $settings = array('config' => array('home' => $this->testPath)); @@ -87,7 +87,7 @@ class PerforceDownloaderTest extends TestCase /** * @return string[] */ - protected function getRepoConfig() + protected function getRepoConfig(): array { return array('url' => 'TEST_URL', 'p4user' => 'TEST_USER'); } @@ -112,12 +112,12 @@ class PerforceDownloaderTest extends TestCase /** * @doesNotPerformAssertions */ - public function testInitPerforceInstantiatesANewPerforceObject() + public function testInitPerforceInstantiatesANewPerforceObject(): void { $this->downloader->initPerforce($this->package, $this->testPath, 'SOURCE_REF'); } - public function testInitPerforceDoesNothingIfPerforceAlreadySet() + public function testInitPerforceDoesNothingIfPerforceAlreadySet(): void { $perforce = $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); $this->downloader->setPerforce($perforce); @@ -129,7 +129,7 @@ class PerforceDownloaderTest extends TestCase * @depends testInitPerforceInstantiatesANewPerforceObject * @depends testInitPerforceDoesNothingIfPerforceAlreadySet */ - public function testDoInstallWithTag() + public function testDoInstallWithTag(): void { //I really don't like this test but the logic of each Perforce method is tested in the Perforce class. Really I am just enforcing workflow. $ref = 'SOURCE_REF@123'; @@ -153,7 +153,7 @@ class PerforceDownloaderTest extends TestCase * @depends testInitPerforceInstantiatesANewPerforceObject * @depends testInitPerforceDoesNothingIfPerforceAlreadySet */ - public function testDoInstallWithNoTag() + public function testDoInstallWithNoTag(): void { $ref = 'SOURCE_REF'; $label = null; diff --git a/tests/Composer/Test/Downloader/XzDownloaderTest.php b/tests/Composer/Test/Downloader/XzDownloaderTest.php index cae7bf299..1f2501d37 100644 --- a/tests/Composer/Test/Downloader/XzDownloaderTest.php +++ b/tests/Composer/Test/Downloader/XzDownloaderTest.php @@ -49,7 +49,7 @@ class XzDownloaderTest extends TestCase $this->fs->removeDirectory($this->testDir); } - public function testErrorMessages() + public function testErrorMessages(): void { $packageMock = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); $packageMock->expects($this->any()) diff --git a/tests/Composer/Test/Downloader/ZipDownloaderTest.php b/tests/Composer/Test/Downloader/ZipDownloaderTest.php index 8ecb2719f..49e9dcda4 100644 --- a/tests/Composer/Test/Downloader/ZipDownloaderTest.php +++ b/tests/Composer/Test/Downloader/ZipDownloaderTest.php @@ -12,6 +12,7 @@ namespace Composer\Test\Downloader; +use React\Promise\PromiseInterface; use Composer\Downloader\ZipDownloader; use Composer\Package\PackageInterface; use Composer\Test\TestCase; @@ -56,7 +57,7 @@ class ZipDownloaderTest extends TestCase * @param ?\Composer\Test\Downloader\MockedZipDownloader $obj * @return void */ - public function setPrivateProperty($name, $value, $obj = null) + public function setPrivateProperty($name, $value, $obj = null): void { $reflectionClass = new \ReflectionClass('Composer\Downloader\ZipDownloader'); $reflectedProperty = $reflectionClass->getProperty($name); @@ -68,7 +69,7 @@ class ZipDownloaderTest extends TestCase } } - public function testErrorMessages() + public function testErrorMessages(): void { if (!class_exists('ZipArchive')) { $this->markTestSkipped('zip extension missing'); @@ -106,7 +107,7 @@ class ZipDownloaderTest extends TestCase } } - public function testZipArchiveOnlyFailed() + public function testZipArchiveOnlyFailed(): void { self::expectException('RuntimeException'); self::expectExceptionMessage('There was an error extracting the ZIP file'); @@ -129,7 +130,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testZipArchiveExtractOnlyFailed() + public function testZipArchiveExtractOnlyFailed(): void { self::expectException('RuntimeException'); self::expectExceptionMessage('The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems): Not a directory'); @@ -152,7 +153,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testZipArchiveOnlyGood() + public function testZipArchiveOnlyGood(): void { if (!class_exists('ZipArchive')) { $this->markTestSkipped('zip extension missing'); @@ -173,7 +174,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testSystemUnzipOnlyFailed() + public function testSystemUnzipOnlyFailed(): void { self::expectException('Exception'); self::expectExceptionMessage('Failed to extract : (1) unzip'); @@ -202,7 +203,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testSystemUnzipOnlyGood() + public function testSystemUnzipOnlyGood(): void { $this->setPrivateProperty('isWindows', false); $this->setPrivateProperty('hasZipArchive', false); @@ -229,7 +230,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testNonWindowsFallbackGood() + public function testNonWindowsFallbackGood(): void { if (!class_exists('ZipArchive')) { $this->markTestSkipped('zip extension missing'); @@ -268,7 +269,7 @@ class ZipDownloaderTest extends TestCase $this->wait($promise); } - public function testNonWindowsFallbackFailed() + public function testNonWindowsFallbackFailed(): void { self::expectException('Exception'); self::expectExceptionMessage('There was an error extracting the ZIP file'); @@ -313,16 +314,16 @@ class ZipDownloaderTest extends TestCase * @param ?\React\Promise\PromiseInterface $promise * @return void */ - private function wait($promise) + private function wait($promise): void { if (null === $promise) { return; } $e = null; - $promise->then(function () { + $promise->then(function (): void { // noop - }, function ($ex) use (&$e) { + }, function ($ex) use (&$e): void { $e = $ex; }); @@ -334,17 +335,17 @@ class ZipDownloaderTest extends TestCase class MockedZipDownloader extends ZipDownloader { - public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true) + public function download(PackageInterface $package, $path, PackageInterface $prevPackage = null, $output = true): ?PromiseInterface { return \React\Promise\resolve(); } - public function install(PackageInterface $package, $path, $output = true) + public function install(PackageInterface $package, $path, $output = true): PromiseInterface { return \React\Promise\resolve(); } - public function extract(PackageInterface $package, $file, $path) + public function extract(PackageInterface $package, $file, $path): ?PromiseInterface { return parent::extract($package, $file, $path); } diff --git a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php index 3217d8bf4..57b8efb5c 100644 --- a/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php +++ b/tests/Composer/Test/EventDispatcher/EventDispatcherTest.php @@ -28,7 +28,7 @@ use Symfony\Component\Console\Output\OutputInterface; class EventDispatcherTest extends TestCase { - public function testListenerExceptionsAreCaught() + public function testListenerExceptionsAreCaught(): void { self::expectException('RuntimeException'); @@ -56,7 +56,7 @@ class EventDispatcherTest extends TestCase * * @param string $command */ - public function testDispatcherCanExecuteSingleCommandLineScript($command) + public function testDispatcherCanExecuteSingleCommandLineScript($command): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -85,7 +85,7 @@ class EventDispatcherTest extends TestCase * * @param bool $devMode */ - public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($devMode) + public function testDispatcherPassDevModeToAutoloadGeneratorForScriptEvents($devMode): void { $composer = $this->createComposerInstance(); @@ -120,7 +120,7 @@ class EventDispatcherTest extends TestCase $dispatcher->hasEventListeners($event); } - public function provideDevModes() + public function provideDevModes(): array { return array( array(true), @@ -177,7 +177,7 @@ class EventDispatcherTest extends TestCase return $rm; } - public function testDispatcherRemoveListener() + public function testDispatcherRemoveListener(): void { $composer = $this->createComposerInstance(); @@ -220,7 +220,7 @@ class EventDispatcherTest extends TestCase $this->assertEquals($expected, $io->getOutput()); } - public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack() + public function testDispatcherCanExecuteCliAndPhpInSameEventScriptStack(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -257,7 +257,7 @@ class EventDispatcherTest extends TestCase $this->assertEquals($expected, $io->getOutput()); } - public function testDispatcherCanPutEnv() + public function testDispatcherCanPutEnv(): void { $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->setConstructorArgs(array( @@ -286,7 +286,7 @@ class EventDispatcherTest extends TestCase $this->assertEquals($expected, $io->getOutput()); } - public function testDispatcherAppendsDirBinOnPathForEveryListener() + public function testDispatcherAppendsDirBinOnPathForEveryListener(): void { $currentDirectoryBkp = getcwd(); $composerBinDirBkp = Platform::getEnv('COMPOSER_BIN_DIR'); @@ -323,7 +323,7 @@ class EventDispatcherTest extends TestCase /** * @return void */ - public static function createsVendorBinFolderChecksEnvDoesNotContainsBin() + public static function createsVendorBinFolderChecksEnvDoesNotContainsBin(): void { mkdir(__DIR__ . '/vendor/bin', 0700, true); $val = getenv('PATH'); @@ -338,7 +338,7 @@ class EventDispatcherTest extends TestCase /** * @return void */ - public static function createsVendorBinFolderChecksEnvContainsBin() + public static function createsVendorBinFolderChecksEnvContainsBin(): void { $val = getenv('PATH'); @@ -352,7 +352,7 @@ class EventDispatcherTest extends TestCase /** * @return void */ - public static function getTestEnv() + public static function getTestEnv(): void { $val = getenv('ABC'); if ($val !== '123') { @@ -360,7 +360,7 @@ class EventDispatcherTest extends TestCase } } - public function testDispatcherCanExecuteComposerScriptGroups() + public function testDispatcherCanExecuteComposerScriptGroups(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -382,7 +382,7 @@ class EventDispatcherTest extends TestCase $dispatcher->expects($this->atLeastOnce()) ->method('getListeners') - ->will($this->returnCallback(function (Event $event) { + ->will($this->returnCallback(function (Event $event): array { if ($event->getName() === 'root') { return array('@group'); } @@ -407,7 +407,7 @@ class EventDispatcherTest extends TestCase $this->assertEquals($expected, $io->getOutput()); } - public function testRecursionInScriptsNames() + public function testRecursionInScriptsNames(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -427,7 +427,7 @@ class EventDispatcherTest extends TestCase $dispatcher->expects($this->atLeastOnce()) ->method('getListeners') - ->will($this->returnCallback(function (Event $event) { + ->will($this->returnCallback(function (Event $event): array { if ($event->getName() === 'hello') { return array('echo Hello'); } @@ -446,7 +446,7 @@ class EventDispatcherTest extends TestCase $this->assertEquals($expected, $io->getOutput()); } - public function testDispatcherDetectInfiniteRecursion() + public function testDispatcherDetectInfiniteRecursion(): void { self::expectException('RuntimeException'); @@ -463,7 +463,7 @@ class EventDispatcherTest extends TestCase $dispatcher->expects($this->atLeastOnce()) ->method('getListeners') - ->will($this->returnCallback(function (Event $event) { + ->will($this->returnCallback(function (Event $event): array { if ($event->getName() === 'root') { return array('@recurse'); } @@ -500,7 +500,7 @@ class EventDispatcherTest extends TestCase return $dispatcher; } - public function provideValidCommands() + public function provideValidCommands(): array { return array( array('phpunit'), @@ -509,7 +509,7 @@ class EventDispatcherTest extends TestCase ); } - public function testDispatcherOutputsCommand() + public function testDispatcherOutputsCommand(): void { $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->setConstructorArgs(array( @@ -536,7 +536,7 @@ class EventDispatcherTest extends TestCase $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); } - public function testDispatcherOutputsErrorOnFailedCommand() + public function testDispatcherOutputsErrorOnFailedCommand(): void { $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->setConstructorArgs(array( @@ -572,7 +572,7 @@ class EventDispatcherTest extends TestCase $dispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, false); } - public function testDispatcherInstallerEvents() + public function testDispatcherInstallerEvents(): void { $dispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher') ->setConstructorArgs(array( @@ -595,7 +595,7 @@ class EventDispatcherTest extends TestCase /** * @return void */ - public static function call() + public static function call(): void { throw new \RuntimeException(); } @@ -603,7 +603,7 @@ class EventDispatcherTest extends TestCase /** * @return true */ - public static function someMethod() + public static function someMethod(): bool { return true; } @@ -611,7 +611,7 @@ class EventDispatcherTest extends TestCase /** * @return true */ - public static function someMethod2() + public static function someMethod2(): bool { return true; } @@ -619,7 +619,7 @@ class EventDispatcherTest extends TestCase /** * @return Composer */ - private function createComposerInstance() + private function createComposerInstance(): Composer { $composer = new Composer; $config = new Config(); diff --git a/tests/Composer/Test/FactoryTest.php b/tests/Composer/Test/FactoryTest.php index 96b0e95d5..ec41827fb 100644 --- a/tests/Composer/Test/FactoryTest.php +++ b/tests/Composer/Test/FactoryTest.php @@ -19,7 +19,7 @@ class FactoryTest extends TestCase /** * @group TLS */ - public function testDefaultValuesAreAsExpected() + public function testDefaultValuesAreAsExpected(): void { $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php index 8d97636a9..d7dcd9b33 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php @@ -23,7 +23,7 @@ final class IgnoreAllPlatformRequirementFilterTest extends TestCase * @param string $req * @param bool $expectIgnored */ - public function testIsIgnored($req, $expectIgnored) + public function testIsIgnored($req, $expectIgnored): void { $platformRequirementFilter = new IgnoreAllPlatformRequirementFilter(); @@ -33,7 +33,7 @@ final class IgnoreAllPlatformRequirementFilterTest extends TestCase /** * @return array */ - public function dataIsIgnored() + public function dataIsIgnored(): array { return array( 'php is ignored' => array('php', true), diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php index 3cf7469a4..47af67fd2 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php @@ -24,7 +24,7 @@ final class IgnoreListPlatformRequirementFilterTest extends TestCase * @param string $req * @param bool $expectIgnored */ - public function testIsIgnored(array $reqList, $req, $expectIgnored) + public function testIsIgnored(array $reqList, $req, $expectIgnored): void { $platformRequirementFilter = new IgnoreListPlatformRequirementFilter($reqList); @@ -34,7 +34,7 @@ final class IgnoreListPlatformRequirementFilterTest extends TestCase /** * @return array */ - public function dataIsIgnored() + public function dataIsIgnored(): array { return array( 'ext-json is ignored if listed' => array(array('ext-json', 'monolog/monolog'), 'ext-json', true), diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php index 4698e94fa..8b5b1f897 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php @@ -22,7 +22,7 @@ final class IgnoreNothingPlatformRequirementFilterTest extends TestCase * * @param string $req */ - public function testIsIgnored($req) + public function testIsIgnored($req): void { $platformRequirementFilter = new IgnoreNothingPlatformRequirementFilter(); @@ -32,7 +32,7 @@ final class IgnoreNothingPlatformRequirementFilterTest extends TestCase /** * @return array */ - public function dataIsIgnored() + public function dataIsIgnored(): array { return array( 'php is not ignored' => array('php'), diff --git a/tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php b/tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php index 44bcfce9e..d443532e3 100644 --- a/tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php +++ b/tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php @@ -23,7 +23,7 @@ final class PlatformRequirementFilterFactoryTest extends TestCase * @param mixed $boolOrList * @param class-string $expectedInstance */ - public function testFromBoolOrList($boolOrList, $expectedInstance) + public function testFromBoolOrList($boolOrList, $expectedInstance): void { $this->assertInstanceOf($expectedInstance, PlatformRequirementFilterFactory::fromBoolOrList($boolOrList)); } @@ -31,7 +31,7 @@ final class PlatformRequirementFilterFactoryTest extends TestCase /** * @return array */ - public function dataFromBoolOrList() + public function dataFromBoolOrList(): array { return array( 'true creates IgnoreAllFilter' => array(true, 'Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter'), @@ -40,7 +40,7 @@ final class PlatformRequirementFilterFactoryTest extends TestCase ); } - public function testFromBoolThrowsExceptionIfTypeIsUnknown() + public function testFromBoolThrowsExceptionIfTypeIsUnknown(): void { self::expectException('InvalidArgumentException'); self::expectExceptionMessage('PlatformRequirementFilter: Unknown $boolOrList parameter NULL. Please report at https://github.com/composer/composer/issues/new.'); @@ -48,14 +48,14 @@ final class PlatformRequirementFilterFactoryTest extends TestCase PlatformRequirementFilterFactory::fromBoolOrList(null); } - public function testIgnoreAll() + public function testIgnoreAll(): void { $platformRequirementFilter = PlatformRequirementFilterFactory::ignoreAll(); $this->assertInstanceOf('Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter', $platformRequirementFilter); } - public function testIgnoreNothing() + public function testIgnoreNothing(): void { $platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing(); diff --git a/tests/Composer/Test/IO/BufferIOTest.php b/tests/Composer/Test/IO/BufferIOTest.php index 52c11562a..8e86f1903 100644 --- a/tests/Composer/Test/IO/BufferIOTest.php +++ b/tests/Composer/Test/IO/BufferIOTest.php @@ -18,7 +18,7 @@ use Symfony\Component\Console\Input\StreamableInputInterface; class BufferIOTest extends TestCase { - public function testSetUserInputs() + public function testSetUserInputs(): void { $bufferIO = new BufferIO(); diff --git a/tests/Composer/Test/IO/ConsoleIOTest.php b/tests/Composer/Test/IO/ConsoleIOTest.php index e275274cc..65995c884 100644 --- a/tests/Composer/Test/IO/ConsoleIOTest.php +++ b/tests/Composer/Test/IO/ConsoleIOTest.php @@ -19,7 +19,7 @@ use Symfony\Component\Console\Output\OutputInterface; class ConsoleIOTest extends TestCase { - public function testIsInteractive() + public function testIsInteractive(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $inputMock->expects($this->exactly(2)) @@ -38,7 +38,7 @@ class ConsoleIOTest extends TestCase $this->assertFalse($consoleIO->isInteractive()); } - public function testWrite() + public function testWrite(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -54,7 +54,7 @@ class ConsoleIOTest extends TestCase $consoleIO->write('some information about something', false); } - public function testWriteError() + public function testWriteError(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\ConsoleOutputInterface')->getMock(); @@ -73,7 +73,7 @@ class ConsoleIOTest extends TestCase $consoleIO->writeError('some information about something', false); } - public function testWriteWithMultipleLineStringWhenDebugging() + public function testWriteWithMultipleLineStringWhenDebugging(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -83,7 +83,7 @@ class ConsoleIOTest extends TestCase $outputMock->expects($this->once()) ->method('write') ->with( - $this->callback(function ($messages) { + $this->callback(function ($messages): bool { $result = Preg::isMatch("[(.*)/(.*) First line]", $messages[0]); $result = $result && Preg::isMatch("[(.*)/(.*) Second line]", $messages[1]); @@ -101,7 +101,7 @@ class ConsoleIOTest extends TestCase $consoleIO->write($example, false); } - public function testOverwrite() + public function testOverwrite(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -129,7 +129,7 @@ class ConsoleIOTest extends TestCase $consoleIO->overwrite('something longer than initial (34)'); } - public function testAsk() + public function testAsk(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -157,7 +157,7 @@ class ConsoleIOTest extends TestCase $consoleIO->ask('Why?', 'default'); } - public function testAskConfirmation() + public function testAskConfirmation(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -185,7 +185,7 @@ class ConsoleIOTest extends TestCase $consoleIO->askConfirmation('Why?', false); } - public function testAskAndValidate() + public function testAskAndValidate(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -209,14 +209,14 @@ class ConsoleIOTest extends TestCase ->will($this->returnValue($helperMock)) ; - $validator = function ($value) { + $validator = function ($value): bool { return true; }; $consoleIO = new ConsoleIO($inputMock, $outputMock, $setMock); $consoleIO->askAndValidate('Why?', $validator, 10, 'default'); } - public function testSelect() + public function testSelect(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -245,7 +245,7 @@ class ConsoleIOTest extends TestCase $this->assertEquals(array('1'), $result); } - public function testSetAndgetAuthentication() + public function testSetAndgetAuthentication(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -260,7 +260,7 @@ class ConsoleIOTest extends TestCase ); } - public function testGetAuthenticationWhenDidNotSet() + public function testGetAuthenticationWhenDidNotSet(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); @@ -274,7 +274,7 @@ class ConsoleIOTest extends TestCase ); } - public function testHasAuthentication() + public function testHasAuthentication(): void { $inputMock = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface')->getMock(); $outputMock = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface')->getMock(); diff --git a/tests/Composer/Test/IO/NullIOTest.php b/tests/Composer/Test/IO/NullIOTest.php index eecdc0aec..b2ecc84d8 100644 --- a/tests/Composer/Test/IO/NullIOTest.php +++ b/tests/Composer/Test/IO/NullIOTest.php @@ -17,28 +17,28 @@ use Composer\Test\TestCase; class NullIOTest extends TestCase { - public function testIsInteractive() + public function testIsInteractive(): void { $io = new NullIO(); $this->assertFalse($io->isInteractive()); } - public function testhasAuthentication() + public function testhasAuthentication(): void { $io = new NullIO(); $this->assertFalse($io->hasAuthentication('foo')); } - public function testAskAndHideAnswer() + public function testAskAndHideAnswer(): void { $io = new NullIO(); $this->assertNull($io->askAndHideAnswer('foo')); } - public function testgetAuthentications() + public function testgetAuthentications(): void { $io = new NullIO(); @@ -47,30 +47,30 @@ class NullIOTest extends TestCase $this->assertEquals(array('username' => null, 'password' => null), $io->getAuthentication('foo')); } - public function testAsk() + public function testAsk(): void { $io = new NullIO(); $this->assertEquals('foo', $io->ask('bar', 'foo')); } - public function testAskConfirmation() + public function testAskConfirmation(): void { $io = new NullIO(); $this->assertEquals(false, $io->askConfirmation('bar', false)); } - public function testAskAndValidate() + public function testAskAndValidate(): void { $io = new NullIO(); - $this->assertEquals('foo', $io->askAndValidate('question', function ($x) { + $this->assertEquals('foo', $io->askAndValidate('question', function ($x): bool { return true; }, null, 'foo')); } - public function testSelect() + public function testSelect(): void { $io = new NullIO(); diff --git a/tests/Composer/Test/InstalledVersionsTest.php b/tests/Composer/Test/InstalledVersionsTest.php index 3865beb0e..9cfb96faf 100644 --- a/tests/Composer/Test/InstalledVersionsTest.php +++ b/tests/Composer/Test/InstalledVersionsTest.php @@ -52,7 +52,7 @@ class InstalledVersionsTest extends TestCase InstalledVersions::reload(require __DIR__.'/Repository/Fixtures/installed.php'); } - public function testGetInstalledPackages() + public function testGetInstalledPackages(): void { $names = array( '__root__', @@ -74,12 +74,12 @@ class InstalledVersionsTest extends TestCase * @param string $name * @param bool $includeDevRequirements */ - public function testIsInstalled($expected, $name, $includeDevRequirements = true) + public function testIsInstalled($expected, $name, $includeDevRequirements = true): void { $this->assertSame($expected, InstalledVersions::isInstalled($name, $includeDevRequirements)); } - public static function isInstalledProvider() + public static function isInstalledProvider(): array { return array( array(true, 'foo/impl'), @@ -99,12 +99,12 @@ class InstalledVersionsTest extends TestCase * @param string $name * @param string $constraint */ - public function testSatisfies($expected, $name, $constraint) + public function testSatisfies($expected, $name, $constraint): void { $this->assertSame($expected, InstalledVersions::satisfies(new VersionParser, $name, $constraint)); } - public static function satisfiesProvider() + public static function satisfiesProvider(): array { return array( array(true, 'foo/impl', '1.5'), @@ -139,12 +139,12 @@ class InstalledVersionsTest extends TestCase * @param string $expected * @param string $name */ - public function testGetVersionRanges($expected, $name) + public function testGetVersionRanges($expected, $name): void { $this->assertSame($expected, InstalledVersions::getVersionRanges($name)); } - public static function getVersionRangesProvider() + public static function getVersionRangesProvider(): array { return array( array('dev-master || 1.10.x-dev', '__root__'), @@ -163,12 +163,12 @@ class InstalledVersionsTest extends TestCase * @param ?string $expected * @param string $name */ - public function testGetVersion($expected, $name) + public function testGetVersion($expected, $name): void { $this->assertSame($expected, InstalledVersions::getVersion($name)); } - public static function getVersionProvider() + public static function getVersionProvider(): array { return array( array('dev-master', '__root__'), @@ -187,12 +187,12 @@ class InstalledVersionsTest extends TestCase * @param ?string $expected * @param string $name */ - public function testGetPrettyVersion($expected, $name) + public function testGetPrettyVersion($expected, $name): void { $this->assertSame($expected, InstalledVersions::getPrettyVersion($name)); } - public static function getPrettyVersionProvider() + public static function getPrettyVersionProvider(): array { return array( array('dev-master', '__root__'), @@ -206,13 +206,13 @@ class InstalledVersionsTest extends TestCase ); } - public function testGetVersionOutOfBounds() + public function testGetVersionOutOfBounds(): void { self::expectException('OutOfBoundsException'); InstalledVersions::getVersion('not/installed'); } - public function testGetRootPackage() + public function testGetRootPackage(): void { $this->assertSame(array( 'pretty_version' => 'dev-master', @@ -231,7 +231,7 @@ class InstalledVersionsTest extends TestCase /** * @group legacy */ - public function testGetRawData() + public function testGetRawData(): void { $dir = $this->root; $this->assertSame(require __DIR__.'/Repository/Fixtures/installed.php', InstalledVersions::getRawData()); @@ -242,12 +242,12 @@ class InstalledVersionsTest extends TestCase * @param ?string $expected * @param string $name */ - public function testGetReference($expected, $name) + public function testGetReference($expected, $name): void { $this->assertSame($expected, InstalledVersions::getReference($name)); } - public static function getReferenceProvider() + public static function getReferenceProvider(): array { return array( array('sourceref-by-default', '__root__'), @@ -261,7 +261,7 @@ class InstalledVersionsTest extends TestCase ); } - public function testGetInstalledPackagesByType() + public function testGetInstalledPackagesByType(): void { $names = array( '__root__', @@ -274,7 +274,7 @@ class InstalledVersionsTest extends TestCase $this->assertSame($names, \Composer\InstalledVersions::getInstalledPackagesByType('library')); } - public function testGetInstallPath() + public function testGetInstallPath(): void { $this->assertSame(realpath($this->root), realpath(\Composer\InstalledVersions::getInstallPath('__root__'))); $this->assertSame('/foo/bar/vendor/c/c', \Composer\InstalledVersions::getInstallPath('c/c')); diff --git a/tests/Composer/Test/Installer/BinaryInstallerTest.php b/tests/Composer/Test/Installer/BinaryInstallerTest.php index 5bb991f90..821bc3ce4 100644 --- a/tests/Composer/Test/Installer/BinaryInstallerTest.php +++ b/tests/Composer/Test/Installer/BinaryInstallerTest.php @@ -68,7 +68,7 @@ class BinaryInstallerTest extends TestCase * @dataProvider executableBinaryProvider * @param string $contents */ - public function testInstallAndExecBinaryWithFullCompat($contents) + public function testInstallAndExecBinaryWithFullCompat($contents): void { $package = $this->createPackageMock(); $package->expects($this->any()) @@ -87,7 +87,7 @@ class BinaryInstallerTest extends TestCase $this->assertEquals('success arg', $output); } - public function executableBinaryProvider() + public function executableBinaryProvider(): array { return array( 'simple php file' => array(<<<'EOL' diff --git a/tests/Composer/Test/Installer/InstallationManagerTest.php b/tests/Composer/Test/Installer/InstallationManagerTest.php index 4447919a3..91057a72a 100644 --- a/tests/Composer/Test/Installer/InstallationManagerTest.php +++ b/tests/Composer/Test/Installer/InstallationManagerTest.php @@ -43,14 +43,14 @@ class InstallationManagerTest extends TestCase $this->io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); } - public function testAddGetInstaller() + public function testAddGetInstaller(): void { $installer = $this->createInstallerMock(); $installer ->expects($this->exactly(2)) ->method('supports') - ->will($this->returnCallback(function ($arg) { + ->will($this->returnCallback(function ($arg): bool { return $arg === 'vendor'; })); @@ -63,14 +63,14 @@ class InstallationManagerTest extends TestCase $manager->getInstaller('unregistered'); } - public function testAddRemoveInstaller() + public function testAddRemoveInstaller(): void { $installer = $this->createInstallerMock(); $installer ->expects($this->exactly(2)) ->method('supports') - ->will($this->returnCallback(function ($arg) { + ->will($this->returnCallback(function ($arg): bool { return $arg === 'vendor'; })); @@ -79,7 +79,7 @@ class InstallationManagerTest extends TestCase $installer2 ->expects($this->exactly(1)) ->method('supports') - ->will($this->returnCallback(function ($arg) { + ->will($this->returnCallback(function ($arg): bool { return $arg === 'vendor'; })); @@ -93,7 +93,7 @@ class InstallationManagerTest extends TestCase $this->assertSame($installer, $manager->getInstaller('vendor')); } - public function testExecute() + public function testExecute(): void { $manager = $this->getMockBuilder('Composer\Installer\InstallationManager') ->setConstructorArgs(array($this->loop, $this->io)) @@ -128,7 +128,7 @@ class InstallationManagerTest extends TestCase $manager->execute($this->repository, array($installOperation, $removeOperation, $updateOperation)); } - public function testInstall() + public function testInstall(): void { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); @@ -156,7 +156,7 @@ class InstallationManagerTest extends TestCase $manager->install($this->repository, $operation); } - public function testUpdateWithEqualTypes() + public function testUpdateWithEqualTypes(): void { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); @@ -189,7 +189,7 @@ class InstallationManagerTest extends TestCase $manager->update($this->repository, $operation); } - public function testUpdateWithNotEqualTypes() + public function testUpdateWithNotEqualTypes(): void { $libInstaller = $this->createInstallerMock(); $bundleInstaller = $this->createInstallerMock(); @@ -212,7 +212,7 @@ class InstallationManagerTest extends TestCase $bundleInstaller ->expects($this->exactly(2)) ->method('supports') - ->will($this->returnCallback(function ($arg) { + ->will($this->returnCallback(function ($arg): bool { return $arg === 'bundles'; })); @@ -236,7 +236,7 @@ class InstallationManagerTest extends TestCase $manager->update($this->repository, $operation); } - public function testUninstall() + public function testUninstall(): void { $installer = $this->createInstallerMock(); $manager = new InstallationManager($this->loop, $this->io); @@ -264,7 +264,7 @@ class InstallationManagerTest extends TestCase $manager->uninstall($this->repository, $operation); } - public function testInstallBinary() + public function testInstallBinary(): void { $installer = $this->getMockBuilder('Composer\Installer\LibraryInstaller') ->disableOriginalConstructor() diff --git a/tests/Composer/Test/Installer/InstallerEventTest.php b/tests/Composer/Test/Installer/InstallerEventTest.php index 6c0689844..d2146f3a7 100644 --- a/tests/Composer/Test/Installer/InstallerEventTest.php +++ b/tests/Composer/Test/Installer/InstallerEventTest.php @@ -17,7 +17,7 @@ use Composer\Test\TestCase; class InstallerEventTest extends TestCase { - public function testGetter() + public function testGetter(): void { $composer = $this->getMockBuilder('Composer\Composer')->getMock(); $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); diff --git a/tests/Composer/Test/Installer/LibraryInstallerTest.php b/tests/Composer/Test/Installer/LibraryInstallerTest.php index a302c0b90..5f2cc55f8 100644 --- a/tests/Composer/Test/Installer/LibraryInstallerTest.php +++ b/tests/Composer/Test/Installer/LibraryInstallerTest.php @@ -13,6 +13,7 @@ namespace Composer\Test\Installer; use Composer\Installer\LibraryInstaller; +use Composer\Repository\InstalledArrayRepository; use Composer\Util\Filesystem; use Composer\Test\TestCase; use Composer\Composer; @@ -75,10 +76,10 @@ class LibraryInstallerTest extends TestCase $this->rootDir = $this->getUniqueTmpDirectory(); $this->vendorDir = $this->rootDir.DIRECTORY_SEPARATOR.'vendor'; - $this->ensureDirectoryExistsAndClear($this->vendorDir); + self::ensureDirectoryExistsAndClear($this->vendorDir); $this->binDir = $this->rootDir.DIRECTORY_SEPARATOR.'bin'; - $this->ensureDirectoryExistsAndClear($this->binDir); + self::ensureDirectoryExistsAndClear($this->binDir); $this->config->merge(array( 'config' => array( @@ -102,7 +103,7 @@ class LibraryInstallerTest extends TestCase $this->fs->removeDirectory($this->rootDir); } - public function testInstallerCreationShouldNotCreateVendorDirectory() + public function testInstallerCreationShouldNotCreateVendorDirectory(): void { $this->fs->removeDirectory($this->vendorDir); @@ -110,7 +111,7 @@ class LibraryInstallerTest extends TestCase $this->assertFileDoesNotExist($this->vendorDir); } - public function testInstallerCreationShouldNotCreateBinDirectory() + public function testInstallerCreationShouldNotCreateBinDirectory(): void { $this->fs->removeDirectory($this->binDir); @@ -118,34 +119,34 @@ class LibraryInstallerTest extends TestCase $this->assertFileDoesNotExist($this->binDir); } - public function testIsInstalled() + public function testIsInstalled(): void { $library = new LibraryInstaller($this->io, $this->composer); - $package = $this->createPackageMock(); + $package = $this->getPackage('test/pkg', '1.0.0'); - $this->repository - ->expects($this->exactly(2)) - ->method('hasPackage') - ->with($package) - ->will($this->onConsecutiveCalls(true, false)); + $repository = new InstalledArrayRepository(); + $this->assertFalse($library->isInstalled($repository, $package)); - $this->assertTrue($library->isInstalled($this->repository, $package)); - $this->assertFalse($library->isInstalled($this->repository, $package)); + // package being in repo is not enough to be installed + $repository->addPackage($package); + $this->assertFalse($library->isInstalled($repository, $package)); + + // package being in repo and vendor/pkg/foo dir present means it is seen as installed + self::ensureDirectoryExistsAndClear($this->vendorDir.'/'.$package->getPrettyName()); + $this->assertTrue($library->isInstalled($repository, $package)); + + $repository->removePackage($package); + $this->assertFalse($library->isInstalled($repository, $package)); } /** * @depends testInstallerCreationShouldNotCreateVendorDirectory * @depends testInstallerCreationShouldNotCreateBinDirectory */ - public function testInstall() + public function testInstall(): void { $library = new LibraryInstaller($this->io, $this->composer); - $package = $this->createPackageMock(); - - $package - ->expects($this->any()) - ->method('getPrettyName') - ->will($this->returnValue('some/package')); + $package = $this->getPackage('some/package', '1.0.0'); $this->dm ->expects($this->once()) @@ -166,37 +167,20 @@ class LibraryInstallerTest extends TestCase * @depends testInstallerCreationShouldNotCreateVendorDirectory * @depends testInstallerCreationShouldNotCreateBinDirectory */ - public function testUpdate() + public function testUpdate(): void { $filesystem = $this->getMockBuilder('Composer\Util\Filesystem') ->getMock(); $filesystem ->expects($this->once()) ->method('rename') - ->with($this->vendorDir.'/package1/oldtarget', $this->vendorDir.'/package1/newtarget'); + ->with($this->vendorDir.'/vendor/package1/oldtarget', $this->vendorDir.'/vendor/package1/newtarget'); - $initial = $this->createPackageMock(); - $target = $this->createPackageMock(); + $initial = $this->getPackage('vendor/package1', '1.0.0'); + $target = $this->getPackage('vendor/package1', '2.0.0'); - $initial - ->expects($this->any()) - ->method('getPrettyName') - ->will($this->returnValue('package1')); - - $initial - ->expects($this->any()) - ->method('getTargetDir') - ->will($this->returnValue('oldtarget')); - - $target - ->expects($this->any()) - ->method('getPrettyName') - ->will($this->returnValue('package1')); - - $target - ->expects($this->any()) - ->method('getTargetDir') - ->will($this->returnValue('newtarget')); + $initial->setTargetDir('oldtarget'); + $target->setTargetDir('newtarget'); $this->repository ->expects($this->exactly(3)) @@ -206,7 +190,7 @@ class LibraryInstallerTest extends TestCase $this->dm ->expects($this->once()) ->method('update') - ->with($initial, $target, $this->vendorDir.'/package1/newtarget'); + ->with($initial, $target, $this->vendorDir.'/vendor/package1/newtarget'); $this->repository ->expects($this->once()) @@ -228,19 +212,10 @@ class LibraryInstallerTest extends TestCase $library->update($this->repository, $initial, $target); } - public function testUninstall() + public function testUninstall(): void { $library = new LibraryInstaller($this->io, $this->composer); - $package = $this->createPackageMock(); - - $package - ->expects($this->any()) - ->method('getPrettyName') - ->will($this->returnValue('pkg')); - $package - ->expects($this->any()) - ->method('getName') - ->will($this->returnValue('pkg')); + $package = $this->getPackage('vendor/pkg', '1.0.0'); $this->repository ->expects($this->exactly(2)) @@ -251,7 +226,7 @@ class LibraryInstallerTest extends TestCase $this->dm ->expects($this->once()) ->method('remove') - ->with($package, $this->vendorDir.'/pkg'); + ->with($package, $this->vendorDir.'/vendor/pkg'); $this->repository ->expects($this->once()) @@ -265,32 +240,19 @@ class LibraryInstallerTest extends TestCase $library->uninstall($this->repository, $package); } - public function testGetInstallPath() + public function testGetInstallPathWithoutTargetDir(): void { $library = new LibraryInstaller($this->io, $this->composer); - $package = $this->createPackageMock(); + $package = $this->getPackage('Vendor/Pkg', '1.0.0'); - $package - ->expects($this->once()) - ->method('getTargetDir') - ->will($this->returnValue(null)); - - $this->assertEquals($this->vendorDir.'/'.$package->getName(), $library->getInstallPath($package)); + $this->assertEquals($this->vendorDir.'/'.$package->getPrettyName(), $library->getInstallPath($package)); } - public function testGetInstallPathWithTargetDir() + public function testGetInstallPathWithTargetDir(): void { $library = new LibraryInstaller($this->io, $this->composer); - $package = $this->createPackageMock(); - - $package - ->expects($this->once()) - ->method('getTargetDir') - ->will($this->returnValue('Some/Namespace')); - $package - ->expects($this->any()) - ->method('getPrettyName') - ->will($this->returnValue('foo/bar')); + $package = $this->getPackage('Foo/Bar', '1.0.0'); + $package->setTargetDir('Some/Namespace'); $this->assertEquals($this->vendorDir.'/'.$package->getPrettyName().'/Some/Namespace', $library->getInstallPath($package)); } @@ -299,14 +261,14 @@ class LibraryInstallerTest extends TestCase * @depends testInstallerCreationShouldNotCreateVendorDirectory * @depends testInstallerCreationShouldNotCreateBinDirectory */ - public function testEnsureBinariesInstalled() + public function testEnsureBinariesInstalled(): void { $binaryInstallerMock = $this->getMockBuilder('Composer\Installer\BinaryInstaller') ->disableOriginalConstructor() ->getMock(); $library = new LibraryInstaller($this->io, $this->composer, 'library', null, $binaryInstallerMock); - $package = $this->createPackageMock(); + $package = $this->getPackage('foo/bar', '1.0.0'); $binaryInstallerMock ->expects($this->never()) @@ -320,14 +282,4 @@ class LibraryInstallerTest extends TestCase $library->ensureBinariesPresence($package); } - - /** - * @return \Composer\Package\PackageInterface&\PHPUnit\Framework\MockObject\MockObject - */ - protected function createPackageMock() - { - return $this->getMockBuilder('Composer\Package\Package') - ->setConstructorArgs(array(md5((string) mt_rand()), '1.0.0.0', '1.0.0')) - ->getMock(); - } } diff --git a/tests/Composer/Test/Installer/MetapackageInstallerTest.php b/tests/Composer/Test/Installer/MetapackageInstallerTest.php index e66bf28d3..0b0b2035a 100644 --- a/tests/Composer/Test/Installer/MetapackageInstallerTest.php +++ b/tests/Composer/Test/Installer/MetapackageInstallerTest.php @@ -39,7 +39,7 @@ class MetapackageInstallerTest extends TestCase $this->installer = new MetapackageInstaller($this->io); } - public function testInstall() + public function testInstall(): void { $package = $this->createPackageMock(); @@ -51,7 +51,7 @@ class MetapackageInstallerTest extends TestCase $this->installer->install($this->repository, $package); } - public function testUpdate() + public function testUpdate(): void { $initial = $this->createPackageMock(); $initial->expects($this->once()) @@ -85,7 +85,7 @@ class MetapackageInstallerTest extends TestCase $this->installer->update($this->repository, $initial, $target); } - public function testUninstall() + public function testUninstall(): void { $package = $this->createPackageMock(); diff --git a/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php b/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php index 47152ff90..5cd693d4f 100644 --- a/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php +++ b/tests/Composer/Test/Installer/SuggestedPackagesReporterTest.php @@ -42,7 +42,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::__construct */ - public function testConstructor() + public function testConstructor(): void { $this->io->expects($this->once()) ->method('write'); @@ -54,7 +54,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::getPackages */ - public function testGetPackagesEmptyByDefault() + public function testGetPackagesEmptyByDefault(): void { $this->assertEmpty($this->suggestedPackagesReporter->getPackages()); } @@ -63,7 +63,7 @@ class SuggestedPackagesReporterTest extends TestCase * @covers ::getPackages * @covers ::addPackage */ - public function testGetPackages() + public function testGetPackages(): void { $suggestedPackage = $this->getSuggestedPackageArray(); $this->suggestedPackagesReporter->addPackage( @@ -83,7 +83,7 @@ class SuggestedPackagesReporterTest extends TestCase * * @covers ::addPackage */ - public function testAddPackageAppends() + public function testAddPackageAppends(): void { $suggestedPackageA = $this->getSuggestedPackageArray(); $suggestedPackageB = $this->getSuggestedPackageArray(); @@ -108,7 +108,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::addSuggestionsFromPackage */ - public function testAddSuggestionsFromPackage() + public function testAddSuggestionsFromPackage(): void { $package = $this->createPackageMock(); $package->expects($this->once()) @@ -139,7 +139,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutput() + public function testOutput(): void { $this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); @@ -157,7 +157,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutputWithNoSuggestionReason() + public function testOutputWithNoSuggestionReason(): void { $this->suggestedPackagesReporter->addPackage('a', 'b', ''); @@ -175,7 +175,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutputIgnoresFormatting() + public function testOutputIgnoresFormatting(): void { $this->suggestedPackagesReporter->addPackage('source', 'target1', "\x1b[1;37;42m Like us\r\non Facebook \x1b[0m"); $this->suggestedPackagesReporter->addPackage('source', 'target2', "Like us on Facebook"); @@ -199,7 +199,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutputMultiplePackages() + public function testOutputMultiplePackages(): void { $this->suggestedPackagesReporter->addPackage('a', 'b', 'c'); $this->suggestedPackagesReporter->addPackage('source package', 'target', 'because reasons'); @@ -221,7 +221,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutputSkipInstalledPackages() + public function testOutputSkipInstalledPackages(): void { $repository = $this->getMockBuilder('Composer\Repository\InstalledRepository')->disableOriginalConstructor()->getMock(); $package1 = $this->getMockBuilder('Composer\Package\PackageInterface')->getMock(); @@ -259,7 +259,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @covers ::output */ - public function testOutputNotGettingInstalledPackagesWhenNoSuggestions() + public function testOutputNotGettingInstalledPackagesWhenNoSuggestions(): void { $repository = $this->getMockBuilder('Composer\Repository\InstalledRepository')->disableOriginalConstructor()->getMock(); $repository->expects($this->exactly(0)) @@ -271,7 +271,7 @@ class SuggestedPackagesReporterTest extends TestCase /** * @return array */ - private function getSuggestedPackageArray() + private function getSuggestedPackageArray(): array { return array( 'source' => 'a', diff --git a/tests/Composer/Test/InstallerTest.php b/tests/Composer/Test/InstallerTest.php index c0ea9b1af..a38d02424 100644 --- a/tests/Composer/Test/InstallerTest.php +++ b/tests/Composer/Test/InstallerTest.php @@ -74,7 +74,7 @@ class InstallerTest extends TestCase * @param RepositoryInterface[] $repositories * @param mixed[] $options */ - public function testInstaller(RootPackageInterface $rootPackage, $repositories, array $options) + public function testInstaller(RootPackageInterface $rootPackage, $repositories, array $options): void { $io = new BufferIO('', OutputInterface::VERBOSITY_NORMAL, new OutputFormatter(false)); @@ -122,12 +122,12 @@ class InstallerTest extends TestCase })); $lockJsonMock->expects($this->any()) ->method('exists') - ->will($this->returnCallback(function () use (&$lockData) { + ->will($this->returnCallback(function () use (&$lockData): bool { return $lockData !== null; })); $lockJsonMock->expects($this->any()) ->method('write') - ->will($this->returnCallback(function ($value, $options = 0) use (&$lockData) { + ->will($this->returnCallback(function ($value, $options = 0) use (&$lockData): void { $lockData = json_encode($value, JSON_PRETTY_PRINT); })); @@ -160,7 +160,7 @@ class InstallerTest extends TestCase * @param PackageInterface[] $packages * @return mixed[] */ - protected function makePackagesComparable($packages) + protected function makePackagesComparable($packages): array { $dumper = new ArrayDumper(); @@ -172,7 +172,7 @@ class InstallerTest extends TestCase return $comparable; } - public function provideInstaller() + public function provideInstaller(): array { $cases = array(); @@ -237,7 +237,7 @@ class InstallerTest extends TestCase * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testSlowIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult) + public function testSlowIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); @@ -260,7 +260,7 @@ class InstallerTest extends TestCase * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testIntegrationWithPoolOptimizer($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult) + public function testIntegrationWithPoolOptimizer($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '1'); @@ -283,7 +283,7 @@ class InstallerTest extends TestCase * @param string $expect * @param int|class-string<\Throwable> $expectResult */ - public function testIntegrationWithRawPool($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult) + public function testIntegrationWithRawPool($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); @@ -305,11 +305,11 @@ class InstallerTest extends TestCase * @param int|class-string<\Throwable> $expectResult * @return void */ - private function doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult) + private function doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult): void { if ($condition) { eval('$res = '.$condition.';'); - if (!$res) { + if (!$res) { // @phpstan-ignore-line $this->markTestSkipped($condition); } } @@ -348,12 +348,12 @@ class InstallerTest extends TestCase })); $lockJsonMock->expects($this->any()) ->method('exists') - ->will($this->returnCallback(function () use (&$lockData) { + ->will($this->returnCallback(function () use (&$lockData): bool { return $lockData !== null; })); $lockJsonMock->expects($this->any()) ->method('write') - ->will($this->returnCallback(function ($value, $options = 0) use (&$lockData) { + ->will($this->returnCallback(function ($value, $options = 0) use (&$lockData): void { $lockData = json_encode($value, JSON_PRETTY_PRINT); })); @@ -361,7 +361,7 @@ class InstallerTest extends TestCase $actualLock = array(); $lockJsonMock->expects($this->atLeastOnce()) ->method('write') - ->will($this->returnCallback(function ($hash, $options) use (&$actualLock) { + ->will($this->returnCallback(function ($hash, $options) use (&$actualLock): void { // need to do assertion outside of mock for nice phpunit output // so store value temporarily in reference for later assetion $actualLock = $hash; @@ -390,7 +390,7 @@ class InstallerTest extends TestCase $install->addOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY); $install->addOption('no-dev', null, InputOption::VALUE_NONE); $install->addOption('dry-run', null, InputOption::VALUE_NONE); - $install->setCode(function ($input, $output) use ($installer) { + $install->setCode(function ($input, $output) use ($installer): int { $ignorePlatformReqs = $input->getOption('ignore-platform-reqs') ?: ($input->getOption('ignore-platform-req') ?: false); $installer @@ -414,9 +414,9 @@ class InstallerTest extends TestCase $update->addOption('prefer-stable', null, InputOption::VALUE_NONE); $update->addOption('prefer-lowest', null, InputOption::VALUE_NONE); $update->addArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL); - $update->setCode(function ($input, $output) use ($installer) { + $update->setCode(function ($input, $output) use ($installer): int { $packages = $input->getArgument('packages'); - $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); @@ -483,7 +483,7 @@ class InstallerTest extends TestCase $actualInstalled[] = $package; } - usort($actualInstalled, function ($a, $b) { + usort($actualInstalled, function ($a, $b): int { return strcmp($a['name'], $b['name']); }); @@ -502,12 +502,12 @@ class InstallerTest extends TestCase } } - public function provideSlowIntegrationTests() + public function provideSlowIntegrationTests(): array { return $this->loadIntegrationTests('installer-slow/'); } - public function provideIntegrationTests() + public function provideIntegrationTests(): array { return $this->loadIntegrationTests('installer/'); } @@ -516,7 +516,7 @@ class InstallerTest extends TestCase * @param string $path * @return mixed[] */ - public function loadIntegrationTests($path) + public function loadIntegrationTests($path): array { $fixturesDir = realpath(__DIR__.'/Fixtures/'.$path); $tests = array(); @@ -602,7 +602,7 @@ class InstallerTest extends TestCase * @param string $fixturesDir * @return mixed[] */ - protected function readTestFile(\SplFileInfo $file, $fixturesDir) + protected function readTestFile(\SplFileInfo $file, $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file->getRealPath()), -1, PREG_SPLIT_DELIM_CAPTURE); diff --git a/tests/Composer/Test/Json/ComposerSchemaTest.php b/tests/Composer/Test/Json/ComposerSchemaTest.php index e45da5df3..474523b46 100644 --- a/tests/Composer/Test/Json/ComposerSchemaTest.php +++ b/tests/Composer/Test/Json/ComposerSchemaTest.php @@ -20,7 +20,7 @@ use Composer\Test\TestCase; */ class ComposerSchemaTest extends TestCase { - public function testNamePattern() + public function testNamePattern(): void { $expectedError = array( array( @@ -37,13 +37,13 @@ class ComposerSchemaTest extends TestCase $this->assertEquals($expectedError, $this->check($json)); } - public function testOptionalAbandonedProperty() + public function testOptionalAbandonedProperty(): void { $json = '{"name": "vendor/package", "description": "description", "abandoned": true}'; $this->assertTrue($this->check($json)); } - public function testRequireTypes() + public function testRequireTypes(): void { $json = '{"name": "vendor/package", "description": "description", "require": {"a": ["b"]} }'; $this->assertEquals(array( @@ -51,7 +51,7 @@ class ComposerSchemaTest extends TestCase ), $this->check($json)); } - public function testMinimumStabilityValues() + public function testMinimumStabilityValues(): void { $expectedError = array( array( diff --git a/tests/Composer/Test/Json/JsonFileTest.php b/tests/Composer/Test/Json/JsonFileTest.php index b0242622f..131730c9d 100644 --- a/tests/Composer/Test/Json/JsonFileTest.php +++ b/tests/Composer/Test/Json/JsonFileTest.php @@ -19,7 +19,7 @@ use Composer\Test\TestCase; class JsonFileTest extends TestCase { - public function testParseErrorDetectExtraComma() + public function testParseErrorDetectExtraComma(): void { $json = '{ "foo": "bar", @@ -27,7 +27,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 2', $json); } - public function testParseErrorDetectExtraCommaInArray() + public function testParseErrorDetectExtraCommaInArray(): void { $json = '{ "foo": [ @@ -37,7 +37,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 3', $json); } - public function testParseErrorDetectUnescapedBackslash() + public function testParseErrorDetectUnescapedBackslash(): void { $json = '{ "fo\o": "bar" @@ -45,7 +45,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 1', $json); } - public function testParseErrorSkipsEscapedBackslash() + public function testParseErrorSkipsEscapedBackslash(): void { $json = '{ "fo\\\\o": "bar" @@ -54,7 +54,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 2', $json); } - public function testParseErrorDetectSingleQuotes() + public function testParseErrorDetectSingleQuotes(): void { if (defined('JSON_PARSER_NOTSTRICT') && version_compare(phpversion('json'), '1.3.9', '<')) { $this->markTestSkipped('jsonc issue, see https://github.com/remicollet/pecl-json-c/issues/23'); @@ -65,7 +65,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 1', $json); } - public function testParseErrorDetectMissingQuotes() + public function testParseErrorDetectMissingQuotes(): void { $json = '{ foo: "bar" @@ -73,7 +73,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 1', $json); } - public function testParseErrorDetectArrayAsHash() + public function testParseErrorDetectArrayAsHash(): void { $json = '{ "foo": ["bar": "baz"] @@ -81,7 +81,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 2', $json); } - public function testParseErrorDetectMissingComma() + public function testParseErrorDetectMissingComma(): void { $json = '{ "foo": "bar" @@ -90,14 +90,14 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 2', $json); } - public function testSchemaValidation() + public function testSchemaValidation(): void { $json = new JsonFile(__DIR__.'/Fixtures/composer.json'); $this->assertTrue($json->validateSchema()); $this->assertTrue($json->validateSchema(JsonFile::LAX_SCHEMA)); } - public function testSchemaValidationError() + public function testSchemaValidationError(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "name": null }'); @@ -121,7 +121,7 @@ class JsonFileTest extends TestCase unlink($file); } - public function testSchemaValidationLaxAdditionalProperties() + public function testSchemaValidationLaxAdditionalProperties(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "name": "vendor/package", "description": "generic description", "foo": "bar" }'); @@ -137,7 +137,7 @@ class JsonFileTest extends TestCase unlink($file); } - public function testSchemaValidationLaxRequired() + public function testSchemaValidationLaxRequired(): void { $file = $this->createTempFile(); $json = new JsonFile($file); @@ -207,7 +207,7 @@ class JsonFileTest extends TestCase unlink($file); } - public function testCustomSchemaValidationLax() + public function testCustomSchemaValidationLax(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "custom": "property", "another custom": "property" }'); @@ -223,7 +223,7 @@ class JsonFileTest extends TestCase unlink($schema); } - public function testCustomSchemaValidationStrict() + public function testCustomSchemaValidationStrict(): void { $file = $this->createTempFile(); file_put_contents($file, '{ "custom": "property" }'); @@ -239,7 +239,7 @@ class JsonFileTest extends TestCase unlink($schema); } - public function testParseErrorDetectMissingCommaMultiline() + public function testParseErrorDetectMissingCommaMultiline(): void { $json = '{ "foo": "barbar" @@ -249,7 +249,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 2', $json); } - public function testParseErrorDetectMissingColon() + public function testParseErrorDetectMissingColon(): void { $json = '{ "foo": "bar", @@ -258,7 +258,7 @@ class JsonFileTest extends TestCase $this->expectParseException('Parse error on line 3', $json); } - public function testSimpleJsonString() + public function testSimpleJsonString(): void { $data = array('name' => 'composer/composer'); $json = '{ @@ -267,7 +267,7 @@ class JsonFileTest extends TestCase $this->assertJsonFormat($json, $data); } - public function testTrailingBackslash() + public function testTrailingBackslash(): void { $data = array('Metadata\\' => 'src/'); $json = '{ @@ -276,7 +276,7 @@ class JsonFileTest extends TestCase $this->assertJsonFormat($json, $data); } - public function testFormatEmptyArray() + public function testFormatEmptyArray(): void { $data = array('test' => array(), 'test2' => new \stdClass); $json = '{ @@ -286,7 +286,7 @@ class JsonFileTest extends TestCase $this->assertJsonFormat($json, $data); } - public function testEscape() + public function testEscape(): void { $data = array("Metadata\\\"" => 'src/'); $json = '{ @@ -296,7 +296,7 @@ class JsonFileTest extends TestCase $this->assertJsonFormat($json, $data); } - public function testUnicode() + public function testUnicode(): void { $data = array("Žluťoučký \" kůň" => "úpěl ďábelské ódy za €"); $json = '{ @@ -306,35 +306,35 @@ class JsonFileTest extends TestCase $this->assertJsonFormat($json, $data); } - public function testOnlyUnicode() + public function testOnlyUnicode(): void { $data = "\\/ƌ"; $this->assertJsonFormat('"\\\\\\/ƌ"', $data, JSON_UNESCAPED_UNICODE); } - public function testEscapedSlashes() + public function testEscapedSlashes(): void { $data = "\\/foo"; $this->assertJsonFormat('"\\\\\\/foo"', $data, 0); } - public function testEscapedBackslashes() + public function testEscapedBackslashes(): void { $data = "a\\b"; $this->assertJsonFormat('"a\\\\b"', $data, 0); } - public function testEscapedUnicode() + public function testEscapedUnicode(): void { $data = "ƌ"; $this->assertJsonFormat('"\\u018c"', $data, 0); } - public function testDoubleEscapedUnicode() + public function testDoubleEscapedUnicode(): void { $jsonFile = new JsonFile('composer.json'); $data = array("Zdjęcia","hjkjhl\\u0119kkjk"); @@ -351,7 +351,7 @@ class JsonFileTest extends TestCase * @param string $json * @return void */ - private function expectParseException($text, $json) + private function expectParseException($text, $json): void { try { $result = JsonFile::parseJson($json); @@ -367,7 +367,7 @@ class JsonFileTest extends TestCase * @param int|null $options * @return void */ - private function assertJsonFormat($json, $data, $options = null) + private function assertJsonFormat($json, $data, $options = null): void { $file = new JsonFile('composer.json'); diff --git a/tests/Composer/Test/Json/JsonFormatterTest.php b/tests/Composer/Test/Json/JsonFormatterTest.php index d2bd8e0d6..cd95c6fc9 100644 --- a/tests/Composer/Test/Json/JsonFormatterTest.php +++ b/tests/Composer/Test/Json/JsonFormatterTest.php @@ -21,7 +21,7 @@ class JsonFormatterTest extends TestCase * Test if \u0119 will get correctly formatted (unescaped) * https://github.com/composer/composer/issues/2613 */ - public function testUnicodeWithPrependedSlash() + public function testUnicodeWithPrependedSlash(): void { if (!extension_loaded('mbstring')) { $this->markTestSkipped('Test requires the mbstring extension'); @@ -37,7 +37,7 @@ class JsonFormatterTest extends TestCase * Surrogate pairs are intentionally skipped and not unescaped * https://github.com/composer/composer/issues/7510 */ - public function testUtf16SurrogatePair() + public function testUtf16SurrogatePair(): void { if (!extension_loaded('mbstring')) { $this->markTestSkipped('Test requires the mbstring extension'); diff --git a/tests/Composer/Test/Json/JsonManipulatorTest.php b/tests/Composer/Test/Json/JsonManipulatorTest.php index 00fd74bae..6d0900b91 100644 --- a/tests/Composer/Test/Json/JsonManipulatorTest.php +++ b/tests/Composer/Test/Json/JsonManipulatorTest.php @@ -25,14 +25,14 @@ class JsonManipulatorTest extends TestCase * @param string $constraint * @param string $expected */ - public function testAddLink($json, $type, $package, $constraint, $expected) + public function testAddLink($json, $type, $package, $constraint, $expected): void { $manipulator = new JsonManipulator($json); $this->assertTrue($manipulator->addLink($type, $package, $constraint)); $this->assertEquals($expected, $manipulator->getContents()); } - public function linkProvider() + public function linkProvider(): array { return array( array( @@ -1301,14 +1301,14 @@ class JsonManipulatorTest extends TestCase * @param bool $sortPackages * @param string $expected */ - public function testAddLinkAndSortPackages($json, $type, $package, $constraint, $sortPackages, $expected) + public function testAddLinkAndSortPackages($json, $type, $package, $constraint, $sortPackages, $expected): void { $manipulator = new JsonManipulator($json); $this->assertTrue($manipulator->addLink($type, $package, $constraint, $sortPackages)); $this->assertEquals($expected, $manipulator->getContents()); } - public function providerAddLinkAndSortPackages() + public function providerAddLinkAndSortPackages(): array { return array( array( @@ -1385,7 +1385,7 @@ class JsonManipulatorTest extends TestCase * @param string $expected * @param ?string $expectedContent */ - public function testRemoveSubNode($json, $name, $expected, $expectedContent = null) + public function testRemoveSubNode($json, $name, $expected, $expectedContent = null): void { $manipulator = new JsonManipulator($json); @@ -1395,7 +1395,7 @@ class JsonManipulatorTest extends TestCase } } - public function removeSubNodeProvider() + public function removeSubNodeProvider(): array { return array( 'works on simple ones first' => array( @@ -1686,7 +1686,7 @@ class JsonManipulatorTest extends TestCase ); } - public function testRemoveSubNodeFromRequire() + public function testRemoveSubNodeFromRequire(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -1736,7 +1736,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddSubNodeInRequire() + public function testAddSubNodeInRequire(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -1788,7 +1788,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddExtraWithPackage() + public function testAddExtraWithPackage(): void { //$this->markTestSkipped(); $manipulator = new JsonManipulator('{ @@ -1829,7 +1829,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigWithPackage() + public function testAddConfigWithPackage(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -1875,7 +1875,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddSuggestWithPackage() + public function testAddSuggestWithPackage(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -1915,7 +1915,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddRepositoryCanInitializeEmptyRepositories() + public function testAddRepositoryCanInitializeEmptyRepositories(): void { $manipulator = new JsonManipulator('{ "repositories": { @@ -1933,7 +1933,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddRepositoryCanInitializeFromScratch() + public function testAddRepositoryCanInitializeFromScratch(): void { $manipulator = new JsonManipulator("{ \t\"a\": \"b\" @@ -1951,7 +1951,7 @@ class JsonManipulatorTest extends TestCase ", $manipulator->getContents()); } - public function testAddRepositoryCanAppend() + public function testAddRepositoryCanAppend(): void { $manipulator = new JsonManipulator('{ "repositories": { @@ -1977,7 +1977,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddRepositoryCanPrepend() + public function testAddRepositoryCanPrepend(): void { $manipulator = new JsonManipulator('{ "repositories": { @@ -2003,7 +2003,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddRepositoryCanOverrideDeepRepos() + public function testAddRepositoryCanOverrideDeepRepos(): void { $manipulator = new JsonManipulator('{ "repositories": { @@ -2025,7 +2025,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingEscapes() + public function testAddConfigSettingEscapes(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2043,7 +2043,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingWorksFromScratch() + public function testAddConfigSettingWorksFromScratch(): void { $manipulator = new JsonManipulator('{ }'); @@ -2059,7 +2059,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanAdd() + public function testAddConfigSettingCanAdd(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2077,7 +2077,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanOverwrite() + public function testAddConfigSettingCanOverwrite(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2096,7 +2096,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanOverwriteNumbers() + public function testAddConfigSettingCanOverwriteNumbers(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2113,7 +2113,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanOverwriteArrays() + public function testAddConfigSettingCanOverwriteArrays(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2148,7 +2148,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanAddSubKeyInEmptyConfig() + public function testAddConfigSettingCanAddSubKeyInEmptyConfig(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2166,7 +2166,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanAddSubKeyInEmptyVal() + public function testAddConfigSettingCanAddSubKeyInEmptyVal(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2195,7 +2195,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddConfigSettingCanAddSubKeyInHash() + public function testAddConfigSettingCanAddSubKeyInHash(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2217,7 +2217,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddRootSettingDoesNotBreakDots() + public function testAddRootSettingDoesNotBreakDots(): void { $manipulator = new JsonManipulator('{ "github-oauth": { @@ -2235,7 +2235,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveConfigSettingCanRemoveSubKeyInHash() + public function testRemoveConfigSettingCanRemoveSubKeyInHash(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2257,7 +2257,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveConfigSettingCanRemoveSubKeyInHashWithSiblings() + public function testRemoveConfigSettingCanRemoveSubKeyInHashWithSiblings(): void { $manipulator = new JsonManipulator('{ "config": { @@ -2281,7 +2281,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddMainKey() + public function testAddMainKey(): void { $manipulator = new JsonManipulator('{ "foo": "bar" @@ -2295,7 +2295,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddMainKeyWithContentHavingDollarSignFollowedByDigit() + public function testAddMainKeyWithContentHavingDollarSignFollowedByDigit(): void { $manipulator = new JsonManipulator('{ "foo": "bar" @@ -2309,7 +2309,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testAddMainKeyWithContentHavingDollarSignFollowedByDigit2() + public function testAddMainKeyWithContentHavingDollarSignFollowedByDigit2(): void { $manipulator = new JsonManipulator('{}'); @@ -2320,7 +2320,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testUpdateMainKey() + public function testUpdateMainKey(): void { $manipulator = new JsonManipulator('{ "foo": "bar" @@ -2333,7 +2333,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testUpdateMainKey2() + public function testUpdateMainKey2(): void { $manipulator = new JsonManipulator('{ "a": { @@ -2357,7 +2357,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testUpdateMainKey3() + public function testUpdateMainKey3(): void { $manipulator = new JsonManipulator('{ "require": { @@ -2380,7 +2380,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testUpdateMainKeyWithContentHavingDollarSignFollowedByDigit() + public function testUpdateMainKeyWithContentHavingDollarSignFollowedByDigit(): void { $manipulator = new JsonManipulator('{ "foo": "bar" @@ -2393,7 +2393,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveMainKey() + public function testRemoveMainKey(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -2453,7 +2453,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveMainKeyIfEmpty() + public function testRemoveMainKeyIfEmpty(): void { $manipulator = new JsonManipulator('{ "repositories": [ @@ -2495,7 +2495,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveMainKeyRemovesKeyWhereValueIsNull() + public function testRemoveMainKeyRemovesKeyWhereValueIsNull(): void { $manipulator = new JsonManipulator(json_encode(array( 'foo' => 9000, @@ -2511,7 +2511,7 @@ class JsonManipulatorTest extends TestCase $this->assertJsonStringEqualsJsonString($expected, $manipulator->getContents()); } - public function testIndentDetection() + public function testIndentDetection(): void { $manipulator = new JsonManipulator('{ @@ -2533,7 +2533,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testRemoveMainKeyAtEndOfFile() + public function testRemoveMainKeyAtEndOfFile(): void { $manipulator = new JsonManipulator('{ "require": { @@ -2562,7 +2562,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testEscapedUnicodeDoesNotCauseBacktrackLimitErrorGithubIssue8131() + public function testEscapedUnicodeDoesNotCauseBacktrackLimitErrorGithubIssue8131(): void { $manipulator = new JsonManipulator('{ "description": "Some U\u00F1icode", @@ -2582,7 +2582,7 @@ class JsonManipulatorTest extends TestCase ', $manipulator->getContents()); } - public function testLargeFileDoesNotCauseBacktrackLimitErrorGithubIssue9595() + public function testLargeFileDoesNotCauseBacktrackLimitErrorGithubIssue9595(): void { $manipulator = new JsonManipulator('{ "name": "leoloso/pop", diff --git a/tests/Composer/Test/Json/JsonValidationExceptionTest.php b/tests/Composer/Test/Json/JsonValidationExceptionTest.php index 2212b26c2..79c436833 100644 --- a/tests/Composer/Test/Json/JsonValidationExceptionTest.php +++ b/tests/Composer/Test/Json/JsonValidationExceptionTest.php @@ -19,27 +19,27 @@ class JsonValidationExceptionTest extends TestCase { /** * @dataProvider errorProvider - * @param string|null $message - * @param string[]|null $errors + * @param string[] $errors + * @param string[] $expectedErrors */ - public function testGetErrors($message, $errors) + public function testGetErrors(?string $message, array $errors, string $expectedMessage, array $expectedErrors): void { $object = new JsonValidationException($message, $errors); - $this->assertEquals($message, $object->getMessage()); - $this->assertEquals($errors, $object->getErrors()); + $this->assertSame($expectedMessage, $object->getMessage()); + $this->assertSame($expectedErrors, $object->getErrors()); } - public function testGetErrorsWhenNoErrorsProvided() + public function testGetErrorsWhenNoErrorsProvided(): void { $object = new JsonValidationException('test message'); $this->assertEquals(array(), $object->getErrors()); } - public function errorProvider() + public function errorProvider(): array { return array( - array('test message', array()), - array(null, null), + array('test message', array(), 'test message', []), + array(null, ['foo'], '', ['foo']), ); } } diff --git a/tests/Composer/Test/Mock/FactoryMock.php b/tests/Composer/Test/Mock/FactoryMock.php index 79b50e19d..8db24fe11 100644 --- a/tests/Composer/Test/Mock/FactoryMock.php +++ b/tests/Composer/Test/Mock/FactoryMock.php @@ -12,9 +12,12 @@ namespace Composer\Test\Mock; +use Composer\Installer\InstallationManager; +use Composer\Package\Loader\RootPackageLoader; use Composer\Composer; use Composer\Config; use Composer\Factory; +use Composer\PartialComposer; use Composer\Repository\RepositoryManager; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; @@ -30,7 +33,7 @@ use Composer\Util\ProcessExecutor; class FactoryMock extends Factory { - public static function createConfig(IOInterface $io = null, $cwd = null) + public static function createConfig(IOInterface $io = null, ?string $cwd = null): Config { $config = new Config(true, $cwd); @@ -42,26 +45,26 @@ class FactoryMock extends Factory return $config; } - 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): RootPackageLoader { return new \Composer\Package\Loader\RootPackageLoader($rm, $config, $parser, new VersionGuesserMock(), $io); } - 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 { $rm->setLocalRepository(new InstalledArrayRepository); } - public function createInstallationManager(Loop $loop, IOInterface $io, EventDispatcher $dispatcher = null) + public function createInstallationManager(Loop $loop, IOInterface $io, EventDispatcher $dispatcher = null): InstallationManager { return new InstallationManagerMock(); } - protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io, ProcessExecutor $process = null) + protected function createDefaultInstallers(InstallationManager $im, PartialComposer $composer, IOInterface $io, ProcessExecutor $process = null): void { } - protected function purgePackages(InstalledRepositoryInterface $repo, Installer\InstallationManager $im) + protected function purgePackages(InstalledRepositoryInterface $repo, InstallationManager $im): void { } } diff --git a/tests/Composer/Test/Mock/HttpDownloaderMock.php b/tests/Composer/Test/Mock/HttpDownloaderMock.php index a317d8b45..b919b294b 100644 --- a/tests/Composer/Test/Mock/HttpDownloaderMock.php +++ b/tests/Composer/Test/Mock/HttpDownloaderMock.php @@ -91,7 +91,7 @@ class HttpDownloaderMock extends HttpDownloader } if (count($this->expectations) > 0) { - $expectations = array_map(function ($expect) { + $expectations = array_map(function ($expect): string { return $expect['url']; }, $this->expectations); throw new AssertionFailedError( diff --git a/tests/Composer/Test/Mock/InstallationManagerMock.php b/tests/Composer/Test/Mock/InstallationManagerMock.php index ed4b33996..ed4eaa873 100644 --- a/tests/Composer/Test/Mock/InstallationManagerMock.php +++ b/tests/Composer/Test/Mock/InstallationManagerMock.php @@ -12,6 +12,7 @@ namespace Composer\Test\Mock; +use React\Promise\PromiseInterface; use Composer\Installer\InstallationManager; use Composer\Repository\InstalledRepositoryInterface; use Composer\Package\PackageInterface; @@ -45,7 +46,7 @@ class InstallationManagerMock extends InstallationManager { } - public function execute(InstalledRepositoryInterface $repo, array $operations, $devMode = true, $runScripts = true) + public function execute(InstalledRepositoryInterface $repo, array $operations, $devMode = true, $runScripts = true): void { foreach ($operations as $operation) { $method = $operation->getOperationType(); @@ -54,12 +55,12 @@ class InstallationManagerMock extends InstallationManager } } - public function getInstallPath(PackageInterface $package) + public function getInstallPath(PackageInterface $package): string { return ''; } - public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) + public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool { return $repo->hasPackage($package); } @@ -67,7 +68,7 @@ class InstallationManagerMock extends InstallationManager /** * @inheritDoc */ - public function install(InstalledRepositoryInterface $repo, InstallOperation $operation) + public function install(InstalledRepositoryInterface $repo, InstallOperation $operation): ?PromiseInterface { $this->installed[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); @@ -79,7 +80,7 @@ class InstallationManagerMock extends InstallationManager /** * @inheritDoc */ - public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation) + public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface { $this->updated[] = array($operation->getInitialPackage(), $operation->getTargetPackage()); $this->trace[] = strip_tags((string) $operation); @@ -94,7 +95,7 @@ class InstallationManagerMock extends InstallationManager /** * @inheritDoc */ - public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation) + public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation): ?PromiseInterface { $this->uninstalled[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); @@ -103,7 +104,7 @@ class InstallationManagerMock extends InstallationManager return null; } - public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation) + public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void { $package = $operation->getPackage(); @@ -113,7 +114,7 @@ class InstallationManagerMock extends InstallationManager parent::markAliasInstalled($repo, $operation); } - public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation) + public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void { $this->uninstalled[] = $operation->getPackage(); $this->trace[] = strip_tags((string) $operation); @@ -122,36 +123,36 @@ class InstallationManagerMock extends InstallationManager } /** @return string[] */ - public function getTrace() + public function getTrace(): array { return $this->trace; } /** @return PackageInterface[] */ - public function getInstalledPackages() + public function getInstalledPackages(): array { return $this->installed; } /** @return PackageInterface[][] */ - public function getUpdatedPackages() + public function getUpdatedPackages(): array { return $this->updated; } /** @return PackageInterface[] */ - public function getUninstalledPackages() + public function getUninstalledPackages(): array { return $this->uninstalled; } - public function notifyInstalls(IOInterface $io) + public function notifyInstalls(IOInterface $io): void { // noop } /** @return PackageInterface[] */ - public function getInstalledPackagesByType() + public function getInstalledPackagesByType(): array { return $this->installed; } diff --git a/tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php b/tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php index 574cfbd83..101005cda 100644 --- a/tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php +++ b/tests/Composer/Test/Mock/InstalledFilesystemRepositoryMock.php @@ -17,11 +17,11 @@ use Composer\Installer\InstallationManager; class InstalledFilesystemRepositoryMock extends InstalledFilesystemRepository { - public function reload() + public function reload(): void { } - public function write($devMode, InstallationManager $installationManager) + public function write($devMode, InstallationManager $installationManager): void { } } diff --git a/tests/Composer/Test/Mock/ProcessExecutorMock.php b/tests/Composer/Test/Mock/ProcessExecutorMock.php index 9228c1310..277ead749 100644 --- a/tests/Composer/Test/Mock/ProcessExecutorMock.php +++ b/tests/Composer/Test/Mock/ProcessExecutorMock.php @@ -12,6 +12,7 @@ namespace Composer\Test\Mock; +use React\Promise\PromiseInterface; use Composer\Util\ProcessExecutor; use Composer\Util\Platform; use PHPUnit\Framework\Assert; @@ -48,11 +49,11 @@ class ProcessExecutorMock extends ProcessExecutor * * @return void */ - public function expects(array $expectations, $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')) + public function expects(array $expectations, $strict = false, array $defaultHandler = array('return' => 0, 'stdout' => '', 'stderr' => '')): void { /** @var array{cmd: string|list, return?: int, stdout?: string, stderr?: string, callback?: callable} $default */ $default = array('cmd' => '', 'return' => 0, 'stdout' => '', 'stderr' => '', 'callback' => null); - $this->expectations = array_map(function ($expect) use ($default) { + $this->expectations = array_map(function ($expect) use ($default): array { if (is_string($expect)) { $command = $expect; $expect = $default; @@ -88,7 +89,7 @@ class ProcessExecutorMock extends ProcessExecutor } if (count($this->expectations) > 0) { - $expectations = array_map(function ($expect) { + $expectations = array_map(function ($expect): string { return is_array($expect['cmd']) ? implode(' ', $expect['cmd']) : $expect['cmd']; }, $this->expectations); throw new AssertionFailedError( @@ -102,7 +103,7 @@ class ProcessExecutorMock extends ProcessExecutor Assert::assertTrue(true); // @phpstan-ignore-line } - public function execute($command, &$output = null, $cwd = null) + public function execute($command, &$output = null, $cwd = null): int { if (func_num_args() > 1) { return $this->doExecute($command, $cwd, false, $output); @@ -111,7 +112,7 @@ class ProcessExecutorMock extends ProcessExecutor return $this->doExecute($command, $cwd, false); } - public function executeTty($command, $cwd = null) + public function executeTty($command, $cwd = null): int { if (Platform::isTty()) { return $this->doExecute($command, $cwd, true); @@ -173,21 +174,21 @@ class ProcessExecutorMock extends ProcessExecutor return $return; } - public function executeAsync($command, $cwd = null) + public function executeAsync($command, $cwd = null): PromiseInterface { - $resolver = function ($resolve, $reject) { + $resolver = function ($resolve, $reject): void { // TODO strictly speaking this should resolve with a mock Process instance here $resolve(); }; - $canceler = function () { + $canceler = function (): void { throw new \RuntimeException('Aborted process'); }; return new Promise($resolver, $canceler); } - public function getErrorOutput() + public function getErrorOutput(): string { return $this->errorOutput; } diff --git a/tests/Composer/Test/Mock/VersionGuesserMock.php b/tests/Composer/Test/Mock/VersionGuesserMock.php index d2fe1236c..b634b0297 100644 --- a/tests/Composer/Test/Mock/VersionGuesserMock.php +++ b/tests/Composer/Test/Mock/VersionGuesserMock.php @@ -20,7 +20,7 @@ class VersionGuesserMock extends VersionGuesser { } - public function guessVersion(array $packageConfig, $path) + public function guessVersion(array $packageConfig, $path): ?array { return null; } diff --git a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php index 883dd4278..ad9bce604 100644 --- a/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchivableFilesFinderTest.php @@ -102,7 +102,7 @@ class ArchivableFilesFinderTest extends TestCase $fs->removeDirectory($this->sources); } - public function testManualExcludes() + public function testManualExcludes(): void { $excludes = array( 'prefixB.foo', @@ -154,7 +154,7 @@ class ArchivableFilesFinderTest extends TestCase )); } - public function testGitExcludes() + public function testGitExcludes(): void { $this->skipIfNotExecutable('git'); @@ -202,7 +202,7 @@ class ArchivableFilesFinderTest extends TestCase )); } - public function testSkipExcludes() + public function testSkipExcludes(): void { $excludes = array( 'prefixB.foo', @@ -260,7 +260,7 @@ class ArchivableFilesFinderTest extends TestCase /** * @return string[] */ - protected function getArchivableFiles() + protected function getArchivableFiles(): array { $files = array(); foreach ($this->finder as $file) { @@ -279,7 +279,7 @@ class ArchivableFilesFinderTest extends TestCase * * @return string[] */ - protected function getArchivedFiles($command) + protected function getArchivedFiles($command): array { $process = Process::fromShellCommandline($command, $this->sources); $process->run(); @@ -303,7 +303,7 @@ class ArchivableFilesFinderTest extends TestCase * * @return void */ - protected function assertArchivableFiles($expectedFiles) + protected function assertArchivableFiles($expectedFiles): void { $actualFiles = $this->getArchivableFiles(); diff --git a/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php b/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php index 9d1aff56e..8d620fbc9 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiveManagerTest.php @@ -48,7 +48,7 @@ class ArchiveManagerTest extends ArchiverTest $this->targetDir = $this->testDir.'/composer_archiver_tests'; } - public function testUnknownFormat() + public function testUnknownFormat(): void { self::expectException('RuntimeException'); @@ -57,7 +57,7 @@ class ArchiveManagerTest extends ArchiverTest $this->manager->archive($package, '__unknown_format__', $this->targetDir); } - public function testArchiveTar() + public function testArchiveTar(): void { $this->skipIfNotExecutable('git'); @@ -76,7 +76,7 @@ class ArchiveManagerTest extends ArchiverTest unlink($target); } - public function testArchiveCustomFileName() + public function testArchiveCustomFileName(): void { $this->skipIfNotExecutable('git'); @@ -104,7 +104,7 @@ class ArchiveManagerTest extends ArchiverTest * * @return string */ - protected function getTargetName(CompletePackage $package, $format, $fileName = null) + protected function getTargetName(CompletePackage $package, $format, $fileName = null): string { if (null === $fileName) { $packageName = $this->manager->getPackageFilename($package); @@ -120,7 +120,7 @@ class ArchiveManagerTest extends ArchiverTest * * @return void */ - protected function setupGitRepo() + protected function setupGitRepo(): void { $currentWorkDir = getcwd(); chdir($this->testDir); diff --git a/tests/Composer/Test/Package/Archiver/ArchiverTest.php b/tests/Composer/Test/Package/Archiver/ArchiverTest.php index 9601fa1c6..5ac901d1b 100644 --- a/tests/Composer/Test/Package/Archiver/ArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ArchiverTest.php @@ -52,7 +52,7 @@ abstract class ArchiverTest extends TestCase * * @return CompletePackage */ - protected function setupPackage() + protected function setupPackage(): CompletePackage { $package = new CompletePackage('archivertest/archivertest', 'master', 'master'); $package->setSourceUrl(realpath($this->testDir)); diff --git a/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php b/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php index e8cae5853..2c8f96a2e 100644 --- a/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php +++ b/tests/Composer/Test/Package/Archiver/GitExcludeFilterTest.php @@ -23,14 +23,14 @@ class GitExcludeFilterTest extends TestCase * @param string $ignore * @param mixed[] $expected */ - public function testPatternEscape($ignore, $expected) + public function testPatternEscape($ignore, $expected): void { $filter = new GitExcludeFilter('/'); $this->assertEquals($expected, $filter->parseGitAttributesLine($ignore)); } - public function providePatterns() + public function providePatterns(): array { return array( array('app/config/parameters.yml export-ignore', array('{(?=[^\.])app/(?=[^\.])config/(?=[^\.])parameters\.yml(?=$|/)}', false, false)), diff --git a/tests/Composer/Test/Package/Archiver/PharArchiverTest.php b/tests/Composer/Test/Package/Archiver/PharArchiverTest.php index 82ed226f3..5c571316a 100644 --- a/tests/Composer/Test/Package/Archiver/PharArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/PharArchiverTest.php @@ -16,7 +16,7 @@ use Composer\Package\Archiver\PharArchiver; class PharArchiverTest extends ArchiverTest { - public function testTarArchive() + public function testTarArchive(): void { // Set up repository $this->setupDummyRepo(); @@ -31,7 +31,7 @@ class PharArchiverTest extends ArchiverTest $this->filesystem->removeDirectory(dirname($target)); } - public function testZipArchive() + public function testZipArchive(): void { // Set up repository $this->setupDummyRepo(); @@ -51,7 +51,7 @@ class PharArchiverTest extends ArchiverTest * * @return void */ - protected function setupDummyRepo() + protected function setupDummyRepo(): void { $currentWorkDir = getcwd(); chdir($this->testDir); @@ -72,7 +72,7 @@ class PharArchiverTest extends ArchiverTest * * @return void */ - protected function writeFile($path, $content, $currentWorkDir) + protected function writeFile($path, $content, $currentWorkDir): void { if (!file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); diff --git a/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php b/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php index 616768c01..e88711a4c 100644 --- a/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php +++ b/tests/Composer/Test/Package/Archiver/ZipArchiverTest.php @@ -23,7 +23,7 @@ class ZipArchiverTest extends ArchiverTest * * @dataProvider provideGitignoreExcludeNegationTestCases */ - public function testGitignoreExcludeNegation($include) + public function testGitignoreExcludeNegation($include): void { $this->testZipArchive(array( 'docs/README.md' => '# The doc', @@ -31,7 +31,7 @@ class ZipArchiverTest extends ArchiverTest )); } - public function provideGitignoreExcludeNegationTestCases() + public function provideGitignoreExcludeNegationTestCases(): array { return array( array('!/docs'), @@ -42,7 +42,7 @@ class ZipArchiverTest extends ArchiverTest /** * @param array $files */ - public function testZipArchive(array $files = array()) + public function testZipArchive(array $files = array()): void { if (!class_exists('ZipArchive')) { $this->markTestSkipped('Cannot run ZipArchiverTest, missing class "ZipArchive".'); @@ -87,7 +87,7 @@ class ZipArchiverTest extends ArchiverTest * * @return void */ - protected function setupDummyRepo(array &$files) + protected function setupDummyRepo(array &$files): void { $currentWorkDir = getcwd(); chdir($this->testDir); @@ -108,7 +108,7 @@ class ZipArchiverTest extends ArchiverTest * * @return void */ - protected function writeFile($path, $content, $currentWorkDir) + protected function writeFile($path, $content, $currentWorkDir): void { if (!file_exists(dirname($path))) { mkdir(dirname($path), 0777, true); diff --git a/tests/Composer/Test/Package/BasePackageTest.php b/tests/Composer/Test/Package/BasePackageTest.php index 627bbfb62..3b92316b2 100644 --- a/tests/Composer/Test/Package/BasePackageTest.php +++ b/tests/Composer/Test/Package/BasePackageTest.php @@ -20,7 +20,7 @@ class BasePackageTest extends TestCase /** * @doesNotPerformAssertions */ - public function testSetSameRepository() + public function testSetSameRepository(): void { $package = $this->getMockForAbstractClass('Composer\Package\BasePackage', array('foo')); $repository = $this->getMockBuilder('Composer\Repository\RepositoryInterface')->getMock(); @@ -33,7 +33,7 @@ class BasePackageTest extends TestCase } } - public function testSetAnotherRepository() + public function testSetAnotherRepository(): void { self::expectException('LogicException'); @@ -49,12 +49,12 @@ class BasePackageTest extends TestCase * @param bool $truncate * @param string $expected */ - public function testFormatVersionForDevPackage(BasePackage $package, $truncate, $expected) + public function testFormatVersionForDevPackage(BasePackage $package, $truncate, $expected): void { $this->assertSame($expected, $package->getFullPrettyVersion($truncate)); } - public function provideFormattedVersions() + public function provideFormattedVersions(): array { $data = array( array( @@ -79,7 +79,7 @@ class BasePackageTest extends TestCase ), ); - $createPackage = function ($arr) { + $createPackage = function ($arr): array { $package = $this->getMockForAbstractClass('\Composer\Package\BasePackage', array(), '', false); $package->expects($this->once())->method('isDev')->will($this->returnValue(true)); $package->expects($this->any())->method('getSourceType')->will($this->returnValue('git')); @@ -99,7 +99,7 @@ class BasePackageTest extends TestCase * * @dataProvider dataPackageNamesToRegexp */ - public function testPackageNamesToRegexp(array $packageNames, $wrap, $expectedRegexp) + public function testPackageNamesToRegexp(array $packageNames, $wrap, $expectedRegexp): void { $regexp = BasePackage::packageNamesToRegexp($packageNames, $wrap); @@ -109,7 +109,7 @@ class BasePackageTest extends TestCase /** * @return mixed[][] */ - public function dataPackageNamesToRegexp() + public function dataPackageNamesToRegexp(): array { return array( array( diff --git a/tests/Composer/Test/Package/CompletePackageTest.php b/tests/Composer/Test/Package/CompletePackageTest.php index 848315a1d..2f8de80d1 100644 --- a/tests/Composer/Test/Package/CompletePackageTest.php +++ b/tests/Composer/Test/Package/CompletePackageTest.php @@ -23,7 +23,7 @@ class CompletePackageTest extends TestCase * * demonstrates several versioning schemes */ - public function providerVersioningSchemes() + public function providerVersioningSchemes(): array { $provider[] = array('foo', '1-beta'); $provider[] = array('node', '0.5.6'); @@ -40,7 +40,7 @@ class CompletePackageTest extends TestCase * @param string $name * @param string $version */ - public function testPackageHasExpectedNamingSemantics($name, $version) + public function testPackageHasExpectedNamingSemantics($name, $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); @@ -54,7 +54,7 @@ class CompletePackageTest extends TestCase * @param string $name * @param string $version */ - public function testPackageHasExpectedVersioningSemantics($name, $version) + public function testPackageHasExpectedVersioningSemantics($name, $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); @@ -69,7 +69,7 @@ class CompletePackageTest extends TestCase * @param string $name * @param string $version */ - public function testPackageHasExpectedMarshallingSemantics($name, $version) + public function testPackageHasExpectedMarshallingSemantics($name, $version): void { $versionParser = new VersionParser(); $normVersion = $versionParser->normalize($version); @@ -77,7 +77,7 @@ class CompletePackageTest extends TestCase $this->assertEquals(strtolower($name).'-'.$normVersion, (string) $package); } - public function testGetTargetDir() + public function testGetTargetDir(): void { $package = new Package('a', '1.0.0.0', '1.0'); diff --git a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php index f3ab86c3c..b5ee6d073 100644 --- a/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php +++ b/tests/Composer/Test/Package/Dumper/ArrayDumperTest.php @@ -35,7 +35,7 @@ class ArrayDumperTest extends TestCase $this->packageExpects('getTransportOptions', array()); } - public function testRequiredInformation() + public function testRequiredInformation(): void { $this ->packageExpects('getPrettyName', 'foo') @@ -54,7 +54,7 @@ class ArrayDumperTest extends TestCase ); } - public function testRootPackage() + public function testRootPackage(): void { $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); @@ -67,7 +67,7 @@ class ArrayDumperTest extends TestCase $this->assertSame('dev', $config['minimum-stability']); } - public function testDumpAbandoned() + public function testDumpAbandoned(): void { $this->packageExpects('isAbandoned', true); $this->packageExpects('getReplacementPackage', true); @@ -77,7 +77,7 @@ class ArrayDumperTest extends TestCase $this->assertTrue($config['abandoned']); } - public function testDumpAbandonedReplacement() + public function testDumpAbandonedReplacement(): void { $this->packageExpects('isAbandoned', true); $this->packageExpects('getReplacementPackage', 'foo/bar'); @@ -95,7 +95,7 @@ class ArrayDumperTest extends TestCase * @param string $method * @param mixed $expectedValue */ - public function testKeys($key, $value, $method = null, $expectedValue = null) + public function testKeys($key, $value, $method = null, $expectedValue = null): void { $this->package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); @@ -111,7 +111,7 @@ class ArrayDumperTest extends TestCase $this->assertSame($expectedValue ?: $value, $config[$key]); } - public function provideKeys() + public function provideKeys(): array { return array( array( @@ -247,10 +247,8 @@ class ArrayDumperTest extends TestCase /** * @param string $method * @param mixed $value - * - * @return self */ - private function packageExpects($method, $value) + private function packageExpects($method, $value): \Composer\Test\Package\Dumper\ArrayDumperTest { $this->package ->expects($this->any()) diff --git a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php index 86a016e55..cc961575e 100644 --- a/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/ArrayLoaderTest.php @@ -29,7 +29,7 @@ class ArrayLoaderTest extends TestCase $this->loader = new ArrayLoader(null); } - public function testSelfVersion() + public function testSelfVersion(): void { $config = array( 'name' => 'A', @@ -44,7 +44,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals('== 1.2.3.4', (string) $replaces['foo']->getConstraint()); } - public function testTypeDefault() + public function testTypeDefault(): void { $config = array( 'name' => 'A', @@ -64,7 +64,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals('foo', $package->getType()); } - public function testNormalizedVersionOptimization() + public function testNormalizedVersionOptimization(): void { $config = array( 'name' => 'A', @@ -84,7 +84,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals('1.2.3.4', $package->getVersion()); } - public function parseDumpProvider() + public function parseDumpProvider(): array { $validConfig = array( 'name' => 'A/B', @@ -139,7 +139,7 @@ class ArrayLoaderTest extends TestCase * * @return array */ - protected function fixConfigWhenLoadConfigIsFalse($config) + protected function fixConfigWhenLoadConfigIsFalse($config): array { $expectedConfig = $config; unset($expectedConfig['transport-options']); @@ -155,7 +155,7 @@ class ArrayLoaderTest extends TestCase * * @param array $config */ - public function testParseDumpDefaultLoadConfig($config) + public function testParseDumpDefaultLoadConfig($config): void { $package = $this->loader->load($config); $dumper = new ArrayDumper; @@ -168,7 +168,7 @@ class ArrayLoaderTest extends TestCase * * @param array $config */ - public function testParseDumpTrueLoadConfig($config) + public function testParseDumpTrueLoadConfig($config): void { $loader = new ArrayLoader(null, true); $package = $loader->load($config); @@ -182,7 +182,7 @@ class ArrayLoaderTest extends TestCase * * @param array $config */ - public function testParseDumpFalseLoadConfig($config) + public function testParseDumpFalseLoadConfig($config): void { $loader = new ArrayLoader(null, false); $package = $loader->load($config); @@ -191,7 +191,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals($expectedConfig, $dumper->dump($package)); } - public function testPackageWithBranchAlias() + public function testPackageWithBranchAlias(): void { $config = array( 'name' => 'A', @@ -249,7 +249,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals('4.x-dev', $package->getPrettyVersion()); } - public function testAbandoned() + public function testAbandoned(): void { $config = array( 'name' => 'A', @@ -262,7 +262,7 @@ class ArrayLoaderTest extends TestCase $this->assertEquals('foo/bar', $package->getReplacementPackage()); } - public function testNotAbandoned() + public function testNotAbandoned(): void { $config = array( 'name' => 'A', @@ -273,7 +273,7 @@ class ArrayLoaderTest extends TestCase $this->assertFalse($package->isAbandoned()); } - public function providePluginApiVersions() + public function providePluginApiVersions(): array { return array( array('1.0'), @@ -299,7 +299,7 @@ class ArrayLoaderTest extends TestCase * * @param string $apiVersion */ - public function testPluginApiVersionAreKeptAsDeclared($apiVersion) + public function testPluginApiVersionAreKeptAsDeclared($apiVersion): void { $links = $this->loader->parseLinks('Plugin', '9.9.9', Link::TYPE_REQUIRE, array('composer-plugin-api' => $apiVersion)); @@ -307,7 +307,7 @@ class ArrayLoaderTest extends TestCase $this->assertSame($apiVersion, $links['composer-plugin-api']->getConstraint()->getPrettyString()); } - public function testPluginApiVersionDoesSupportSelfVersion() + public function testPluginApiVersionDoesSupportSelfVersion(): void { $links = $this->loader->parseLinks('Plugin', '6.6.6', Link::TYPE_REQUIRE, array('composer-plugin-api' => 'self.version')); @@ -315,7 +315,7 @@ class ArrayLoaderTest extends TestCase $this->assertSame('6.6.6', $links['composer-plugin-api']->getConstraint()->getPrettyString()); } - public function testNoneStringVersion() + public function testNoneStringVersion(): void { $config = array( 'name' => 'acme/package', diff --git a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php index 252fb4840..a2fa3730a 100644 --- a/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/RootPackageLoaderTest.php @@ -28,7 +28,7 @@ class RootPackageLoaderTest extends TestCase * * @return RootPackage|RootAliasPackage */ - protected function loadPackage($data) + protected function loadPackage($data): \Composer\Package\PackageInterface { $manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager') ->disableOriginalConstructor() @@ -42,7 +42,7 @@ class RootPackageLoaderTest extends TestCase return $loader->load($data); } - public function testStabilityFlagsParsing() + public function testStabilityFlagsParsing(): void { $package = $this->loadPackage(array( 'require' => array( @@ -70,7 +70,7 @@ class RootPackageLoaderTest extends TestCase ), $package->getStabilityFlags()); } - public function testNoVersionIsVisibleInPrettyVersion() + public function testNoVersionIsVisibleInPrettyVersion(): void { $manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager') ->disableOriginalConstructor() @@ -88,7 +88,7 @@ class RootPackageLoaderTest extends TestCase $this->assertEquals(RootPackage::DEFAULT_PRETTY_VERSION, $package->getPrettyVersion()); } - public function testPrettyVersionForRootPackageInVersionBranch() + public function testPrettyVersionForRootPackageInVersionBranch(): void { // see #6845 $manager = $this->getMockBuilder('Composer\\Repository\\RepositoryManager')->disableOriginalConstructor()->getMock(); @@ -109,7 +109,7 @@ class RootPackageLoaderTest extends TestCase $this->assertEquals('3.0-dev', $package->getPrettyVersion()); } - public function testFeatureBranchPrettyVersion() + public function testFeatureBranchPrettyVersion(): void { if (!function_exists('proc_open')) { $this->markTestSkipped('proc_open() is not available'); @@ -137,7 +137,7 @@ class RootPackageLoaderTest extends TestCase $this->assertEquals("dev-master", $package->getPrettyVersion()); } - public function testNonFeatureBranchPrettyVersion() + public function testNonFeatureBranchPrettyVersion(): void { if (!function_exists('proc_open')) { $this->markTestSkipped('proc_open() is not available'); diff --git a/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php b/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php index 68768ca69..0b214cb56 100644 --- a/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php +++ b/tests/Composer/Test/Package/Loader/ValidatingArrayLoaderTest.php @@ -23,7 +23,7 @@ class ValidatingArrayLoaderTest extends TestCase * * @param array $config */ - public function testLoadSuccess($config) + public function testLoadSuccess($config): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $internalLoader @@ -35,7 +35,7 @@ class ValidatingArrayLoaderTest extends TestCase $loader->load($config); } - public function successProvider() + public function successProvider(): array { return array( array( // minimal @@ -212,7 +212,7 @@ class ValidatingArrayLoaderTest extends TestCase * @param array $config * @param string[] $expectedErrors */ - public function testLoadFailureThrowsException($config, $expectedErrors) + public function testLoadFailureThrowsException($config, $expectedErrors): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL); @@ -233,7 +233,7 @@ class ValidatingArrayLoaderTest extends TestCase * @param array $config * @param string[] $expectedWarnings */ - public function testLoadWarnings($config, $expectedWarnings) + public function testLoadWarnings($config, $expectedWarnings): void { $internalLoader = $this->getMockBuilder('Composer\Package\Loader\LoaderInterface')->getMock(); $loader = new ValidatingArrayLoader($internalLoader, true, null, ValidatingArrayLoader::CHECK_ALL); @@ -252,7 +252,7 @@ class ValidatingArrayLoaderTest extends TestCase * @param string[] $expectedWarnings * @param bool $mustCheck */ - public function testLoadSkipsWarningDataWhenIgnoringErrors($config, $expectedWarnings, $mustCheck = true) + public function testLoadSkipsWarningDataWhenIgnoringErrors($config, $expectedWarnings, $mustCheck = true): void { if (!$mustCheck) { $this->assertTrue(true); @@ -270,7 +270,7 @@ class ValidatingArrayLoaderTest extends TestCase $loader->load($config); } - public function errorProvider() + public function errorProvider(): array { $invalidNames = array( 'foo', @@ -420,7 +420,7 @@ class ValidatingArrayLoaderTest extends TestCase )); } - public function warningProvider() + public function warningProvider(): array { return array( array( diff --git a/tests/Composer/Test/Package/LockerTest.php b/tests/Composer/Test/Package/LockerTest.php index 3541de44f..17168f62a 100644 --- a/tests/Composer/Test/Package/LockerTest.php +++ b/tests/Composer/Test/Package/LockerTest.php @@ -20,7 +20,7 @@ use Composer\Test\TestCase; class LockerTest extends TestCase { - public function testIsLocked() + public function testIsLocked(): void { $json = $this->createJsonFileMock(); $locker = new Locker( @@ -42,7 +42,7 @@ class LockerTest extends TestCase $this->assertTrue($locker->isLocked()); } - public function testGetNotLockedPackages() + public function testGetNotLockedPackages(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -59,7 +59,7 @@ class LockerTest extends TestCase $locker->getLockedRepository(); } - public function testGetLockedPackages() + public function testGetLockedPackages(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -85,7 +85,7 @@ class LockerTest extends TestCase $this->assertNotNull($repo->findPackage('pkg2', '0.1.10')); } - public function testSetLockData() + public function testSetLockData(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -158,7 +158,7 @@ class LockerTest extends TestCase $locker->setLockData(array($package1, $package2), array(), array(), array(), array(), 'dev', array(), false, false, array('foo/bar' => '1.0')); } - public function testLockBadPackages() + public function testLockBadPackages(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -176,7 +176,7 @@ class LockerTest extends TestCase $locker->setLockData(array($package1), array(), array(), array(), array(), 'dev', array(), false, false, array()); } - public function testIsFresh() + public function testIsFresh(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -192,7 +192,7 @@ class LockerTest extends TestCase $this->assertTrue($locker->isFresh()); } - public function testIsFreshFalse() + public function testIsFreshFalse(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -207,7 +207,7 @@ class LockerTest extends TestCase $this->assertFalse($locker->isFresh()); } - public function testIsFreshWithContentHash() + public function testIsFreshWithContentHash(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -223,7 +223,7 @@ class LockerTest extends TestCase $this->assertTrue($locker->isFresh()); } - public function testIsFreshWithContentHashAndNoHash() + public function testIsFreshWithContentHashAndNoHash(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); @@ -239,7 +239,7 @@ class LockerTest extends TestCase $this->assertTrue($locker->isFresh()); } - public function testIsFreshFalseWithContentHash() + public function testIsFreshFalseWithContentHash(): void { $json = $this->createJsonFileMock(); $inst = $this->createInstallationManagerMock(); diff --git a/tests/Composer/Test/Package/RootAliasPackageTest.php b/tests/Composer/Test/Package/RootAliasPackageTest.php index 72ffbebcb..0a42fd31d 100644 --- a/tests/Composer/Test/Package/RootAliasPackageTest.php +++ b/tests/Composer/Test/Package/RootAliasPackageTest.php @@ -21,7 +21,7 @@ use PHPUnit\Framework\MockObject\MockObject; class RootAliasPackageTest extends TestCase { - public function testUpdateRequires() + public function testUpdateRequires(): void { $links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REQUIRE, 'self.version')); @@ -36,7 +36,7 @@ class RootAliasPackageTest extends TestCase $this->assertNotEmpty($alias->getRequires()); } - public function testUpdateDevRequires() + public function testUpdateDevRequires(): void { $links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_DEV_REQUIRE, 'self.version')); @@ -51,7 +51,7 @@ class RootAliasPackageTest extends TestCase $this->assertNotEmpty($alias->getDevRequires()); } - public function testUpdateConflicts() + public function testUpdateConflicts(): void { $links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_CONFLICT, 'self.version')); @@ -66,7 +66,7 @@ class RootAliasPackageTest extends TestCase $this->assertNotEmpty($alias->getConflicts()); } - public function testUpdateProvides() + public function testUpdateProvides(): void { $links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_PROVIDE, 'self.version')); @@ -81,7 +81,7 @@ class RootAliasPackageTest extends TestCase $this->assertNotEmpty($alias->getProvides()); } - public function testUpdateReplaces() + public function testUpdateReplaces(): void { $links = array(new Link('a', 'b', new MatchAllConstraint(), Link::TYPE_REPLACE, 'self.version')); diff --git a/tests/Composer/Test/Package/Version/VersionGuesserTest.php b/tests/Composer/Test/Package/Version/VersionGuesserTest.php index 5bb666180..4ec717681 100644 --- a/tests/Composer/Test/Package/Version/VersionGuesserTest.php +++ b/tests/Composer/Test/Package/Version/VersionGuesserTest.php @@ -28,7 +28,7 @@ class VersionGuesserTest extends TestCase } } - public function testHgGuessVersionReturnsData() + public function testHgGuessVersionReturnsData(): void { $branch = 'default'; @@ -54,7 +54,7 @@ class VersionGuesserTest extends TestCase $this->assertEmpty($versionArray['commit']); } - public function testGuessVersionReturnsData() + public function testGuessVersionReturnsData(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -79,7 +79,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals($commitHash, $versionArray['commit']); } - public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch() + public function testGuessVersionDoesNotSeeCustomDefaultBranchAsNonFeatureBranch(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -102,7 +102,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals($anotherCommitHash, $versionArray['commit']); } - public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming() + public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNaming(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -130,7 +130,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); } - public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex() + public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingRegex(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -158,7 +158,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-feature", $versionArray['feature_pretty_version']); } - public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch() + public function testGuessVersionReadsAndRespectsNonFeatureBranchesConfigurationForArbitraryNamingWhenOnNonFeatureBranch(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; $anotherCommitHash = '13a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -182,7 +182,7 @@ class VersionGuesserTest extends TestCase $this->assertArrayNotHasKey('feature_pretty_version', $versionArray); } - public function testDetachedHeadBecomesDevHash() + public function testDetachedHeadBecomesDevHash(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -203,7 +203,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-$commitHash", $versionData['version']); } - public function testDetachedFetchHeadBecomesDevHashGit2() + public function testDetachedFetchHeadBecomesDevHashGit2(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -224,7 +224,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-$commitHash", $versionData['version']); } - public function testDetachedCommitHeadBecomesDevHashGit2() + public function testDetachedCommitHeadBecomesDevHashGit2(): void { $commitHash = '03a15d220da53c52eddd5f32ffca64a7b3801bea'; @@ -245,7 +245,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-$commitHash", $versionData['version']); } - public function testTagBecomesVersion() + public function testTagBecomesVersion(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -267,7 +267,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("2.0.5.0-alpha2", $versionData['version']); } - public function testTagBecomesPrettyVersion() + public function testTagBecomesPrettyVersion(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -290,7 +290,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals('1.0.0', $versionData['pretty_version']); } - public function testInvalidTagBecomesVersion() + public function testInvalidTagBecomesVersion(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -308,7 +308,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("dev-foo", $versionData['version']); } - public function testNumericBranchesShowNicely() + public function testNumericBranchesShowNicely(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( @@ -327,7 +327,7 @@ class VersionGuesserTest extends TestCase $this->assertEquals("1.5.9999999.9999999-dev", $versionData['version']); } - public function testRemoteBranchesAreSelected() + public function testRemoteBranchesAreSelected(): void { $process = $this->getProcessExecutorMock(); $process->expects(array( diff --git a/tests/Composer/Test/Package/Version/VersionParserTest.php b/tests/Composer/Test/Package/Version/VersionParserTest.php index 8277a0c0e..e467ba25e 100644 --- a/tests/Composer/Test/Package/Version/VersionParserTest.php +++ b/tests/Composer/Test/Package/Version/VersionParserTest.php @@ -23,14 +23,14 @@ class VersionParserTest extends TestCase * @param string[] $pairs * @param array> $result */ - public function testParseNameVersionPairs($pairs, $result) + public function testParseNameVersionPairs($pairs, $result): void { $versionParser = new VersionParser(); $this->assertSame($result, $versionParser->parseNameVersionPairs($pairs)); } - public function provideParseNameVersionPairsData() + public function provideParseNameVersionPairsData(): array { return array( array(array('php:^7.0'), array(array('name' => 'php', 'version' => '^7.0'))), @@ -48,12 +48,12 @@ class VersionParserTest extends TestCase * @param string $to * @param bool $expected */ - public function testIsUpgrade($from, $to, $expected) + public function testIsUpgrade($from, $to, $expected): void { $this->assertSame($expected, VersionParser::isUpgrade($from, $to)); } - public function provideIsUpgradeTests() + public function provideIsUpgradeTests(): array { return array( array('0.9.0.0', '1.0.0.0', true), diff --git a/tests/Composer/Test/Package/Version/VersionSelectorTest.php b/tests/Composer/Test/Package/Version/VersionSelectorTest.php index 027534c6e..7a8041031 100644 --- a/tests/Composer/Test/Package/Version/VersionSelectorTest.php +++ b/tests/Composer/Test/Package/Version/VersionSelectorTest.php @@ -27,7 +27,7 @@ class VersionSelectorTest extends TestCase // B) targetPackageVersion will pass to repo set // C) No results, throw exception - public function testLatestVersionIsReturned() + public function testLatestVersionIsReturned(): void { $packageName = 'foobar'; @@ -49,7 +49,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be 1.2.2'); } - public function testLatestVersionIsReturnedThatMatchesPhpRequirements() + public function testLatestVersionIsReturnedThatMatchesPhpRequirements(): void { $packageName = 'foobar'; @@ -75,7 +75,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)'); } - public function testLatestVersionIsReturnedThatMatchesExtRequirements() + public function testLatestVersionIsReturnedThatMatchesExtRequirements(): void { $packageName = 'foobar'; @@ -101,7 +101,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)'); } - public function testLatestVersionIsReturnedThatMatchesPlatformExt() + public function testLatestVersionIsReturnedThatMatchesPlatformExt(): void { $packageName = 'foobar'; @@ -126,7 +126,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (2.0.0)'); } - public function testLatestVersionIsReturnedThatMatchesComposerRequirements() + public function testLatestVersionIsReturnedThatMatchesComposerRequirements(): void { $packageName = 'foobar'; @@ -152,7 +152,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned when ignoring platform reqs (1.1.0)'); } - public function testMostStableVersionIsReturned() + public function testMostStableVersionIsReturned(): void { $packageName = 'foobar'; @@ -172,7 +172,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package1, $best, 'Latest most stable version should be returned (1.0.0)'); } - public function testMostStableVersionIsReturnedRegardlessOfOrder() + public function testMostStableVersionIsReturnedRegardlessOfOrder(): void { $packageName = 'foobar'; @@ -197,7 +197,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Expecting 2.0.0-beta3, cause beta is more stable than dev'); } - public function testHighestVersionIsReturned() + public function testHighestVersionIsReturned(): void { $packageName = 'foobar'; @@ -217,7 +217,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)'); } - public function testHighestVersionMatchingStabilityIsReturned() + public function testHighestVersionMatchingStabilityIsReturned(): void { $packageName = 'foobar'; @@ -238,7 +238,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)'); } - public function testMostStableUnstableVersionIsReturned() + public function testMostStableUnstableVersionIsReturned(): void { $packageName = 'foobar'; @@ -258,7 +258,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned (1.1.0-beta)'); } - public function testDefaultBranchAliasIsNeverReturned() + public function testDefaultBranchAliasIsNeverReturned(): void { $packageName = 'foobar'; @@ -279,7 +279,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($package2, $best, 'Latest version should be returned (dev-main)'); } - public function testFalseReturnedOnNoPackages() + public function testFalseReturnedOnNoPackages(): void { $repositorySet = $this->createMockRepositorySet(); $repositorySet->expects($this->once()) @@ -299,7 +299,7 @@ class VersionSelectorTest extends TestCase * @param string|null $branchAlias * @param string $packageName */ - public function testFindRecommendedRequireVersion($prettyVersion, $expectedVersion, $branchAlias = null, $packageName = 'foo/bar') + public function testFindRecommendedRequireVersion($prettyVersion, $expectedVersion, $branchAlias = null, $packageName = 'foo/bar'): void { $repositorySet = $this->createMockRepositorySet(); $versionSelector = new VersionSelector($repositorySet); @@ -317,7 +317,7 @@ class VersionSelectorTest extends TestCase $this->assertSame($expectedVersion, $recommended); } - public function provideRecommendedRequireVersionPackages() + public function provideRecommendedRequireVersionPackages(): array { return array( // real version, expected recommendation, [branch-alias], [pkg name] @@ -362,7 +362,7 @@ class VersionSelectorTest extends TestCase * * @return Package */ - private function createPackage($version) + private function createPackage($version): Package { $parser = new VersionParser(); diff --git a/tests/Composer/Test/Platform/HhvmDetectorTest.php b/tests/Composer/Test/Platform/HhvmDetectorTest.php index 736a8ae43..eaf93c982 100644 --- a/tests/Composer/Test/Platform/HhvmDetectorTest.php +++ b/tests/Composer/Test/Platform/HhvmDetectorTest.php @@ -31,7 +31,7 @@ class HhvmDetectorTest extends TestCase $this->hhvmDetector->reset(); } - public function testHHVMVersionWhenExecutingInHHVM() + public function testHHVMVersionWhenExecutingInHHVM(): void { if (!defined('HHVM_VERSION_ID')) { self::markTestSkipped('Not running with HHVM'); @@ -40,7 +40,7 @@ class HhvmDetectorTest extends TestCase self::assertSame(self::versionIdToVersion(), $version); } - public function testHHVMVersionWhenExecutingInPHP() + public function testHHVMVersionWhenExecutingInPHP(): void { if (defined('HHVM_VERSION_ID')) { self::markTestSkipped('Running with HHVM'); @@ -71,7 +71,7 @@ class HhvmDetectorTest extends TestCase /** * @return ?string */ - private static function versionIdToVersion() + private static function versionIdToVersion(): ?string { if (!defined('HHVM_VERSION_ID')) { return null; diff --git a/tests/Composer/Test/Platform/VersionTest.php b/tests/Composer/Test/Platform/VersionTest.php index 3ebb03724..f2cf6f8f2 100644 --- a/tests/Composer/Test/Platform/VersionTest.php +++ b/tests/Composer/Test/Platform/VersionTest.php @@ -27,7 +27,7 @@ class VersionTest extends TestCase * 2) git log --pretty=%h --all -- crypto/opensslv.h include/openssl/opensslv.h | while read hash ; do (git show $hash:crypto/opensslv.h; git show $hash:include/openssl/opensslv.h) | grep "define OPENSSL_VERSION_TEXT" ; done > versions.txt * 3) cat versions.txt | awk -F "OpenSSL " '{print $2}' | awk -F " " '{print $1}' | sed -e "s:\([0-9]*\.[0-9]*\.[0-9]*\):1.2.3:g" -e "s:1\.2\.3[a-z]\(-.*\)\{0,1\}$:1.2.3a\1:g" -e "s:1\.2\.3[a-z]\{2\}\(-.*\)\{0,1\}$:1.2.3zh\1:g" -e "s:beta[0-9]:beta3:g" -e "s:pre[0-9]*:pre2:g" | sort | uniq */ - public static function provideOpenSslVersions() + public static function provideOpenSslVersions(): array { return array( // Generated @@ -79,7 +79,7 @@ class VersionTest extends TestCase * @param bool $fipsExpected * @param string|null $normalizedVersion */ - public function testParseOpensslVersions($input, $parsedVersion, $fipsExpected = false, $normalizedVersion = null) + public function testParseOpensslVersions($input, $parsedVersion, $fipsExpected = false, $normalizedVersion = null): void { self::assertSame($parsedVersion, Version::parseOpenssl($input, $isFips)); self::assertSame($fipsExpected, $isFips); @@ -88,7 +88,7 @@ class VersionTest extends TestCase self::assertSame($normalizedVersion, $this->getVersionParser()->normalize($parsedVersion)); } - public function provideLibJpegVersions() + public function provideLibJpegVersions(): array { return array( array('9', '9.0'), @@ -104,12 +104,12 @@ class VersionTest extends TestCase * @param string $input * @param string $parsedVersion */ - public function testParseLibjpegVersion($input, $parsedVersion) + public function testParseLibjpegVersion($input, $parsedVersion): void { self::assertSame($parsedVersion, Version::parseLibjpeg($input)); } - public function provideZoneinfoVersions() + public function provideZoneinfoVersions(): array { return array( array('2019c', '2019.3'), @@ -124,7 +124,7 @@ class VersionTest extends TestCase * @param string $input * @param string $parsedVersion */ - public function testParseZoneinfoVersion($input, $parsedVersion) + public function testParseZoneinfoVersion($input, $parsedVersion): void { self::assertSame($parsedVersion, Version::parseZoneinfoVersion($input)); } diff --git a/tests/Composer/Test/Plugin/PluginInstallerTest.php b/tests/Composer/Test/Plugin/PluginInstallerTest.php index 43022a20d..325f26671 100644 --- a/tests/Composer/Test/Plugin/PluginInstallerTest.php +++ b/tests/Composer/Test/Plugin/PluginInstallerTest.php @@ -96,7 +96,7 @@ class PluginInstallerTest extends TestCase $im = $this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock(); $im->expects($this->any()) ->method('getInstallPath') - ->will($this->returnCallback(function ($package) { + ->will($this->returnCallback(function ($package): string { return __DIR__.'/Fixtures/'.$package->getPrettyName(); })); @@ -135,7 +135,7 @@ class PluginInstallerTest extends TestCase $filesystem->removeDirectory($this->directory); } - public function testInstallNewPlugin() + public function testInstallNewPlugin(): void { $this->repository ->expects($this->any()) @@ -154,7 +154,7 @@ class PluginInstallerTest extends TestCase ); } - public function testInstallPluginWithRootPackageHavingFilesAutoload() + public function testInstallPluginWithRootPackageHavingFilesAutoload(): void { $this->repository ->expects($this->any()) @@ -176,7 +176,7 @@ class PluginInstallerTest extends TestCase $this->assertEquals('installer-v1', $plugins[0]->version); // @phpstan-ignore-line } - public function testInstallMultiplePlugins() + public function testInstallMultiplePlugins(): void { $this->repository ->expects($this->any()) @@ -195,7 +195,7 @@ class PluginInstallerTest extends TestCase $this->assertEquals('activate v4-plugin1'.PHP_EOL.'activate v4-plugin2'.PHP_EOL, $this->io->getOutput()); } - public function testUpgradeWithNewClassName() + public function testUpgradeWithNewClassName(): void { $this->repository ->expects($this->any()) @@ -216,7 +216,7 @@ class PluginInstallerTest extends TestCase $this->assertEquals('activate v1'.PHP_EOL.'deactivate v1'.PHP_EOL.'activate v2'.PHP_EOL, $this->io->getOutput()); } - public function testUninstall() + public function testUninstall(): void { $this->repository ->expects($this->any()) @@ -236,7 +236,7 @@ class PluginInstallerTest extends TestCase $this->assertEquals('activate v1'.PHP_EOL.'deactivate v1'.PHP_EOL.'uninstall v1'.PHP_EOL, $this->io->getOutput()); } - public function testUpgradeWithSameClassName() + public function testUpgradeWithSameClassName(): void { $this->repository ->expects($this->any()) @@ -256,7 +256,7 @@ class PluginInstallerTest extends TestCase $this->assertEquals('activate v2'.PHP_EOL.'deactivate v2'.PHP_EOL.'activate v3'.PHP_EOL, $this->io->getOutput()); } - public function testRegisterPluginOnlyOneTime() + public function testRegisterPluginOnlyOneTime(): void { $this->repository ->expects($this->any()) @@ -280,7 +280,7 @@ class PluginInstallerTest extends TestCase * * @return void */ - private function setPluginApiVersionWithPlugins($newPluginApiVersion, array $plugins = array()) + private function setPluginApiVersionWithPlugins($newPluginApiVersion, array $plugins = array()): void { // reset the plugin manager's installed plugins $this->pm = $this->getMockBuilder('Composer\Plugin\PluginManager') @@ -303,14 +303,14 @@ class PluginInstallerTest extends TestCase $this->repository ->expects($this->any()) ->method('getPackages') - ->will($this->returnCallback(function () use ($plugApiInternalPackage, $plugins) { + ->will($this->returnCallback(function () use ($plugApiInternalPackage, $plugins): array { return array_merge(array($plugApiInternalPackage), $plugins); })); $this->pm->loadInstalledPlugins(); } - public function testStarPluginVersionWorksWithAnyAPIVersion() + public function testStarPluginVersionWorksWithAnyAPIVersion(): void { $starVersionPlugin = array($this->packages[4]); @@ -327,7 +327,7 @@ class PluginInstallerTest extends TestCase $this->assertCount(1, $this->pm->getPlugins()); } - public function testPluginConstraintWorksOnlyWithCertainAPIVersion() + public function testPluginConstraintWorksOnlyWithCertainAPIVersion(): void { $pluginWithApiConstraint = array($this->packages[5]); @@ -344,7 +344,7 @@ class PluginInstallerTest extends TestCase $this->assertCount(1, $this->pm->getPlugins()); } - public function testPluginRangeConstraintsWorkOnlyWithCertainAPIVersion() + public function testPluginRangeConstraintsWorkOnlyWithCertainAPIVersion(): void { $pluginWithApiConstraint = array($this->packages[6]); @@ -358,7 +358,7 @@ class PluginInstallerTest extends TestCase $this->assertCount(0, $this->pm->getPlugins()); } - public function testCommandProviderCapability() + public function testCommandProviderCapability(): void { $this->repository ->expects($this->any()) @@ -377,14 +377,14 @@ class PluginInstallerTest extends TestCase $this->assertInstanceOf('Composer\Command\BaseCommand', $commands[0]); } - public function testIncapablePluginIsCorrectlyDetected() + public function testIncapablePluginIsCorrectlyDetected(): void { $plugin = $this->getMockBuilder('Composer\Plugin\PluginInterface') ->getMock(); $this->assertNull($this->pm->getPluginCapability($plugin, 'Fake\Ability')); } - public function testCapabilityImplementsComposerPluginApiClassAndIsConstructedWithArgs() + public function testCapabilityImplementsComposerPluginApiClassAndIsConstructedWithArgs(): void { $capabilityApi = 'Composer\Plugin\Capability\Capability'; $capabilityImplementation = 'Composer\Test\Plugin\Mock\Capability'; @@ -394,7 +394,7 @@ class PluginInstallerTest extends TestCase $plugin->expects($this->once()) ->method('getCapabilities') - ->will($this->returnCallback(function () use ($capabilityImplementation, $capabilityApi) { + ->will($this->returnCallback(function () use ($capabilityImplementation, $capabilityApi): array { return array($capabilityApi => $capabilityImplementation); })); @@ -407,7 +407,7 @@ class PluginInstallerTest extends TestCase } /** @return mixed[] */ - public function invalidImplementationClassNames() + public function invalidImplementationClassNames(): array { return array( array(null), @@ -422,7 +422,7 @@ class PluginInstallerTest extends TestCase } /** @return mixed[] */ - public function nonExistingOrInvalidImplementationClassTypes() + public function nonExistingOrInvalidImplementationClassTypes(): array { return array( array('\stdClass'), @@ -437,7 +437,7 @@ class PluginInstallerTest extends TestCase * * @return void */ - public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, $expect = 'UnexpectedValueException') + public function testQueryingWithInvalidCapabilityClassNameThrows($invalidImplementationClassNames, $expect = 'UnexpectedValueException'): void { self::expectException($expect); @@ -448,7 +448,7 @@ class PluginInstallerTest extends TestCase $plugin->expects($this->once()) ->method('getCapabilities') - ->will($this->returnCallback(function () use ($invalidImplementationClassNames, $capabilityApi) { + ->will($this->returnCallback(function () use ($invalidImplementationClassNames, $capabilityApi): array { return array($capabilityApi => $invalidImplementationClassNames); })); @@ -456,7 +456,7 @@ class PluginInstallerTest extends TestCase } /** @return void */ - public function testQueryingNonProvidedCapabilityReturnsNullSafely() + public function testQueryingNonProvidedCapabilityReturnsNullSafely(): void { $capabilityApi = 'Composer\Plugin\Capability\MadeUpCapability'; @@ -465,7 +465,7 @@ class PluginInstallerTest extends TestCase $plugin->expects($this->once()) ->method('getCapabilities') - ->will($this->returnCallback(function () { + ->will($this->returnCallback(function (): array { return array(); })); @@ -478,7 +478,7 @@ class PluginInstallerTest extends TestCase * * @return void */ - public function testQueryingWithNonExistingOrWrongCapabilityClassTypesThrows($wrongImplementationClassTypes) + public function testQueryingWithNonExistingOrWrongCapabilityClassTypesThrows($wrongImplementationClassTypes): void { $this->testQueryingWithInvalidCapabilityClassNameThrows($wrongImplementationClassTypes, 'RuntimeException'); } diff --git a/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php b/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php index 925f278bb..7d9c94a75 100644 --- a/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php +++ b/tests/Composer/Test/Question/StrictConfirmationQuestionTest.php @@ -30,7 +30,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @phpstan-return list */ - public function getAskConfirmationBadData() + public function getAskConfirmationBadData(): array { return array( array('not correct'), @@ -45,7 +45,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @param string $answer */ - public function testAskConfirmationBadAnswer($answer) + public function testAskConfirmationBadAnswer($answer): void { list($input, $dialog) = $this->createInput($answer."\n"); @@ -64,7 +64,7 @@ class StrictConfirmationQuestionTest extends TestCase * @param bool $expected * @param bool $default */ - public function testAskConfirmation($question, $expected, $default = true) + public function testAskConfirmation($question, $expected, $default = true): void { list($input, $dialog) = $this->createInput($question."\n"); @@ -77,7 +77,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @phpstan-return list|list */ - public function getAskConfirmationData() + public function getAskConfirmationData(): array { return array( array('', true), @@ -89,7 +89,7 @@ class StrictConfirmationQuestionTest extends TestCase ); } - public function testAskConfirmationWithCustomTrueAndFalseAnswer() + public function testAskConfirmationWithCustomTrueAndFalseAnswer(): void { $question = new StrictConfirmationQuestion('Do you like French fries?', false, '/^ja$/i', '/^nein$/i'); @@ -119,7 +119,7 @@ class StrictConfirmationQuestionTest extends TestCase /** * @return StreamOutput */ - protected function createOutputInterface() + protected function createOutputInterface(): StreamOutput { return new StreamOutput(fopen('php://memory', 'r+', false)); } @@ -131,7 +131,7 @@ class StrictConfirmationQuestionTest extends TestCase * * @phpstan-return array{ArrayInput, QuestionHelper} */ - protected function createInput($entry) + protected function createInput($entry): array { $input = new ArrayInput(array('--no-interaction')); $input->setStream($this->getInputStream($entry)); diff --git a/tests/Composer/Test/Repository/ArrayRepositoryTest.php b/tests/Composer/Test/Repository/ArrayRepositoryTest.php index fe50a29b2..f2261eac2 100644 --- a/tests/Composer/Test/Repository/ArrayRepositoryTest.php +++ b/tests/Composer/Test/Repository/ArrayRepositoryTest.php @@ -18,7 +18,7 @@ use Composer\Test\TestCase; class ArrayRepositoryTest extends TestCase { - public function testAddPackage() + public function testAddPackage(): void { $repo = new ArrayRepository; $repo->addPackage($this->getPackage('foo', '1')); @@ -26,7 +26,7 @@ class ArrayRepositoryTest extends TestCase $this->assertCount(1, $repo); } - public function testRemovePackage() + public function testRemovePackage(): void { $package = $this->getPackage('bar', '2'); @@ -42,7 +42,7 @@ class ArrayRepositoryTest extends TestCase $this->assertEquals(array($package), $repo->getPackages()); } - public function testHasPackage() + public function testHasPackage(): void { $repo = new ArrayRepository; $repo->addPackage($this->getPackage('foo', '1')); @@ -52,7 +52,7 @@ class ArrayRepositoryTest extends TestCase $this->assertFalse($repo->hasPackage($this->getPackage('bar', '1'))); } - public function testFindPackages() + public function testFindPackages(): void { $repo = new ArrayRepository(); $repo->addPackage($this->getPackage('foo', '1')); @@ -68,7 +68,7 @@ class ArrayRepositoryTest extends TestCase $this->assertEquals('bar', $bar[0]->getName()); } - public function testAutomaticallyAddAliasedPackageButNotRemove() + public function testAutomaticallyAddAliasedPackageButNotRemove(): void { $repo = new ArrayRepository(); @@ -86,7 +86,7 @@ class ArrayRepositoryTest extends TestCase $this->assertCount(1, $repo); } - public function testSearch() + public function testSearch(): void { $repo = new ArrayRepository(); @@ -108,7 +108,7 @@ class ArrayRepositoryTest extends TestCase ); } - public function testSearchWithPackageType() + public function testSearchWithPackageType(): void { $repo = new ArrayRepository(); @@ -132,7 +132,7 @@ class ArrayRepositoryTest extends TestCase ); } - public function testSearchWithAbandonedPackages() + public function testSearchWithAbandonedPackages(): void { $repo = new ArrayRepository(); diff --git a/tests/Composer/Test/Repository/ArtifactRepositoryTest.php b/tests/Composer/Test/Repository/ArtifactRepositoryTest.php index 49c37a61a..ee44153a3 100644 --- a/tests/Composer/Test/Repository/ArtifactRepositoryTest.php +++ b/tests/Composer/Test/Repository/ArtifactRepositoryTest.php @@ -27,7 +27,7 @@ class ArtifactRepositoryTest extends TestCase } } - public function testExtractsConfigsFromZipArchives() + public function testExtractsConfigsFromZipArchives(): void { $expectedPackages = array( 'vendor0/package0-0.0.1', @@ -53,7 +53,7 @@ class ArtifactRepositoryTest extends TestCase $this->assertSame($expectedPackages, $foundPackages); - $tarPackage = array_filter($repo->getPackages(), function (BasePackage $package) { + $tarPackage = array_filter($repo->getPackages(), function (BasePackage $package): bool { return $package->getPrettyName() === 'test/jsonInRootTarFile'; }); $this->assertCount(1, $tarPackage); @@ -61,7 +61,7 @@ class ArtifactRepositoryTest extends TestCase $this->assertSame('tar', $tarPackage->getDistType()); } - public function testAbsoluteRepoUrlCreatesAbsoluteUrlPackages() + public function testAbsoluteRepoUrlCreatesAbsoluteUrlPackages(): void { $absolutePath = __DIR__ . '/Fixtures/artifacts'; $coordinates = array('type' => 'artifact', 'url' => $absolutePath); @@ -72,7 +72,7 @@ class ArtifactRepositoryTest extends TestCase } } - public function testRelativeRepoUrlCreatesRelativeUrlPackages() + public function testRelativeRepoUrlCreatesRelativeUrlPackages(): void { $relativePath = 'tests/Composer/Test/Repository/Fixtures/artifacts'; $coordinates = array('type' => 'artifact', 'url' => $relativePath); diff --git a/tests/Composer/Test/Repository/ComposerRepositoryTest.php b/tests/Composer/Test/Repository/ComposerRepositoryTest.php index 21b9f56be..f6076b3f5 100644 --- a/tests/Composer/Test/Repository/ComposerRepositoryTest.php +++ b/tests/Composer/Test/Repository/ComposerRepositoryTest.php @@ -28,7 +28,7 @@ class ComposerRepositoryTest extends TestCase * @param mixed[] $expected * @param array $repoPackages */ - public function testLoadData(array $expected, array $repoPackages) + public function testLoadData(array $expected, array $repoPackages): void { $repoConfig = array( 'url' => 'http://example.org', @@ -61,7 +61,7 @@ class ComposerRepositoryTest extends TestCase } } - public function loadDataProvider() + public function loadDataProvider(): array { return array( // Old repository format @@ -92,7 +92,7 @@ class ComposerRepositoryTest extends TestCase ); } - public function testWhatProvides() + public function testWhatProvides(): void { $repo = $this->getMockBuilder('Composer\Repository\ComposerRepository') ->setConstructorArgs(array( @@ -156,7 +156,7 @@ class ComposerRepositoryTest extends TestCase $this->assertSame($packages['2'], $packages['2-alias']->getAliasOf()); } - public function testSearchWithType() + public function testSearchWithType(): void { $repoConfig = array( 'url' => 'http://example.org', @@ -198,7 +198,7 @@ class ComposerRepositoryTest extends TestCase ); } - public function testSearchWithSpecialChars() + public function testSearchWithSpecialChars(): void { $repoConfig = array( 'url' => 'http://example.org', @@ -225,7 +225,7 @@ class ComposerRepositoryTest extends TestCase ); } - public function testSearchWithAbandonedPackages() + public function testSearchWithAbandonedPackages(): void { $repoConfig = array( 'url' => 'http://example.org', @@ -279,7 +279,7 @@ class ComposerRepositoryTest extends TestCase * @param string $url * @param string $repositoryUrl */ - public function testCanonicalizeUrl($expected, $url, $repositoryUrl) + public function testCanonicalizeUrl($expected, $url, $repositoryUrl): void { $repository = new ComposerRepository( array('url' => $repositoryUrl), @@ -303,7 +303,7 @@ class ComposerRepositoryTest extends TestCase $this->assertSame($expected, $method->invoke($repository, $url)); } - public function provideCanonicalizeUrlTestCases() + public function provideCanonicalizeUrlTestCases(): array { return array( array( @@ -341,7 +341,7 @@ class ComposerRepositoryTest extends TestCase ); } - public function testGetProviderNamesWillReturnPartialPackageNames() + public function testGetProviderNamesWillReturnPartialPackageNames(): void { $httpDownloader = $this->getHttpDownloaderMock(); $httpDownloader->expects( diff --git a/tests/Composer/Test/Repository/CompositeRepositoryTest.php b/tests/Composer/Test/Repository/CompositeRepositoryTest.php index 5e49d725a..1cf8cbe84 100644 --- a/tests/Composer/Test/Repository/CompositeRepositoryTest.php +++ b/tests/Composer/Test/Repository/CompositeRepositoryTest.php @@ -18,7 +18,7 @@ use Composer\Test\TestCase; class CompositeRepositoryTest extends TestCase { - public function testHasPackage() + public function testHasPackage(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -35,7 +35,7 @@ class CompositeRepositoryTest extends TestCase $this->assertFalse($repo->hasPackage($this->getPackage('bar', '2')), "Should not have package 'bar/2'"); } - public function testFindPackage() + public function testFindPackage(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -52,7 +52,7 @@ class CompositeRepositoryTest extends TestCase $this->assertNull($repo->findPackage('foo', '2'), "Should not find package 'foo/2'"); } - public function testFindPackages() + public function testFindPackages(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -79,7 +79,7 @@ class CompositeRepositoryTest extends TestCase $this->assertEquals('foo', $foos[0]->getName(), "Should find packages named 'foo'"); } - public function testGetPackages() + public function testGetPackages(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -97,7 +97,7 @@ class CompositeRepositoryTest extends TestCase $this->assertEquals("1", $packages[1]->getPrettyVersion(), "Second package should have pretty version of '1'"); } - public function testAddRepository() + public function testAddRepository(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -113,7 +113,7 @@ class CompositeRepositoryTest extends TestCase $this->assertCount(4, $repo, "Composite repository should have four packages after addRepository() is called"); } - public function testCount() + public function testCount(): void { $arrayRepoOne = new ArrayRepository; $arrayRepoOne->addPackage($this->getPackage('foo', '1')); @@ -132,13 +132,13 @@ class CompositeRepositoryTest extends TestCase * @param string $method * @param mixed[] $args */ - public function testNoRepositories($method, $args) + public function testNoRepositories($method, $args): void { $repo = new CompositeRepository(array()); $this->assertEquals(array(), call_user_func_array(array($repo, $method), $args)); } - public function provideMethodCalls() + public function provideMethodCalls(): array { return array( array('findPackages', array('foo')), diff --git a/tests/Composer/Test/Repository/FilesystemRepositoryTest.php b/tests/Composer/Test/Repository/FilesystemRepositoryTest.php index ac1d78e4d..ad0466191 100644 --- a/tests/Composer/Test/Repository/FilesystemRepositoryTest.php +++ b/tests/Composer/Test/Repository/FilesystemRepositoryTest.php @@ -21,7 +21,7 @@ use Composer\Util\Filesystem; class FilesystemRepositoryTest extends TestCase { - public function testRepositoryRead() + public function testRepositoryRead(): void { $json = $this->createJsonFileMock(); @@ -46,7 +46,7 @@ class FilesystemRepositoryTest extends TestCase $this->assertSame('vendor', $packages[0]->getType()); } - public function testCorruptedRepositoryFile() + public function testCorruptedRepositoryFile(): void { self::expectException('Composer\Repository\InvalidRepositoryException'); $json = $this->createJsonFileMock(); @@ -65,7 +65,7 @@ class FilesystemRepositoryTest extends TestCase $repository->getPackages(); } - public function testUnexistentRepositoryFile() + public function testUnexistentRepositoryFile(): void { $json = $this->createJsonFileMock(); @@ -79,7 +79,7 @@ class FilesystemRepositoryTest extends TestCase $this->assertEquals(array(), $repository->getPackages()); } - public function testRepositoryWrite() + public function testRepositoryWrite(): void { $json = $this->createJsonFileMock(); @@ -125,7 +125,7 @@ class FilesystemRepositoryTest extends TestCase $repository->write(true, $im); } - public function testRepositoryWritesInstalledPhp() + public function testRepositoryWritesInstalledPhp(): void { $dir = $this->getUniqueTmpDirectory(); chdir($dir); @@ -171,7 +171,7 @@ class FilesystemRepositoryTest extends TestCase ->getMock(); $im->expects($this->any()) ->method('getInstallPath') - ->will($this->returnCallback(function ($package) use ($dir) { + ->will($this->returnCallback(function ($package) use ($dir): string { // check for empty paths handling if ($package->getType() === 'metapackage') { return ''; diff --git a/tests/Composer/Test/Repository/FilterRepositoryTest.php b/tests/Composer/Test/Repository/FilterRepositoryTest.php index d18e8a13e..3a1c34e11 100644 --- a/tests/Composer/Test/Repository/FilterRepositoryTest.php +++ b/tests/Composer/Test/Repository/FilterRepositoryTest.php @@ -40,17 +40,17 @@ class FilterRepositoryTest extends TestCase * @param string[] $expected * @param array{only?: array, exclude?: array, canonical?: bool} $config */ - public function testRepoMatching($expected, $config) + public function testRepoMatching($expected, $config): void { $repo = new FilterRepository($this->arrayRepo, $config); $packages = $repo->getPackages(); - $this->assertSame($expected, array_map(function ($p) { + $this->assertSame($expected, array_map(function ($p): string { return $p->getName(); }, $packages)); } - public static function provideRepoMatchingTestCases() + public static function provideRepoMatchingTestCases(): array { return array( array(array('foo/aaa', 'foo/bbb'), array('only' => array('foo/*'))), @@ -62,7 +62,7 @@ class FilterRepositoryTest extends TestCase ); } - public function testCanonicalDefaultTrue() + public function testCanonicalDefaultTrue(): void { $repo = new FilterRepository($this->arrayRepo, array()); $result = $repo->loadPackages(array('foo/aaa' => new MatchAllConstraint), BasePackage::$stabilities, array()); @@ -70,7 +70,7 @@ class FilterRepositoryTest extends TestCase $this->assertCount(1, $result['namesFound']); } - public function testNonCanonical() + public function testNonCanonical(): void { $repo = new FilterRepository($this->arrayRepo, array('canonical' => false)); $result = $repo->loadPackages(array('foo/aaa' => new MatchAllConstraint), BasePackage::$stabilities, array()); diff --git a/tests/Composer/Test/Repository/InstalledRepositoryTest.php b/tests/Composer/Test/Repository/InstalledRepositoryTest.php index 136c19c7b..c4f32a1a5 100644 --- a/tests/Composer/Test/Repository/InstalledRepositoryTest.php +++ b/tests/Composer/Test/Repository/InstalledRepositoryTest.php @@ -21,7 +21,7 @@ use Composer\Test\TestCase; class InstalledRepositoryTest extends TestCase { - public function testFindPackagesWithReplacersAndProviders() + public function testFindPackagesWithReplacersAndProviders(): void { $arrayRepoOne = new InstalledArrayRepository; $arrayRepoOne->addPackage($foo = $this->getPackage('foo', '1')); @@ -41,7 +41,7 @@ class InstalledRepositoryTest extends TestCase $this->assertEquals(array($foo, $bar2), $repo->findPackagesWithReplacersAndProviders('provided')); } - public function testAddRepository() + public function testAddRepository(): void { $arrayRepoOne = new ArrayRepository; diff --git a/tests/Composer/Test/Repository/PathRepositoryTest.php b/tests/Composer/Test/Repository/PathRepositoryTest.php index bff6fd6b2..9717a4457 100644 --- a/tests/Composer/Test/Repository/PathRepositoryTest.php +++ b/tests/Composer/Test/Repository/PathRepositoryTest.php @@ -17,7 +17,7 @@ use Composer\Test\TestCase; class PathRepositoryTest extends TestCase { - public function testLoadPackageFromFileSystemWithIncorrectPath() + public function testLoadPackageFromFileSystemWithIncorrectPath(): void { self::expectException('RuntimeException'); $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') @@ -30,7 +30,7 @@ class PathRepositoryTest extends TestCase $repository->getPackages(); } - public function testLoadPackageFromFileSystemWithVersion() + public function testLoadPackageFromFileSystemWithVersion(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -46,7 +46,7 @@ class PathRepositoryTest extends TestCase $this->assertTrue($repository->hasPackage($this->getPackage('test/path-versioned', '0.0.2'))); } - public function testLoadPackageFromFileSystemWithoutVersion() + public function testLoadPackageFromFileSystemWithoutVersion(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -67,7 +67,7 @@ class PathRepositoryTest extends TestCase $this->assertNotEmpty($packageVersion); } - public function testLoadPackageFromFileSystemWithWildcard() + public function testLoadPackageFromFileSystemWithWildcard(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -92,7 +92,7 @@ class PathRepositoryTest extends TestCase $this->assertEquals(array('test/path-unversioned', 'test/path-versioned'), $names); } - public function testLoadPackageWithExplicitVersions() + public function testLoadPackageWithExplicitVersions(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -127,7 +127,7 @@ class PathRepositoryTest extends TestCase /** * Verify relative repository URLs remain relative, see #4439 */ - public function testUrlRemainsRelative() + public function testUrlRemainsRelative(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -155,7 +155,7 @@ class PathRepositoryTest extends TestCase $this->assertSame($relativeUrl, $package->getDistUrl()); } - public function testReferenceNone() + public function testReferenceNone(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); @@ -176,7 +176,7 @@ class PathRepositoryTest extends TestCase } } - public function testReferenceConfig() + public function testReferenceConfig(): void { $ioInterface = $this->getMockBuilder('Composer\IO\IOInterface') ->getMock(); diff --git a/tests/Composer/Test/Repository/PlatformRepositoryTest.php b/tests/Composer/Test/Repository/PlatformRepositoryTest.php index 05f030eac..68418d72b 100644 --- a/tests/Composer/Test/Repository/PlatformRepositoryTest.php +++ b/tests/Composer/Test/Repository/PlatformRepositoryTest.php @@ -21,7 +21,7 @@ use PHPUnit\Framework\Assert; class PlatformRepositoryTest extends TestCase { - public function testHhvmPackage() + public function testHhvmPackage(): void { $hhvmDetector = $this->getMockBuilder('Composer\Platform\HhvmDetector')->getMock(); $platformRepository = new PlatformRepository(array(), array(), null, $hhvmDetector); @@ -36,7 +36,7 @@ class PlatformRepositoryTest extends TestCase self::assertSame('2.1.0', $hhvm->getPrettyVersion()); } - public function providePhpFlavorTestCases() + public function providePhpFlavorTestCases(): array { return array( array( @@ -120,7 +120,7 @@ class PlatformRepositoryTest extends TestCase * @param array $packages * @param list, string|bool}> $functions */ - public function testPhpVersion(array $constants, array $packages, array $functions = array()) + public function testPhpVersion(array $constants, array $packages, array $functions = array()): void { $runtime = $this->getMockBuilder('Composer\Platform\Runtime')->getMock(); $runtime @@ -128,18 +128,14 @@ class PlatformRepositoryTest extends TestCase ->willReturn(array()); $runtime ->method('hasConstant') - ->willReturnMap( - array_map(function ($constant) { - return array($constant, null, true); - }, array_keys($constants)) - ); + ->willReturnCallback(function ($constant, $class = null) use ($constants): bool { + return isset($constants[ltrim($class.'::'.$constant, ':')]); + }); $runtime ->method('getConstant') - ->willReturnMap( - array_map(function ($constant, $value) { - return array($constant, null, $value); - }, array_keys($constants), array_values($constants)) - ); + ->willReturnCallback(function ($constant, $class = null) use ($constants) { + return $constants[ltrim($class.'::'.$constant, ':')] ?? null; + }); $runtime ->method('invoke') ->willReturnMap($functions); @@ -152,7 +148,7 @@ class PlatformRepositoryTest extends TestCase } } - public function testInetPtonRegression() + public function testInetPtonRegression(): void { $runtime = $this->getMockBuilder('Composer\Platform\Runtime')->getMock(); @@ -163,29 +159,26 @@ class PlatformRepositoryTest extends TestCase ->willReturn(false); $runtime ->method('hasConstant') - ->willReturnMap( - array( - array('PHP_ZTS', false), - array('AF_INET6', false), - ) - ); + ->willReturn(false); // suppressing PHP_ZTS & AF_INET6 + + $constants = [ + 'PHP_VERSION' => '7.0.0', + 'PHP_DEBUG' => false, + ]; + $runtime + ->method('getConstant') + ->willReturnCallback(function ($constant, $class = null) use ($constants) { + return $constants[ltrim($class.'::'.$constant, ':')] ?? null; + }); $runtime ->method('getExtensions') ->willReturn(array()); - $runtime - ->method('getConstant') - ->willReturnMap( - array( - array('PHP_VERSION', null, '7.0.0'), - array('PHP_DEBUG', null, false), - ) - ); $repository = new PlatformRepository(array(), array(), $runtime); $package = $repository->findPackage('php-ipv6', '*'); self::assertNull($package); } - public static function provideLibraryTestCases() + public static function provideLibraryTestCases(): array { return array( 'amqp' => array( @@ -1097,7 +1090,7 @@ Linked Version => 1.2.11', array $functions = array(), array $constants = array(), array $classDefinitions = array() - ) { + ): void { $extensions = (array) $extensions; $extensionVersion = '100.200.300'; @@ -1110,7 +1103,7 @@ Linked Version => 1.2.11', $runtime ->method('getExtensionVersion') ->willReturnMap( - array_map(function ($extension) use ($extensionVersion) { + array_map(function ($extension) use ($extensionVersion): array { return array($extension, $extensionVersion); }, $extensions) ); @@ -1118,7 +1111,7 @@ Linked Version => 1.2.11', $runtime ->method('getExtensionInfo') ->willReturnMap( - array_map(function ($extension) use ($info) { + array_map(function ($extension) use ($info): array { return array($extension, $info); }, $extensions) ); @@ -1130,55 +1123,57 @@ Linked Version => 1.2.11', $constants[] = array('PHP_VERSION', null, '7.1.0'); $runtime ->method('hasConstant') - ->willReturnMap( - array_map( - function ($constantDefintion) { - return array($constantDefintion[0], $constantDefintion[1], true); - }, - $constants - ) - ); + ->willReturnCallback(function ($constant, $class = null) use ($constants): bool { + foreach ($constants as $definition) { + if ($definition[0] === $constant && $definition[1] === $class) { + return true; + } + } + + return false; + }); $runtime ->method('getConstant') ->willReturnMap($constants); $runtime ->method('hasClass') - ->willReturnMap( - array_map( - function ($classDefinition) { - return array($classDefinition[0], true); - }, - $classDefinitions - ) - ); + ->willReturnCallback(function ($class) use ($classDefinitions): bool { + foreach ($classDefinitions as $definition) { + if ($definition[0] === $class) { + return true; + } + } + + return false; + }); $runtime ->method('construct') ->willReturnMap($classDefinitions); $platformRepository = new PlatformRepository(array(), array(), $runtime); - $expectations = array_map(function ($expectation) { + $expectations = array_map(function ($expectation): array { return array_replace(array(null, array(), array()), (array) $expectation); }, $expectations); $libraries = array_map( - function ($package) { + function ($package): string { return $package['name']; }, array_filter( $platformRepository->search('lib', PlatformRepository::SEARCH_NAME), - function ($package) { + function ($package): bool { return strpos($package['name'], 'lib-') === 0; } ) ); - $expectedLibraries = array_merge(array_keys(array_filter($expectations, function ($expectation) { + $expectedLibraries = array_merge(array_keys(array_filter($expectations, function ($expectation): bool { return $expectation[0] !== false; }))); self::assertCount(count(array_filter($expectedLibraries)), $libraries, sprintf('Expected: %s, got %s', var_export($expectedLibraries, true), var_export($libraries, true))); - $expectations = array_merge($expectations, array_combine(array_map(function ($extension) { + $expectations = array_merge($expectations, array_combine(array_map(function ($extension): string { return 'ext-'.$extension; }, $extensions), array_fill(0, count($extensions), array($extensionVersion, array(), array())))); @@ -1204,7 +1199,7 @@ Linked Version => 1.2.11', * * @return void */ - private function assertPackageLinks($context, array $expectedLinks, PackageInterface $sourcePackage, array $links) + private function assertPackageLinks($context, array $expectedLinks, PackageInterface $sourcePackage, array $links): void { self::assertCount(count($expectedLinks), $links, sprintf('%s: expected package count to match', $context)); @@ -1215,7 +1210,7 @@ Linked Version => 1.2.11', } } - public function testComposerPlatformVersion() + public function testComposerPlatformVersion(): void { $runtime = $this->getMockBuilder('Composer\Platform\Runtime')->getMock(); $runtime @@ -1236,7 +1231,7 @@ Linked Version => 1.2.11', self::assertNotNull($package, 'Composer package exists'); } - public static function providePlatformPackages() + public static function providePlatformPackages(): array { return array( array('php', true), @@ -1268,7 +1263,7 @@ Linked Version => 1.2.11', * @param bool $expectation * @dataProvider providePlatformPackages */ - public function testValidPlatformPackages($packageName, $expectation) + public function testValidPlatformPackages($packageName, $expectation): void { self::assertSame($expectation, PlatformRepository::isPlatformPackage($packageName)); } @@ -1285,7 +1280,7 @@ class ResourceBundleStub * * @return ResourceBundleStub */ - public static function create($locale, $bundleName, $fallback) + public static function create($locale, $bundleName, $fallback): ResourceBundleStub { Assert::assertSame(3, func_num_args()); Assert::assertSame('root', $locale); @@ -1300,7 +1295,7 @@ class ResourceBundleStub * * @return string */ - public function get($field) + public function get($field): string { Assert::assertSame(1, func_num_args()); Assert::assertSame('Version', $field); @@ -1328,7 +1323,7 @@ class ImagickStub * @return array * @phpstan-return array{versionString: string} */ - public function getVersion() + public function getVersion(): array { Assert::assertSame(0, func_num_args()); diff --git a/tests/Composer/Test/Repository/RepositoryFactoryTest.php b/tests/Composer/Test/Repository/RepositoryFactoryTest.php index ab725b18f..3928d0288 100644 --- a/tests/Composer/Test/Repository/RepositoryFactoryTest.php +++ b/tests/Composer/Test/Repository/RepositoryFactoryTest.php @@ -17,7 +17,7 @@ use Composer\Test\TestCase; class RepositoryFactoryTest extends TestCase { - public function testManagerWithAllRepositoryTypes() + public function testManagerWithAllRepositoryTypes(): void { $manager = RepositoryFactory::manager( $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), @@ -55,19 +55,18 @@ class RepositoryFactoryTest extends TestCase * @param int|string $index * @param array $config * @param array $existingRepos - * @param int|string $expected * * @phpstan-param array{url?: string} $config */ - public function testGenerateRepositoryName($index, array $config, array $existingRepos, $expected) + public function testGenerateRepositoryName($index, array $config, array $existingRepos, string $expected): void { $this->assertSame($expected, RepositoryFactory::generateRepositoryName($index, $config, $existingRepos)); } - public function generateRepositoryNameProvider() + public function generateRepositoryNameProvider(): array { return array( - array(0, array(), array(), 0), + array(0, array(), array(), '0'), array(0, array(), array(array()), '02'), array(0, array('url' => 'https://example.org'), array(), 'example.org'), array(0, array('url' => 'https://example.org'), array('example.org' => array()), 'example.org2'), diff --git a/tests/Composer/Test/Repository/RepositoryManagerTest.php b/tests/Composer/Test/Repository/RepositoryManagerTest.php index 1596c0a40..14db37204 100644 --- a/tests/Composer/Test/Repository/RepositoryManagerTest.php +++ b/tests/Composer/Test/Repository/RepositoryManagerTest.php @@ -35,7 +35,7 @@ class RepositoryManagerTest extends TestCase } } - public function testPrepend() + public function testPrepend(): void { $rm = new RepositoryManager( $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), @@ -59,7 +59,7 @@ class RepositoryManagerTest extends TestCase * @param array $options * @param class-string<\Throwable>|null $exception */ - public function testRepoCreation($type, $options, ?string $exception = null) + public function testRepoCreation($type, $options, ?string $exception = null): void { if ($exception !== null) { self::expectException($exception); @@ -76,7 +76,7 @@ class RepositoryManagerTest extends TestCase $config ->expects($this->any()) ->method('get') - ->will($this->returnCallback(function ($arg) use ($tmpdir) { + ->will($this->returnCallback(function ($arg) use ($tmpdir): ?string { return 'cache-repo-dir' === $arg ? $tmpdir : null; })) ; @@ -95,7 +95,7 @@ class RepositoryManagerTest extends TestCase $this->assertInstanceOf('Composer\Repository\RepositoryInterface', $rm->createRepository($type, $options)); } - public function provideRepoCreationTestCases() + public function provideRepoCreationTestCases(): array { $cases = array( array('composer', array('url' => 'http://example.org')), @@ -115,7 +115,7 @@ class RepositoryManagerTest extends TestCase return $cases; } - public function testFilterRepoWrapping() + public function testFilterRepoWrapping(): void { $rm = new RepositoryManager( $this->getMockBuilder('Composer\IO\IOInterface')->getMock(), diff --git a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php index 06c6bd5b6..cd51b6c3c 100644 --- a/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/FossilDriverTest.php @@ -46,7 +46,7 @@ class FossilDriverTest extends TestCase $fs->removeDirectory($this->home); } - public static function supportProvider() + public static function supportProvider(): array { return array( array('http://fossil.kd2.org/kd2fw/', true), @@ -61,7 +61,7 @@ class FossilDriverTest extends TestCase * @param string $url * @param bool $assertion */ - public function testSupport($url, $assertion) + public function testSupport($url, $assertion): void { $config = new Config(); $result = FossilDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url); diff --git a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php index 66de8b7eb..144852f5a 100644 --- a/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitBitbucketDriverTest.php @@ -64,7 +64,7 @@ class GitBitbucketDriverTest extends TestCase * * @phpstan-param array{url: string}&array $repoConfig */ - private function getDriver(array $repoConfig) + private function getDriver(array $repoConfig): GitBitbucketDriver { $driver = new GitBitbucketDriver( $repoConfig, @@ -79,7 +79,7 @@ class GitBitbucketDriverTest extends TestCase return $driver; } - public function testGetRootIdentifierWrongScmType() + public function testGetRootIdentifierWrongScmType(): void { self::expectException('RuntimeException'); self::expectExceptionMessage('https://bitbucket.org/user/repo.git does not appear to be a git repository, use https://bitbucket.org/user/repo but remember that Bitbucket no longer supports the mercurial repositories. https://bitbucket.org/blog/sunsetting-mercurial-support-in-bitbucket'); @@ -99,7 +99,7 @@ class GitBitbucketDriverTest extends TestCase $driver->getRootIdentifier(); } - public function testDriver() + public function testDriver(): \Composer\Repository\Vcs\GitBitbucketDriver { $driver = $this->getDriver(array('url' => 'https://bitbucket.org/user/repo.git')); @@ -195,7 +195,7 @@ class GitBitbucketDriverTest extends TestCase * @depends testDriver * @param \Composer\Repository\Vcs\VcsDriverInterface $driver */ - public function testGetParams($driver) + public function testGetParams($driver): void { $url = 'https://bitbucket.org/user/repo.git'; @@ -217,7 +217,7 @@ class GitBitbucketDriverTest extends TestCase ); } - public function testInitializeInvalidRepositoryUrl() + public function testInitializeInvalidRepositoryUrl(): void { $this->expectException('\InvalidArgumentException'); @@ -225,7 +225,7 @@ class GitBitbucketDriverTest extends TestCase $driver->initialize(); } - public function testSupports() + public function testSupports(): void { $this->assertTrue( GitBitbucketDriver::supports($this->io, $this->config, 'https://bitbucket.org/user/repo.git') diff --git a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php index 7a721a1be..8482b28bd 100644 --- a/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitHubDriverTest.php @@ -44,7 +44,7 @@ class GitHubDriverTest extends TestCase $fs->removeDirectory($this->home); } - public function testPrivateRepository() + public function testPrivateRepository(): void { $repoUrl = 'http://github.com/composer/packagist'; $repoApiUrl = 'https://api.github.com/repos/composer/packagist'; @@ -105,7 +105,7 @@ class GitHubDriverTest extends TestCase $this->assertEquals('SOMESHA', $source['reference']); } - public function testPublicRepository() + public function testPublicRepository(): void { $repoUrl = 'http://github.com/composer/packagist'; $repoApiUrl = 'https://api.github.com/repos/composer/packagist'; @@ -147,7 +147,7 @@ class GitHubDriverTest extends TestCase $this->assertEquals($sha, $source['reference']); } - public function testPublicRepository2() + public function testPublicRepository2(): void { $repoUrl = 'http://github.com/composer/packagist'; $repoApiUrl = 'https://api.github.com/repos/composer/packagist'; @@ -196,7 +196,7 @@ class GitHubDriverTest extends TestCase $this->assertArrayNotHasKey('abandoned', $data); } - public function testPublicRepositoryArchived() + public function testPublicRepositoryArchived(): void { $repoUrl = 'http://github.com/composer/packagist'; $repoApiUrl = 'https://api.github.com/repos/composer/packagist'; @@ -233,7 +233,7 @@ class GitHubDriverTest extends TestCase $this->assertTrue($data['abandoned']); } - public function testPrivateRepositoryNoInteraction() + public function testPrivateRepositoryNoInteraction(): void { $repoUrl = 'http://github.com/composer/packagist'; $repoApiUrl = 'https://api.github.com/repos/composer/packagist'; @@ -305,7 +305,7 @@ class GitHubDriverTest extends TestCase /** * @return void */ - public function initializeInvalidReoUrl() + public function initializeInvalidReoUrl(): void { $this->expectException('\InvalidArgumentException'); @@ -327,7 +327,7 @@ class GitHubDriverTest extends TestCase * @param bool $expected * @param string $repoUrl */ - public function testSupports($expected, $repoUrl) + public function testSupports($expected, $repoUrl): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); @@ -337,7 +337,7 @@ class GitHubDriverTest extends TestCase /** * @return list */ - public function supportsProvider() + public function supportsProvider(): array { return array( array(false, 'https://github.com/acme'), @@ -353,7 +353,7 @@ class GitHubDriverTest extends TestCase * * @return void */ - protected function setAttribute($object, $attribute, $value) + protected function setAttribute($object, $attribute, $value): void { $attr = new \ReflectionProperty($object, $attribute); $attr->setAccessible(true); diff --git a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php index e2b79774d..b2706d613 100644 --- a/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/GitLabDriverTest.php @@ -77,7 +77,7 @@ class GitLabDriverTest extends TestCase $fs->removeDirectory($this->home); } - public function provideInitializeUrls() + public function provideInitializeUrls(): array { return array( array('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'), @@ -92,7 +92,7 @@ class GitLabDriverTest extends TestCase * @param string $url * @param string $apiUrl */ - public function testInitialize($url, $apiUrl) + public function testInitialize($url, $apiUrl): \Composer\Repository\Vcs\GitLabDriver { // @link http://doc.gitlab.com/ce/api/projects.html#get-single-project $projectData = <<assertEquals($url, $driver->getUrl()); } - public function testGetDist() + public function testGetDist(): void { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -264,7 +264,7 @@ JSON; $this->assertEquals($expected, $driver->getDist($reference)); } - public function testGetSource() + public function testGetSource(): void { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -278,7 +278,7 @@ JSON; $this->assertEquals($expected, $driver->getSource($reference)); } - public function testGetSource_GivenPublicProject() + public function testGetSource_GivenPublicProject(): void { $driver = $this->testInitializePublicProject('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -292,7 +292,7 @@ JSON; $this->assertEquals($expected, $driver->getSource($reference)); } - public function testGetTags() + public function testGetTags(): void { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -333,7 +333,7 @@ JSON; $this->assertEquals($expected, $driver->getTags(), 'Tags are cached'); } - public function testGetPaginatedRefs() + public function testGetPaginatedRefs(): void { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -395,7 +395,7 @@ JSON; $this->assertEquals($expected, $driver->getBranches(), 'Branches are cached'); } - public function testGetBranches() + public function testGetBranches(): void { $driver = $this->testInitialize('https://gitlab.com/mygroup/myproject', 'https://gitlab.com/api/v4/projects/mygroup%2Fmyproject'); @@ -444,12 +444,12 @@ JSON; * @param string $url * @param bool $expected */ - public function testSupports($url, $expected) + public function testSupports($url, $expected): void { $this->assertSame($expected, GitLabDriver::supports($this->io, $this->config, $url)); } - public function dataForTestSupports() + public function dataForTestSupports(): array { return array( array('http://gitlab.com/foo/bar', true), @@ -473,7 +473,7 @@ JSON; ); } - public function testGitlabSubDirectory() + public function testGitlabSubDirectory(): void { $url = 'https://mycompany.com/gitlab/mygroup/my-pro.ject'; $apiUrl = 'https://mycompany.com/gitlab/api/v4/projects/mygroup%2Fmy-pro%2Eject'; @@ -505,7 +505,7 @@ JSON; $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); } - public function testGitlabSubGroup() + public function testGitlabSubGroup(): void { $url = 'https://gitlab.com/mygroup/mysubgroup/myproject'; $apiUrl = 'https://gitlab.com/api/v4/projects/mygroup%2Fmysubgroup%2Fmyproject'; @@ -537,7 +537,7 @@ JSON; $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); } - public function testGitlabSubDirectorySubGroup() + public function testGitlabSubDirectorySubGroup(): void { $url = 'https://mycompany.com/gitlab/mygroup/mysubgroup/myproject'; $apiUrl = 'https://mycompany.com/gitlab/api/v4/projects/mygroup%2Fmysubgroup%2Fmyproject'; @@ -569,7 +569,7 @@ JSON; $this->assertEquals($apiUrl, $driver->getApiUrl(), 'API URL is derived from the repository URL'); } - public function testForwardsOptions() + public function testForwardsOptions(): void { $options = array( 'ssl' => array( @@ -607,7 +607,7 @@ JSON; $driver->initialize(); } - public function testProtocolOverrideRepositoryUrlGeneration() + public function testProtocolOverrideRepositoryUrlGeneration(): void { // @link http://doc.gitlab.com/ce/api/projects.html#get-single-project $projectData = <<assertTrue( HgDriver::supports($this->io, $this->config, $repositoryUrl) ); } - public function supportsDataProvider() + public function supportsDataProvider(): array { return array( array('ssh://bitbucket.org/user/repo'), diff --git a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php index a918b7ff9..00acd67df 100644 --- a/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/PerforceDriverTest.php @@ -89,7 +89,7 @@ class PerforceDriverTest extends TestCase /** * @return void */ - protected function overrideDriverInternalPerforce(Perforce $perforce) + protected function overrideDriverInternalPerforce(Perforce $perforce): void { $reflectionClass = new \ReflectionClass($this->driver); $property = $reflectionClass->getProperty('perforce'); @@ -102,7 +102,7 @@ class PerforceDriverTest extends TestCase * * @return Config */ - protected function getTestConfig($testPath) + protected function getTestConfig($testPath): Config { $config = new Config(); $config->merge(array('config' => array('home' => $testPath))); @@ -136,7 +136,7 @@ class PerforceDriverTest extends TestCase return $this->getMockBuilder('Composer\Util\Perforce')->disableOriginalConstructor()->getMock(); } - public function testInitializeCapturesVariablesFromRepoConfig() + public function testInitializeCapturesVariablesFromRepoConfig(): void { $driver = new PerforceDriver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->process); $driver->initialize(); @@ -145,7 +145,7 @@ class PerforceDriverTest extends TestCase $this->assertEquals(self::TEST_BRANCH, $driver->getBranch()); } - public function testInitializeLogsInAndConnectsClient() + public function testInitializeLogsInAndConnectsClient(): void { $this->perforce->expects($this->once())->method('p4Login'); $this->perforce->expects($this->once())->method('checkStream'); @@ -158,7 +158,7 @@ class PerforceDriverTest extends TestCase * @depends testInitializeCapturesVariablesFromRepoConfig * @depends testInitializeLogsInAndConnectsClient */ - public function testHasComposerFileReturnsFalseOnNoComposerFile() + public function testHasComposerFileReturnsFalseOnNoComposerFile(): void { $identifier = 'TEST_IDENTIFIER'; $formatted_depot_path = '//' . self::TEST_DEPOT . '/' . $identifier; @@ -172,7 +172,7 @@ class PerforceDriverTest extends TestCase * @depends testInitializeCapturesVariablesFromRepoConfig * @depends testInitializeLogsInAndConnectsClient */ - public function testHasComposerFileReturnsTrueWithOneOrMoreComposerFiles() + public function testHasComposerFileReturnsTrueWithOneOrMoreComposerFiles(): void { $identifier = 'TEST_IDENTIFIER'; $formatted_depot_path = '//' . self::TEST_DEPOT . '/' . $identifier; @@ -189,13 +189,13 @@ class PerforceDriverTest extends TestCase * * @return void */ - public function testSupportsReturnsFalseNoDeepCheck() + public function testSupportsReturnsFalseNoDeepCheck(): void { $this->expectOutputString(''); $this->assertFalse(PerforceDriver::supports($this->io, $this->config, 'existing.url')); } - public function testCleanup() + public function testCleanup(): void { $this->perforce->expects($this->once())->method('cleanupClientSpec'); $this->driver->cleanup(); diff --git a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php index e3b32b9bf..f08891a41 100644 --- a/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php +++ b/tests/Composer/Test/Repository/Vcs/SvnDriverTest.php @@ -47,7 +47,7 @@ class SvnDriverTest extends TestCase $fs->removeDirectory($this->home); } - public function testWrongCredentialsInUrl() + public function testWrongCredentialsInUrl(): void { self::expectException('RuntimeException'); self::expectExceptionMessage("Repository https://till:secret@corp.svn.local/repo could not be processed, wrong credentials provided (svn: OPTIONS of 'https://corp.svn.local/repo': authorization failed: Could not authenticate to server: rejected Basic challenge (https://corp.svn.local/))"); @@ -84,7 +84,7 @@ class SvnDriverTest extends TestCase $svn->initialize(); } - public static function supportProvider() + public static function supportProvider(): array { return array( array('http://svn.apache.org', true), @@ -100,7 +100,7 @@ class SvnDriverTest extends TestCase * @param string $url * @param bool $assertion */ - public function testSupport($url, $assertion) + public function testSupport($url, $assertion): void { $config = new Config(); $result = SvnDriver::supports($this->getMockBuilder('Composer\IO\IOInterface')->getMock(), $config, $url); diff --git a/tests/Composer/Test/Repository/VcsRepositoryTest.php b/tests/Composer/Test/Repository/VcsRepositoryTest.php index 470c9bced..819dcd08d 100644 --- a/tests/Composer/Test/Repository/VcsRepositoryTest.php +++ b/tests/Composer/Test/Repository/VcsRepositoryTest.php @@ -42,7 +42,7 @@ class VcsRepositoryTest extends TestCase /** * @return void */ - protected function initialize() + protected function initialize(): void { $locator = new ExecutableFinder(); if (!$locator->find('git')) { @@ -63,7 +63,7 @@ class VcsRepositoryTest extends TestCase // init $process = new ProcessExecutor; - $exec = function ($command) use ($process) { + $exec = function ($command) use ($process): void { $cwd = getcwd(); if ($process->execute($command, $output, $cwd) !== 0) { throw new \RuntimeException('Failed to execute '.$command.': '.$process->getErrorOutput()); @@ -147,7 +147,7 @@ class VcsRepositoryTest extends TestCase $fs->removeDirectory(self::$gitRepo); } - public function testLoadVersions() + public function testLoadVersions(): void { $expected = array( '0.6.0' => true, diff --git a/tests/Composer/Test/Script/EventTest.php b/tests/Composer/Test/Script/EventTest.php index 8ef3c916b..724d0e886 100644 --- a/tests/Composer/Test/Script/EventTest.php +++ b/tests/Composer/Test/Script/EventTest.php @@ -19,7 +19,7 @@ use Composer\Test\TestCase; class EventTest extends TestCase { - public function testEventSetsOriginatingEvent() + public function testEventSetsOriginatingEvent(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $composer = $this->createComposerInstance(); @@ -43,7 +43,7 @@ class EventTest extends TestCase ); } - public function testEventCalculatesNestedOriginatingEvent() + public function testEventCalculatesNestedOriginatingEvent(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $composer = $this->createComposerInstance(); @@ -71,7 +71,7 @@ class EventTest extends TestCase /** * @return Composer */ - private function createComposerInstance() + private function createComposerInstance(): Composer { $composer = new Composer; $config = new Config; diff --git a/tests/Composer/Test/TestCase.php b/tests/Composer/Test/TestCase.php index e6a171621..a8136edb5 100644 --- a/tests/Composer/Test/TestCase.php +++ b/tests/Composer/Test/TestCase.php @@ -67,7 +67,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase /** * @return string */ - public static function getUniqueTmpDirectory() + public static function getUniqueTmpDirectory(): string { $attempts = 5; $root = sys_get_temp_dir(); @@ -86,7 +86,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase /** * @return VersionParser */ - protected static function getVersionParser() + protected static function getVersionParser(): VersionParser { if (!self::$parser) { self::$parser = new VersionParser(); @@ -100,7 +100,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $version * @return Constraint */ - protected function getVersionConstraint($operator, $version) + protected function getVersionConstraint($operator, $version): Constraint { $constraint = new Constraint( $operator, @@ -122,6 +122,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage * * @phpstan-param class-string $class + * @phpstan-return PackageClass */ protected function getPackage($name, $version, $class = 'Composer\Package\CompletePackage') { @@ -134,7 +135,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $version * @return AliasPackage|RootAliasPackage|CompleteAliasPackage */ - protected function getAliasPackage(Package $package, $version) + protected function getAliasPackage(Package $package, $version): \Composer\Package\AliasPackage { $normVersion = self::getVersionParser()->normalize($version); @@ -152,7 +153,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param array> $config * @return void */ - protected function configureLinks(PackageInterface $package, array $config) + protected function configureLinks(PackageInterface $package, array $config): void { $arrayLoader = new ArrayLoader(); @@ -175,7 +176,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * @param string $directory * @return void */ - protected static function ensureDirectoryExistsAndClear($directory) + protected static function ensureDirectoryExistsAndClear($directory): void { $fs = new Filesystem(); @@ -195,7 +196,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * * @throws \PHPUnit\Framework\SkippedTestError */ - protected function skipIfNotExecutable($executableName) + protected function skipIfNotExecutable($executableName): void { if (!isset(self::$executableCache[$executableName])) { $finder = new ExecutableFinder(); @@ -214,7 +215,7 @@ abstract class TestCase extends \PHPUnit\Framework\TestCase * * @return string The transformed command */ - protected function getCmd($cmd) + protected function getCmd($cmd): string { if (Platform::isWindows()) { $cmd = Preg::replaceCallback("/('[^']*')/", function ($m) { diff --git a/tests/Composer/Test/Util/AuthHelperTest.php b/tests/Composer/Test/Util/AuthHelperTest.php index a65d022c1..d12f87066 100644 --- a/tests/Composer/Test/Util/AuthHelperTest.php +++ b/tests/Composer/Test/Util/AuthHelperTest.php @@ -43,7 +43,7 @@ class AuthHelperTest extends TestCase $this->authHelper = new AuthHelper($this->io, $this->config); } - public function testAddAuthenticationHeaderWithoutAuthCredentials() + public function testAddAuthenticationHeaderWithoutAuthCredentials(): void { $headers = array( 'Accept-Encoding: gzip', @@ -63,7 +63,7 @@ class AuthHelperTest extends TestCase ); } - public function testAddAuthenticationHeaderWithBearerPassword() + public function testAddAuthenticationHeaderWithBearerPassword(): void { $headers = array( 'Accept-Encoding: gzip', @@ -86,7 +86,7 @@ class AuthHelperTest extends TestCase ); } - public function testAddAuthenticationHeaderWithGithubToken() + public function testAddAuthenticationHeaderWithGithubToken(): void { $headers = array( 'Accept-Encoding: gzip', @@ -113,7 +113,7 @@ class AuthHelperTest extends TestCase ); } - public function testAddAuthenticationHeaderWithGitlabOathToken() + public function testAddAuthenticationHeaderWithGitlabOathToken(): void { $headers = array( 'Accept-Encoding: gzip', @@ -145,7 +145,7 @@ class AuthHelperTest extends TestCase ); } - public function gitlabPrivateTokenProvider() + public function gitlabPrivateTokenProvider(): array { return array( array('private-token'), @@ -158,7 +158,7 @@ class AuthHelperTest extends TestCase * * @param string $password */ - public function testAddAuthenticationHeaderWithGitlabPrivateToken($password) + public function testAddAuthenticationHeaderWithGitlabPrivateToken($password): void { $headers = array( 'Accept-Encoding: gzip', @@ -190,7 +190,7 @@ class AuthHelperTest extends TestCase ); } - public function testAddAuthenticationHeaderWithBitbucketOathToken() + public function testAddAuthenticationHeaderWithBitbucketOathToken(): void { $headers = array( 'Accept-Encoding: gzip', @@ -222,7 +222,7 @@ class AuthHelperTest extends TestCase ); } - public function bitbucketPublicUrlProvider() + public function bitbucketPublicUrlProvider(): array { return array( array('https://bitbucket.org/user/repo/downloads/whatever'), @@ -235,7 +235,7 @@ class AuthHelperTest extends TestCase * * @param string $url */ - public function testAddAuthenticationHeaderWithBitbucketPublicUrl($url) + public function testAddAuthenticationHeaderWithBitbucketPublicUrl($url): void { $headers = array( 'Accept-Encoding: gzip', @@ -260,7 +260,7 @@ class AuthHelperTest extends TestCase ); } - public function basicHttpAuthenticationProvider() + public function basicHttpAuthenticationProvider(): array { return array( array( @@ -299,7 +299,7 @@ class AuthHelperTest extends TestCase * * @phpstan-param array{username: string|null, password: string|null} $auth */ - public function testAddAuthenticationHeaderWithBasicHttpAuthentication($url, $origin, $auth) + public function testAddAuthenticationHeaderWithBasicHttpAuthentication($url, $origin, $auth): void { $headers = array( 'Accept-Encoding: gzip', @@ -337,12 +337,12 @@ class AuthHelperTest extends TestCase * * @param string $url */ - public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl($url) + public function testIsPublicBitBucketDownloadWithBitbucketPublicUrl($url): void { $this->assertTrue($this->authHelper->isPublicBitBucketDownload($url)); } - public function testIsPublicBitBucketDownloadWithNonBitbucketPublicUrl() + public function testIsPublicBitBucketDownloadWithNonBitbucketPublicUrl(): void { $this->assertFalse( $this->authHelper->isPublicBitBucketDownload( @@ -351,7 +351,7 @@ class AuthHelperTest extends TestCase ); } - public function testStoreAuthAutomatically() + public function testStoreAuthAutomatically(): void { $origin = 'github.com'; $storeAuth = true; @@ -383,7 +383,7 @@ class AuthHelperTest extends TestCase $this->authHelper->storeAuth($origin, $storeAuth); } - public function testStoreAuthWithPromptYesAnswer() + public function testStoreAuthWithPromptYesAnswer(): void { $origin = 'github.com'; $storeAuth = 'prompt'; @@ -416,7 +416,7 @@ class AuthHelperTest extends TestCase null, 'y' ) - ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer) { + ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer): string { $validator($answer); return $answer; @@ -435,7 +435,7 @@ class AuthHelperTest extends TestCase $this->authHelper->storeAuth($origin, $storeAuth); } - public function testStoreAuthWithPromptNoAnswer() + public function testStoreAuthWithPromptNoAnswer(): void { $origin = 'github.com'; $storeAuth = 'prompt'; @@ -464,7 +464,7 @@ class AuthHelperTest extends TestCase null, 'y' ) - ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer) { + ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer): string { $validator($answer); return $answer; @@ -473,7 +473,7 @@ class AuthHelperTest extends TestCase $this->authHelper->storeAuth($origin, $storeAuth); } - public function testStoreAuthWithPromptInvalidAnswer() + public function testStoreAuthWithPromptInvalidAnswer(): void { self::expectException('RuntimeException'); @@ -504,7 +504,7 @@ class AuthHelperTest extends TestCase null, 'y' ) - ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer) { + ->willReturnCallback(function ($question, $validator, $attempts, $default) use ($answer): string { $validator($answer); return $answer; @@ -521,7 +521,7 @@ class AuthHelperTest extends TestCase * * @phpstan-param array{username: string|null, password: string|null} $auth */ - private function expectsAuthentication($origin, $auth) + private function expectsAuthentication($origin, $auth): void { $this->io->expects($this->once()) ->method('hasAuthentication') diff --git a/tests/Composer/Test/Util/BitbucketTest.php b/tests/Composer/Test/Util/BitbucketTest.php index afc7f7aa2..643b1f64e 100644 --- a/tests/Composer/Test/Util/BitbucketTest.php +++ b/tests/Composer/Test/Util/BitbucketTest.php @@ -68,7 +68,7 @@ class BitbucketTest extends TestCase $this->bitbucket = new Bitbucket($this->io, $this->config, null, $this->httpDownloader, $this->time); } - public function testRequestAccessTokenWithValidOAuthConsumer() + public function testRequestAccessTokenWithValidOAuthConsumer(): void { $this->io->expects($this->once()) ->method('setAuthentication') @@ -111,7 +111,7 @@ class BitbucketTest extends TestCase ); } - public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken() + public function testRequestAccessTokenWithValidOAuthConsumerAndValidStoredAccessToken(): \Composer\Util\Bitbucket { $this->config->expects($this->once()) ->method('get') @@ -135,7 +135,7 @@ class BitbucketTest extends TestCase return $this->bitbucket; } - public function testRequestAccessTokenWithValidOAuthConsumerAndExpiredAccessToken() + public function testRequestAccessTokenWithValidOAuthConsumerAndExpiredAccessToken(): void { $this->config->expects($this->once()) ->method('get') @@ -187,7 +187,7 @@ class BitbucketTest extends TestCase ); } - public function testRequestAccessTokenWithUsernameAndPassword() + public function testRequestAccessTokenWithUsernameAndPassword(): void { $this->io->expects($this->once()) ->method('setAuthentication') @@ -232,7 +232,7 @@ class BitbucketTest extends TestCase $this->assertEquals('', $this->bitbucket->requestToken($this->origin, $this->username, $this->password)); } - public function testRequestAccessTokenWithUsernameAndPasswordWithUnauthorizedResponse() + public function testRequestAccessTokenWithUsernameAndPasswordWithUnauthorizedResponse(): void { $this->config->expects($this->once()) ->method('get') @@ -267,7 +267,7 @@ class BitbucketTest extends TestCase $this->assertEquals('', $this->bitbucket->requestToken($this->origin, $this->username, $this->password)); } - public function testRequestAccessTokenWithUsernameAndPasswordWithNotFoundResponse() + public function testRequestAccessTokenWithUsernameAndPasswordWithNotFoundResponse(): void { self::expectException('Composer\Downloader\TransportException'); $this->config->expects($this->once()) @@ -297,7 +297,7 @@ class BitbucketTest extends TestCase $this->bitbucket->requestToken($this->origin, $this->username, $this->password); } - public function testUsernamePasswordAuthenticationFlow() + public function testUsernamePasswordAuthenticationFlow(): void { $this->io ->expects($this->atLeastOnce()) @@ -338,7 +338,7 @@ class BitbucketTest extends TestCase $this->assertTrue($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message)); } - public function testAuthorizeOAuthInteractivelyWithEmptyUsername() + public function testAuthorizeOAuthInteractivelyWithEmptyUsername(): void { $authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->expects($this->atLeastOnce()) @@ -353,7 +353,7 @@ class BitbucketTest extends TestCase $this->assertFalse($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message)); } - public function testAuthorizeOAuthInteractivelyWithEmptyPassword() + public function testAuthorizeOAuthInteractivelyWithEmptyPassword(): void { $authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->expects($this->atLeastOnce()) @@ -371,7 +371,7 @@ class BitbucketTest extends TestCase $this->assertFalse($this->bitbucket->authorizeOAuthInteractively($this->origin, $this->message)); } - public function testAuthorizeOAuthInteractivelyWithRequestAccessTokenFailure() + public function testAuthorizeOAuthInteractivelyWithRequestAccessTokenFailure(): void { $authConfigSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->expects($this->atLeastOnce()) @@ -411,7 +411,7 @@ class BitbucketTest extends TestCase * * @return void */ - private function setExpectationsForStoringAccessToken($removeBasicAuth = false) + private function setExpectationsForStoringAccessToken($removeBasicAuth = false): void { $configSourceMock = $this->getMockBuilder('Composer\Config\ConfigSourceInterface')->getMock(); $this->config->expects($this->once()) @@ -446,7 +446,7 @@ class BitbucketTest extends TestCase } } - public function testGetTokenWithoutAccessToken() + public function testGetTokenWithoutAccessToken(): void { $this->assertSame('', $this->bitbucket->getToken()); } @@ -456,17 +456,17 @@ class BitbucketTest extends TestCase * * @param Bitbucket $bitbucket */ - public function testGetTokenWithAccessToken(Bitbucket $bitbucket) + public function testGetTokenWithAccessToken(Bitbucket $bitbucket): void { $this->assertSame($this->token, $bitbucket->getToken()); } - public function testAuthorizeOAuthWithWrongOriginUrl() + public function testAuthorizeOAuthWithWrongOriginUrl(): void { $this->assertFalse($this->bitbucket->authorizeOAuth('non-' . $this->origin)); } - public function testAuthorizeOAuthWithoutAvailableGitConfigToken() + public function testAuthorizeOAuthWithoutAvailableGitConfigToken(): void { $process = $this->getProcessExecutorMock(); $process->expects(array(), false, array('return' => -1)); @@ -476,7 +476,7 @@ class BitbucketTest extends TestCase $this->assertFalse($bitbucket->authorizeOAuth($this->origin)); } - public function testAuthorizeOAuthWithAvailableGitConfigToken() + public function testAuthorizeOAuthWithAvailableGitConfigToken(): void { $process = $this->getProcessExecutorMock(); diff --git a/tests/Composer/Test/Util/ConfigValidatorTest.php b/tests/Composer/Test/Util/ConfigValidatorTest.php index 0e53e1c54..c755ea6e5 100644 --- a/tests/Composer/Test/Util/ConfigValidatorTest.php +++ b/tests/Composer/Test/Util/ConfigValidatorTest.php @@ -24,7 +24,7 @@ class ConfigValidatorTest extends TestCase /** * Test ConfigValidator warns on commit reference */ - public function testConfigValidatorCommitRefWarning() + public function testConfigValidatorCommitRefWarning(): void { $configValidator = new ConfigValidator(new NullIO()); list(, , $warnings) = $configValidator->validate(__DIR__ . '/Fixtures/composer_commit-ref.json'); @@ -35,7 +35,7 @@ class ConfigValidatorTest extends TestCase ); } - public function testConfigValidatorWarnsOnScriptDescriptionForNonexistentScript() + public function testConfigValidatorWarnsOnScriptDescriptionForNonexistentScript(): void { $configValidator = new ConfigValidator(new NullIO()); list(, , $warnings) = $configValidator->validate(__DIR__ . '/Fixtures/composer_scripts-descriptions.json'); @@ -46,7 +46,7 @@ class ConfigValidatorTest extends TestCase ); } - public function testConfigValidatorWarnsOnUnnecessaryProvideReplace() + public function testConfigValidatorWarnsOnUnnecessaryProvideReplace(): void { $configValidator = new ConfigValidator(new NullIO()); list(, , $warnings) = $configValidator->validate(__DIR__ . '/Fixtures/composer_provide-replace-requirements.json'); diff --git a/tests/Composer/Test/Util/ErrorHandlerTest.php b/tests/Composer/Test/Util/ErrorHandlerTest.php index 6dc0c8ec6..4def526a4 100644 --- a/tests/Composer/Test/Util/ErrorHandlerTest.php +++ b/tests/Composer/Test/Util/ErrorHandlerTest.php @@ -34,7 +34,7 @@ class ErrorHandlerTest extends TestCase /** * Test ErrorHandler handles notices */ - public function testErrorHandlerCaptureNotice() + public function testErrorHandlerCaptureNotice(): void { if (PHP_VERSION_ID >= 80000) { self::expectException('\ErrorException'); @@ -52,7 +52,7 @@ class ErrorHandlerTest extends TestCase /** * Test ErrorHandler handles warnings */ - public function testErrorHandlerCaptureWarning() + public function testErrorHandlerCaptureWarning(): void { if (PHP_VERSION_ID >= 80000) { self::expectException('TypeError'); @@ -70,7 +70,7 @@ class ErrorHandlerTest extends TestCase * Test ErrorHandler handles warnings * @doesNotPerformAssertions */ - public function testErrorHandlerRespectsAtOperator() + public function testErrorHandlerRespectsAtOperator(): void { @trigger_error('test', E_USER_NOTICE); } diff --git a/tests/Composer/Test/Util/FilesystemTest.php b/tests/Composer/Test/Util/FilesystemTest.php index 2c7fa5657..dc6706b27 100644 --- a/tests/Composer/Test/Util/FilesystemTest.php +++ b/tests/Composer/Test/Util/FilesystemTest.php @@ -59,13 +59,13 @@ class FilesystemTest extends TestCase * @param string $expected * @param bool $static */ - public function testFindShortestPathCode($a, $b, $directory, $expected, $static = false) + public function testFindShortestPathCode($a, $b, $directory, $expected, $static = false): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->findShortestPathCode($a, $b, $directory, $static)); } - public function providePathCouplesAsCode() + public function providePathCouplesAsCode(): array { return array( array('/foo/bar', '/foo/bar', false, "__FILE__"), @@ -122,13 +122,13 @@ class FilesystemTest extends TestCase * @param string $expected * @param bool $directory */ - public function testFindShortestPath($a, $b, $expected, $directory = false) + public function testFindShortestPath($a, $b, $expected, $directory = false): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->findShortestPath($a, $b, $directory)); } - public function providePathCouples() + public function providePathCouples(): array { return array( array('/foo/bar', '/foo/bar', "./bar"), @@ -173,7 +173,7 @@ class FilesystemTest extends TestCase /** * @group GH-1339 */ - public function testRemoveDirectoryPhp() + public function testRemoveDirectoryPhp(): void { @mkdir($this->workingDir . "/level1/level2", 0777, true); file_put_contents($this->workingDir . "/level1/level2/hello.txt", "hello world"); @@ -183,7 +183,7 @@ class FilesystemTest extends TestCase $this->assertFileDoesNotExist($this->workingDir . "/level1/level2/hello.txt"); } - public function testFileSize() + public function testFileSize(): void { file_put_contents($this->testFile, 'Hello'); @@ -191,7 +191,7 @@ class FilesystemTest extends TestCase $this->assertGreaterThanOrEqual(5, $fs->size($this->testFile)); } - public function testDirectorySize() + public function testDirectorySize(): void { @mkdir($this->workingDir, 0777, true); file_put_contents($this->workingDir."/file1.txt", 'Hello'); @@ -207,13 +207,13 @@ class FilesystemTest extends TestCase * @param string $expected * @param string $actual */ - public function testNormalizePath($expected, $actual) + public function testNormalizePath($expected, $actual): void { $fs = new Filesystem; $this->assertEquals($expected, $fs->normalizePath($actual)); } - public function provideNormalizedPaths() + public function provideNormalizedPaths(): array { return array( array('../foo', '../foo'), @@ -243,7 +243,7 @@ class FilesystemTest extends TestCase * @link https://github.com/composer/composer/issues/3157 * @requires function symlink */ - public function testUnlinkSymlinkedDirectory() + public function testUnlinkSymlinkedDirectory(): void { $basepath = $this->workingDir; $symlinked = $basepath . "/linked"; @@ -270,7 +270,7 @@ class FilesystemTest extends TestCase * @link https://github.com/composer/composer/issues/3144 * @requires function symlink */ - public function testRemoveSymlinkedDirectoryWithTrailingSlash() + public function testRemoveSymlinkedDirectoryWithTrailingSlash(): void { @mkdir($this->workingDir . "/real", 0777, true); touch($this->workingDir . "/real/FILE"); @@ -299,7 +299,7 @@ class FilesystemTest extends TestCase $this->assertFileDoesNotExist($symlinked); } - public function testJunctions() + public function testJunctions(): void { @mkdir($this->workingDir . '/real/nesting/testing', 0777, true); $fs = new Filesystem(); @@ -329,7 +329,7 @@ class FilesystemTest extends TestCase $this->assertFalse(is_dir($junction), $junction . ' is not a directory'); } - public function testCopy() + public function testCopy(): void { @mkdir($this->workingDir . '/foo/bar', 0777, true); @mkdir($this->workingDir . '/foo/baz', 0777, true); @@ -354,7 +354,7 @@ class FilesystemTest extends TestCase $this->assertTrue(is_file($this->workingDir . '/testfile.file')); } - public function testCopyThenRemove() + public function testCopyThenRemove(): void { @mkdir($this->workingDir . '/foo/bar', 0777, true); @mkdir($this->workingDir . '/foo/baz', 0777, true); diff --git a/tests/Composer/Test/Util/GitHubTest.php b/tests/Composer/Test/Util/GitHubTest.php index 0da22733a..a4151f489 100644 --- a/tests/Composer/Test/Util/GitHubTest.php +++ b/tests/Composer/Test/Util/GitHubTest.php @@ -27,7 +27,7 @@ class GitHubTest extends TestCase /** @var string */ private $origin = 'github.com'; - public function testUsernamePasswordAuthenticationFlow() + public function testUsernamePasswordAuthenticationFlow(): void { $io = $this->getIOMock(); $io @@ -65,7 +65,7 @@ class GitHubTest extends TestCase $this->assertTrue($github->authorizeOAuthInteractively($this->origin, $this->message)); } - public function testUsernamePasswordFailure() + public function testUsernamePasswordFailure(): void { $io = $this->getIOMock(); $io diff --git a/tests/Composer/Test/Util/GitLabTest.php b/tests/Composer/Test/Util/GitLabTest.php index 397b164ad..61bc35c72 100644 --- a/tests/Composer/Test/Util/GitLabTest.php +++ b/tests/Composer/Test/Util/GitLabTest.php @@ -31,7 +31,7 @@ class GitLabTest extends TestCase /** @var string */ private $token = 'gitlabtoken'; - public function testUsernamePasswordAuthenticationFlow() + public function testUsernamePasswordAuthenticationFlow(): void { $io = $this->getIOMock(); $io @@ -70,7 +70,7 @@ class GitLabTest extends TestCase $this->assertTrue($gitLab->authorizeOAuthInteractively('http', $this->origin, $this->message)); } - public function testUsernamePasswordFailure() + public function testUsernamePasswordFailure(): void { self::expectException('RuntimeException'); self::expectExceptionMessage('Invalid GitLab credentials 5 times in a row, aborting.'); diff --git a/tests/Composer/Test/Util/GitTest.php b/tests/Composer/Test/Util/GitTest.php index 9379d5b2e..e6df4e1ed 100644 --- a/tests/Composer/Test/Util/GitTest.php +++ b/tests/Composer/Test/Util/GitTest.php @@ -47,9 +47,9 @@ class GitTest extends TestCase * @param string $protocol * @param string $expectedUrl */ - public function testRunCommandPublicGitHubRepositoryNotInitialClone($protocol, $expectedUrl) + public function testRunCommandPublicGitHubRepositoryNotInitialClone($protocol, $expectedUrl): void { - $commandCallable = function ($url) use ($expectedUrl) { + $commandCallable = function ($url) use ($expectedUrl): string { $this->assertSame($expectedUrl, $url); return 'git command'; @@ -62,7 +62,7 @@ class GitTest extends TestCase $this->git->runCommand($commandCallable, 'https://github.com/acme/repo', null, true); } - public function publicGithubNoCredentialsProvider() + public function publicGithubNoCredentialsProvider(): array { return array( array('ssh', 'git@github.com:acme/repo'), @@ -70,11 +70,11 @@ class GitTest extends TestCase ); } - public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithoutAuthentication() + public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithoutAuthentication(): void { self::expectException('RuntimeException'); - $commandCallable = function ($url) { + $commandCallable = function ($url): string { $this->assertSame('https://github.com/acme/repo', $url); return 'git command'; @@ -99,9 +99,9 @@ class GitTest extends TestCase * @param string $expectedUrl * @param int $expectedFailuresBeforeSuccess */ - public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication($gitUrl, $protocol, $gitHubToken, $expectedUrl, $expectedFailuresBeforeSuccess) + public function testRunCommandPrivateGitHubRepositoryNotInitialCloneNotInteractiveWithAuthentication($gitUrl, $protocol, $gitHubToken, $expectedUrl, $expectedFailuresBeforeSuccess): void { - $commandCallable = function ($url) use ($expectedUrl) { + $commandCallable = function ($url) use ($expectedUrl): string { if ($url !== $expectedUrl) { return 'git command failing'; } @@ -135,7 +135,7 @@ class GitTest extends TestCase $this->git->runCommand($commandCallable, $gitUrl, null, true); } - public function privateGithubWithCredentialsProvider() + public function privateGithubWithCredentialsProvider(): array { return array( array('git@github.com:acme/repo.git', 'ssh', 'MY_GITHUB_TOKEN', 'https://token:MY_GITHUB_TOKEN@github.com/acme/repo.git', 1), @@ -148,7 +148,7 @@ class GitTest extends TestCase * * @return void */ - private function mockConfig($protocol) + private function mockConfig($protocol): void { $this->config ->method('get') diff --git a/tests/Composer/Test/Util/Http/ProxyHelperTest.php b/tests/Composer/Test/Util/Http/ProxyHelperTest.php index 72e1d2f6d..15fd85069 100644 --- a/tests/Composer/Test/Util/Http/ProxyHelperTest.php +++ b/tests/Composer/Test/Util/Http/ProxyHelperTest.php @@ -49,7 +49,7 @@ class ProxyHelperTest extends TestCase * * @param string $url */ - public function testThrowsOnMalformedUrl($url) + public function testThrowsOnMalformedUrl($url): void { $_SERVER['http_proxy'] = $url; @@ -57,7 +57,7 @@ class ProxyHelperTest extends TestCase ProxyHelper::getProxyData(); } - public function dataMalformed() + public function dataMalformed(): array { return array( 'no-host' => array('localhost'), @@ -71,7 +71,7 @@ class ProxyHelperTest extends TestCase * @param string $url * @param string $expected */ - public function testUrlFormatting($url, $expected) + public function testUrlFormatting($url, $expected): void { $_SERVER['http_proxy'] = $url; @@ -79,7 +79,7 @@ class ProxyHelperTest extends TestCase $this->assertSame($expected, $httpProxy); } - public function dataFormatting() + public function dataFormatting(): array { // url, expected return array( @@ -96,7 +96,7 @@ class ProxyHelperTest extends TestCase * @param string $expected * @param int $index */ - public function testLowercaseOverridesUppercase(array $server, $expected, $index) + public function testLowercaseOverridesUppercase(array $server, $expected, $index): void { $_SERVER = array_merge($_SERVER, $server); @@ -104,7 +104,7 @@ class ProxyHelperTest extends TestCase $this->assertSame($expected, $list[$index]); } - public function dataCaseOverrides() + public function dataCaseOverrides(): array { // server, expected, list index return array( @@ -121,7 +121,7 @@ class ProxyHelperTest extends TestCase * @param string $expected * @param int $index */ - public function testCGIUpperCaseOverridesHttp(array $server, $expected, $index) + public function testCGIUpperCaseOverridesHttp(array $server, $expected, $index): void { $_SERVER = array_merge($_SERVER, $server); @@ -129,7 +129,7 @@ class ProxyHelperTest extends TestCase $this->assertSame($expected, $list[$index]); } - public function dataCGIOverrides() + public function dataCGIOverrides(): array { // server, expected, list index return array( @@ -138,7 +138,7 @@ class ProxyHelperTest extends TestCase ); } - public function testNoHttpsProxyUsesHttpProxy() + public function testNoHttpsProxyUsesHttpProxy(): void { $_SERVER['http_proxy'] = 'http://http.com'; @@ -146,7 +146,7 @@ class ProxyHelperTest extends TestCase $this->assertSame('http://http.com:80', $httpsProxy); } - public function testNoHttpProxyDoesNotUseHttpsProxy() + public function testNoHttpProxyDoesNotUseHttpsProxy(): void { $_SERVER['https_proxy'] = 'http://https.com'; @@ -162,12 +162,12 @@ class ProxyHelperTest extends TestCase * * @phpstan-param array{http: array{proxy: string, header?: string}} $expected */ - public function testGetContextOptions($url, $expected) + public function testGetContextOptions($url, $expected): void { $this->assertEquals($expected, ProxyHelper::getContextOptions($url)); } - public function dataContextOptions() + public function dataContextOptions(): array { // url, expected return array( @@ -190,7 +190,7 @@ class ProxyHelperTest extends TestCase * @param string $requestUrl * @param mixed[] $expected */ - public function testSetRequestFullUri($requestUrl, $expected) + public function testSetRequestFullUri($requestUrl, $expected): void { $options = array(); ProxyHelper::setRequestFullUri($requestUrl, $options); @@ -198,7 +198,7 @@ class ProxyHelperTest extends TestCase $this->assertEquals($expected, $options); } - public function dataRequestFullUri() + public function dataRequestFullUri(): array { $options = array('http' => array('request_fulluri' => true)); diff --git a/tests/Composer/Test/Util/Http/ProxyManagerTest.php b/tests/Composer/Test/Util/Http/ProxyManagerTest.php index 16d926039..729e12da3 100644 --- a/tests/Composer/Test/Util/Http/ProxyManagerTest.php +++ b/tests/Composer/Test/Util/Http/ProxyManagerTest.php @@ -46,7 +46,7 @@ class ProxyManagerTest extends TestCase ProxyManager::reset(); } - public function testInstantiation() + public function testInstantiation(): void { $originalInstance = ProxyManager::getInstance(); $this->assertInstanceOf('Composer\Util\Http\ProxyManager', $originalInstance); @@ -59,7 +59,7 @@ class ProxyManagerTest extends TestCase $this->assertFalse($sameInstance === $newInstance); } - public function testGetProxyForRequestThrowsOnBadProxyUrl() + public function testGetProxyForRequestThrowsOnBadProxyUrl(): void { $_SERVER['http_proxy'] = 'localhost'; $proxyManager = ProxyManager::getInstance(); @@ -77,7 +77,7 @@ class ProxyManagerTest extends TestCase * @param bool $expectedSecure * @param string $expectedMessage */ - public function testGetProxyForRequest($server, $url, $expectedUrl, $expectedOptions, $expectedSecure, $expectedMessage) + public function testGetProxyForRequest($server, $url, $expectedUrl, $expectedOptions, $expectedSecure, $expectedMessage): void { $_SERVER = array_merge($_SERVER, $server); $proxyManager = ProxyManager::getInstance(); @@ -100,7 +100,7 @@ class ProxyManagerTest extends TestCase $this->assertTrue($condition, 'lastProxy check'); } - public function dataRequest() + public function dataRequest(): array { $server = array( 'http_proxy' => 'http://user:p%40ss@proxy.com', @@ -139,7 +139,7 @@ class ProxyManagerTest extends TestCase * @param bool $expectedStatus * @param string $expectedMessage */ - public function testGetStatus($server, $expectedStatus, $expectedMessage) + public function testGetStatus($server, $expectedStatus, $expectedMessage): void { $_SERVER = array_merge($_SERVER, $server); $proxyManager = ProxyManager::getInstance(); @@ -156,7 +156,7 @@ class ProxyManagerTest extends TestCase $this->assertTrue($condition, 'message check'); } - public function dataStatus() + public function dataStatus(): array { // server, expectedStatus, expectedMessage return array( diff --git a/tests/Composer/Test/Util/Http/RequestProxyTest.php b/tests/Composer/Test/Util/Http/RequestProxyTest.php index 33f5664a8..120ff8263 100644 --- a/tests/Composer/Test/Util/Http/RequestProxyTest.php +++ b/tests/Composer/Test/Util/Http/RequestProxyTest.php @@ -23,14 +23,14 @@ class RequestProxyTest extends TestCase * @param string $url * @param bool $expectedSecure */ - public function testIsSecure($url, $expectedSecure) + public function testIsSecure($url, $expectedSecure): void { $proxy = new RequestProxy($url, array(), ''); $this->assertSame($expectedSecure, $proxy->isSecure()); } - public function dataSecure() + public function dataSecure(): array { // url, secure return array( @@ -47,7 +47,7 @@ class RequestProxyTest extends TestCase * @param string $format * @param string $expected */ - public function testGetFormattedUrlFormat($url, $format, $expected) + public function testGetFormattedUrlFormat($url, $format, $expected): void { $proxy = new RequestProxy($url, array(), $url); @@ -55,7 +55,7 @@ class RequestProxyTest extends TestCase $this->assertSame($expected, $message); } - public function dataProxyUrl() + public function dataProxyUrl(): array { $format = 'proxy (%s)'; diff --git a/tests/Composer/Test/Util/HttpDownloaderTest.php b/tests/Composer/Test/Util/HttpDownloaderTest.php index e35ab514e..fe49c1ca5 100644 --- a/tests/Composer/Test/Util/HttpDownloaderTest.php +++ b/tests/Composer/Test/Util/HttpDownloaderTest.php @@ -38,7 +38,7 @@ class HttpDownloaderTest extends TestCase /** * @group slow */ - public function testCaptureAuthenticationParamsFromUrl() + public function testCaptureAuthenticationParamsFromUrl(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $io->expects($this->once()) @@ -53,7 +53,7 @@ class HttpDownloaderTest extends TestCase } } - public function testOutputWarnings() + public function testOutputWarnings(): void { $io = new BufferIO(); HttpDownloader::outputWarnings($io, '$URL', array()); diff --git a/tests/Composer/Test/Util/IniHelperTest.php b/tests/Composer/Test/Util/IniHelperTest.php index a6d83bb09..a3e8bc8e6 100644 --- a/tests/Composer/Test/Util/IniHelperTest.php +++ b/tests/Composer/Test/Util/IniHelperTest.php @@ -26,7 +26,7 @@ class IniHelperTest extends TestCase */ public static $envOriginal; - public function testWithNoIni() + public function testWithNoIni(): void { $paths = array( '', @@ -37,7 +37,7 @@ class IniHelperTest extends TestCase $this->assertEquals($paths, IniHelper::getAll()); } - public function testWithLoadedIniOnly() + public function testWithLoadedIniOnly(): void { $paths = array( 'loaded.ini', @@ -47,7 +47,7 @@ class IniHelperTest extends TestCase $this->assertStringContainsString('loaded.ini', IniHelper::getMessage()); } - public function testWithLoadedIniAndAdditional() + public function testWithLoadedIniAndAdditional(): void { $paths = array( 'loaded.ini', @@ -60,7 +60,7 @@ class IniHelperTest extends TestCase $this->assertEquals($paths, IniHelper::getAll()); } - public function testWithoutLoadedIniAndAdditional() + public function testWithoutLoadedIniAndAdditional(): void { $paths = array( '', @@ -96,7 +96,7 @@ class IniHelperTest extends TestCase * * @return void */ - protected function setEnv(array $paths) + protected function setEnv(array $paths): void { putenv('COMPOSER_ORIGINAL_INIS='.implode(PATH_SEPARATOR, $paths)); } diff --git a/tests/Composer/Test/Util/MetadataMinifierTest.php b/tests/Composer/Test/Util/MetadataMinifierTest.php index fa69e928d..44e28c9b2 100644 --- a/tests/Composer/Test/Util/MetadataMinifierTest.php +++ b/tests/Composer/Test/Util/MetadataMinifierTest.php @@ -19,7 +19,7 @@ use PHPUnit\Framework\TestCase; class MetadataMinifierTest extends TestCase { - public function testMinifyExpand() + public function testMinifyExpand(): void { $package1 = new CompletePackage('foo/bar', '2.0.0.0', '2.0.0'); $package1->setScripts(array('foo' => array('bar'))); diff --git a/tests/Composer/Test/Util/NoProxyPatternTest.php b/tests/Composer/Test/Util/NoProxyPatternTest.php index 940eff5cc..c70c9774d 100644 --- a/tests/Composer/Test/Util/NoProxyPatternTest.php +++ b/tests/Composer/Test/Util/NoProxyPatternTest.php @@ -24,14 +24,14 @@ class NoProxyPatternTest extends TestCase * @param string $url * @param bool $expected */ - public function testHostName($noproxy, $url, $expected) + public function testHostName($noproxy, $url, $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); $this->assertEquals($expected, $matcher->test($url)); } - public function dataHostName() + public function dataHostName(): array { $noproxy = 'foobar.com, .barbaz.net'; @@ -55,14 +55,14 @@ class NoProxyPatternTest extends TestCase * @param string $url * @param bool $expected */ - public function testIpAddress($noproxy, $url, $expected) + public function testIpAddress($noproxy, $url, $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); $this->assertEquals($expected, $matcher->test($url)); } - public function dataIpAddress() + public function dataIpAddress(): array { $noproxy = '192.168.1.1, 2001:db8::52:0:1'; @@ -84,14 +84,14 @@ class NoProxyPatternTest extends TestCase * @param string $url * @param bool $expected */ - public function testIpRange($noproxy, $url, $expected) + public function testIpRange($noproxy, $url, $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); $this->assertEquals($expected, $matcher->test($url)); } - public function dataIpRange() + public function dataIpRange(): array { $noproxy = '10.0.0.0/30, 2002:db8:a::45/121'; @@ -113,14 +113,14 @@ class NoProxyPatternTest extends TestCase * @param string $url * @param bool $expected */ - public function testPort($noproxy, $url, $expected) + public function testPort($noproxy, $url, $expected): void { $matcher = new NoProxyPattern($noproxy); $url = $this->getUrl($url); $this->assertEquals($expected, $matcher->test($url)); } - public function dataPort() + public function dataPort(): array { $noproxy = '192.168.1.2:81, 192.168.1.3:80, [2001:db8::52:0:2]:443, [2001:db8::52:0:3]:80'; @@ -140,7 +140,7 @@ class NoProxyPatternTest extends TestCase * * @return string */ - private function getUrl($url) + private function getUrl($url): string { if (parse_url($url, PHP_URL_SCHEME)) { return $url; diff --git a/tests/Composer/Test/Util/PackageSorterTest.php b/tests/Composer/Test/Util/PackageSorterTest.php index 7ee94982c..4f25f5633 100644 --- a/tests/Composer/Test/Util/PackageSorterTest.php +++ b/tests/Composer/Test/Util/PackageSorterTest.php @@ -20,7 +20,7 @@ use Composer\Semver\Constraint\MatchAllConstraint; class PackageSorterTest extends TestCase { - public function testSortingDoesNothingWithNoDependencies() + public function testSortingDoesNothingWithNoDependencies(): void { $packages[] = $this->createPackage('foo/bar1', array()); $packages[] = $this->createPackage('foo/bar2', array()); @@ -32,7 +32,7 @@ class PackageSorterTest extends TestCase self::assertSame($packages, $sortedPackages); } - public function sortingOrdersDependenciesHigherThanPackageDataProvider() + public function sortingOrdersDependenciesHigherThanPackageDataProvider(): array { return array( 'one package is dep' => array( @@ -108,10 +108,10 @@ class PackageSorterTest extends TestCase * @param Package[] $packages * @param string[] $expectedOrderedList */ - public function testSortingOrdersDependenciesHigherThanPackage($packages, $expectedOrderedList) + public function testSortingOrdersDependenciesHigherThanPackage($packages, $expectedOrderedList): void { $sortedPackages = PackageSorter::sortPackages($packages); - $sortedPackageNames = array_map(function ($package) { + $sortedPackageNames = array_map(function ($package): string { return $package->getName(); }, $sortedPackages); @@ -124,7 +124,7 @@ class PackageSorterTest extends TestCase * * @return Package */ - private function createPackage($name, $requires) + private function createPackage($name, $requires): Package { $package = new Package($name, '1.0.0.0', '1.0.0'); diff --git a/tests/Composer/Test/Util/PerforceTest.php b/tests/Composer/Test/Util/PerforceTest.php index 817e4fe48..4e3f7d5b9 100644 --- a/tests/Composer/Test/Util/PerforceTest.php +++ b/tests/Composer/Test/Util/PerforceTest.php @@ -50,7 +50,7 @@ class PerforceTest extends TestCase /** * @return array */ - public function getTestRepoConfig() + public function getTestRepoConfig(): array { return array( 'depot' => self::TEST_DEPOT, @@ -73,12 +73,12 @@ class PerforceTest extends TestCase * * @return void */ - protected function createNewPerforceWithWindowsFlag($flag) + protected function createNewPerforceWithWindowsFlag($flag): void { $this->perforce = new Perforce($this->repoConfig, self::TEST_PORT, self::TEST_PATH, $this->processExecutor, $flag, $this->io); } - public function testGetClientWithoutStream() + public function testGetClientWithoutStream(): void { $client = $this->perforce->getClient(); @@ -86,7 +86,7 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $client); } - public function testGetClientFromStream() + public function testGetClientFromStream(): void { $this->setPerforceToStream(); @@ -96,13 +96,13 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $client); } - public function testGetStreamWithoutStream() + public function testGetStreamWithoutStream(): void { $stream = $this->perforce->getStream(); $this->assertEquals("//depot", $stream); } - public function testGetStreamWithStream() + public function testGetStreamWithStream(): void { $this->setPerforceToStream(); @@ -110,26 +110,26 @@ class PerforceTest extends TestCase $this->assertEquals('//depot/branch', $stream); } - public function testGetStreamWithoutLabelWithStreamWithoutLabel() + public function testGetStreamWithoutLabelWithStreamWithoutLabel(): void { $stream = $this->perforce->getStreamWithoutLabel('//depot/branch'); $this->assertEquals('//depot/branch', $stream); } - public function testGetStreamWithoutLabelWithStreamWithLabel() + public function testGetStreamWithoutLabelWithStreamWithLabel(): void { $stream = $this->perforce->getStreamWithoutLabel('//depot/branching@label'); $this->assertEquals('//depot/branching', $stream); } - public function testGetClientSpec() + public function testGetClientSpec(): void { $clientSpec = $this->perforce->getP4ClientSpec(); $expected = 'path/composer_perforce_TEST_depot.p4.spec'; $this->assertEquals($expected, $clientSpec); } - public function testGenerateP4Command() + public function testGenerateP4Command(): void { $command = 'do something'; $p4Command = $this->perforce->generateP4Command($command); @@ -137,13 +137,13 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $p4Command); } - public function testQueryP4UserWithUserAlreadySet() + public function testQueryP4UserWithUserAlreadySet(): void { $this->perforce->queryP4user(); $this->assertEquals(self::TEST_P4USER, $this->perforce->getUser()); } - public function testQueryP4UserWithUserSetInP4VariablesWithWindowsOS() + public function testQueryP4UserWithUserSetInP4VariablesWithWindowsOS(): void { $this->createNewPerforceWithWindowsFlag(true); $this->perforce->setUser(null); @@ -156,7 +156,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); } - public function testQueryP4UserWithUserSetInP4VariablesNotWindowsOS() + public function testQueryP4UserWithUserSetInP4VariablesNotWindowsOS(): void { $this->createNewPerforceWithWindowsFlag(false); $this->perforce->setUser(null); @@ -170,7 +170,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_P4VARIABLE_USER', $this->perforce->getUser()); } - public function testQueryP4UserQueriesForUser() + public function testQueryP4UserQueriesForUser(): void { $this->perforce->setUser(null); $expectedQuestion = 'Enter P4 User:'; @@ -181,7 +181,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_QUERY_USER', $this->perforce->getUser()); } - public function testQueryP4UserStoresResponseToQueryForUserWithWindows() + public function testQueryP4UserStoresResponseToQueryForUserWithWindows(): void { $this->createNewPerforceWithWindowsFlag(true); $this->perforce->setUser(null); @@ -203,7 +203,7 @@ class PerforceTest extends TestCase $this->perforce->queryP4user(); } - public function testQueryP4UserStoresResponseToQueryForUserWithoutWindows() + public function testQueryP4UserStoresResponseToQueryForUserWithoutWindows(): void { $this->createNewPerforceWithWindowsFlag(false); $this->perforce->setUser(null); @@ -223,7 +223,7 @@ class PerforceTest extends TestCase $this->perforce->queryP4user(); } - public function testQueryP4PasswordWithPasswordAlreadySet() + public function testQueryP4PasswordWithPasswordAlreadySet(): void { $repoConfig = array( 'depot' => 'depot', @@ -236,7 +236,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_PASSWORD', $password); } - public function testQueryP4PasswordWithPasswordSetInP4VariablesWithWindowsOS() + public function testQueryP4PasswordWithPasswordSetInP4VariablesWithWindowsOS(): void { $this->createNewPerforceWithWindowsFlag(true); @@ -249,7 +249,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); } - public function testQueryP4PasswordWithPasswordSetInP4VariablesNotWindowsOS() + public function testQueryP4PasswordWithPasswordSetInP4VariablesNotWindowsOS(): void { $this->createNewPerforceWithWindowsFlag(false); @@ -262,7 +262,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_P4VARIABLE_PASSWORD', $password); } - public function testQueryP4PasswordQueriesForPassword() + public function testQueryP4PasswordQueriesForPassword(): void { $expectedQuestion = 'Enter password for Perforce user user: '; $this->io->expects($this->once()) @@ -274,7 +274,7 @@ class PerforceTest extends TestCase $this->assertEquals('TEST_QUERY_PASSWORD', $password); } - public function testWriteP4ClientSpecWithoutStream() + public function testWriteP4ClientSpecWithoutStream(): void { $stream = fopen('php://memory', 'w+'); if (false === $stream) { @@ -297,7 +297,7 @@ class PerforceTest extends TestCase fclose($stream); } - public function testWriteP4ClientSpecWithStream() + public function testWriteP4ClientSpecWithStream(): void { $this->setPerforceToStream(); $stream = fopen('php://memory', 'w+'); @@ -321,7 +321,7 @@ class PerforceTest extends TestCase fclose($stream); } - public function testIsLoggedIn() + public function testIsLoggedIn(): void { $this->processExecutor->expects( [['cmd' => 'p4 -u user -p port login -s']], @@ -330,7 +330,7 @@ class PerforceTest extends TestCase $this->perforce->isLoggedIn(); } - public function testConnectClient() + public function testConnectClient(): void { $this->processExecutor->expects( ['p4 -u user -c composer_perforce_TEST_depot -p port client -i < path/composer_perforce_TEST_depot.p4.spec'], @@ -340,7 +340,7 @@ class PerforceTest extends TestCase $this->perforce->connectClient(); } - public function testGetBranchesWithStream() + public function testGetBranchesWithStream(): void { $this->setPerforceToStream(); @@ -362,7 +362,7 @@ class PerforceTest extends TestCase $this->assertEquals('//depot/branch@1234', $branches['master']); } - public function testGetBranchesWithoutStream() + public function testGetBranchesWithoutStream(): void { $this->processExecutor->expects( [ @@ -378,7 +378,7 @@ class PerforceTest extends TestCase $this->assertEquals('//depot@5678', $branches['master']); } - public function testGetTagsWithoutStream() + public function testGetTagsWithoutStream(): void { $this->processExecutor->expects( [ @@ -395,7 +395,7 @@ class PerforceTest extends TestCase $this->assertEquals('//depot@0.0.2', $tags['0.0.2']); } - public function testGetTagsWithStream() + public function testGetTagsWithStream(): void { $this->setPerforceToStream(); @@ -414,14 +414,14 @@ class PerforceTest extends TestCase $this->assertEquals('//depot/branch@0.0.2', $tags['0.0.2']); } - public function testCheckStreamWithoutStream() + public function testCheckStreamWithoutStream(): void { $result = $this->perforce->checkStream(); $this->assertFalse($result); $this->assertFalse($this->perforce->isStream()); } - public function testCheckStreamWithStream() + public function testCheckStreamWithStream(): void { $this->processExecutor->expects( [ @@ -438,7 +438,7 @@ class PerforceTest extends TestCase $this->assertTrue($this->perforce->isStream()); } - public function testGetComposerInformationWithoutLabelWithoutStream() + public function testGetComposerInformationWithoutLabelWithoutStream(): void { $this->processExecutor->expects( [ @@ -460,7 +460,7 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $result); } - public function testGetComposerInformationWithLabelWithoutStream() + public function testGetComposerInformationWithLabelWithoutStream(): void { $this->processExecutor->expects( [ @@ -487,7 +487,7 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $result); } - public function testGetComposerInformationWithoutLabelWithStream() + public function testGetComposerInformationWithoutLabelWithStream(): void { $this->setPerforceToStream(); @@ -512,7 +512,7 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $result); } - public function testGetComposerInformationWithLabelWithStream() + public function testGetComposerInformationWithLabelWithStream(): void { $this->processExecutor->expects( [ @@ -541,7 +541,7 @@ class PerforceTest extends TestCase $this->assertEquals($expected, $result); } - public function testSyncCodeBaseWithoutStream() + public function testSyncCodeBaseWithoutStream(): void { $this->processExecutor->expects( ['p4 -u user -c composer_perforce_TEST_depot -p port sync -f @label'], @@ -551,7 +551,7 @@ class PerforceTest extends TestCase $this->perforce->syncCodeBase('label'); } - public function testSyncCodeBaseWithStream() + public function testSyncCodeBaseWithStream(): void { $this->setPerforceToStream(); @@ -563,7 +563,7 @@ class PerforceTest extends TestCase $this->perforce->syncCodeBase('label'); } - public function testCheckServerExists() + public function testCheckServerExists(): void { $this->processExecutor->expects( ['p4 -p '.ProcessExecutor::escape('perforce.does.exist:port').' info -s'], @@ -581,7 +581,7 @@ class PerforceTest extends TestCase * * @return void */ - public function testCheckServerClientError() + public function testCheckServerClientError(): void { $processExecutor = $this->getMockBuilder('Composer\Util\ProcessExecutor')->getMock(); @@ -598,7 +598,7 @@ class PerforceTest extends TestCase /** * @return string */ - public static function getComposerJson() + public static function getComposerJson(): string { return JsonFile::encode([ 'name' => 'test/perforce', @@ -615,7 +615,7 @@ class PerforceTest extends TestCase * * @return string[] */ - private function getExpectedClientSpec($withStream) + private function getExpectedClientSpec($withStream): array { $expectedArray = array( 'Client: composer_perforce_TEST_depot', @@ -650,12 +650,12 @@ class PerforceTest extends TestCase /** * @return void */ - private function setPerforceToStream() + private function setPerforceToStream(): void { $this->perforce->setStream('//depot/branch'); } - public function testCleanupClientSpecShouldDeleteClient() + public function testCleanupClientSpecShouldDeleteClient(): void { $fs = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $this->perforce->setFilesystem($fs); diff --git a/tests/Composer/Test/Util/PlatformTest.php b/tests/Composer/Test/Util/PlatformTest.php index 70777d69a..f05d3a736 100644 --- a/tests/Composer/Test/Util/PlatformTest.php +++ b/tests/Composer/Test/Util/PlatformTest.php @@ -22,7 +22,7 @@ use Composer\Test\TestCase; */ class PlatformTest extends TestCase { - public function testExpandPath() + public function testExpandPath(): void { putenv('TESTENV=/home/test'); $this->assertEquals('/home/test/myPath', Platform::expandPath('%TESTENV%/myPath')); @@ -30,7 +30,7 @@ class PlatformTest extends TestCase $this->assertEquals((getenv('HOME') ?: getenv('USERPROFILE')) . '/test', Platform::expandPath('~/test')); } - public function testIsWindows() + public function testIsWindows(): void { // Compare 2 common tests for Windows to the built-in Windows test $this->assertEquals(('\\' === DIRECTORY_SEPARATOR), Platform::isWindows()); diff --git a/tests/Composer/Test/Util/ProcessExecutorTest.php b/tests/Composer/Test/Util/ProcessExecutorTest.php index ff2acd82e..c0ef2f43e 100644 --- a/tests/Composer/Test/Util/ProcessExecutorTest.php +++ b/tests/Composer/Test/Util/ProcessExecutorTest.php @@ -25,14 +25,14 @@ use Symfony\Component\Console\Output\StreamOutput; class ProcessExecutorTest extends TestCase { - public function testExecuteCapturesOutput() + public function testExecuteCapturesOutput(): void { $process = new ProcessExecutor; $process->execute('echo foo', $output); $this->assertEquals("foo".PHP_EOL, $output); } - public function testExecuteOutputsIfNotCaptured() + public function testExecuteOutputsIfNotCaptured(): void { $process = new ProcessExecutor; ob_start(); @@ -41,7 +41,7 @@ class ProcessExecutorTest extends TestCase $this->assertEquals("foo".PHP_EOL, $output); } - public function testUseIOIsNotNullAndIfNotCaptured() + public function testUseIOIsNotNullAndIfNotCaptured(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $io->expects($this->once()) @@ -52,14 +52,14 @@ class ProcessExecutorTest extends TestCase $process->execute('echo foo'); } - public function testExecuteCapturesStderr() + public function testExecuteCapturesStderr(): void { $process = new ProcessExecutor; $process->execute('cat foo', $output); $this->assertNotNull($process->getErrorOutput()); } - public function testTimeout() + public function testTimeout(): void { ProcessExecutor::setTimeout(1); $process = new ProcessExecutor; @@ -73,14 +73,14 @@ class ProcessExecutorTest extends TestCase * @param string $command * @param string $expectedCommandOutput */ - public function testHidePasswords($command, $expectedCommandOutput) + public function testHidePasswords($command, $expectedCommandOutput): void { $process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG)); $process->execute($command, $output); $this->assertEquals('Executing command (CWD): ' . $expectedCommandOutput, trim($buffer->getOutput())); } - public function hidePasswordProvider() + public function hidePasswordProvider(): array { return array( array('echo https://foo:bar@example.org/', 'echo https://foo:***@example.org/'), @@ -91,14 +91,14 @@ class ProcessExecutorTest extends TestCase ); } - public function testDoesntHidePorts() + public function testDoesntHidePorts(): void { $process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG)); $process->execute('echo https://localhost:1234/', $output); $this->assertEquals('Executing command (CWD): echo https://localhost:1234/', trim($buffer->getOutput())); } - public function testSplitLines() + public function testSplitLines(): void { $process = new ProcessExecutor; $this->assertEquals(array(), $process->splitLines('')); @@ -109,7 +109,7 @@ class ProcessExecutorTest extends TestCase $this->assertEquals(array('foo', 'bar'), $process->splitLines("foo\r\nbar\n")); } - public function testConsoleIODoesNotFormatSymfonyConsoleStyle() + public function testConsoleIODoesNotFormatSymfonyConsoleStyle(): void { $output = new BufferedOutput(OutputInterface::VERBOSITY_NORMAL, true); $process = new ProcessExecutor(new ConsoleIO(new ArrayInput(array()), $output, new HelperSet(array()))); @@ -118,7 +118,7 @@ class ProcessExecutorTest extends TestCase $this->assertSame('foo'.PHP_EOL, $output->fetch()); } - public function testExecuteAsyncCancel() + public function testExecuteAsyncCancel(): void { $process = new ProcessExecutor($buffer = new BufferIO('', StreamOutput::VERBOSITY_DEBUG)); $process->enableAsync(); @@ -141,7 +141,7 @@ class ProcessExecutorTest extends TestCase * @param string $win * @param string $unix */ - public function testEscapeArgument($argument, $win, $unix) + public function testEscapeArgument($argument, $win, $unix): void { $expected = defined('PHP_WINDOWS_VERSION_BUILD') ? $win : $unix; $this->assertSame($expected, ProcessExecutor::escape($argument)); @@ -151,7 +151,7 @@ class ProcessExecutorTest extends TestCase * Each named test is an array of: * argument, win-expected, unix-expected */ - public function dataEscapeArguments() + public function dataEscapeArguments(): array { return array( // empty argument - must be quoted diff --git a/tests/Composer/Test/Util/RemoteFilesystemTest.php b/tests/Composer/Test/Util/RemoteFilesystemTest.php index a63e24bb3..06df39b88 100644 --- a/tests/Composer/Test/Util/RemoteFilesystemTest.php +++ b/tests/Composer/Test/Util/RemoteFilesystemTest.php @@ -24,7 +24,7 @@ use ReflectionProperty; class RemoteFilesystemTest extends TestCase { - public function testGetOptionsForUrl() + public function testGetOptionsForUrl(): void { $io = $this->getIOInterfaceMock(); $io @@ -37,7 +37,7 @@ class RemoteFilesystemTest extends TestCase $this->assertTrue(isset($res['http']['header']) && is_array($res['http']['header']), 'getOptions must return an array with headers'); } - public function testGetOptionsForUrlWithAuthorization() + public function testGetOptionsForUrlWithAuthorization(): void { $io = $this->getIOInterfaceMock(); $io @@ -62,7 +62,7 @@ class RemoteFilesystemTest extends TestCase $this->assertTrue($found, 'getOptions must have an Authorization header'); } - public function testGetOptionsForUrlWithStreamOptions() + public function testGetOptionsForUrlWithStreamOptions(): void { $io = $this->getIOInterfaceMock(); $io @@ -88,7 +88,7 @@ class RemoteFilesystemTest extends TestCase ); } - public function testGetOptionsForUrlWithCallOptionsKeepsHeader() + public function testGetOptionsForUrlWithCallOptionsKeepsHeader(): void { $io = $this->getIOInterfaceMock(); $io @@ -121,14 +121,14 @@ class RemoteFilesystemTest extends TestCase $this->assertGreaterThan(1, count($res['http']['header'])); } - public function testCallbackGetFileSize() + public function testCallbackGetFileSize(): void { $fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock()); $this->callCallbackGet($fs, STREAM_NOTIFY_FILE_SIZE_IS, 0, '', 0, 0, 20); $this->assertAttributeEqualsCustom(20, 'bytesMax', $fs); } - public function testCallbackGetNotifyProgress() + public function testCallbackGetNotifyProgress(): void { $io = $this->getIOInterfaceMock(); $io @@ -144,7 +144,7 @@ class RemoteFilesystemTest extends TestCase $this->assertAttributeEqualsCustom(50, 'lastProgress', $fs); } - public function testCallbackGetPassesThrough404() + public function testCallbackGetPassesThrough404(): void { $fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock()); @@ -152,14 +152,14 @@ class RemoteFilesystemTest extends TestCase $this->assertTrue(true, 'callbackGet must pass through 404'); } - public function testGetContents() + public function testGetContents(): void { $fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock()); $this->assertStringContainsString('testGetContents', $fs->getContents('http://example.org', 'file://'.__FILE__)); } - public function testCopy() + public function testCopy(): void { $fs = new RemoteFilesystem($this->getIOInterfaceMock(), $this->getConfigMock()); @@ -170,13 +170,13 @@ class RemoteFilesystemTest extends TestCase unlink($file); } - public function testCopyWithNoRetryOnFailure() + public function testCopyWithNoRetryOnFailure(): void { self::expectException('Composer\Downloader\TransportException'); $fs = $this->getRemoteFilesystemWithMockedMethods(array('getRemoteContents')); $fs->expects($this->once())->method('getRemoteContents') - ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header) { + ->willReturnCallback(function ($originUrl, $fileUrl, $ctx, &$http_response_header): string { $http_response_header = array('http/1.1 401 unauthorized'); return ''; @@ -194,7 +194,7 @@ class RemoteFilesystemTest extends TestCase ); } - public function testCopyWithSuccessOnRetry() + public function testCopyWithSuccessOnRetry(): void { $authHelper = $this->getAuthHelperWithMockedMethods(array('promptAuthIfNeeded')); $fs = $this->getRemoteFilesystemWithMockedMethods(array('getRemoteContents'), $authHelper); @@ -241,7 +241,7 @@ class RemoteFilesystemTest extends TestCase /** * @group TLS */ - public function testGetOptionsForUrlCreatesSecureTlsDefaults() + public function testGetOptionsForUrlCreatesSecureTlsDefaults(): void { $io = $this->getIOInterfaceMock(); @@ -265,7 +265,7 @@ class RemoteFilesystemTest extends TestCase * * @return string[][] */ - public function provideBitbucketPublicDownloadUrls() + public function provideBitbucketPublicDownloadUrls(): array { return array( array('https://bitbucket.org/seldaek/composer-live-test-repo/downloads/composer-unit-test-download-me.txt', '1234'), @@ -279,7 +279,7 @@ class RemoteFilesystemTest extends TestCase * @param string $contents * @dataProvider provideBitbucketPublicDownloadUrls */ - public function testBitBucketPublicDownload($url, $contents) + public function testBitBucketPublicDownload($url, $contents): void { /** @var ConsoleIO $io */ $io = $this @@ -302,7 +302,7 @@ class RemoteFilesystemTest extends TestCase * @param string $contents * @dataProvider provideBitbucketPublicDownloadUrls */ - public function testBitBucketPublicDownloadWithAuthConfigured($url, $contents) + public function testBitBucketPublicDownloadWithAuthConfigured($url, $contents): void { /** @var MockObject|ConsoleIO $io */ $io = $this @@ -313,7 +313,7 @@ class RemoteFilesystemTest extends TestCase $domains = array(); $io ->method('hasAuthentication') - ->willReturnCallback(function ($arg) use (&$domains) { + ->willReturnCallback(function ($arg) use (&$domains): bool { $domains[] = $arg; // first time is called with bitbucket.org, then it redirects to bbuseruploads.s3.amazonaws.com so next time we have no auth configured return $arg === 'bitbucket.org'; @@ -343,7 +343,7 @@ class RemoteFilesystemTest extends TestCase * * @return mixed[] */ - private function callGetOptionsForUrl(IOInterface $io, array $args = array(), array $options = array(), $fileUrl = '') + private function callGetOptionsForUrl(IOInterface $io, array $args = array(), array $options = array(), $fileUrl = ''): array { $fs = new RemoteFilesystem($io, $this->getConfigMock(), $options); $ref = new ReflectionMethod($fs, 'getOptionsForUrl'); @@ -385,7 +385,7 @@ class RemoteFilesystemTest extends TestCase * * @return void */ - private function callCallbackGet(RemoteFilesystem $fs, $notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax) + private function callCallbackGet(RemoteFilesystem $fs, $notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax): void { $ref = new ReflectionMethod($fs, 'callbackGet'); $ref->setAccessible(true); @@ -399,7 +399,7 @@ class RemoteFilesystemTest extends TestCase * * @return void */ - private function setAttribute($object, $attribute, $value) + private function setAttribute($object, $attribute, $value): void { $attr = new ReflectionProperty($object, $attribute); $attr->setAccessible(true); @@ -413,7 +413,7 @@ class RemoteFilesystemTest extends TestCase * * @return void */ - private function assertAttributeEqualsCustom($value, $attribute, $object) + private function assertAttributeEqualsCustom($value, $attribute, $object): void { $attr = new ReflectionProperty($object, $attribute); $attr->setAccessible(true); diff --git a/tests/Composer/Test/Util/SilencerTest.php b/tests/Composer/Test/Util/SilencerTest.php index 9072a7cda..58a81eb92 100644 --- a/tests/Composer/Test/Util/SilencerTest.php +++ b/tests/Composer/Test/Util/SilencerTest.php @@ -25,7 +25,7 @@ class SilencerTest extends TestCase /** * Test succeeds when no warnings are emitted externally, and original level is restored. */ - public function testSilencer() + public function testSilencer(): void { $before = error_reporting(); @@ -49,12 +49,12 @@ class SilencerTest extends TestCase /** * Test whether exception from silent callbacks are correctly forwarded. */ - public function testSilencedException() + public function testSilencedException(): void { $verification = microtime(); self::expectException('RuntimeException'); self::expectExceptionMessage($verification); - Silencer::call(function () use ($verification) { + Silencer::call(function () use ($verification): void { throw new \RuntimeException($verification); }); } diff --git a/tests/Composer/Test/Util/StreamContextFactoryTest.php b/tests/Composer/Test/Util/StreamContextFactoryTest.php index ca86d16ce..0d90672ba 100644 --- a/tests/Composer/Test/Util/StreamContextFactoryTest.php +++ b/tests/Composer/Test/Util/StreamContextFactoryTest.php @@ -39,7 +39,7 @@ class StreamContextFactoryTest extends TestCase * @param mixed[] $expectedParams * @param mixed[] $defaultParams */ - public function testGetContext($expectedOptions, $defaultOptions, $expectedParams, $defaultParams) + public function testGetContext($expectedOptions, $defaultOptions, $expectedParams, $defaultParams): void { $context = StreamContextFactory::getContext('http://example.org', $defaultOptions, $defaultParams); $options = stream_context_get_options($context); @@ -49,7 +49,7 @@ class StreamContextFactoryTest extends TestCase $this->assertEquals($expectedParams, $params); } - public function dataGetContext() + public function dataGetContext(): array { return array( array( @@ -58,13 +58,13 @@ class StreamContextFactoryTest extends TestCase ), array( $a = array('http' => array('method' => 'GET', 'max_redirects' => 20, 'follow_location' => 1, 'header' => array('User-Agent: foo'))), array('http' => array('method' => 'GET', 'header' => 'User-Agent: foo')), - array('options' => $a, 'notification' => $f = function () { + array('options' => $a, 'notification' => $f = function (): void { }), array('notification' => $f), ), ); } - public function testHttpProxy() + public function testHttpProxy(): void { $_SERVER['http_proxy'] = 'http://username:p%40ssword@proxyserver.net:3128/'; $_SERVER['HTTP_PROXY'] = 'http://proxyserver/'; @@ -82,7 +82,7 @@ class StreamContextFactoryTest extends TestCase )), $options); } - public function testHttpProxyWithNoProxy() + public function testHttpProxyWithNoProxy(): void { $_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/'; $_SERVER['no_proxy'] = 'foo,example.org'; @@ -98,7 +98,7 @@ class StreamContextFactoryTest extends TestCase )), $options); } - public function testHttpProxyWithNoProxyWildcard() + public function testHttpProxyWithNoProxyWildcard(): void { $_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/'; $_SERVER['no_proxy'] = '*'; @@ -114,7 +114,7 @@ class StreamContextFactoryTest extends TestCase )), $options); } - public function testOptionsArePreserved() + public function testOptionsArePreserved(): void { $_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/'; @@ -131,7 +131,7 @@ class StreamContextFactoryTest extends TestCase )), $options); } - public function testHttpProxyWithoutPort() + public function testHttpProxyWithoutPort(): void { $_SERVER['http_proxy'] = 'http://username:password@proxyserver.net'; @@ -147,7 +147,7 @@ class StreamContextFactoryTest extends TestCase )), $options); } - public function testHttpsProxyOverride() + public function testHttpsProxyOverride(): void { if (!extension_loaded('openssl')) { $this->markTestSkipped('Requires openssl'); @@ -167,7 +167,7 @@ class StreamContextFactoryTest extends TestCase * @param string $expected * @param string $proxy */ - public function testSSLProxy($expected, $proxy) + public function testSSLProxy($expected, $proxy): void { $_SERVER['http_proxy'] = $proxy; @@ -192,7 +192,7 @@ class StreamContextFactoryTest extends TestCase } } - public function dataSSLProxy() + public function dataSSLProxy(): array { return array( array('ssl://proxyserver:443', 'https://proxyserver/'), @@ -200,7 +200,7 @@ class StreamContextFactoryTest extends TestCase ); } - public function testEnsureThatfixHttpHeaderFieldMovesContentTypeToEndOfOptions() + public function testEnsureThatfixHttpHeaderFieldMovesContentTypeToEndOfOptions(): void { $options = array( 'http' => array( @@ -222,7 +222,7 @@ class StreamContextFactoryTest extends TestCase $this->assertEquals(end($expectedOptions['http']['header']), end($ctxoptions['http']['header'])); } - public function testInitOptionsDoesIncludeProxyAuthHeaders() + public function testInitOptionsDoesIncludeProxyAuthHeaders(): void { $_SERVER['http_proxy'] = 'http://username:password@proxyserver.net:3128/'; @@ -233,7 +233,7 @@ class StreamContextFactoryTest extends TestCase $this->assertTrue(false !== stripos($headers, 'Proxy-Authorization')); } - public function testInitOptionsForCurlDoesNotIncludeProxyAuthHeaders() + public function testInitOptionsForCurlDoesNotIncludeProxyAuthHeaders(): void { if (!extension_loaded('curl')) { $this->markTestSkipped('The curl is not available.'); diff --git a/tests/Composer/Test/Util/SvnTest.php b/tests/Composer/Test/Util/SvnTest.php index 0ab43dd45..7aa7c73b2 100644 --- a/tests/Composer/Test/Util/SvnTest.php +++ b/tests/Composer/Test/Util/SvnTest.php @@ -27,7 +27,7 @@ class SvnTest extends TestCase * * @dataProvider urlProvider */ - public function testCredentials($url, $expect) + public function testCredentials($url, $expect): void { $svn = new Svn($url, new NullIO, new Config()); $reflMethod = new \ReflectionMethod('Composer\\Util\\Svn', 'getCredentialString'); @@ -36,7 +36,7 @@ class SvnTest extends TestCase $this->assertEquals($expect, $reflMethod->invoke($svn)); } - public function urlProvider() + public function urlProvider(): array { return array( array('http://till:test@svn.example.org/', $this->getCmd(" --username 'till' --password 'test' ")), @@ -45,7 +45,7 @@ class SvnTest extends TestCase ); } - public function testInteractiveString() + public function testInteractiveString(): void { $url = 'http://svn.example.org'; @@ -59,7 +59,7 @@ class SvnTest extends TestCase ); } - public function testCredentialsFromConfig() + public function testCredentialsFromConfig(): void { $url = 'http://svn.apache.org'; @@ -79,7 +79,7 @@ class SvnTest extends TestCase $this->assertEquals($this->getCmd(" --username 'foo' --password 'bar' "), $reflMethod->invoke($svn)); } - public function testCredentialsFromConfigWithCacheCredentialsTrue() + public function testCredentialsFromConfigWithCacheCredentialsTrue(): void { $url = 'http://svn.apache.org'; @@ -102,7 +102,7 @@ class SvnTest extends TestCase $this->assertEquals($this->getCmd(" --username 'foo' --password 'bar' "), $reflMethod->invoke($svn)); } - public function testCredentialsFromConfigWithCacheCredentialsFalse() + public function testCredentialsFromConfigWithCacheCredentialsFalse(): void { $url = 'http://svn.apache.org'; diff --git a/tests/Composer/Test/Util/TarTest.php b/tests/Composer/Test/Util/TarTest.php index c15470071..b0e697819 100644 --- a/tests/Composer/Test/Util/TarTest.php +++ b/tests/Composer/Test/Util/TarTest.php @@ -20,44 +20,44 @@ use Composer\Test\TestCase; */ class TarTest extends TestCase { - public function testReturnsNullifTheTarIsNotFound() + public function testReturnsNullifTheTarIsNotFound(): void { $result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/invalid.zip'); $this->assertNull($result); } - public function testReturnsNullIfTheTarIsEmpty() + public function testReturnsNullIfTheTarIsEmpty(): void { $result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/empty.tar.gz'); $this->assertNull($result); } - public function testThrowsExceptionIfTheTarHasNoComposerJson() + public function testThrowsExceptionIfTheTarHasNoComposerJson(): void { self::expectException('RuntimeException'); Tar::getComposerJson(__DIR__.'/Fixtures/Tar/nojson.tar.gz'); } - public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder() + public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder(): void { self::expectException('RuntimeException'); Tar::getComposerJson(__DIR__.'/Fixtures/Tar/subfolders.tar.gz'); } - public function testReturnsComposerJsonInTarRoot() + public function testReturnsComposerJsonInTarRoot(): void { $result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/root.tar.gz'); $this->assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result); } - public function testReturnsComposerJsonInFirstFolder() + public function testReturnsComposerJsonInFirstFolder(): void { $result = Tar::getComposerJson(__DIR__.'/Fixtures/Tar/folder.tar.gz'); $this->assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result); } - public function testMultipleTopLevelDirsIsInvalid() + public function testMultipleTopLevelDirsIsInvalid(): void { self::expectException('RuntimeException'); Tar::getComposerJson(__DIR__.'/Fixtures/Tar/multiple.tar.gz'); diff --git a/tests/Composer/Test/Util/TlsHelperTest.php b/tests/Composer/Test/Util/TlsHelperTest.php index 3b9549951..1bc7d9151 100644 --- a/tests/Composer/Test/Util/TlsHelperTest.php +++ b/tests/Composer/Test/Util/TlsHelperTest.php @@ -24,7 +24,7 @@ class TlsHelperTest extends TestCase * @param string $hostname * @param string[] $certNames */ - public function testCheckCertificateHost($expectedResult, $hostname, $certNames) + public function testCheckCertificateHost($expectedResult, $hostname, $certNames): void { $certificate['subject']['commonName'] = $expectedCn = array_shift($certNames); $certificate['extensions']['subjectAltName'] = $certNames ? 'DNS:'.implode(',DNS:', $certNames) : ''; @@ -41,7 +41,7 @@ class TlsHelperTest extends TestCase } } - public function dataCheckCertificateHost() + public function dataCheckCertificateHost(): array { return array( array(true, 'getcomposer.org', array('getcomposer.org')), @@ -67,7 +67,7 @@ class TlsHelperTest extends TestCase ); } - public function testGetCertificateNames() + public function testGetCertificateNames(): void { $certificate['subject']['commonName'] = 'example.net'; $certificate['extensions']['subjectAltName'] = 'DNS: example.com, IP: 127.0.0.1, DNS: getcomposer.org, Junk: blah, DNS: composer.example.org'; diff --git a/tests/Composer/Test/Util/UrlTest.php b/tests/Composer/Test/Util/UrlTest.php index 66165b4b8..650d53875 100644 --- a/tests/Composer/Test/Util/UrlTest.php +++ b/tests/Composer/Test/Util/UrlTest.php @@ -26,7 +26,7 @@ class UrlTest extends TestCase * @param array $conf * @param string $ref */ - public function testUpdateDistReference($url, $expectedUrl, $conf = array(), $ref = 'newref') + public function testUpdateDistReference($url, $expectedUrl, $conf = array(), $ref = 'newref'): void { $config = new Config(); $config->merge(array('config' => $conf)); @@ -34,7 +34,7 @@ class UrlTest extends TestCase $this->assertSame($expectedUrl, Url::updateDistReference($config, $url, $ref)); } - public static function distRefsProvider() + public static function distRefsProvider(): array { return array( // github @@ -70,12 +70,12 @@ class UrlTest extends TestCase * @param string $expected * @param string $url */ - public function testSanitize($expected, $url) + public function testSanitize($expected, $url): void { $this->assertSame($expected, Url::sanitize($url)); } - public static function sanitizeProvider() + public static function sanitizeProvider(): array { return array( // with scheme diff --git a/tests/Composer/Test/Util/ZipTest.php b/tests/Composer/Test/Util/ZipTest.php index b55208c3e..fa92fd897 100644 --- a/tests/Composer/Test/Util/ZipTest.php +++ b/tests/Composer/Test/Util/ZipTest.php @@ -20,7 +20,7 @@ use Composer\Test\TestCase; */ class ZipTest extends TestCase { - public function testThrowsExceptionIfZipExtensionIsNotLoaded() + public function testThrowsExceptionIfZipExtensionIsNotLoaded(): void { if (extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is loaded.'); @@ -32,7 +32,7 @@ class ZipTest extends TestCase Zip::getComposerJson(''); } - public function testReturnsNullifTheZipIsNotFound() + public function testReturnsNullifTheZipIsNotFound(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -43,7 +43,7 @@ class ZipTest extends TestCase $this->assertNull($result); } - public function testReturnsNullIfTheZipIsEmpty() + public function testReturnsNullIfTheZipIsEmpty(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -54,7 +54,7 @@ class ZipTest extends TestCase $this->assertNull($result); } - public function testThrowsExceptionIfTheZipHasNoComposerJson() + public function testThrowsExceptionIfTheZipHasNoComposerJson(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -66,7 +66,7 @@ class ZipTest extends TestCase Zip::getComposerJson(__DIR__.'/Fixtures/Zip/nojson.zip'); } - public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder() + public function testThrowsExceptionIfTheComposerJsonIsInASubSubfolder(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -78,7 +78,7 @@ class ZipTest extends TestCase Zip::getComposerJson(__DIR__.'/Fixtures/Zip/subfolders.zip'); } - public function testReturnsComposerJsonInZipRoot() + public function testReturnsComposerJsonInZipRoot(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -89,7 +89,7 @@ class ZipTest extends TestCase $this->assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result); } - public function testReturnsComposerJsonInFirstFolder() + public function testReturnsComposerJsonInFirstFolder(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -99,7 +99,7 @@ class ZipTest extends TestCase $this->assertEquals("{\n \"name\": \"foo/bar\"\n}\n", $result); } - public function testMultipleTopLevelDirsIsInvalid() + public function testMultipleTopLevelDirsIsInvalid(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.'); @@ -111,7 +111,7 @@ class ZipTest extends TestCase Zip::getComposerJson(__DIR__.'/Fixtures/Zip/multiple.zip'); } - public function testReturnsComposerJsonFromFirstSubfolder() + public function testReturnsComposerJsonFromFirstSubfolder(): void { if (!extension_loaded('zip')) { $this->markTestSkipped('The PHP zip extension is not loaded.');