repo
stringlengths
7
63
file_url
stringlengths
81
284
file_path
stringlengths
5
200
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:02:33
2026-01-05 05:24:06
truncated
bool
2 classes
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/ForgejoDriver.php
src/Composer/Repository/Vcs/ForgejoDriver.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Config; use Composer\Downloader\TransportException; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Pcre\Preg; use Composer\Util\Forgejo; use Composer\Util\ForgejoRepositoryData; use Composer\Util\ForgejoUrl; use Composer\Util\Http\Response; class ForgejoDriver extends VcsDriver { /** @var ForgejoUrl */ private $forgejoUrl; /** @var ForgejoRepositoryData */ private $repositoryData; /** @var ?GitDriver */ protected $gitDriver = null; /** @var array<int|string, string> Map of tag name to identifier */ private $tags; /** @var array<int|string, string> Map of branch name to identifier */ private $branches; public function initialize(): void { $this->forgejoUrl = ForgejoUrl::create($this->url); $this->originUrl = $this->forgejoUrl->originUrl; $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->forgejoUrl->owner.'/'.$this->forgejoUrl->repository); $this->cache->setReadOnly($this->config->get('cache-read-only')); $this->fetchRepositoryData(); } public function getFileContent(string $file, string $identifier): ?string { if ($this->gitDriver !== null) { return $this->gitDriver->getFileContent($file, $identifier); } $resource = $this->forgejoUrl->apiUrl.'/contents/' . $file . '?ref='.urlencode($identifier); $resource = $this->getContents($resource)->decodeJson(); // The Forgejo contents API only returns files up to 1MB as base64 encoded files // larger files either need be fetched with a raw accept header or by using the git blob endpoint if ((!isset($resource['content']) || $resource['content'] === '') && $resource['encoding'] === 'none' && isset($resource['git_url'])) { $resource = $this->getContents($resource['git_url'])->decodeJson(); } if (!isset($resource['content']) || $resource['encoding'] !== 'base64' || false === ($content = base64_decode($resource['content'], true))) { throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier); } return $content; } public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->gitDriver !== null) { return $this->gitDriver->getChangeDate($identifier); } $resource = $this->forgejoUrl->apiUrl.'/git/commits/'.urlencode($identifier).'?verification=false&files=false'; $commit = $this->getContents($resource)->decodeJson(); return new \DateTimeImmutable($commit['commit']['committer']['date']); } public function getRootIdentifier(): string { if ($this->gitDriver !== null) { return $this->gitDriver->getRootIdentifier(); } return $this->repositoryData->defaultBranch; } public function getBranches(): array { if ($this->gitDriver !== null) { return $this->gitDriver->getBranches(); } if (null === $this->branches) { $branches = []; $resource = $this->forgejoUrl->apiUrl.'/branches?per_page=100'; do { $response = $this->getContents($resource); $branchData = $response->decodeJson(); foreach ($branchData as $branch) { $branches[$branch['name']] = $branch['commit']['id']; } $resource = $this->getNextPage($response); } while ($resource); $this->branches = $branches; } return $this->branches; } public function getTags(): array { if ($this->gitDriver !== null) { return $this->gitDriver->getTags(); } if (null === $this->tags) { $tags = []; $resource = $this->forgejoUrl->apiUrl.'/tags?per_page=100'; do { $response = $this->getContents($resource); $tagsData = $response->decodeJson(); foreach ($tagsData as $tag) { $tags[$tag['name']] = $tag['commit']['sha']; } $resource = $this->getNextPage($response); } while ($resource); $this->tags = $tags; } return $this->tags; } public function getDist(string $identifier): ?array { $url = $this->forgejoUrl->apiUrl.'/archive/'.$identifier.'.zip'; return ['type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '']; } public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver !== null) { return $this->gitDriver->getComposerInformation($identifier); } if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && false !== ($res = $this->cache->read($identifier))) { $composer = JsonFile::parseJson($res); } else { $composer = $this->getBaseComposerInformation($identifier); if ($this->shouldCache($identifier)) { $this->cache->write($identifier, JsonFile::encode($composer, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); } } if ($composer !== null) { // specials for forgejo if (isset($composer['support']) && !is_array($composer['support'])) { $composer['support'] = []; } if (!isset($composer['support']['source'])) { if (false !== ($label = array_search($identifier, $this->getTags(), true))) { $composer['support']['source'] = $this->repositoryData->htmlUrl.'/tag/' . $label; } elseif (false !== ($label = array_search($identifier, $this->getBranches(), true))) { $composer['support']['source'] = $this->repositoryData->htmlUrl.'/branch/'.$label; } else { $composer['support']['source'] = $this->repositoryData->htmlUrl.'/commit/'.$identifier; } } if (!isset($composer['support']['issues']) && $this->repositoryData->hasIssues) { $composer['support']['issues'] = $this->repositoryData->htmlUrl.'/issues'; } if (!isset($composer['abandoned']) && $this->repositoryData->isArchived) { $composer['abandoned'] = true; } } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } public function getSource(string $identifier): array { if ($this->gitDriver !== null) { return $this->gitDriver->getSource($identifier); } return ['type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier]; } public function getUrl(): string { if ($this->gitDriver !== null) { return $this->gitDriver->getUrl(); } return $this->repositoryData->isPrivate ? $this->repositoryData->sshUrl : $this->repositoryData->httpCloneUrl; } public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { $forgejoUrl = ForgejoUrl::tryFrom($url); if ($forgejoUrl === null) { return false; } if (!in_array(strtolower($forgejoUrl->originUrl), $config->get('forgejo-domains'), true)) { return false; } if (!extension_loaded('openssl')) { $io->writeError('Skipping Forgejo driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( ['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process ); $this->gitDriver->initialize(); } private function fetchRepositoryData(): void { if ($this->repositoryData !== null) { return; } $data = $this->getContents($this->forgejoUrl->apiUrl, true)->decodeJson(); if (null === $data && null !== $this->gitDriver) { return; } $this->repositoryData = ForgejoRepositoryData::fromRemoteData($data); } protected function getNextPage(Response $response): ?string { $header = $response->getHeader('link'); if ($header === null) { return null; } $links = explode(',', $header); foreach ($links as $link) { if (Preg::isMatch('{<(.+?)>; *rel="next"}', $link, $match)) { return $match[1]; } } return null; } protected function getContents(string $url, bool $fetchingRepoData = false): Response { $forgejo = new Forgejo($this->io, $this->config, $this->httpDownloader); try { return parent::getContents($url); } catch (TransportException $e) { switch ($e->getCode()) { case 401: case 403: case 404: case 429: if (!$fetchingRepoData) { throw $e; } if (!$this->io->isInteractive()) { $this->attemptCloneFallback(); return new Response(['url' => 'dummy'], 200, [], 'null'); } if ( !$this->io->hasAuthentication($this->originUrl) && $forgejo->authorizeOAuthInteractively($this->forgejoUrl->originUrl, $e->getCode() === 429 ? 'API limit exhausted. Enter your Forgejo credentials to get a larger API limit (<info>'.$this->url.'</info>)' : null) ) { return parent::getContents($url); } throw $e; default: throw $e; } } } /** * @phpstan-impure * * @return true * @throws \RuntimeException */ protected function attemptCloneFallback(): bool { try { // If this repository may be private (hard to say for sure, // Forgejo returns 404 for private repositories) and we // cannot ask for authentication credentials (because we // are not interactive) then we fallback to GitDriver. $this->setupGitDriver($this->forgejoUrl->generateSshUrl()); return true; } catch (\RuntimeException $e) { $this->gitDriver = null; $this->io->writeError('<error>Failed to clone the '.$this->forgejoUrl->generateSshUrl().' repository, try running in interactive mode so that you can enter your Forgejo credentials</error>'); throw $e; } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/FossilDriver.php
src/Composer/Repository/Vcs/FossilDriver.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Config; use Composer\Pcre\Preg; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\IO\IOInterface; /** * @author BohwaZ <http://bohwaz.net/> */ class FossilDriver extends VcsDriver { /** @var array<int|string, string> Map of tag name to identifier */ protected $tags; /** @var array<int|string, string> Map of branch name to identifier */ protected $branches; /** @var ?string */ protected $rootIdentifier = null; /** @var ?string */ protected $repoFile = null; /** @var string */ protected $checkoutDir; /** * @inheritDoc */ public function initialize(): void { // Make sure fossil is installed and reachable. $this->checkFossil(); // Ensure we are allowed to use this URL by config. $this->config->prohibitUrlByConfig($this->url, $this->io); // Only if url points to a locally accessible directory, assume it's the checkout directory. // Otherwise, it should be something fossil can clone from. if (Filesystem::isLocalPath($this->url) && is_dir($this->url)) { $this->checkoutDir = $this->url; } else { if (!Cache::isUsable($this->config->get('cache-repo-dir')) || !Cache::isUsable($this->config->get('cache-vcs-dir'))) { throw new \RuntimeException('FossilDriver requires a usable cache directory, and it looks like you set it to be disabled'); } $localName = Preg::replace('{[^a-z0-9]}i', '-', $this->url); $this->repoFile = $this->config->get('cache-repo-dir') . '/' . $localName . '.fossil'; $this->checkoutDir = $this->config->get('cache-vcs-dir') . '/' . $localName . '/'; $this->updateLocalRepo(); } $this->getTags(); $this->getBranches(); } /** * Check that fossil can be invoked via command line. */ 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()); } } /** * Clone or update existing local fossil repository. */ protected function updateLocalRepo(): void { assert($this->repoFile !== null); $fs = new Filesystem(); $fs->ensureDirectoryExists($this->checkoutDir); if (!is_writable(dirname($this->checkoutDir))) { throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$this->checkoutDir.'" directory is not writable by the current user.'); } // update the repo if it is a valid fossil repository if (is_file($this->repoFile) && is_dir($this->checkoutDir) && 0 === $this->process->execute(['fossil', 'info'], $output, $this->checkoutDir)) { if (0 !== $this->process->execute(['fossil', 'pull'], $output, $this->checkoutDir)) { $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$this->process->getErrorOutput().')</error>'); } } else { // clean up directory and do a fresh clone into it $fs->removeDirectory($this->checkoutDir); $fs->remove($this->repoFile); $fs->ensureDirectoryExists($this->checkoutDir); if (0 !== $this->process->execute(['fossil', 'clone', '--', $this->url, $this->repoFile], $output)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to clone '.$this->url.' to repository ' . $this->repoFile . "\n\n" .$output); } if (0 !== $this->process->execute(['fossil', 'open', '--nested', '--', $this->repoFile], $output, $this->checkoutDir)) { $output = $this->process->getErrorOutput(); throw new \RuntimeException('Failed to open repository '.$this->repoFile.' in ' . $this->checkoutDir . "\n\n" .$output); } } } /** * @inheritDoc */ public function getRootIdentifier(): string { if (null === $this->rootIdentifier) { $this->rootIdentifier = 'trunk'; } return $this->rootIdentifier; } /** * @inheritDoc */ public function getUrl(): string { return $this->url; } /** * @inheritDoc */ public function getSource(string $identifier): array { return ['type' => 'fossil', 'url' => $this->getUrl(), 'reference' => $identifier]; } /** * @inheritDoc */ public function getDist(string $identifier): ?array { return null; } /** * @inheritDoc */ public function getFileContent(string $file, string $identifier): ?string { $this->process->execute(['fossil', 'cat', '-r', $identifier, '--', $file], $content, $this->checkoutDir); if ('' === trim($content)) { return null; } return $content; } /** * @inheritDoc */ public function getChangeDate(string $identifier): ?\DateTimeImmutable { $this->process->execute(['fossil', 'finfo', '-b', '-n', '1', 'composer.json'], $output, $this->checkoutDir); [, $date] = explode(' ', trim($output), 3); return new \DateTimeImmutable($date, new \DateTimeZone('UTC')); } /** * @inheritDoc */ public function getTags(): array { if (null === $this->tags) { $tags = []; $this->process->execute(['fossil', 'tag', 'list'], $output, $this->checkoutDir); foreach ($this->process->splitLines($output) as $tag) { $tags[$tag] = $tag; } $this->tags = $tags; } return $this->tags; } /** * @inheritDoc */ public function getBranches(): array { if (null === $this->branches) { $branches = []; $this->process->execute(['fossil', 'branch', 'list'], $output, $this->checkoutDir); foreach ($this->process->splitLines($output) as $branch) { $branch = trim(Preg::replace('/^\*/', '', trim($branch))); $branches[$branch] = $branch; } $this->branches = $branches; } return $this->branches; } /** * @inheritDoc */ public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (Preg::isMatch('#(^(?:https?|ssh)://(?:[^@]@)?(?:chiselapp\.com|fossil\.))#i', $url)) { return true; } if (Preg::isMatch('!/fossil/|\.fossil!', $url)) { return true; } // local filesystem if (Filesystem::isLocalPath($url)) { $url = Filesystem::getPlatformPath($url); if (!is_dir($url)) { return false; } $process = new ProcessExecutor($io); // check whether there is a fossil repo in that path if ($process->execute(['fossil', 'info'], $output, $url) === 0) { return true; } } return false; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/SvnDriver.php
src/Composer/Repository/Vcs/SvnDriver.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Config; use Composer\Json\JsonFile; use Composer\Pcre\Preg; use Composer\Util\ProcessExecutor; use Composer\Util\Filesystem; use Composer\Util\Url; use Composer\Util\Svn as SvnUtil; use Composer\IO\IOInterface; use Composer\Downloader\TransportException; /** * @author Jordi Boggiano <j.boggiano@seld.be> * @author Till Klampaeckel <till@php.net> */ class SvnDriver extends VcsDriver { /** @var string */ protected $baseUrl; /** @var array<int|string, string> Map of tag name to identifier */ protected $tags; /** @var array<int|string, string> Map of branch name to identifier */ protected $branches; /** @var ?string */ protected $rootIdentifier; /** @var string|false */ protected $trunkPath = 'trunk'; /** @var string */ protected $branchesPath = 'branches'; /** @var string */ protected $tagsPath = 'tags'; /** @var string */ protected $packagePath = ''; /** @var bool */ protected $cacheCredentials = true; /** * @var SvnUtil */ private $util; /** * @inheritDoc */ public function initialize(): void { $this->url = $this->baseUrl = rtrim(self::normalizeUrl($this->url), '/'); SvnUtil::cleanEnv(); if (isset($this->repoConfig['trunk-path'])) { $this->trunkPath = $this->repoConfig['trunk-path']; } if (isset($this->repoConfig['branches-path'])) { $this->branchesPath = $this->repoConfig['branches-path']; } if (isset($this->repoConfig['tags-path'])) { $this->tagsPath = $this->repoConfig['tags-path']; } if (array_key_exists('svn-cache-credentials', $this->repoConfig)) { $this->cacheCredentials = (bool) $this->repoConfig['svn-cache-credentials']; } if (isset($this->repoConfig['package-path'])) { $this->packagePath = '/' . trim($this->repoConfig['package-path'], '/'); } if (false !== ($pos = strrpos($this->url, '/' . $this->trunkPath))) { $this->baseUrl = substr($this->url, 0, $pos); } $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($this->baseUrl))); $this->cache->setReadOnly($this->config->get('cache-read-only')); $this->getBranches(); $this->getTags(); } /** * @inheritDoc */ public function getRootIdentifier(): string { return $this->rootIdentifier ?: $this->trunkPath; } /** * @inheritDoc */ public function getUrl(): string { return $this->url; } /** * @inheritDoc */ public function getSource(string $identifier): array { return ['type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier]; } /** * @inheritDoc */ public function getDist(string $identifier): ?array { return null; } /** * @inheritDoc */ protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{@\d+$}', $identifier); } /** * @inheritDoc */ public function getComposerInformation(string $identifier): ?array { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier.'.json')) { // old cache files had '' stored instead of null due to af3783b5f40bae32a23e353eaf0a00c9b8ce82e2, so we make sure here that we always return null or array // and fix outdated invalid cache files if ($res === '""') { $res = 'null'; $this->cache->write($identifier.'.json', $res); } return $this->infoCache[$identifier] = JsonFile::parseJson($res); } try { $composer = $this->getBaseComposerInformation($identifier); } catch (TransportException $e) { $message = $e->getMessage(); if (stripos($message, 'path not found') === false && stripos($message, 'svn: warning: W160013') === false) { throw $e; } // remember a not-existent composer.json $composer = null; } if ($this->shouldCache($identifier)) { $this->cache->write($identifier.'.json', JsonFile::encode($composer, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); } $this->infoCache[$identifier] = $composer; } // old cache files had '' stored instead of null due to af3783b5f40bae32a23e353eaf0a00c9b8ce82e2, so we make sure here that we always return null or array if (!is_array($this->infoCache[$identifier])) { return null; } return $this->infoCache[$identifier]; } public function getFileContent(string $file, string $identifier): ?string { $identifier = '/' . trim($identifier, '/') . '/'; if (Preg::isMatch('{^(.+?)(@\d+)?/$}', $identifier, $match) && $match[2] !== null) { $path = $match[1]; $rev = $match[2]; } else { $path = $identifier; $rev = ''; } try { $resource = $path.$file; $output = $this->execute(['svn', 'cat'], $this->baseUrl . $resource . $rev); if ('' === trim($output)) { return null; } } catch (\RuntimeException $e) { throw new TransportException($e->getMessage()); } return $output; } /** * @inheritDoc */ public function getChangeDate(string $identifier): ?\DateTimeImmutable { $identifier = '/' . trim($identifier, '/') . '/'; if (Preg::isMatch('{^(.+?)(@\d+)?/$}', $identifier, $match) && null !== $match[2]) { $path = $match[1]; $rev = $match[2]; } else { $path = $identifier; $rev = ''; } $output = $this->execute(['svn', 'info'], $this->baseUrl . $path . $rev); foreach ($this->process->splitLines($output) as $line) { if ($line !== '' && Preg::isMatchStrictGroups('{^Last Changed Date: ([^(]+)}', $line, $match)) { return new \DateTimeImmutable($match[1], new \DateTimeZone('UTC')); } } return null; } /** * @inheritDoc */ public function getTags(): array { if (null === $this->tags) { $tags = []; if ($this->tagsPath !== false) { $output = $this->execute(['svn', 'ls', '--verbose'], $this->baseUrl . '/' . $this->tagsPath); if ($output !== '') { $lastRev = 0; foreach ($this->process->splitLines($output) as $line) { $line = trim($line); if ($line !== '' && Preg::isMatch('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if ($match[2] === './') { $lastRev = (int) $match[1]; } else { $tags[rtrim($match[2], '/')] = $this->buildIdentifier( '/' . $this->tagsPath . '/' . $match[2], max($lastRev, (int) $match[1]) ); } } } } } $this->tags = $tags; } return $this->tags; } /** * @inheritDoc */ public function getBranches(): array { if (null === $this->branches) { $branches = []; if (false === $this->trunkPath) { $trunkParent = $this->baseUrl . '/'; } else { $trunkParent = $this->baseUrl . '/' . $this->trunkPath; } $output = $this->execute(['svn', 'ls', '--verbose'], $trunkParent); if ($output !== '') { foreach ($this->process->splitLines($output) as $line) { $line = trim($line); if ($line !== '' && Preg::isMatch('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if ($match[2] === './') { $branches['trunk'] = $this->buildIdentifier( '/' . $this->trunkPath, (int) $match[1] ); $this->rootIdentifier = $branches['trunk']; break; } } } } unset($output); if ($this->branchesPath !== false) { $output = $this->execute(['svn', 'ls', '--verbose'], $this->baseUrl . '/' . $this->branchesPath); if ($output !== '') { $lastRev = 0; foreach ($this->process->splitLines(trim($output)) as $line) { $line = trim($line); if ($line !== '' && Preg::isMatch('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) { if ($match[2] === './') { $lastRev = (int) $match[1]; } else { $branches[rtrim($match[2], '/')] = $this->buildIdentifier( '/' . $this->branchesPath . '/' . $match[2], max($lastRev, (int) $match[1]) ); } } } } } $this->branches = $branches; } return $this->branches; } /** * @inheritDoc */ public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { $url = self::normalizeUrl($url); if (Preg::isMatch('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) { return true; } // proceed with deep check for local urls since they are fast to process if (!$deep && !Filesystem::isLocalPath($url)) { return false; } $process = new ProcessExecutor($io); $exit = $process->execute(['svn', 'info', '--non-interactive', '--', $url], $ignoredOutput); if ($exit === 0) { // This is definitely a Subversion repository. return true; } // Subversion client 1.7 and older if (false !== stripos($process->getErrorOutput(), 'authorization failed:')) { // This is likely a remote Subversion repository that requires // authentication. We will handle actual authentication later. return true; } // Subversion client 1.8 and newer if (false !== stripos($process->getErrorOutput(), 'Authentication failed')) { // This is likely a remote Subversion or newer repository that requires // authentication. We will handle actual authentication later. return true; } return false; } /** * An absolute path (leading '/') is converted to a file:// url. */ protected static function normalizeUrl(string $url): string { $fs = new Filesystem(); if ($fs->isAbsolutePath($url)) { return 'file://' . strtr($url, '\\', '/'); } return $url; } /** * Execute an SVN command and try to fix up the process with credentials * if necessary. * * @param non-empty-list<string> $command The svn command to run. * @param string $url The SVN URL. * @throws \RuntimeException */ protected function execute(array $command, string $url): string { if (null === $this->util) { $this->util = new SvnUtil($this->baseUrl, $this->io, $this->config, $this->process); $this->util->setCacheCredentials($this->cacheCredentials); } try { return $this->util->execute($command, $url); } catch (\RuntimeException $e) { if (null === $this->util->binaryVersion()) { throw new \RuntimeException('Failed to load '.$this->url.', svn was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput()); } throw new \RuntimeException( 'Repository '.$this->url.' could not be processed, '.$e->getMessage() ); } } /** * Build the identifier respecting "package-path" config option * * @param string $baseDir The path to trunk/branch/tag * @param int $revision The revision mark to add to identifier */ protected function buildIdentifier(string $baseDir, int $revision): string { return rtrim($baseDir, '/') . $this->packagePath . '/@' . $revision; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/GitLabDriver.php
src/Composer/Repository/Vcs/GitLabDriver.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Config; use Composer\Cache; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Downloader\TransportException; use Composer\Pcre\Preg; use Composer\Util\HttpDownloader; use Composer\Util\GitLab; use Composer\Util\Http\Response; /** * Driver for GitLab API, use the Git driver for local checkouts. * * @author Henrik Bjørnskov <henrik@bjrnskov.dk> * @author Jérôme Tamarelle <jerome@tamarelle.net> */ class GitLabDriver extends VcsDriver { /** * @var string * @phpstan-var 'https'|'http' */ private $scheme; /** @var string */ private $namespace; /** @var string */ private $repository; /** * @var mixed[] Project data returned by GitLab API */ private $project = null; /** * @var array<string|int, mixed[]> Keeps commits returned by GitLab API as commit id => info */ private $commits = []; /** @var array<int|string, string> Map of tag name to identifier */ private $tags; /** @var array<int|string, string> Map of branch name to identifier */ private $branches; /** * Git Driver * * @var ?GitDriver */ protected $gitDriver = null; /** * Protocol to force use of for repository URLs. * * @var string One of ssh, http */ protected $protocol; /** * Defaults to true unless we can make sure it is public * * @var bool defines whether the repo is private or not */ private $isPrivate = true; /** * @var bool true if the origin has a port number or a path component in it */ private $hasNonstandardOrigin = false; public const URL_REGEX = '#^(?:(?P<scheme>https?)://(?P<domain>.+?)(?::(?P<port>[0-9]+))?/|git@(?P<domain2>[^:]+):)(?P<parts>.+)/(?P<repo>[^/]+?)(?:\.git|/)?$#'; /** * Extracts information from the repository url. * * SSH urls use https by default. Set "secure-http": false on the repository config to use http instead. * * @inheritDoc */ 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)); } $guessedDomain = $match['domain'] ?? (string) $match['domain2']; $configuredDomains = $this->config->get('gitlab-domains'); $urlParts = explode('/', $match['parts']); $this->scheme = in_array($match['scheme'], ['https', 'http'], true) ? $match['scheme'] : (isset($this->repoConfig['secure-http']) && $this->repoConfig['secure-http'] === false ? 'http' : 'https') ; $origin = self::determineOrigin($configuredDomains, $guessedDomain, $urlParts, $match['port']); if (false === $origin) { throw new \LogicException('It should not be possible to create a gitlab driver with an unparsable origin URL ('.$this->url.')'); } $this->originUrl = $origin; if (is_string($protocol = $this->config->get('gitlab-protocol'))) { // https treated as a synonym for http. if (!in_array($protocol, ['git', 'http', 'https'], true)) { throw new \RuntimeException('gitlab-protocol must be one of git, http.'); } $this->protocol = $protocol === 'git' ? 'ssh' : 'http'; } if (false !== strpos($this->originUrl, ':') || false !== strpos($this->originUrl, '/')) { $this->hasNonstandardOrigin = true; } $this->namespace = implode('/', $urlParts); $this->repository = Preg::replace('#(\.git)$#', '', $match['repo']); $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository); $this->cache->setReadOnly($this->config->get('cache-read-only')); $this->fetchProject(); } /** * Updates the HttpDownloader instance. * Mainly useful for tests. * * @internal */ public function setHttpDownloader(HttpDownloader $httpDownloader): void { $this->httpDownloader = $httpDownloader; } /** * @inheritDoc */ public function getComposerInformation(string $identifier): ?array { if ($this->gitDriver) { return $this->gitDriver->getComposerInformation($identifier); } if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { $composer = JsonFile::parseJson($res); } else { $composer = $this->getBaseComposerInformation($identifier); if ($this->shouldCache($identifier)) { $this->cache->write($identifier, JsonFile::encode($composer, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); } } if (null !== $composer) { // specials for gitlab (this data is only available if authentication is provided) if (isset($composer['support']) && !is_array($composer['support'])) { $composer['support'] = []; } if (!isset($composer['support']['source']) && isset($this->project['web_url'])) { $label = array_search($identifier, $this->getTags(), true) ?: array_search($identifier, $this->getBranches(), true) ?: $identifier; $composer['support']['source'] = sprintf('%s/-/tree/%s', $this->project['web_url'], $label); } if (!isset($composer['support']['issues']) && !empty($this->project['issues_enabled']) && isset($this->project['web_url'])) { $composer['support']['issues'] = sprintf('%s/-/issues', $this->project['web_url']); } if (!isset($composer['abandoned']) && !empty($this->project['archived'])) { $composer['abandoned'] = true; } } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } /** * @inheritDoc */ public function getFileContent(string $file, string $identifier): ?string { if ($this->gitDriver) { return $this->gitDriver->getFileContent($file, $identifier); } // Convert the root identifier to a cacheable commit id if (!Preg::isMatch('{[a-f0-9]{40}}i', $identifier)) { $branches = $this->getBranches(); if (isset($branches[$identifier])) { $identifier = $branches[$identifier]; } } $resource = $this->getApiUrl().'/repository/files/'.$this->urlEncodeAll($file).'/raw?ref='.$identifier; try { $content = $this->getContents($resource)->getBody(); } catch (TransportException $e) { if ($e->getCode() !== 404) { throw $e; } return null; } return $content; } /** * @inheritDoc */ public function getChangeDate(string $identifier): ?\DateTimeImmutable { if ($this->gitDriver) { return $this->gitDriver->getChangeDate($identifier); } if (isset($this->commits[$identifier])) { return new \DateTimeImmutable($this->commits[$identifier]['committed_date']); } return null; } public function getRepositoryUrl(): string { if ($this->protocol) { return $this->project["{$this->protocol}_url_to_repo"]; } return $this->isPrivate ? $this->project['ssh_url_to_repo'] : $this->project['http_url_to_repo']; } /** * @inheritDoc */ public function getUrl(): string { if ($this->gitDriver) { return $this->gitDriver->getUrl(); } return $this->project['web_url']; } /** * @inheritDoc */ public function getDist(string $identifier): ?array { $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier; return ['type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '']; } /** * @inheritDoc */ public function getSource(string $identifier): array { if ($this->gitDriver) { return $this->gitDriver->getSource($identifier); } return ['type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier]; } /** * @inheritDoc */ public function getRootIdentifier(): string { if ($this->gitDriver) { return $this->gitDriver->getRootIdentifier(); } return $this->project['default_branch']; } /** * @inheritDoc */ public function getBranches(): array { if ($this->gitDriver) { return $this->gitDriver->getBranches(); } if (null === $this->branches) { $this->branches = $this->getReferences('branches'); } return $this->branches; } /** * @inheritDoc */ public function getTags(): array { if ($this->gitDriver) { return $this->gitDriver->getTags(); } if (null === $this->tags) { $this->tags = $this->getReferences('tags'); } return $this->tags; } /** * @return string Base URL for GitLab API v3 */ public function getApiUrl(): string { return $this->scheme.'://'.$this->originUrl.'/api/v4/projects/'.$this->urlEncodeAll($this->namespace).'%2F'.$this->urlEncodeAll($this->repository); } /** * Urlencode all non alphanumeric characters. rawurlencode() can not be used as it does not encode `.` */ private function urlEncodeAll(string $string): string { $encoded = ''; for ($i = 0; isset($string[$i]); $i++) { $character = $string[$i]; if (!ctype_alnum($character) && !in_array($character, ['-', '_'], true)) { $character = '%' . sprintf('%02X', ord($character)); } $encoded .= $character; } return $encoded; } /** * @return string[] where keys are named references like tags or branches and the value a sha */ protected function getReferences(string $type): array { $perPage = 100; $resource = $this->getApiUrl().'/repository/'.$type.'?per_page='.$perPage; $references = []; do { $response = $this->getContents($resource); $data = $response->decodeJson(); foreach ($data as $datum) { $references[$datum['name']] = $datum['commit']['id']; // Keep the last commit date of a reference to avoid // unnecessary API call when retrieving the composer file. $this->commits[$datum['commit']['id']] = $datum['commit']; } if (count($data) >= $perPage) { $resource = $this->getNextPage($response); } else { $resource = false; } } while ($resource); return $references; } protected function fetchProject(): void { if (!is_null($this->project)) { return; } // we need to fetch the default branch from the api $resource = $this->getApiUrl(); $this->project = $this->getContents($resource, true)->decodeJson(); if (isset($this->project['visibility'])) { $this->isPrivate = $this->project['visibility'] !== 'public'; } else { // client is not authenticated, therefore repository has to be public $this->isPrivate = false; } } /** * @phpstan-impure * * @return true * @throws \RuntimeException */ protected function attemptCloneFallback(): bool { if ($this->isPrivate === false) { $url = $this->generatePublicUrl(); } else { $url = $this->generateSshUrl(); } try { // If this repository may be private and we // cannot ask for authentication credentials (because we // are not interactive) then we fallback to GitDriver. $this->setupGitDriver($url); return true; } catch (\RuntimeException $e) { $this->gitDriver = null; $this->io->writeError('<error>Failed to clone the '.$url.' repository, try running in interactive mode so that you can enter your credentials</error>'); throw $e; } } /** * Generate an SSH URL */ protected function generateSshUrl(): string { if ($this->hasNonstandardOrigin) { return 'ssh://git@'.$this->originUrl.'/'.$this->namespace.'/'.$this->repository.'.git'; } return 'git@' . $this->originUrl . ':'.$this->namespace.'/'.$this->repository.'.git'; } protected function generatePublicUrl(): string { return $this->scheme . '://' . $this->originUrl . '/'.$this->namespace.'/'.$this->repository.'.git'; } protected function setupGitDriver(string $url): void { $this->gitDriver = new GitDriver( ['url' => $url], $this->io, $this->config, $this->httpDownloader, $this->process ); $this->gitDriver->initialize(); } /** * @inheritDoc */ protected function getContents(string $url, bool $fetchingRepoData = false): Response { try { $response = parent::getContents($url); if ($fetchingRepoData) { $json = $response->decodeJson(); // Accessing the API with a token with Guest (10) or Planner (15) access will return // more data than unauthenticated access but no default_branch data // accessing files via the API will then also fail if (!isset($json['default_branch']) && isset($json['permissions'])) { $this->isPrivate = $json['visibility'] !== 'public'; $moreThanGuestAccess = false; // Check both access levels (e.g. project, group) // - value will be null if no access is set // - value will be array with key access_level if set foreach ($json['permissions'] as $permission) { if ($permission && $permission['access_level'] >= 20) { $moreThanGuestAccess = true; } } if (!$moreThanGuestAccess) { $this->io->writeError('<warning>GitLab token with Guest or Planner only access detected</warning>'); $this->attemptCloneFallback(); return new Response(['url' => 'dummy'], 200, [], 'null'); } } // force auth as the unauthenticated version of the API is broken if (!isset($json['default_branch'])) { // GitLab allows you to disable the repository inside a project to use a project only for issues and wiki if (isset($json['repository_access_level']) && $json['repository_access_level'] === 'disabled') { throw new TransportException('The GitLab repository is disabled in the project', 400); } if (!empty($json['id'])) { $this->isPrivate = false; } throw new TransportException('GitLab API seems to not be authenticated as it did not return a default_branch', 401); } } return $response; } catch (TransportException $e) { $gitLabUtil = new GitLab($this->io, $this->config, $this->process, $this->httpDownloader); switch ($e->getCode()) { case 401: case 404: // try to authorize only if we are fetching the main /repos/foo/bar data, otherwise it must be a real 404 if (!$fetchingRepoData) { throw $e; } if ($gitLabUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if ($gitLabUtil->isOAuthExpired($this->originUrl) && $gitLabUtil->authorizeOAuthRefresh($this->scheme, $this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive()) { $this->attemptCloneFallback(); return new Response(['url' => 'dummy'], 200, [], 'null'); } $this->io->writeError('<warning>Failed to download ' . $this->namespace . '/' . $this->repository . ':' . $e->getMessage() . '</warning>'); $gitLabUtil->authorizeOAuthInteractively($this->scheme, $this->originUrl, 'Your credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)'); return parent::getContents($url); case 403: if (!$this->io->hasAuthentication($this->originUrl) && $gitLabUtil->authorizeOAuth($this->originUrl)) { return parent::getContents($url); } if (!$this->io->isInteractive() && $fetchingRepoData) { $this->attemptCloneFallback(); return new Response(['url' => 'dummy'], 200, [], 'null'); } throw $e; default: throw $e; } } } /** * Uses the config `gitlab-domains` to see if the driver supports the url for the * repository given. * * @inheritDoc */ public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool { if (!Preg::isMatch(self::URL_REGEX, $url, $match)) { return false; } $scheme = $match['scheme']; $guessedDomain = $match['domain'] ?? (string) $match['domain2']; $urlParts = explode('/', $match['parts']); if (false === self::determineOrigin($config->get('gitlab-domains'), $guessedDomain, $urlParts, $match['port'])) { return false; } if ('https' === $scheme && !extension_loaded('openssl')) { $io->writeError('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE); return false; } return true; } /** * Gives back the loaded <gitlab-api>/projects/<owner>/<repo> result * * @return mixed[]|null */ public function getRepoData(): ?array { $this->fetchProject(); return $this->project; } protected function getNextPage(Response $response): ?string { $header = $response->getHeader('link'); $links = explode(',', $header); foreach ($links as $link) { if (Preg::isMatchStrictGroups('{<(.+?)>; *rel="next"}', $link, $match)) { return $match[1]; } } return null; } /** * @param array<string> $configuredDomains * @param array<string> $urlParts * * @return string|false */ private static function determineOrigin(array $configuredDomains, string $guessedDomain, array &$urlParts, ?string $portNumber) { $guessedDomain = strtolower($guessedDomain); if (in_array($guessedDomain, $configuredDomains) || (null !== $portNumber && in_array($guessedDomain.':'.$portNumber, $configuredDomains))) { if (null !== $portNumber) { return $guessedDomain.':'.$portNumber; } return $guessedDomain; } if (null !== $portNumber) { $guessedDomain .= ':'.$portNumber; } while (null !== ($part = array_shift($urlParts))) { $guessedDomain .= '/' . $part; if (in_array($guessedDomain, $configuredDomains) || (null !== $portNumber && in_array(Preg::replace('{:\d+}', '', $guessedDomain), $configuredDomains))) { return $guessedDomain; } } return false; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/VcsDriver.php
src/Composer/Repository/Vcs/VcsDriver.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Repository\Vcs; use Composer\Cache; use Composer\Downloader\TransportException; use Composer\Config; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Pcre\Preg; use Composer\Util\ProcessExecutor; use Composer\Util\HttpDownloader; use Composer\Util\Filesystem; use Composer\Util\Http\Response; /** * A driver implementation for driver with authentication interaction. * * @author François Pluchino <francois.pluchino@opendisplay.com> */ abstract class VcsDriver implements VcsDriverInterface { /** @var string */ protected $url; /** @var string */ protected $originUrl; /** @var array<string, mixed> */ protected $repoConfig; /** @var IOInterface */ protected $io; /** @var Config */ protected $config; /** @var ProcessExecutor */ protected $process; /** @var HttpDownloader */ protected $httpDownloader; /** @var array<int|string, mixed> */ protected $infoCache = []; /** @var ?Cache */ protected $cache; /** * Constructor. * * @param array{url: string}&array<string, mixed> $repoConfig The repository configuration * @param IOInterface $io The IO instance * @param Config $config The composer configuration * @param HttpDownloader $httpDownloader Remote Filesystem, injectable for mocking * @param ProcessExecutor $process Process instance, injectable for mocking */ final public function __construct(array $repoConfig, IOInterface $io, Config $config, HttpDownloader $httpDownloader, ProcessExecutor $process) { if (Filesystem::isLocalPath($repoConfig['url'])) { $repoConfig['url'] = Filesystem::getPlatformPath($repoConfig['url']); } $this->url = $repoConfig['url']; $this->originUrl = $repoConfig['url']; $this->repoConfig = $repoConfig; $this->io = $io; $this->config = $config; $this->httpDownloader = $httpDownloader; $this->process = $process; } /** * Returns whether or not the given $identifier should be cached or not. * @phpstan-assert-if-true !null $this->cache */ protected function shouldCache(string $identifier): bool { return $this->cache && Preg::isMatch('{^[a-f0-9]{40}$}iD', $identifier); } /** * @inheritDoc */ public function getComposerInformation(string $identifier): ?array { if (!isset($this->infoCache[$identifier])) { if ($this->shouldCache($identifier) && $res = $this->cache->read($identifier)) { return $this->infoCache[$identifier] = JsonFile::parseJson($res); } $composer = $this->getBaseComposerInformation($identifier); if ($this->shouldCache($identifier)) { $this->cache->write($identifier, JsonFile::encode($composer, \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES)); } $this->infoCache[$identifier] = $composer; } return $this->infoCache[$identifier]; } /** * @return array<mixed>|null */ protected function getBaseComposerInformation(string $identifier): ?array { $composerFileContent = $this->getFileContent('composer.json', $identifier); if (!$composerFileContent) { return null; } $composer = JsonFile::parseJson($composerFileContent, $identifier . ':composer.json'); if ([] === $composer || !is_array($composer)) { return null; } if (empty($composer['time']) && null !== ($changeDate = $this->getChangeDate($identifier))) { $composer['time'] = $changeDate->format(DATE_RFC3339); } return $composer; } /** * @inheritDoc */ public function hasComposerFile(string $identifier): bool { try { return null !== $this->getComposerInformation($identifier); } catch (TransportException $e) { } return false; } /** * Get the https or http protocol depending on SSL support. * * Call this only if you know that the server supports both. * * @return string The correct type of protocol */ protected function getScheme(): string { if (extension_loaded('openssl')) { return 'https'; } return 'http'; } /** * Get the remote content. * * @param string $url The URL of content * * @throws TransportException */ protected function getContents(string $url): Response { $options = $this->repoConfig['options'] ?? []; return $this->httpDownloader->get($url, $options); } /** * @inheritDoc */ public function cleanup(): void { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Platform/Version.php
src/Composer/Platform/Version.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Platform; use Composer\Pcre\Preg; /** * @author Lars Strojny <lars@strojny.net> */ class Version { /** * @param bool $isFips Set by the method * * @param-out bool $isFips */ public static function parseOpenssl(string $opensslVersion, ?bool &$isFips): ?string { $isFips = false; if (!Preg::isMatchStrictGroups('/^(?<version>[0-9.]+)(?<patch>[a-z]{0,2})(?<suffix>(?:-?(?:dev|pre|alpha|beta|rc|fips)[\d]*)*)(?:-\w+)?(?: \(.+?\))?$/', $opensslVersion, $matches)) { return null; } // OpenSSL 1 used 1.2.3a style versioning, 3+ uses semver $patch = ''; if (version_compare($matches['version'], '3.0.0', '<')) { $patch = '.'.self::convertAlphaVersionToIntVersion($matches['patch']); } $isFips = strpos($matches['suffix'], 'fips') !== false; $suffix = strtr('-'.ltrim($matches['suffix'], '-'), ['-fips' => '', '-pre' => '-alpha']); return rtrim($matches['version'].$patch.$suffix, '-'); } public static function parseLibjpeg(string $libjpegVersion): ?string { if (!Preg::isMatchStrictGroups('/^(?<major>\d+)(?<minor>[a-z]*)$/', $libjpegVersion, $matches)) { return null; } return $matches['major'].'.'.self::convertAlphaVersionToIntVersion($matches['minor']); } public static function parseZoneinfoVersion(string $zoneinfoVersion): ?string { if (!Preg::isMatchStrictGroups('/^(?<year>\d{4})(?<revision>[a-z]*)$/', $zoneinfoVersion, $matches)) { return null; } return $matches['year'].'.'.self::convertAlphaVersionToIntVersion($matches['revision']); } /** * "" => 0, "a" => 1, "zg" => 33 */ private static function convertAlphaVersionToIntVersion(string $alpha): int { return strlen($alpha) * (-ord('a') + 1) + array_sum(array_map('ord', str_split($alpha))); } public static function convertLibxpmVersionId(int $versionId): string { return self::convertVersionId($versionId, 100); } public static function convertOpenldapVersionId(int $versionId): string { return self::convertVersionId($versionId, 100); } private static function convertVersionId(int $versionId, int $base): string { return sprintf( '%d.%d.%d', $versionId / ($base * $base), (int) ($versionId / $base) % $base, $versionId % $base ); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Platform/Runtime.php
src/Composer/Platform/Runtime.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Platform; class Runtime { /** * @param class-string $class */ public function hasConstant(string $constant, ?string $class = null): bool { return defined(ltrim($class.'::'.$constant, ':')); } /** * @param class-string $class * * @return mixed */ public function getConstant(string $constant, ?string $class = null) { return constant(ltrim($class.'::'.$constant, ':')); } public function hasFunction(string $fn): bool { return function_exists($fn); } /** * @param mixed[] $arguments * * @return mixed */ public function invoke(callable $callable, array $arguments = []) { return $callable(...$arguments); } /** * @param class-string $class */ public function hasClass(string $class): bool { return class_exists($class, false); } /** * @template T of object * @param mixed[] $arguments * * @phpstan-param class-string<T> $class * @phpstan-return T * * @throws \ReflectionException */ public function construct(string $class, array $arguments = []): object { if (empty($arguments)) { return new $class; } $refl = new \ReflectionClass($class); return $refl->newInstanceArgs($arguments); } /** @return string[] */ public function getExtensions(): array { return get_loaded_extensions(); } public function getExtensionVersion(string $extension): string { $version = phpversion($extension); if ($version === false) { $version = '0'; } return $version; } /** * @throws \ReflectionException */ public function getExtensionInfo(string $extension): string { $reflector = new \ReflectionExtension($extension); ob_start(); $reflector->info(); return ob_get_clean(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Platform/HhvmDetector.php
src/Composer/Platform/HhvmDetector.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Platform; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Symfony\Component\Process\ExecutableFinder; class HhvmDetector { /** @var string|false|null */ private static $hhvmVersion = null; /** @var ?ExecutableFinder */ private $executableFinder; /** @var ?ProcessExecutor */ private $processExecutor; public function __construct(?ExecutableFinder $executableFinder = null, ?ProcessExecutor $processExecutor = null) { $this->executableFinder = $executableFinder; $this->processExecutor = $processExecutor; } public function reset(): void { self::$hhvmVersion = null; } public function getVersion(): ?string { if (null !== self::$hhvmVersion) { return self::$hhvmVersion ?: null; } self::$hhvmVersion = defined('HHVM_VERSION') ? HHVM_VERSION : null; if (self::$hhvmVersion === null && !Platform::isWindows()) { self::$hhvmVersion = false; $this->executableFinder = $this->executableFinder ?: new ExecutableFinder(); $hhvmPath = $this->executableFinder->find('hhvm'); if ($hhvmPath !== null) { $this->processExecutor = $this->processExecutor ?? new ProcessExecutor(); $exitCode = $this->processExecutor->execute([$hhvmPath, '--php', '-d', 'hhvm.jit=0', '-r', 'echo HHVM_VERSION;'], self::$hhvmVersion); if ($exitCode !== 0) { self::$hhvmVersion = false; } } } return self::$hhvmVersion ?: null; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/LicensesCommand.php
src/Composer/Command/LicensesCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Console\Input\InputOption; use Composer\Json\JsonFile; use Composer\Package\CompletePackageInterface; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\RepositoryUtils; use Composer\Util\PackageInfo; use Composer\Util\PackageSorter; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; /** * @author Benoît Merlet <benoit.merlet@gmail.com> */ class LicensesCommand extends BaseCommand { protected function configure(): void { $this ->setName('licenses') ->setDescription('Shows information about licenses of dependencies') ->setDefinition([ new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text, json or summary', 'text', ['text', 'json', 'summary']), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables search in require-dev packages.'), new InputOption('locked', null, InputOption::VALUE_NONE, 'Shows licenses from the lock file instead of installed packages.'), ]) ->setHelp( <<<EOT The license command displays detailed information about the licenses of the installed dependencies. Use --locked to show licenses from composer.lock instead of what's currently installed in the vendor directory. Read more at https://getcomposer.org/doc/03-cli.md#licenses EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'licenses', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $root = $composer->getPackage(); if ($input->getOption('locked')) { if (!$composer->getLocker()->isLocked()) { throw new \UnexpectedValueException('Valid composer.json and composer.lock files are required to run this command with --locked'); } $locker = $composer->getLocker(); $repo = $locker->getLockedRepository(!$input->getOption('no-dev')); $packages = $repo->getPackages(); } else { $repo = $composer->getRepositoryManager()->getLocalRepository(); if ($input->getOption('no-dev')) { $packages = RepositoryUtils::filterRequiredPackages($repo->getPackages(), $root); } else { $packages = $repo->getPackages(); } } $packages = PackageSorter::sortPackagesAlphabetically($packages); $io = $this->getIO(); switch ($format = $input->getOption('format')) { case 'text': $io->write('Name: <comment>'.$root->getPrettyName().'</comment>'); $io->write('Version: <comment>'.$root->getFullPrettyVersion().'</comment>'); $io->write('Licenses: <comment>'.(implode(', ', $root->getLicense()) ?: 'none').'</comment>'); $io->write('Dependencies:'); $io->write(''); $table = new Table($output); $table->setStyle('compact'); $table->setHeaders(['Name', 'Version', 'Licenses']); foreach ($packages as $package) { $link = PackageInfo::getViewSourceOrHomepageUrl($package); if ($link !== null) { $name = '<href='.OutputFormatter::escape($link).'>'.$package->getPrettyName().'</>'; } else { $name = $package->getPrettyName(); } $table->addRow([ $name, $package->getFullPrettyVersion(), implode(', ', $package instanceof CompletePackageInterface ? $package->getLicense() : []) ?: 'none', ]); } $table->render(); break; case 'json': $dependencies = []; foreach ($packages as $package) { $dependencies[$package->getPrettyName()] = [ 'version' => $package->getFullPrettyVersion(), 'license' => $package instanceof CompletePackageInterface ? $package->getLicense() : [], ]; } $io->write(JsonFile::encode([ 'name' => $root->getPrettyName(), 'version' => $root->getFullPrettyVersion(), 'license' => $root->getLicense(), 'dependencies' => $dependencies, ])); break; case 'summary': $usedLicenses = []; foreach ($packages as $package) { $licenses = $package instanceof CompletePackageInterface ? $package->getLicense() : []; if (count($licenses) === 0) { $licenses[] = 'none'; } foreach ($licenses as $licenseName) { if (!isset($usedLicenses[$licenseName])) { $usedLicenses[$licenseName] = 0; } $usedLicenses[$licenseName]++; } } // Sort licenses so that the most used license will appear first arsort($usedLicenses, SORT_NUMERIC); $rows = []; foreach ($usedLicenses as $usedLicense => $numberOfDependencies) { $rows[] = [$usedLicense, $numberOfDependencies]; } $symfonyIo = new SymfonyStyle($input, $output); $symfonyIo->table( ['License', 'Number of dependencies'], $rows ); break; default: throw new \RuntimeException(sprintf('Unsupported format "%s". See help for supported formats.', $format)); } return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ArchiveCommand.php
src/Composer/Command/ArchiveCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Config; use Composer\Composer; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Package\Version\VersionParser; use Composer\Package\Version\VersionSelector; use Composer\Pcre\Preg; use Composer\Repository\CompositeRepository; use Composer\Repository\RepositoryFactory; use Composer\Repository\RepositorySet; use Composer\Script\ScriptEvents; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\Filesystem; use Composer\Util\Loop; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Creates an archive of a package for distribution. * * @author Nils Adermann <naderman@naderman.de> */ class ArchiveCommand extends BaseCommand { use CompletionTrait; private const FORMATS = ['tar', 'tar.gz', 'tar.bz2', 'zip']; protected function configure(): void { $this ->setName('archive') ->setDescription('Creates an archive of this composer package') ->setDefinition([ new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project', null, $this->suggestAvailablePackage()), new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar, tar.gz, tar.bz2 or zip (default tar)', null, self::FORMATS), new InputOption('dir', null, InputOption::VALUE_REQUIRED, 'Write the archive to this directory'), new InputOption('file', null, InputOption::VALUE_REQUIRED, 'Write the archive with the given file name.' .' Note that the format will be appended.'), new InputOption('ignore-filters', null, InputOption::VALUE_NONE, 'Ignore filters when saving package'), ]) ->setHelp( <<<EOT The <info>archive</info> command creates an archive of the specified format containing the files and directories of the Composer project or the specified package in the specified version and writes it to the specified directory. <info>php composer.phar archive [--format=zip] [--dir=/foo] [--file=filename] [package [version]]</info> Read more at https://getcomposer.org/doc/03-cli.md#archive EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->tryComposer(); $config = null; if ($composer) { $config = $composer->getConfig(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output); $eventDispatcher = $composer->getEventDispatcher(); $eventDispatcher->dispatch($commandEvent->getName(), $commandEvent); $eventDispatcher->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD); } if (!$config) { $config = Factory::createConfig(); } $format = $input->getOption('format') ?? $config->get('archive-format'); $dir = $input->getOption('dir') ?? $config->get('archive-dir'); $returnCode = $this->archive( $this->getIO(), $config, $input->getArgument('package'), $input->getArgument('version'), $format, $dir, $input->getOption('file'), $input->getOption('ignore-filters'), $composer ); if (0 === $returnCode && $composer) { $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD); } return $returnCode; } /** * @throws \Exception */ protected function archive(IOInterface $io, Config $config, ?string $packageName, ?string $version, string $format, string $dest, ?string $fileName, bool $ignoreFilters, ?Composer $composer): int { if ($composer) { $archiveManager = $composer->getArchiveManager(); } else { $factory = new Factory; $process = new ProcessExecutor(); $httpDownloader = Factory::createHttpDownloader($io, $config); $downloadManager = $factory->createDownloadManager($io, $config, $httpDownloader, $process); $archiveManager = $factory->createArchiveManager($config, $downloadManager, new Loop($httpDownloader, $process)); } if ($packageName) { $package = $this->selectPackage($io, $packageName, $version); if (!$package) { return 1; } } else { $package = $this->requireComposer()->getPackage(); } $io->writeError('<info>Creating the archive into "'.$dest.'".</info>'); $packagePath = $archiveManager->archive($package, $format, $dest, $fileName, $ignoreFilters); $fs = new Filesystem; $shortPath = $fs->findShortestPath(Platform::getCwd(), $packagePath, true); $io->writeError('Created: ', false); $io->write(strlen($shortPath) < strlen($packagePath) ? $shortPath : $packagePath); return 0; } /** * @return (BasePackage&CompletePackageInterface)|false */ protected function selectPackage(IOInterface $io, string $packageName, ?string $version = null) { $io->writeError('<info>Searching for the specified package.</info>'); if ($composer = $this->tryComposer()) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $repo = new CompositeRepository(array_merge([$localRepo], $composer->getRepositoryManager()->getRepositories())); $minStability = $composer->getPackage()->getMinimumStability(); } else { $defaultRepos = RepositoryFactory::defaultReposWithDefaultManager($io); $io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos))); $repo = new CompositeRepository($defaultRepos); $minStability = 'stable'; } if ($version !== null && Preg::isMatchStrictGroups('{@(stable|RC|beta|alpha|dev)$}i', $version, $match)) { $minStability = VersionParser::normalizeStability($match[1]); $version = (string) substr($version, 0, -strlen($match[0])); } $repoSet = new RepositorySet($minStability); $repoSet->addRepository($repo); $parser = new VersionParser(); $constraint = $version !== null ? $parser->parseConstraints($version) : null; $packages = $repoSet->findPackages(strtolower($packageName), $constraint); if (count($packages) > 1) { $versionSelector = new VersionSelector($repoSet); $package = $versionSelector->findBestCandidate(strtolower($packageName), $version, $minStability); if ($package === false) { $package = reset($packages); } $io->writeError('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>'); $io->writeError('Alternatives were '.implode(', ', array_map(static function ($p): string { return $p->getPrettyString(); }, $packages)).'.'); $io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>'); } elseif (count($packages) === 1) { $package = reset($packages); $io->writeError('<info>Found an exact match '.$package->getPrettyString().'.</info>'); } else { $io->writeError('<error>Could not find a package matching '.$packageName.'.</error>'); return false; } if (!$package instanceof CompletePackageInterface) { throw new \LogicException('Expected a CompletePackageInterface instance but found '.get_class($package)); } if (!$package instanceof BasePackage) { throw new \LogicException('Expected a BasePackage instance but found '.get_class($package)); } return $package; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/SelfUpdateCommand.php
src/Composer/Command/SelfUpdateCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\SelfUpdate\Keys; use Composer\SelfUpdate\Versions; use Composer\IO\IOInterface; use Composer\Downloader\FilesystemException; use Composer\Downloader\TransportException; use Phar; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; /** * @author Igor Wiedler <igor@wiedler.ch> * @author Kevin Ran <kran@adobe.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class SelfUpdateCommand extends BaseCommand { private const HOMEPAGE = 'getcomposer.org'; private const OLD_INSTALL_EXT = '-old.phar'; protected function configure(): void { $this ->setName('self-update') ->setAliases(['selfupdate']) ->setDescription('Updates composer.phar to the latest version') ->setDefinition([ new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'), new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'), new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('update-keys', null, InputOption::VALUE_NONE, 'Prompt user for a key update'), new InputOption('stable', null, InputOption::VALUE_NONE, 'Force an update to the stable channel'), new InputOption('preview', null, InputOption::VALUE_NONE, 'Force an update to the preview channel'), new InputOption('snapshot', null, InputOption::VALUE_NONE, 'Force an update to the snapshot channel'), new InputOption('1', null, InputOption::VALUE_NONE, 'Force an update to the stable channel, but only use 1.x versions'), new InputOption('2', null, InputOption::VALUE_NONE, 'Force an update to the stable channel, but only use 2.x versions'), new InputOption('2.2', null, InputOption::VALUE_NONE, 'Force an update to the stable channel, but only use 2.2.x LTS versions'), new InputOption('set-channel-only', null, InputOption::VALUE_NONE, 'Only store the channel as the default one and then exit'), ]) ->setHelp( <<<EOT The <info>self-update</info> command checks getcomposer.org for newer versions of composer and if found, installs the latest. <info>php composer.phar self-update</info> Read more at https://getcomposer.org/doc/03-cli.md#self-update-selfupdate EOT ) ; } /** * @throws FilesystemException */ protected function execute(InputInterface $input, OutputInterface $output): int { if (strpos(__FILE__, 'phar:') !== 0) { if (str_contains(strtr(__DIR__, '\\', '/'), 'vendor/composer/composer')) { $projDir = dirname(__DIR__, 6); $output->writeln('<error>This instance of Composer does not have the self-update command.</error>'); $output->writeln('<comment>You are running Composer installed as a package in your current project ("'.$projDir.'").</comment>'); $output->writeln('<comment>To update Composer, download a composer.phar from https://getcomposer.org and then run `composer.phar update composer/composer` in your project.</comment>'); } else { $output->writeln('<error>This instance of Composer does not have the self-update command.</error>'); $output->writeln('<comment>This could be due to a number of reasons, such as Composer being installed as a system package on your OS, or Composer being installed as a package in the current project.</comment>'); } return 1; } if ($_SERVER['argv'][0] === 'Standard input code') { return 1; } // trigger autoloading of a few classes which may be needed when verifying/swapping the phar file // to ensure we do not try to load them from the new phar, see https://github.com/composer/composer/issues/10252 class_exists('Composer\Util\Platform'); class_exists('Composer\Downloader\FilesystemException'); $config = Factory::createConfig(); if ($config->get('disable-tls') === true) { $baseUrl = 'http://' . self::HOMEPAGE; } else { $baseUrl = 'https://' . self::HOMEPAGE; } $io = $this->getIO(); $httpDownloader = Factory::createHttpDownloader($io, $config); $versionsUtil = new Versions($config, $httpDownloader); // switch channel if requested $requestedChannel = null; foreach (Versions::CHANNELS as $channel) { if ($input->getOption($channel)) { $requestedChannel = $channel; $versionsUtil->setChannel($channel, $io); break; } } if ($input->getOption('set-channel-only')) { return 0; } $cacheDir = $config->get('cache-dir'); $rollbackDir = $config->get('data-dir'); $home = $config->get('home'); $localFilename = Phar::running(false); if ('' === $localFilename) { throw new \RuntimeException('Could not determine the location of the composer.phar file as it appears you are not running this code from a phar archive.'); } if ($input->getOption('update-keys')) { $this->fetchKeys($io, $config); return 0; } // ensure composer.phar location is accessible if (!file_exists($localFilename)) { throw new FilesystemException('Composer update failed: the "'.$localFilename.'" is not accessible'); } // check if current dir is writable and if not try the cache dir from settings $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir; // check for permissions in local filesystem before start connection process if (!is_writable($tmpDir)) { throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written'); } // check if composer is running as the same user that owns the directory root, only if POSIX is defined and callable if (function_exists('posix_getpwuid') && function_exists('posix_geteuid')) { $composerUser = posix_getpwuid(posix_geteuid()); $homeDirOwnerId = fileowner($home); if (is_array($composerUser) && $homeDirOwnerId !== false) { $homeOwner = posix_getpwuid($homeDirOwnerId); if (is_array($homeOwner) && $composerUser['name'] !== $homeOwner['name']) { $io->writeError('<warning>You are running Composer as "'.$composerUser['name'].'", while "'.$home.'" is owned by "'.$homeOwner['name'].'"</warning>'); } } } if ($input->getOption('rollback')) { return $this->rollback($output, $rollbackDir, $localFilename); } if ($input->getArgument('command') === 'self' && $input->getArgument('version') === 'update') { $input->setArgument('version', null); } $latest = $versionsUtil->getLatest(); $latestStable = $versionsUtil->getLatest('stable'); try { $latestPreview = $versionsUtil->getLatest('preview'); } catch (\UnexpectedValueException $e) { $latestPreview = $latestStable; } $latestVersion = $latest['version']; $updateVersion = $input->getArgument('version') ?? $latestVersion; $currentMajorVersion = Preg::replace('{^(\d+).*}', '$1', Composer::getVersion()); $updateMajorVersion = Preg::replace('{^(\d+).*}', '$1', $updateVersion); $previewMajorVersion = Preg::replace('{^(\d+).*}', '$1', $latestPreview['version']); if ($versionsUtil->getChannel() === 'stable' && null === $input->getArgument('version')) { // if requesting stable channel and no specific version, avoid automatically upgrading to the next major // simply output a warning that the next major stable is available and let users upgrade to it manually if ($currentMajorVersion < $updateMajorVersion) { $skippedVersion = $updateVersion; $versionsUtil->setChannel($currentMajorVersion); $latest = $versionsUtil->getLatest(); $latestStable = $versionsUtil->getLatest('stable'); $latestVersion = $latest['version']; $updateVersion = $latestVersion; $io->writeError('<warning>A new stable major version of Composer is available ('.$skippedVersion.'), run "composer self-update --'.$updateMajorVersion.'" to update to it. See also https://getcomposer.org/'.$updateMajorVersion.'</warning>'); } elseif ($currentMajorVersion < $previewMajorVersion) { // promote next major version if available in preview $io->writeError('<warning>A preview release of the next major version of Composer is available ('.$latestPreview['version'].'), run "composer self-update --preview" to give it a try. See also https://github.com/composer/composer/releases for changelogs.</warning>'); } } $effectiveChannel = $requestedChannel === null ? $versionsUtil->getChannel() : $requestedChannel; if (is_numeric($effectiveChannel) && strpos($latestStable['version'], $effectiveChannel) !== 0) { $io->writeError('<warning>Warning: You forced the install of '.$latestVersion.' via --'.$effectiveChannel.', but '.$latestStable['version'].' is the latest stable version. Updating to it via composer self-update --stable is recommended.</warning>'); } if (isset($latest['eol'])) { $io->writeError('<warning>Warning: Version '.$latestVersion.' is EOL / End of Life. '.$latestStable['version'].' is the latest stable version. Updating to it via composer self-update --stable is recommended.</warning>'); } if (Preg::isMatch('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) { $io->writeError('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>'); return 1; } $channelString = $versionsUtil->getChannel(); if (is_numeric($channelString)) { $channelString .= '.x'; } if (Composer::VERSION === $updateVersion) { $io->writeError( sprintf( '<info>You are already using the latest available Composer version %s (%s channel).</info>', $updateVersion, $channelString ) ); // remove all backups except for the most recent, if any if ($input->getOption('clean-backups')) { $this->cleanBackups($rollbackDir, $this->getLastBackupVersion($rollbackDir)); } return 0; } $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp'.random_int(0, 10000000).'.phar'; $backupFile = sprintf( '%s/%s-%s%s', $rollbackDir, strtr(Composer::RELEASE_DATE, ' :', '_-'), Preg::replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION), self::OLD_INSTALL_EXT ); $updatingToTag = !Preg::isMatch('{^[0-9a-f]{40}$}', $updateVersion); $io->write(sprintf("Upgrading to version <info>%s</info> (%s channel).", $updateVersion, $channelString)); $remoteFilename = $baseUrl . ($updatingToTag ? "/download/{$updateVersion}/composer.phar" : '/composer.phar'); try { $signature = $httpDownloader->get($remoteFilename.'.sig')->getBody(); } catch (TransportException $e) { if ($e->getStatusCode() === 404) { throw new \InvalidArgumentException('Version "'.$updateVersion.'" could not be found.', 0, $e); } throw $e; } $io->writeError(' ', false); $httpDownloader->copy($remoteFilename, $tempFilename); $io->writeError(''); if (!file_exists($tempFilename) || null === $signature || '' === $signature) { $io->writeError('<error>The download of the new composer version failed for an unexpected reason</error>'); return 1; } // verify phar signature if (!extension_loaded('openssl') && $config->get('disable-tls')) { $io->writeError('<warning>Skipping phar signature verification as you have disabled OpenSSL via config.disable-tls</warning>'); } else { if (!extension_loaded('openssl')) { throw new \RuntimeException('The openssl extension is required for phar signatures to be verified but it is not available. ' . 'If you can not enable the openssl extension, you can disable this error, at your own risk, by setting the \'disable-tls\' option to true.'); } $sigFile = 'file://'.$home.'/' . ($updatingToTag ? 'keys.tags.pub' : 'keys.dev.pub'); if (!file_exists($sigFile)) { file_put_contents( $home.'/keys.dev.pub', <<<DEVPUBKEY -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAnBDHjZS6e0ZMoK3xTD7f FNCzlXjX/Aie2dit8QXA03pSrOTbaMnxON3hUL47Lz3g1SC6YJEMVHr0zYq4elWi i3ecFEgzLcj+pZM5X6qWu2Ozz4vWx3JYo1/a/HYdOuW9e3lwS8VtS0AVJA+U8X0A hZnBmGpltHhO8hPKHgkJtkTUxCheTcbqn4wGHl8Z2SediDcPTLwqezWKUfrYzu1f o/j3WFwFs6GtK4wdYtiXr+yspBZHO3y1udf8eFFGcb2V3EaLOrtfur6XQVizjOuk 8lw5zzse1Qp/klHqbDRsjSzJ6iL6F4aynBc6Euqt/8ccNAIz0rLjLhOraeyj4eNn 8iokwMKiXpcrQLTKH+RH1JCuOVxQ436bJwbSsp1VwiqftPQieN+tzqy+EiHJJmGf TBAbWcncicCk9q2md+AmhNbvHO4PWbbz9TzC7HJb460jyWeuMEvw3gNIpEo2jYa9 pMV6cVqnSa+wOc0D7pC9a6bne0bvLcm3S+w6I5iDB3lZsb3A9UtRiSP7aGSo7D72 8tC8+cIgZcI7k9vjvOqH+d7sdOU2yPCnRY6wFh62/g8bDnUpr56nZN1G89GwM4d4 r/TU7BQQIzsZgAiqOGXvVklIgAMiV0iucgf3rNBLjjeNEwNSTTG9F0CtQ+7JLwaE wSEuAuRm+pRqi8BRnQ/GKUcCAwEAAQ== -----END PUBLIC KEY----- DEVPUBKEY ); file_put_contents( $home.'/keys.tags.pub', <<<TAGSPUBKEY -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA0Vi/2K6apCVj76nCnCl2 MQUPdK+A9eqkYBacXo2wQBYmyVlXm2/n/ZsX6pCLYPQTHyr5jXbkQzBw8SKqPdlh vA7NpbMeNCz7wP/AobvUXM8xQuXKbMDTY2uZ4O7sM+PfGbptKPBGLe8Z8d2sUnTO bXtX6Lrj13wkRto7st/w/Yp33RHe9SlqkiiS4MsH1jBkcIkEHsRaveZzedUaxY0M mba0uPhGUInpPzEHwrYqBBEtWvP97t2vtfx8I5qv28kh0Y6t+jnjL1Urid2iuQZf noCMFIOu4vksK5HxJxxrN0GOmGmwVQjOOtxkwikNiotZGPR4KsVj8NnBrLX7oGuM nQvGciiu+KoC2r3HDBrpDeBVdOWxDzT5R4iI0KoLzFh2pKqwbY+obNPS2bj+2dgJ rV3V5Jjry42QOCBN3c88wU1PKftOLj2ECpewY6vnE478IipiEu7EAdK8Zwj2LmTr RKQUSa9k7ggBkYZWAeO/2Ag0ey3g2bg7eqk+sHEq5ynIXd5lhv6tC5PBdHlWipDK tl2IxiEnejnOmAzGVivE1YGduYBjN+mjxDVy8KGBrjnz1JPgAvgdwJ2dYw4Rsc/e TzCFWGk/HM6a4f0IzBWbJ5ot0PIi4amk07IotBXDWwqDiQTwyuGCym5EqWQ2BD95 RGv89BPD+2DLnJysngsvVaUCAwEAAQ== -----END PUBLIC KEY----- TAGSPUBKEY ); } $pubkeyid = openssl_pkey_get_public($sigFile); if (false === $pubkeyid) { throw new \RuntimeException('Failed loading the public key from '.$sigFile); } $algo = defined('OPENSSL_ALGO_SHA384') ? OPENSSL_ALGO_SHA384 : 'SHA384'; if (!in_array('sha384', array_map('strtolower', openssl_get_md_methods()), true)) { throw new \RuntimeException('SHA384 is not supported by your openssl extension, could not verify the phar file integrity'); } $signatureData = json_decode($signature, true); $signatureSha384 = base64_decode($signatureData['sha384'], true); if (false === $signatureSha384) { throw new \RuntimeException('Failed loading the phar signature from '.$remoteFilename.'.sig, got '.$signature); } $verified = 1 === openssl_verify((string) file_get_contents($tempFilename), $signatureSha384, $pubkeyid, $algo); // PHP 8 automatically frees the key instance and deprecates the function if (\PHP_VERSION_ID < 80000) { // @phpstan-ignore function.deprecated openssl_free_key($pubkeyid); } if (!$verified) { throw new \RuntimeException('The phar signature did not match the file you downloaded, this means your public keys are outdated or that the phar file is corrupt/has been modified'); } } // remove saved installations of composer if ($input->getOption('clean-backups')) { $this->cleanBackups($rollbackDir); } if (!$this->setLocalPhar($localFilename, $tempFilename, $backupFile)) { @unlink($tempFilename); return 1; } if (file_exists($backupFile)) { $io->writeError(sprintf( 'Use <info>composer self-update --rollback</info> to return to version <comment>%s</comment>', Composer::VERSION )); } else { $io->writeError('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>'); } return 0; } /** * @throws \Exception */ 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'); } $io->write('Open <info>https://composer.github.io/pubkeys.html</info> to find the latest keys'); $validator = static function ($value): string { $value = (string) $value; if (!Preg::isMatch('{^-----BEGIN PUBLIC KEY-----$}', trim($value))) { throw new \UnexpectedValueException('Invalid input'); } return trim($value)."\n"; }; $devKey = ''; while (!Preg::isMatch('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $devKey, $match)) { $devKey = $io->askAndValidate('Enter Dev / Snapshot Public Key (including lines with -----): ', $validator); while ($line = $io->ask('', '')) { $devKey .= trim($line)."\n"; if (trim($line) === '-----END PUBLIC KEY-----') { break; } } } file_put_contents($keyPath = $config->get('home').'/keys.dev.pub', $match[0]); $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $tagsKey = ''; while (!Preg::isMatch('{(-----BEGIN PUBLIC KEY-----.+?-----END PUBLIC KEY-----)}s', $tagsKey, $match)) { $tagsKey = $io->askAndValidate('Enter Tags Public Key (including lines with -----): ', $validator); while ($line = $io->ask('', '')) { $tagsKey .= trim($line)."\n"; if (trim($line) === '-----END PUBLIC KEY-----') { break; } } } file_put_contents($keyPath = $config->get('home').'/keys.tags.pub', $match[0]); $io->write('Stored key with fingerprint: ' . Keys::fingerprint($keyPath)); $io->write('Public keys stored in '.$config->get('home')); } /** * @throws FilesystemException */ protected function rollback(OutputInterface $output, string $rollbackDir, string $localFilename): int { $rollbackVersion = $this->getLastBackupVersion($rollbackDir); if (null === $rollbackVersion) { throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"'); } $oldFile = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT; if (!is_file($oldFile)) { throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be found'); } if (!Filesystem::isReadable($oldFile)) { throw new FilesystemException('Composer rollback failed: "'.$oldFile.'" could not be read'); } $io = $this->getIO(); $io->writeError(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion)); if (!$this->setLocalPhar($localFilename, $oldFile)) { return 1; } return 0; } /** * Checks if the downloaded/rollback phar is valid then moves it * * @param string $localFilename The composer.phar location * @param string $newFilename The downloaded or backup phar * @param string $backupTarget The filename to use for the backup * @throws FilesystemException If the file cannot be moved * @return bool Whether the phar is valid and has been moved */ protected function setLocalPhar(string $localFilename, string $newFilename, ?string $backupTarget = null): bool { $io = $this->getIO(); $perms = @fileperms($localFilename); if ($perms !== false) { @chmod($newFilename, $perms); } // check phar validity if (!$this->validatePhar($newFilename, $error)) { $io->writeError('<error>The '.($backupTarget !== null ? 'update' : 'backup').' file is corrupted ('.$error.')</error>'); if ($backupTarget !== null) { $io->writeError('<error>Please re-run the self-update command to try again.</error>'); } return false; } // copy current file into backups dir if ($backupTarget !== null) { @copy($localFilename, $backupTarget); } try { if (Platform::isWindows()) { // use copy to apply permissions from the destination directory // as rename uses source permissions and may block other users copy($newFilename, $localFilename); @unlink($newFilename); } else { rename($newFilename, $localFilename); } return true; } catch (\Exception $e) { // see if we can run this operation as an Admin on Windows if (!is_writable(dirname($localFilename)) && $io->isInteractive() && $this->isWindowsNonAdminUser()) { return $this->tryAsWindowsAdmin($localFilename, $newFilename); } @unlink($newFilename); $action = 'Composer '.($backupTarget !== null ? 'update' : 'rollback'); throw new FilesystemException($action.' failed: "'.$localFilename.'" could not be written.'.PHP_EOL.$e->getMessage()); } } protected function cleanBackups(string $rollbackDir, ?string $except = null): void { $finder = $this->getOldInstallationFinder($rollbackDir); $io = $this->getIO(); $fs = new Filesystem; foreach ($finder as $file) { if ($file->getBasename(self::OLD_INSTALL_EXT) === $except) { continue; } $file = (string) $file; $io->writeError('<info>Removing: '.$file.'</info>'); $fs->remove($file); } } protected function getLastBackupVersion(string $rollbackDir): ?string { $finder = $this->getOldInstallationFinder($rollbackDir); $finder->sortByName(); $files = iterator_to_array($finder); if (count($files) > 0) { return end($files)->getBasename(self::OLD_INSTALL_EXT); } return null; } protected function getOldInstallationFinder(string $rollbackDir): Finder { return Finder::create() ->depth(0) ->files() ->name('*' . self::OLD_INSTALL_EXT) ->in($rollbackDir); } /** * Validates the downloaded/backup phar file * * @param string $pharFile The downloaded or backup phar * @param null|string $error Set by method on failure * * Code taken from getcomposer.org/installer. Any changes should be made * there and replicated here * * @throws \Exception * @return bool If the operation succeeded */ protected function validatePhar(string $pharFile, ?string &$error): bool { if ((bool) ini_get('phar.readonly')) { return true; } try { // Test the phar validity $phar = new Phar($pharFile); // Free the variable to unlock the file unset($phar); $result = true; } catch (\Exception $e) { if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) { throw $e; } $error = $e->getMessage(); $result = false; } return $result; } /** * Returns true if this is a non-admin Windows user account */ protected function isWindowsNonAdminUser(): bool { if (!Platform::isWindows()) { return false; } // fltmc.exe manages filter drivers and errors without admin privileges exec('fltmc.exe filters', $output, $exitCode); return $exitCode !== 0; } /** * Invokes a UAC prompt to update composer.phar as an admin * * Uses either sudo.exe or VBScript to elevate and run cmd.exe move. * * @param string $localFilename The composer.phar location * @param string $newFilename The downloaded or backup phar * @return bool Whether composer.phar has been updated */ protected function tryAsWindowsAdmin(string $localFilename, string $newFilename): bool { $io = $this->getIO(); $io->writeError('<error>Unable to write "'.$localFilename.'". Access is denied.</error>'); $helpMessage = 'Please run the self-update command as an Administrator.'; $question = 'Complete this operation with Administrator privileges [<comment>Y,n</comment>]? '; if (!$io->askConfirmation($question, true)) { $io->writeError('<warning>Operation cancelled. '.$helpMessage.'</warning>'); return false; } $tmpFile = tempnam(sys_get_temp_dir(), ''); if (false === $tmpFile) { $io->writeError('<error>Operation failed. '.$helpMessage.'</error>'); return false; } exec('sudo config 2> NUL', $output, $exitCode); $usingSudo = $exitCode === 0; $script = $usingSudo ? $tmpFile.'.bat' : $tmpFile.'.vbs'; rename($tmpFile, $script); $checksum = hash_file('sha256', $newFilename); // cmd's internal move is fussy about backslashes $source = str_replace('/', '\\', $newFilename); $destination = str_replace('/', '\\', $localFilename); if ($usingSudo) { $code = sprintf('move "%s" "%s"', $source, $destination); } else { $code = <<<EOT Set UAC = CreateObject("Shell.Application") UAC.ShellExecute "cmd.exe", "/c move /y ""$source"" ""$destination""", "", "runas", 0 EOT; } file_put_contents($script, $code); $command = $usingSudo ? sprintf('sudo "%s"', $script) : sprintf('"%s"', $script); exec($command); // Allow time for the operation to complete usleep(300000); @unlink($script); // see if the file was moved and is still accessible if ($result = Filesystem::isReadable($localFilename) && (hash_file('sha256', $localFilename) === $checksum)) { $io->writeError('<info>Operation succeeded.</info>'); } else { $io->writeError('<error>Operation failed. '.$helpMessage.'</error>'); } return $result; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/HomeCommand.php
src/Composer/Command/HomeCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Package\CompletePackageInterface; use Composer\Repository\RepositoryInterface; use Composer\Repository\RootPackageRepository; use Composer\Repository\RepositoryFactory; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Robert Schönthal <seroscho@googlemail.com> */ class HomeCommand extends BaseCommand { use CompletionTrait; /** * @inheritDoc */ protected function configure(): void { $this ->setName('browse') ->setAliases(['home']) ->setDescription('Opens the package\'s repository URL or homepage in your browser') ->setDefinition([ new InputArgument('packages', InputArgument::IS_ARRAY, 'Package(s) to browse to.', null, $this->suggestInstalledPackage()), new InputOption('homepage', 'H', InputOption::VALUE_NONE, 'Open the homepage instead of the repository URL.'), new InputOption('show', 's', InputOption::VALUE_NONE, 'Only show the homepage or repository URL.'), ]) ->setHelp( <<<EOT The home command opens or shows a package's repository URL or homepage in your default browser. To open the homepage by default, use -H or --homepage. To show instead of open the repository or homepage URL, use -s or --show. Read more at https://getcomposer.org/doc/03-cli.md#browse-home EOT ); } protected function execute(InputInterface $input, OutputInterface $output): int { $repos = $this->initializeRepos(); $io = $this->getIO(); $return = 0; $packages = $input->getArgument('packages'); if (count($packages) === 0) { $io->writeError('No package specified, opening homepage for the root package'); $packages = [$this->requireComposer()->getPackage()->getName()]; } foreach ($packages as $packageName) { $handled = false; $packageExists = false; foreach ($repos as $repo) { foreach ($repo->findPackages($packageName) as $package) { $packageExists = true; if ($package instanceof CompletePackageInterface && $this->handlePackage($package, $input->getOption('homepage'), $input->getOption('show'))) { $handled = true; break 2; } } } if (!$packageExists) { $return = 1; $io->writeError('<warning>Package '.$packageName.' not found</warning>'); } if (!$handled) { $return = 1; $io->writeError('<warning>'.($input->getOption('homepage') ? 'Invalid or missing homepage' : 'Invalid or missing repository URL').' for '.$packageName.'</warning>'); } } return $return; } private function handlePackage(CompletePackageInterface $package, bool $showHomepage, bool $showOnly): bool { $support = $package->getSupport(); $url = $support['source'] ?? $package->getSourceUrl(); if (!$url || $showHomepage) { $url = $package->getHomepage(); } if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) { return false; } if ($showOnly) { $this->getIO()->write(sprintf('<info>%s</info>', $url)); } else { $this->openBrowser($url); } return true; } /** * opens a url in your system default browser */ private function openBrowser(string $url): void { $process = new ProcessExecutor($this->getIO()); if (Platform::isWindows()) { $process->execute(['start', '"web"', 'explorer', $url], $output); return; } $linux = $process->execute(['which', 'xdg-open'], $output); $osx = $process->execute(['which', 'open'], $output); if (0 === $linux) { $process->execute(['xdg-open', $url], $output); } elseif (0 === $osx) { $process->execute(['open', $url], $output); } else { $this->getIO()->writeError('No suitable browser opening command found, open yourself: ' . $url); } } /** * Initializes repositories * * Returns an array of repos in order they should be checked in * * @return RepositoryInterface[] */ private function initializeRepos(): array { $composer = $this->tryComposer(); if ($composer) { return array_merge( [new RootPackageRepository(clone $composer->getPackage())], // root package [$composer->getRepositoryManager()->getLocalRepository()], // installed packages $composer->getRepositoryManager()->getRepositories() // remotes ); } return RepositoryFactory::defaultReposWithDefaultManager($this->getIO()); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ShowCommand.php
src/Composer/Command/ShowCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\DependencyResolver\DefaultPolicy; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Package\Link; use Composer\Package\AliasPackage; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; use Composer\Package\Version\VersionSelector; use Composer\Pcre\Preg; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\InstalledArrayRepository; use Composer\Repository\ComposerRepository; use Composer\Repository\CompositeRepository; use Composer\Repository\FilterRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Repository\InstalledRepository; use Composer\Repository\RepositoryInterface; use Composer\Repository\RepositorySet; use Composer\Repository\RepositoryUtils; use Composer\Repository\RootPackageRepository; use Composer\Semver\Constraint\ConstraintInterface; use Composer\Semver\Semver; use Composer\Spdx\SpdxLicenses; use Composer\Util\PackageInfo; use DateTimeInterface; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Robert Schönthal <seroscho@googlemail.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @author Jérémy Romey <jeremyFreeAgent> * @author Mihai Plasoianu <mihai@plasoianu.de> * * @phpstan-import-type AutoloadRules from PackageInterface * @phpstan-type JsonStructure array<string, null|string|array<string|null>|AutoloadRules> */ class ShowCommand extends BaseCommand { use CompletionTrait; /** @var VersionParser */ protected $versionParser; /** @var string[] */ protected $colors; /** @var ?RepositorySet */ private $repositorySet; protected function configure(): void { $this ->setName('show') ->setAliases(['info']) ->setDescription('Shows information about packages') ->setDefinition([ new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect. Or a name including a wildcard (*) to filter lists of packages instead.', null, $this->suggestPackageBasedOnMode()), new InputArgument('version', InputArgument::OPTIONAL, 'Version or version constraint to inspect'), new InputOption('all', null, InputOption::VALUE_NONE, 'List all packages'), new InputOption('locked', null, InputOption::VALUE_NONE, 'List all locked packages'), new InputOption('installed', 'i', InputOption::VALUE_NONE, 'List installed packages only (enabled by default, only present for BC).'), new InputOption('platform', 'p', InputOption::VALUE_NONE, 'List platform packages only'), new InputOption('available', 'a', InputOption::VALUE_NONE, 'List available packages only'), new InputOption('self', 's', InputOption::VALUE_NONE, 'Show the root package information'), new InputOption('name-only', 'N', InputOption::VALUE_NONE, 'List package names only'), new InputOption('path', 'P', InputOption::VALUE_NONE, 'Show package paths'), new InputOption('tree', 't', InputOption::VALUE_NONE, 'List the dependencies as a tree'), new InputOption('latest', 'l', InputOption::VALUE_NONE, 'Show the latest version'), new InputOption('outdated', 'o', InputOption::VALUE_NONE, 'Show the latest version but only for packages that are outdated'), new InputOption('ignore', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore specified package(s). Can contain wildcards (*). Use it with the --outdated option if you don\'t want to be informed about new versions of some packages.', null, $this->suggestInstalledPackage(false)), new InputOption('major-only', 'M', InputOption::VALUE_NONE, 'Show only packages that have major SemVer-compatible updates. Use with the --latest or --outdated option.'), new InputOption('minor-only', 'm', InputOption::VALUE_NONE, 'Show only packages that have minor SemVer-compatible updates. Use with the --latest or --outdated option.'), new InputOption('patch-only', null, InputOption::VALUE_NONE, 'Show only packages that have patch SemVer-compatible updates. Use with the --latest or --outdated option.'), new InputOption('sort-by-age', 'A', InputOption::VALUE_NONE, 'Displays the installed version\'s age, and sorts packages oldest first. Use with the --latest or --outdated option.'), new InputOption('direct', 'D', InputOption::VALUE_NONE, 'Shows only packages that are directly required by the root package'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code when there are outdated packages'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text', ['json', 'text']), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables search in require-dev packages.'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages). Use with the --outdated option'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages). Use with the --outdated option'), ]) ->setHelp( <<<EOT The show command displays detailed information about a package, or lists all packages available. Read more at https://getcomposer.org/doc/03-cli.md#show-info EOT ) ; } protected function suggestPackageBasedOnMode(): \Closure { return function (CompletionInput $input) { if ($input->getOption('available') || $input->getOption('all')) { return $this->suggestAvailablePackageInclPlatform()($input); } if ($input->getOption('platform')) { return $this->suggestPlatformPackage()($input); } return $this->suggestInstalledPackage(false)($input); }; } protected function execute(InputInterface $input, OutputInterface $output): int { $this->versionParser = new VersionParser; if ($input->getOption('tree')) { $this->initStyles($output); } $composer = $this->tryComposer(); $io = $this->getIO(); if ($input->getOption('installed') && !$input->getOption('self')) { $io->writeError('<warning>You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages.</warning>'); } if ($input->getOption('outdated')) { $input->setOption('latest', true); } elseif (count($input->getOption('ignore')) > 0) { $io->writeError('<warning>You are using the option "ignore" for action other than "outdated", it will be ignored.</warning>'); } if ($input->getOption('direct') && ($input->getOption('all') || $input->getOption('available') || $input->getOption('platform'))) { $io->writeError('The --direct (-D) option is not usable in combination with --all, --platform (-p) or --available (-a)'); return 1; } if ($input->getOption('tree') && ($input->getOption('all') || $input->getOption('available'))) { $io->writeError('The --tree (-t) option is not usable in combination with --all or --available (-a)'); return 1; } if (count(array_filter([$input->getOption('patch-only'), $input->getOption('minor-only'), $input->getOption('major-only')])) > 1) { $io->writeError('Only one of --major-only, --minor-only or --patch-only can be used at once'); return 1; } if ($input->getOption('tree') && $input->getOption('latest')) { $io->writeError('The --tree (-t) option is not usable in combination with --latest (-l)'); return 1; } if ($input->getOption('tree') && $input->getOption('path')) { $io->writeError('The --tree (-t) option is not usable in combination with --path (-P)'); return 1; } $format = $input->getOption('format'); if (!in_array($format, ['text', 'json'])) { $io->writeError(sprintf('Unsupported format "%s". See help for supported formats.', $format)); return 1; } $platformReqFilter = $this->getPlatformRequirementFilter($input); // init repos $platformOverrides = []; if ($composer) { $platformOverrides = $composer->getConfig()->get('platform'); } $platformRepo = new PlatformRepository([], $platformOverrides); $lockedRepo = null; if ($input->getOption('self') && !$input->getOption('installed') && !$input->getOption('locked')) { $package = clone $this->requireComposer()->getPackage(); if ($input->getOption('name-only')) { $io->write($package->getName()); return 0; } if ($input->getArgument('package')) { throw new \InvalidArgumentException('You cannot use --self together with a package name'); } $repos = $installedRepo = new InstalledRepository([new RootPackageRepository($package)]); } elseif ($input->getOption('platform')) { $repos = $installedRepo = new InstalledRepository([$platformRepo]); } elseif ($input->getOption('available')) { $installedRepo = new InstalledRepository([$platformRepo]); if ($composer) { $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories()); $installedRepo->addRepository($composer->getRepositoryManager()->getLocalRepository()); } else { $defaultRepos = RepositoryFactory::defaultReposWithDefaultManager($io); $repos = new CompositeRepository($defaultRepos); $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos))); } } elseif ($input->getOption('all') && $composer) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $locker = $composer->getLocker(); if ($locker->isLocked()) { $lockedRepo = $locker->getLockedRepository(true); $installedRepo = new InstalledRepository([$lockedRepo, $localRepo, $platformRepo]); } else { $installedRepo = new InstalledRepository([$localRepo, $platformRepo]); } $repos = new CompositeRepository(array_merge([new FilterRepository($installedRepo, ['canonical' => false])], $composer->getRepositoryManager()->getRepositories())); } elseif ($input->getOption('all')) { $defaultRepos = RepositoryFactory::defaultReposWithDefaultManager($io); $io->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos))); $installedRepo = new InstalledRepository([$platformRepo]); $repos = new CompositeRepository(array_merge([$installedRepo], $defaultRepos)); } elseif ($input->getOption('locked')) { if (!$composer || !$composer->getLocker()->isLocked()) { throw new \UnexpectedValueException('A valid composer.json and composer.lock files is required to run this command with --locked'); } $locker = $composer->getLocker(); $lockedRepo = $locker->getLockedRepository(!$input->getOption('no-dev')); if ($input->getOption('self')) { $lockedRepo->addPackage(clone $composer->getPackage()); } $repos = $installedRepo = new InstalledRepository([$lockedRepo]); } else { // --installed / default case if (!$composer) { $composer = $this->requireComposer(); } $rootPkg = $composer->getPackage(); $rootRepo = new InstalledArrayRepository(); if ($input->getOption('self')) { $rootRepo = new RootPackageRepository(clone $rootPkg); } if ($input->getOption('no-dev')) { $packages = RepositoryUtils::filterRequiredPackages($composer->getRepositoryManager()->getLocalRepository()->getPackages(), $rootPkg); $repos = $installedRepo = new InstalledRepository([$rootRepo, new InstalledArrayRepository(array_map(static function ($pkg): PackageInterface { return clone $pkg; }, $packages))]); } else { $repos = $installedRepo = new InstalledRepository([$rootRepo, $composer->getRepositoryManager()->getLocalRepository()]); } if (!$installedRepo->getPackages()) { $hasNonPlatformReqs = static function (array $reqs): bool { return (bool) array_filter(array_keys($reqs), static function (string $name) { return !PlatformRepository::isPlatformPackage($name); }); }; if ($hasNonPlatformReqs($rootPkg->getRequires()) || $hasNonPlatformReqs($rootPkg->getDevRequires())) { $io->writeError('<warning>No dependencies installed. Try running composer install or update.</warning>'); } } } if ($composer) { $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'show', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); } if ($input->getOption('latest') && null === $composer) { $io->writeError('No composer.json found in the current directory, disabling "latest" option'); $input->setOption('latest', false); } $packageFilter = $input->getArgument('package'); // show single package or single version if (isset($package)) { $versions = [$package->getPrettyVersion() => $package->getVersion()]; } elseif (null !== $packageFilter && !str_contains($packageFilter, '*')) { [$package, $versions] = $this->getPackage($installedRepo, $repos, $packageFilter, $input->getArgument('version')); if (isset($package) && $input->getOption('direct')) { if (!in_array($package->getName(), $this->getRootRequires(), true)) { throw new \InvalidArgumentException('Package "' . $package->getName() . '" is installed but not a direct dependent of the root package.'); } } if (!isset($package)) { $options = $input->getOptions(); $hint = ''; if ($input->getOption('locked')) { $hint .= ' in lock file'; } if (isset($options['working-dir'])) { $hint .= ' in ' . $options['working-dir'] . '/composer.json'; } if (PlatformRepository::isPlatformPackage($packageFilter) && !$input->getOption('platform')) { $hint .= ', try using --platform (-p) to show platform packages'; } if (!$input->getOption('all') && !$input->getOption('available')) { $hint .= ', try using --available (-a) to show all available packages'; } throw new \InvalidArgumentException('Package "' . $packageFilter . '" not found'.$hint.'.'); } } if (isset($package)) { assert(isset($versions)); $exitCode = 0; if ($input->getOption('tree')) { $arrayTree = $this->generatePackageTree($package, $installedRepo, $repos); if ('json' === $format) { $io->write(JsonFile::encode(['installed' => [$arrayTree]])); } else { $this->displayPackageTree([$arrayTree]); } return $exitCode; } $latestPackage = null; if ($input->getOption('latest')) { $latestPackage = $this->findLatestPackage($package, $composer, $platformRepo, $input->getOption('major-only'), $input->getOption('minor-only'), $input->getOption('patch-only'), $platformReqFilter); } if ( $input->getOption('outdated') && $input->getOption('strict') && null !== $latestPackage && $latestPackage->getFullPrettyVersion() !== $package->getFullPrettyVersion() && (!$latestPackage instanceof CompletePackageInterface || !$latestPackage->isAbandoned()) ) { $exitCode = 1; } if ($input->getOption('path')) { $io->write($package->getName(), false); $path = $composer->getInstallationManager()->getInstallPath($package); if (is_string($path)) { $io->write(' ' . strtok(realpath($path), "\r\n")); } else { $io->write(' null'); } return $exitCode; } if ('json' === $format) { $this->printPackageInfoAsJson($package, $versions, $installedRepo, $latestPackage ?: null); } else { $this->printPackageInfo($package, $versions, $installedRepo, $latestPackage ?: null); } return $exitCode; } // show tree view if requested if ($input->getOption('tree')) { $rootRequires = $this->getRootRequires(); $packages = $installedRepo->getPackages(); usort($packages, static function (BasePackage $a, BasePackage $b): int { return strcmp((string) $a, (string) $b); }); $arrayTree = []; foreach ($packages as $package) { if (in_array($package->getName(), $rootRequires, true)) { $arrayTree[] = $this->generatePackageTree($package, $installedRepo, $repos); } } if ('json' === $format) { $io->write(JsonFile::encode(['installed' => $arrayTree])); } else { $this->displayPackageTree($arrayTree); } return 0; } // list packages /** @var array<string, array<string, string|CompletePackageInterface>> $packages */ $packages = []; $packageFilterRegex = null; if (null !== $packageFilter) { $packageFilterRegex = '{^'.str_replace('\\*', '.*?', preg_quote($packageFilter)).'$}i'; } $packageListFilter = null; if ($input->getOption('direct')) { $packageListFilter = $this->getRootRequires(); } if ($input->getOption('path') && null === $composer) { $io->writeError('No composer.json found in the current directory, disabling "path" option'); $input->setOption('path', false); } foreach (RepositoryUtils::flattenRepositories($repos) as $repo) { if ($repo === $platformRepo) { $type = 'platform'; } elseif ($lockedRepo !== null && $repo === $lockedRepo) { $type = 'locked'; } elseif ($repo === $installedRepo || in_array($repo, $installedRepo->getRepositories(), true)) { $type = 'installed'; } else { $type = 'available'; } if ($repo instanceof ComposerRepository) { foreach ($repo->getPackageNames($packageFilter) as $name) { $packages[$type][$name] = $name; } } else { foreach ($repo->getPackages() as $package) { if (!isset($packages[$type][$package->getName()]) || !is_object($packages[$type][$package->getName()]) || version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<') ) { while ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } if (!$packageFilterRegex || Preg::isMatch($packageFilterRegex, $package->getName())) { if (null === $packageListFilter || in_array($package->getName(), $packageListFilter, true)) { $packages[$type][$package->getName()] = $package; } } } } if ($repo === $platformRepo) { foreach ($platformRepo->getDisabledPackages() as $name => $package) { $packages[$type][$name] = $package; } } } } $showAllTypes = $input->getOption('all'); $showLatest = $input->getOption('latest'); $showMajorOnly = $input->getOption('major-only'); $showMinorOnly = $input->getOption('minor-only'); $showPatchOnly = $input->getOption('patch-only'); $ignoredPackagesRegex = BasePackage::packageNamesToRegexp(array_map('strtolower', $input->getOption('ignore'))); $indent = $showAllTypes ? ' ' : ''; /** @var PackageInterface[] $latestPackages */ $latestPackages = []; $exitCode = 0; $viewData = []; $viewMetaData = []; $writeVersion = false; $writeDescription = false; foreach (['platform' => true, 'locked' => true, 'available' => false, 'installed' => true] as $type => $showVersion) { if (isset($packages[$type])) { ksort($packages[$type]); $nameLength = $versionLength = $latestLength = $releaseDateLength = 0; if ($showLatest && $showVersion) { foreach ($packages[$type] as $package) { if (is_object($package) && !Preg::isMatch($ignoredPackagesRegex, $package->getPrettyName())) { $latestPackage = $this->findLatestPackage($package, $composer, $platformRepo, $showMajorOnly, $showMinorOnly, $showPatchOnly, $platformReqFilter); if ($latestPackage === null) { continue; } $latestPackages[$package->getPrettyName()] = $latestPackage; } } } $writePath = !$input->getOption('name-only') && $input->getOption('path'); $writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion; $writeLatest = $writeVersion && $showLatest; $writeDescription = !$input->getOption('name-only') && !$input->getOption('path'); $writeReleaseDate = $writeLatest && ($input->getOption('sort-by-age') || $format === 'json'); $hasOutdatedPackages = false; if ($input->getOption('sort-by-age')) { usort($packages[$type], static function ($a, $b) { if (is_object($a) && is_object($b)) { return $a->getReleaseDate() <=> $b->getReleaseDate(); } return 0; }); } $viewData[$type] = []; foreach ($packages[$type] as $package) { $packageViewData = []; if (is_object($package)) { $latestPackage = null; if ($showLatest && isset($latestPackages[$package->getPrettyName()])) { $latestPackage = $latestPackages[$package->getPrettyName()]; } // Determine if Composer is checking outdated dependencies and if current package should trigger non-default exit code $packageIsUpToDate = $latestPackage && $latestPackage->getFullPrettyVersion() === $package->getFullPrettyVersion() && (!$latestPackage instanceof CompletePackageInterface || !$latestPackage->isAbandoned()); // When using --major-only, and no bigger version than current major is found then it is considered up to date $packageIsUpToDate = $packageIsUpToDate || ($latestPackage === null && $showMajorOnly); $packageIsIgnored = Preg::isMatch($ignoredPackagesRegex, $package->getPrettyName()); if ($input->getOption('outdated') && ($packageIsUpToDate || $packageIsIgnored)) { continue; } if ($input->getOption('outdated') || $input->getOption('strict')) { $hasOutdatedPackages = true; } $packageViewData['name'] = $package->getPrettyName(); $packageViewData['direct-dependency'] = in_array($package->getName(), $this->getRootRequires(), true); if ($format !== 'json' || true !== $input->getOption('name-only')) { $packageViewData['homepage'] = $package instanceof CompletePackageInterface ? $package->getHomepage() : null; $packageViewData['source'] = PackageInfo::getViewSourceUrl($package); } $nameLength = max($nameLength, strlen($packageViewData['name'])); if ($writeVersion) { $packageViewData['version'] = $package->getFullPrettyVersion(); if ($format === 'text') { $packageViewData['version'] = ltrim($packageViewData['version'], 'v'); } $versionLength = max($versionLength, strlen($packageViewData['version'])); } if ($writeReleaseDate) { if ($package->getReleaseDate() !== null) { $packageViewData['release-age'] = str_replace(' ago', ' old', $this->getRelativeTime($package->getReleaseDate())); if (!str_contains($packageViewData['release-age'], ' old')) { $packageViewData['release-age'] = 'from '.$packageViewData['release-age']; } $releaseDateLength = max($releaseDateLength, strlen($packageViewData['release-age'])); $packageViewData['release-date'] = $package->getReleaseDate()->format(DateTimeInterface::ATOM); } else { $packageViewData['release-age'] = ''; $packageViewData['release-date'] = ''; } } if ($writeLatest && $latestPackage) { $packageViewData['latest'] = $latestPackage->getFullPrettyVersion(); if ($format === 'text') { $packageViewData['latest'] = ltrim($packageViewData['latest'], 'v'); } $packageViewData['latest-status'] = $this->getUpdateStatus($latestPackage, $package); $latestLength = max($latestLength, strlen($packageViewData['latest'])); if ($latestPackage->getReleaseDate() !== null) { $packageViewData['latest-release-date'] = $latestPackage->getReleaseDate()->format(DateTimeInterface::ATOM); } else { $packageViewData['latest-release-date'] = ''; } } elseif ($writeLatest) { $packageViewData['latest'] = '[none matched]'; $packageViewData['latest-status'] = 'up-to-date'; $latestLength = max($latestLength, strlen($packageViewData['latest'])); } if ($writeDescription && $package instanceof CompletePackageInterface) { $packageViewData['description'] = $package->getDescription(); } if ($writePath) { $path = $composer->getInstallationManager()->getInstallPath($package); if (is_string($path)) { $packageViewData['path'] = strtok(realpath($path), "\r\n"); } else { $packageViewData['path'] = null; } } $packageIsAbandoned = false; if ($latestPackage instanceof CompletePackageInterface && $latestPackage->isAbandoned()) { $replacementPackageName = $latestPackage->getReplacementPackage(); $replacement = $replacementPackageName !== null ? 'Use ' . $latestPackage->getReplacementPackage() . ' instead' : 'No replacement was suggested'; $packageWarning = sprintf( 'Package %s is abandoned, you should avoid using it. %s.', $package->getPrettyName(), $replacement ); $packageViewData['warning'] = $packageWarning; $packageIsAbandoned = $replacementPackageName ?? true; } $packageViewData['abandoned'] = $packageIsAbandoned; } else { $packageViewData['name'] = $package; $nameLength = max($nameLength, strlen($package)); } $viewData[$type][] = $packageViewData; } $viewMetaData[$type] = [ 'nameLength' => $nameLength, 'versionLength' => $versionLength, 'latestLength' => $latestLength, 'releaseDateLength' => $releaseDateLength, 'writeLatest' => $writeLatest, 'writeReleaseDate' => $writeReleaseDate, ]; if ($input->getOption('strict') && $hasOutdatedPackages) { $exitCode = 1; break; } } } if ('json' === $format) { $io->write(JsonFile::encode($viewData)); } else { if ($input->getOption('latest') && array_filter($viewData)) { if (!$io->isDecorated()) { $io->writeError('Legend:'); $io->writeError('! patch or minor release available - update recommended'); $io->writeError('~ major release available - update possible'); if (!$input->getOption('outdated')) { $io->writeError('= up to date version'); } } else {
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/StatusCommand.php
src/Composer/Command/StatusCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Downloader\ChangeReportInterface; use Composer\Downloader\DvcsDownloaderInterface; use Composer\Downloader\VcsCapableDownloaderInterface; use Composer\Package\Dumper\ArrayDumper; use Composer\Package\Version\VersionGuesser; use Composer\Package\Version\VersionParser; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Script\ScriptEvents; use Composer\Util\ProcessExecutor; /** * @author Tiago Ribeiro <tiago.ribeiro@seegno.com> * @author Rui Marinho <rui.marinho@seegno.com> */ class StatusCommand extends BaseCommand { private const EXIT_CODE_ERRORS = 1; private const EXIT_CODE_UNPUSHED_CHANGES = 2; private const EXIT_CODE_VERSION_CHANGES = 4; /** * @throws \Symfony\Component\Console\Exception\InvalidArgumentException */ protected function configure(): void { $this ->setName('status') ->setDescription('Shows a list of locally modified packages') ->setDefinition([ new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Show modified files for each directory that contains changes.'), ]) ->setHelp( <<<EOT The status command displays a list of dependencies that have been modified locally. Read more at https://getcomposer.org/doc/03-cli.md#status EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'status', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); // Dispatch pre-status-command $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_STATUS_CMD, true); $exitCode = $this->doExecute($input); // Dispatch post-status-command $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_STATUS_CMD, true); return $exitCode; } private function doExecute(InputInterface $input): int { // init repos $composer = $this->requireComposer(); $installedRepo = $composer->getRepositoryManager()->getLocalRepository(); $dm = $composer->getDownloadManager(); $im = $composer->getInstallationManager(); $errors = []; $io = $this->getIO(); $unpushedChanges = []; $vcsVersionChanges = []; $parser = new VersionParser; $guesser = new VersionGuesser($composer->getConfig(), $composer->getLoop()->getProcessExecutor() ?? new ProcessExecutor($io), $parser, $io); $dumper = new ArrayDumper; // list packages foreach ($installedRepo->getCanonicalPackages() as $package) { $downloader = $dm->getDownloaderForPackage($package); $targetDir = $im->getInstallPath($package); if ($targetDir === null) { continue; } if ($downloader instanceof ChangeReportInterface) { if (is_link($targetDir)) { $errors[$targetDir] = $targetDir . ' is a symbolic link.'; } if (null !== ($changes = $downloader->getLocalChanges($package, $targetDir))) { $errors[$targetDir] = $changes; } } if ($downloader instanceof VcsCapableDownloaderInterface) { if ($downloader->getVcsReference($package, $targetDir)) { switch ($package->getInstallationSource()) { case 'source': $previousRef = $package->getSourceReference(); break; case 'dist': $previousRef = $package->getDistReference(); break; default: $previousRef = null; } $currentVersion = $guesser->guessVersion($dumper->dump($package), $targetDir); if ($previousRef && $currentVersion && $currentVersion['commit'] !== $previousRef && $currentVersion['pretty_version'] !== $previousRef) { $vcsVersionChanges[$targetDir] = [ 'previous' => [ 'version' => $package->getPrettyVersion(), 'ref' => $previousRef, ], 'current' => [ 'version' => $currentVersion['pretty_version'], 'ref' => $currentVersion['commit'], ], ]; } } } if ($downloader instanceof DvcsDownloaderInterface) { if ($unpushed = $downloader->getUnpushedChanges($package, $targetDir)) { $unpushedChanges[$targetDir] = $unpushed; } } } // output errors/warnings if (!$errors && !$unpushedChanges && !$vcsVersionChanges) { $io->writeError('<info>No local changes</info>'); return 0; } if ($errors) { $io->writeError('<error>You have changes in the following dependencies:</error>'); foreach ($errors as $path => $changes) { if ($input->getOption('verbose')) { $indentedChanges = implode("\n", array_map(static function ($line): string { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write('<info>'.$path.'</info>:'); $io->write($indentedChanges); } else { $io->write($path); } } } if ($unpushedChanges) { $io->writeError('<warning>You have unpushed changes on the current branch in the following dependencies:</warning>'); foreach ($unpushedChanges as $path => $changes) { if ($input->getOption('verbose')) { $indentedChanges = implode("\n", array_map(static function ($line): string { return ' ' . ltrim($line); }, explode("\n", $changes))); $io->write('<info>'.$path.'</info>:'); $io->write($indentedChanges); } else { $io->write($path); } } } if ($vcsVersionChanges) { $io->writeError('<warning>You have version variations in the following dependencies:</warning>'); foreach ($vcsVersionChanges as $path => $changes) { if ($input->getOption('verbose')) { // If we don't can't find a version, use the ref instead. $currentVersion = $changes['current']['version'] ?: $changes['current']['ref']; $previousVersion = $changes['previous']['version'] ?: $changes['previous']['ref']; if ($io->isVeryVerbose()) { // Output the ref regardless of whether or not it's being used as the version $currentVersion .= sprintf(' (%s)', $changes['current']['ref']); $previousVersion .= sprintf(' (%s)', $changes['previous']['ref']); } $io->write('<info>'.$path.'</info>:'); $io->write(sprintf(' From <comment>%s</comment> to <comment>%s</comment>', $previousVersion, $currentVersion)); } else { $io->write($path); } } } if (($errors || $unpushedChanges || $vcsVersionChanges) && !$input->getOption('verbose')) { $io->writeError('Use --verbose (-v) to see a list of files'); } return ($errors ? self::EXIT_CODE_ERRORS : 0) + ($unpushedChanges ? self::EXIT_CODE_UNPUSHED_CHANGES : 0) + ($vcsVersionChanges ? self::EXIT_CODE_VERSION_CHANGES : 0); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ConfigCommand.php
src/Composer/Command/ConfigCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Advisory\Auditor; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Config; use Composer\Config\JsonConfigSource; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Semver\VersionParser; use Composer\Package\BasePackage; /** * @author Joshua Estes <Joshua.Estes@iostudio.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class ConfigCommand extends BaseConfigCommand { /** * List of additional configurable package-properties * * @var string[] */ protected const CONFIGURABLE_PACKAGE_PROPERTIES = [ 'name', 'type', 'description', 'homepage', 'version', 'minimum-stability', 'prefer-stable', 'keywords', 'license', 'repositories', 'suggest', 'extra', ]; /** * @var JsonFile */ protected $authConfigFile; /** * @var JsonConfigSource */ protected $authConfigSource; protected function configure(): void { $this ->setName('config') ->setDescription('Sets config options') ->setDefinition([ new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'), new InputOption('editor', 'e', InputOption::VALUE_NONE, 'Open editor'), new InputOption('auth', 'a', InputOption::VALUE_NONE, 'Affect auth config file (only used for --editor)'), new InputOption('unset', null, InputOption::VALUE_NONE, 'Unset the given setting-key'), new InputOption('list', 'l', InputOption::VALUE_NONE, 'List configuration settings'), new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json'), new InputOption('absolute', null, InputOption::VALUE_NONE, 'Returns absolute paths when fetching *-dir config values instead of relative'), new InputOption('json', 'j', InputOption::VALUE_NONE, 'JSON decode the setting value, to be used with extra.* keys'), new InputOption('merge', 'm', InputOption::VALUE_NONE, 'Merge the setting value with the current value, to be used with extra.* or audit.ignore[-abandoned] keys in combination with --json'), new InputOption('append', null, InputOption::VALUE_NONE, 'When adding a repository, append it (lowest priority) to the existing ones instead of prepending it (highest priority)'), new InputOption('source', null, InputOption::VALUE_NONE, 'Display where the config value is loaded from'), new InputArgument('setting-key', null, 'Setting key', null, $this->suggestSettingKeys()), new InputArgument('setting-value', InputArgument::IS_ARRAY, 'Setting value'), ]) ->setHelp( <<<EOT This command allows you to edit composer config settings and repositories in either the local composer.json file or the global config.json file. Additionally it lets you edit most properties in the local composer.json. To set a config setting: <comment>%command.full_name% bin-dir bin/</comment> To read a config setting: <comment>%command.full_name% bin-dir</comment> Outputs: <info>bin</info> To edit the global config.json file: <comment>%command.full_name% --global</comment> To add a repository: <comment>%command.full_name% repositories.foo vcs https://bar.com</comment> To remove a repository (repo is a short alias for repositories): <comment>%command.full_name% --unset repo.foo</comment> To disable packagist.org: <comment>%command.full_name% repo.packagist.org false</comment> You can alter repositories in the global config.json file by passing in the <info>--global</info> option. To add or edit suggested packages you can use: <comment>%command.full_name% suggest.package reason for the suggestion</comment> To add or edit extra properties you can use: <comment>%command.full_name% extra.property value</comment> Or to add a complex value you can use json with: <comment>%command.full_name% extra.property --json '{"foo":true, "bar": []}'</comment> To edit the file in an external editor: <comment>%command.full_name% --editor</comment> To choose your editor you can set the "EDITOR" env variable. To get a list of configuration values in the file: <comment>%command.full_name% --list</comment> You can always pass more than one option. As an example, if you want to edit the global config.json file. <comment>%command.full_name% --editor --global</comment> Read more at https://getcomposer.org/doc/03-cli.md#config EOT ) ; } /** * @throws \Exception */ protected function initialize(InputInterface $input, OutputInterface $output): void { parent::initialize($input, $output); $authConfigFile = $this->getAuthConfigFile($input, $this->config); $this->authConfigFile = new JsonFile($authConfigFile, null, $this->getIO()); $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true); // Initialize the global file if it's not there, ignoring any warnings or notices if ($input->getOption('global') && !$this->authConfigFile->exists()) { touch($this->authConfigFile->getPath()); $this->authConfigFile->write(['bitbucket-oauth' => new \ArrayObject, 'github-oauth' => new \ArrayObject, 'gitlab-oauth' => new \ArrayObject, 'gitlab-token' => new \ArrayObject, 'http-basic' => new \ArrayObject, 'bearer' => new \ArrayObject, 'forgejo-token' => new \ArrayObject()]); Silencer::call('chmod', $this->authConfigFile->getPath(), 0600); } } /** * @throws \Seld\JsonLint\ParsingException */ protected function execute(InputInterface $input, OutputInterface $output): int { // Open file in editor if (true === $input->getOption('editor')) { $editor = Platform::getEnv('EDITOR'); if (false === $editor || '' === $editor) { if (Platform::isWindows()) { $editor = 'notepad'; } else { foreach (['editor', 'vim', 'vi', 'nano', 'pico', 'ed'] as $candidate) { if (exec('which '.$candidate)) { $editor = $candidate; break; } } } } else { $editor = escapeshellcmd($editor); } $file = $input->getOption('auth') ? $this->authConfigFile->getPath() : $this->configFile->getPath(); system($editor . ' ' . $file . (Platform::isWindows() ? '' : ' > `tty`')); return 0; } if (false === $input->getOption('global')) { $this->config->merge($this->configFile->read(), $this->configFile->getPath()); $this->config->merge(['config' => $this->authConfigFile->exists() ? $this->authConfigFile->read() : []], $this->authConfigFile->getPath()); } $this->getIO()->loadConfiguration($this->config); // List the configuration of the file settings if (true === $input->getOption('list')) { $this->listConfiguration($this->config->all(), $this->config->raw(), $output, null, $input->getOption('source')); return 0; } $settingKey = $input->getArgument('setting-key'); if (!is_string($settingKey)) { return 0; } // If the user enters in a config variable, parse it and save to file if ([] !== $input->getArgument('setting-value') && $input->getOption('unset')) { throw new \RuntimeException('You can not combine a setting value with --unset'); } // show the value if no value is provided if ([] === $input->getArgument('setting-value') && !$input->getOption('unset')) { $properties = self::CONFIGURABLE_PACKAGE_PROPERTIES; $propertiesDefaults = [ 'type' => 'library', 'description' => '', 'homepage' => '', 'minimum-stability' => 'stable', 'prefer-stable' => false, 'keywords' => [], 'license' => [], 'suggest' => [], 'extra' => [], ]; $rawData = $this->configFile->read(); $data = $this->config->all(); $source = $this->config->getSourceOfValue($settingKey); if (Preg::isMatch('/^repos?(?:itories)?(?:\.(.+))?/', $settingKey, $matches)) { if (!isset($matches[1])) { $value = $data['repositories'] ?? []; } else { if (!isset($data['repositories'][$matches[1]])) { throw new \InvalidArgumentException('There is no '.$matches[1].' repository defined'); } $value = $data['repositories'][$matches[1]]; } } elseif (strpos($settingKey, '.')) { $bits = explode('.', $settingKey); if ($bits[0] === 'extra' || $bits[0] === 'suggest') { $data = $rawData; } else { $data = $data['config']; } $match = false; foreach ($bits as $bit) { $key = isset($key) ? $key.'.'.$bit : $bit; $match = false; if (isset($data[$key])) { $match = true; $data = $data[$key]; unset($key); } } if (!$match) { throw new \RuntimeException($settingKey.' is not defined.'); } $value = $data; } elseif (isset($data['config'][$settingKey])) { $value = $this->config->get($settingKey, $input->getOption('absolute') ? 0 : Config::RELATIVE_PATHS); // ensure we get {} output for properties which are objects if ($value === []) { $schema = JsonFile::parseJson((string) file_get_contents(JsonFile::COMPOSER_SCHEMA_PATH)); if ( isset($schema['properties']['config']['properties'][$settingKey]['type']) && in_array('object', (array) $schema['properties']['config']['properties'][$settingKey]['type'], true) ) { $value = new \stdClass; } } } elseif (isset($rawData[$settingKey]) && in_array($settingKey, $properties, true)) { $value = $rawData[$settingKey]; $source = $this->configFile->getPath(); } elseif (isset($propertiesDefaults[$settingKey])) { $value = $propertiesDefaults[$settingKey]; $source = 'defaults'; } else { throw new \RuntimeException($settingKey.' is not defined'); } if (is_array($value) || is_object($value) || is_bool($value)) { $value = JsonFile::encode($value, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); } $sourceOfConfigValue = ''; if ($input->getOption('source')) { $sourceOfConfigValue = ' (' . $source . ')'; } $this->getIO()->write($value . $sourceOfConfigValue, true, IOInterface::QUIET); return 0; } $values = $input->getArgument('setting-value'); // what the user is trying to add/change $booleanValidator = static function ($val): bool { return in_array($val, ['true', 'false', '1', '0'], true); }; $booleanNormalizer = static function ($val): bool { return $val !== 'false' && (bool) $val; }; // handle config values $uniqueConfigValues = [ 'process-timeout' => ['is_numeric', 'intval'], 'use-include-path' => [$booleanValidator, $booleanNormalizer], 'use-github-api' => [$booleanValidator, $booleanNormalizer], 'preferred-install' => [ static function ($val): bool { return in_array($val, ['auto', 'source', 'dist'], true); }, static function ($val) { return $val; }, ], 'gitlab-protocol' => [ static function ($val): bool { return in_array($val, ['git', 'http', 'https'], true); }, static function ($val) { return $val; }, ], 'store-auths' => [ static function ($val): bool { return in_array($val, ['true', 'false', 'prompt'], true); }, static function ($val) { if ('prompt' === $val) { return 'prompt'; } return $val !== 'false' && (bool) $val; }, ], 'notify-on-install' => [$booleanValidator, $booleanNormalizer], 'vendor-dir' => ['is_string', static function ($val) { return $val; }], 'bin-dir' => ['is_string', static function ($val) { return $val; }], 'archive-dir' => ['is_string', static function ($val) { return $val; }], 'archive-format' => ['is_string', static function ($val) { return $val; }], 'data-dir' => ['is_string', static function ($val) { return $val; }], 'cache-dir' => ['is_string', static function ($val) { return $val; }], 'cache-files-dir' => ['is_string', static function ($val) { return $val; }], 'cache-repo-dir' => ['is_string', static function ($val) { return $val; }], 'cache-vcs-dir' => ['is_string', static function ($val) { return $val; }], 'cache-ttl' => ['is_numeric', 'intval'], 'cache-files-ttl' => ['is_numeric', 'intval'], 'cache-files-maxsize' => [ static function ($val): bool { return Preg::isMatch('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val); }, static function ($val) { return $val; }, ], 'bin-compat' => [ static function ($val): bool { return in_array($val, ['auto', 'full', 'proxy', 'symlink']); }, static function ($val) { return $val; }, ], 'discard-changes' => [ static function ($val): bool { return in_array($val, ['stash', 'true', 'false', '1', '0'], true); }, static function ($val) { if ('stash' === $val) { return 'stash'; } return $val !== 'false' && (bool) $val; }, ], 'autoloader-suffix' => ['is_string', static function ($val) { return $val === 'null' ? null : $val; }], 'sort-packages' => [$booleanValidator, $booleanNormalizer], 'optimize-autoloader' => [$booleanValidator, $booleanNormalizer], 'classmap-authoritative' => [$booleanValidator, $booleanNormalizer], 'apcu-autoloader' => [$booleanValidator, $booleanNormalizer], 'prepend-autoloader' => [$booleanValidator, $booleanNormalizer], 'update-with-minimal-changes' => [$booleanValidator, $booleanNormalizer], 'disable-tls' => [$booleanValidator, $booleanNormalizer], 'secure-http' => [$booleanValidator, $booleanNormalizer], 'bump-after-update' => [ static function ($val): bool { return in_array($val, ['dev', 'no-dev', 'true', 'false', '1', '0'], true); }, static function ($val) { if ('dev' === $val || 'no-dev' === $val) { return $val; } return $val !== 'false' && (bool) $val; }, ], 'cafile' => [ static function ($val): bool { return file_exists($val) && Filesystem::isReadable($val); }, static function ($val) { return $val === 'null' ? null : $val; }, ], 'capath' => [ static function ($val): bool { return is_dir($val) && Filesystem::isReadable($val); }, static function ($val) { return $val === 'null' ? null : $val; }, ], 'github-expose-hostname' => [$booleanValidator, $booleanNormalizer], 'htaccess-protect' => [$booleanValidator, $booleanNormalizer], 'lock' => [$booleanValidator, $booleanNormalizer], 'allow-plugins' => [$booleanValidator, $booleanNormalizer], 'platform-check' => [ static function ($val): bool { return in_array($val, ['php-only', 'true', 'false', '1', '0'], true); }, static function ($val) { if ('php-only' === $val) { return 'php-only'; } return $val !== 'false' && (bool) $val; }, ], 'use-parent-dir' => [ static function ($val): bool { return in_array($val, ['true', 'false', 'prompt'], true); }, static function ($val) { if ('prompt' === $val) { return 'prompt'; } return $val !== 'false' && (bool) $val; }, ], 'audit.abandoned' => [ static function ($val): bool { return in_array($val, [Auditor::ABANDONED_IGNORE, Auditor::ABANDONED_REPORT, Auditor::ABANDONED_FAIL], true); }, static function ($val) { return $val; }, ], 'audit.ignore-unreachable' => [$booleanValidator, $booleanNormalizer], 'audit.block-insecure' => [$booleanValidator, $booleanNormalizer], 'audit.block-abandoned' => [$booleanValidator, $booleanNormalizer], ]; $multiConfigValues = [ 'github-protocols' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } foreach ($vals as $val) { if (!in_array($val, ['git', 'https', 'ssh'])) { return 'valid protocols include: git, https, ssh'; } } return true; }, static function ($vals) { return $vals; }, ], 'github-domains' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, static function ($vals) { return $vals; }, ], 'gitlab-domains' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, static function ($vals) { return $vals; }, ], 'audit.ignore-severity' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } foreach ($vals as $val) { if (!in_array($val, ['low', 'medium', 'high', 'critical'], true)) { return 'valid severities include: low, medium, high, critical'; } } return true; }, static function ($vals) { return $vals; }, ], ]; // allow unsetting audit config entirely if ($input->getOption('unset') && $settingKey === 'audit') { $this->configSource->removeConfigSetting($settingKey); return 0; } if ($input->getOption('unset') && (isset($uniqueConfigValues[$settingKey]) || isset($multiConfigValues[$settingKey]))) { if ($settingKey === 'disable-tls' && $this->config->get('disable-tls')) { $this->getIO()->writeError('<info>You are now running Composer with SSL/TLS protection enabled.</info>'); } $this->configSource->removeConfigSetting($settingKey); return 0; } if (isset($uniqueConfigValues[$settingKey])) { $this->handleSingleValue($settingKey, $uniqueConfigValues[$settingKey], $values, 'addConfigSetting'); return 0; } if (isset($multiConfigValues[$settingKey])) { $this->handleMultiValue($settingKey, $multiConfigValues[$settingKey], $values, 'addConfigSetting'); return 0; } // handle preferred-install per-package config if (Preg::isMatch('/^preferred-install\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } [$validator] = $uniqueConfigValues['preferred-install']; if (!$validator($values[0])) { throw new \RuntimeException('Invalid value for '.$settingKey.'. Should be one of: auto, source, or dist'); } $this->configSource->addConfigSetting($settingKey, $values[0]); return 0; } // handle allow-plugins config setting elements true or false to add/remove if (Preg::isMatch('{^allow-plugins\.([a-zA-Z0-9/*-]+)}', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } if (true !== $booleanValidator($values[0])) { throw new \RuntimeException(sprintf( '"%s" is an invalid value', $values[0] )); } $normalizedValue = $booleanNormalizer($values[0]); $this->configSource->addConfigSetting($settingKey, $normalizedValue); return 0; } // handle properties $uniqueProps = [ 'name' => ['is_string', static function ($val) { return $val; }], 'type' => ['is_string', static function ($val) { return $val; }], 'description' => ['is_string', static function ($val) { return $val; }], 'homepage' => ['is_string', static function ($val) { return $val; }], 'version' => ['is_string', static function ($val) { return $val; }], 'minimum-stability' => [ static function ($val): bool { return isset(BasePackage::STABILITIES[VersionParser::normalizeStability($val)]); }, static function ($val): string { return VersionParser::normalizeStability($val); }, ], 'prefer-stable' => [$booleanValidator, $booleanNormalizer], ]; $multiProps = [ 'keywords' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, static function ($vals) { return $vals; }, ], 'license' => [ static function ($vals) { if (!is_array($vals)) { return 'array expected'; } return true; }, static function ($vals) { return $vals; }, ], ]; if ($input->getOption('global') && (isset($uniqueProps[$settingKey]) || isset($multiProps[$settingKey]) || strpos($settingKey, 'extra.') === 0)) { throw new \InvalidArgumentException('The ' . $settingKey . ' property can not be set in the global config.json file. Use `composer global config` to apply changes to the global composer.json'); } if ($input->getOption('unset') && (isset($uniqueProps[$settingKey]) || isset($multiProps[$settingKey]))) { $this->configSource->removeProperty($settingKey); return 0; } if (isset($uniqueProps[$settingKey])) { $this->handleSingleValue($settingKey, $uniqueProps[$settingKey], $values, 'addProperty'); return 0; } if (isset($multiProps[$settingKey])) { $this->handleMultiValue($settingKey, $multiProps[$settingKey], $values, 'addProperty'); return 0; } // handle repositories if (Preg::isMatchStrictGroups('/^repos?(?:itories)?\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeRepository($matches[1]); return 0; } if (2 === count($values)) { $this->configSource->addRepository($matches[1], [ 'type' => $values[0], 'url' => $values[1], ], $input->getOption('append')); return 0; } if (1 === count($values)) { $value = strtolower($values[0]); if (true === $booleanValidator($value)) { if (false === $booleanNormalizer($value)) { $this->configSource->addRepository($matches[1], false, $input->getOption('append')); return 0; } } else { $value = JsonFile::parseJson($values[0]); $this->configSource->addRepository($matches[1], $value, $input->getOption('append')); return 0; } } throw new \RuntimeException('You must pass the type and a url. Example: php composer.phar config repositories.foo vcs https://bar.com'); } // handle extra if (Preg::isMatch('/^extra\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeProperty($settingKey); return 0; } $value = $values[0]; if ($input->getOption('json')) { $value = JsonFile::parseJson($value); if ($input->getOption('merge')) { $currentValue = $this->configFile->read(); $bits = explode('.', $settingKey); foreach ($bits as $bit) { $currentValue = $currentValue[$bit] ?? null; } if (is_array($currentValue) && is_array($value)) { if (array_is_list($currentValue) && array_is_list($value)) { $value = array_merge($currentValue, $value); } else { $value = $value + $currentValue; } } } } $this->configSource->addProperty($settingKey, $value); return 0; } // handle suggest if (Preg::isMatch('/^suggest\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeProperty($settingKey); return 0; } $this->configSource->addProperty($settingKey, implode(' ', $values)); return 0; } // handle unsetting extra/suggest if (in_array($settingKey, ['suggest', 'extra'], true) && $input->getOption('unset')) { $this->configSource->removeProperty($settingKey); return 0; } // handle platform if (Preg::isMatch('/^platform\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } $this->configSource->addConfigSetting($settingKey, $values[0] === 'false' ? false : $values[0]); return 0; } // handle unsetting platform if ($settingKey === 'platform' && $input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } // handle audit.ignore and audit.ignore-abandoned with --merge support if (in_array($settingKey, ['audit.ignore', 'audit.ignore-abandoned'], true)) { if ($input->getOption('unset')) { $this->configSource->removeConfigSetting($settingKey); return 0; } $value = $values; if ($input->getOption('json')) { $value = JsonFile::parseJson($values[0]); if (!is_array($value)) { throw new \RuntimeException('Expected an array or object for '.$settingKey); } } if ($input->getOption('merge')) { $currentConfig = $this->configFile->read(); $currentValue = $currentConfig['config']['audit'][str_replace('audit.', '', $settingKey)] ?? null; if ($currentValue !== null && is_array($currentValue) && is_array($value)) { if (array_is_list($currentValue) && array_is_list($value)) { // Both are lists, merge them $value = array_merge($currentValue, $value); } elseif (!array_is_list($currentValue) && !array_is_list($value)) { // Both are associative arrays (objects), merge them $value = $value + $currentValue; } else { throw new \RuntimeException('Cannot merge array and object for '.$settingKey); } } } $this->configSource->addConfigSetting($settingKey, $value); return 0; } // handle auth if (Preg::isMatch('/^(bitbucket-oauth|github-oauth|gitlab-oauth|gitlab-token|http-basic|custom-headers|bearer|forgejo-token)\.(.+)/', $settingKey, $matches)) { if ($input->getOption('unset')) { $this->authConfigSource->removeConfigSetting($matches[1].'.'.$matches[2]);
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ScriptAliasCommand.php
src/Composer/Command/ScriptAliasCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Pcre\Preg; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class ScriptAliasCommand extends BaseCommand { /** @var string */ private $script; /** @var string */ private $description; /** @var string[] */ private $aliases; /** * @param string[] $aliases */ public function __construct(string $script, ?string $description, array $aliases = []) { $this->script = $script; $this->description = $description ?? 'Runs the '.$script.' script as defined in composer.json'; $this->aliases = $aliases; foreach ($this->aliases as $alias) { if (!is_string($alias)) { throw new \InvalidArgumentException('"scripts-aliases" element array values should contain only strings'); } } $this->ignoreValidationErrors(); parent::__construct(); } protected function configure(): void { $this ->setName($this->script) ->setDescription($this->description) ->setAliases($this->aliases) ->setDefinition([ new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), ]) ->setHelp( <<<EOT The <info>run-script</info> command runs scripts defined in composer.json: <info>php composer.phar run-script post-update-cmd</info> Read more at https://getcomposer.org/doc/03-cli.md#run-script-run EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $args = $input->getArguments(); // TODO remove for Symfony 6+ as it is then in the interface if (!method_exists($input, '__toString')) { // @phpstan-ignore-line throw new \LogicException('Expected an Input instance that is stringable, got '.get_class($input)); } return $composer->getEventDispatcher()->dispatchScript($this->script, $input->getOption('dev') || !$input->getOption('no-dev'), $args['args'], ['script-alias-input' => Preg::replace('{^\S+ ?}', '', $input->__toString(), 1)]); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ReinstallCommand.php
src/Composer/Command/ReinstallCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Transaction; use Composer\Package\AliasPackage; use Composer\Package\BasePackage; use Composer\Pcre\Preg; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Script\ScriptEvents; use Composer\Util\Platform; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class ReinstallCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('reinstall') ->setDescription('Uninstalls and reinstalls the given package names') ->setDefinition([ new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'), new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()), new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('type', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Filter packages to reinstall by type(s)', null, $this->suggestInstalledPackageTypes(false)), new InputArgument('packages', InputArgument::IS_ARRAY, 'List of package names to reinstall, can include a wildcard (*) to match any substring.', null, $this->suggestInstalledPackage(false)), ]) ->setHelp( <<<EOT The <info>reinstall</info> command looks up installed packages by name, uninstalls them and reinstalls them. This lets you do a clean install of a package if you messed with its files, or if you wish to change the installation type using --prefer-install. <info>php composer.phar reinstall acme/foo "acme/bar-*"</info> Read more at https://getcomposer.org/doc/03-cli.md#reinstall EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $io = $this->getIO(); $composer = $this->requireComposer(); $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $packagesToReinstall = []; $packageNamesToReinstall = []; if (\count($input->getOption('type')) > 0) { if (\count($input->getArgument('packages')) > 0) { throw new \InvalidArgumentException('You cannot specify package names and filter by type at the same time.'); } foreach ($localRepo->getCanonicalPackages() as $package) { if (in_array($package->getType(), $input->getOption('type'), true)) { $packagesToReinstall[] = $package; $packageNamesToReinstall[] = $package->getName(); } } } else { if (\count($input->getArgument('packages')) === 0) { throw new \InvalidArgumentException('You must pass one or more package names to be reinstalled.'); } foreach ($input->getArgument('packages') as $pattern) { $patternRegexp = BasePackage::packageNameToRegexp($pattern); $matched = false; foreach ($localRepo->getCanonicalPackages() as $package) { if (Preg::isMatch($patternRegexp, $package->getName())) { $matched = true; $packagesToReinstall[] = $package; $packageNamesToReinstall[] = $package->getName(); } } if (!$matched) { $io->writeError('<warning>Pattern "' . $pattern . '" does not match any currently installed packages.</warning>'); } } } if (0 === \count($packagesToReinstall)) { $io->writeError('<warning>Found no packages to reinstall, aborting.</warning>'); return 1; } $uninstallOperations = []; foreach ($packagesToReinstall as $package) { $uninstallOperations[] = new UninstallOperation($package); } // make sure we have a list of install operations ordered by dependency/plugins $presentPackages = $localRepo->getPackages(); $resultPackages = $presentPackages; foreach ($presentPackages as $index => $package) { if (in_array($package->getName(), $packageNamesToReinstall, true)) { unset($presentPackages[$index]); } } $transaction = new Transaction($presentPackages, $resultPackages); $installOperations = $transaction->getOperations(); // reverse-sort the uninstalls based on the install order $installOrder = []; foreach ($installOperations as $index => $op) { if ($op instanceof InstallOperation && !$op->getPackage() instanceof AliasPackage) { $installOrder[$op->getPackage()->getName()] = $index; } } usort($uninstallOperations, static function ($a, $b) use ($installOrder): int { return $installOrder[$b->getPackage()->getName()] - $installOrder[$a->getPackage()->getName()]; }); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'reinstall', $input, $output); $eventDispatcher = $composer->getEventDispatcher(); $eventDispatcher->dispatch($commandEvent->getName(), $commandEvent); $config = $composer->getConfig(); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($config, $input); $installationManager = $composer->getInstallationManager(); $downloadManager = $composer->getDownloadManager(); $package = $composer->getPackage(); $installationManager->setOutputProgress(!$input->getOption('no-progress')); if ($input->getOption('no-plugins')) { $installationManager->disablePlugins(); } $downloadManager->setPreferSource($preferSource); $downloadManager->setPreferDist($preferDist); $devMode = $localRepo->getDevMode() !== null ? $localRepo->getDevMode() : true; Platform::putEnv('COMPOSER_DEV_MODE', $devMode ? '1' : '0'); $eventDispatcher->dispatchScript(ScriptEvents::PRE_INSTALL_CMD, $devMode); $installationManager->execute($localRepo, $uninstallOperations, $devMode); $installationManager->execute($localRepo, $installOperations, $devMode); if (!$input->getOption('no-autoloader')) { $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-autoloader-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $generator = $composer->getAutoloadGenerator(); $generator->setClassMapAuthoritative($authoritative); $generator->setApcu($apcu, $apcuPrefix); $generator->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)); $generator->dump( $config, $localRepo, $package, $installationManager, 'composer', $optimize, null, $composer->getLocker() ); } $eventDispatcher->dispatchScript(ScriptEvents::POST_INSTALL_CMD, $devMode); return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/AuditCommand.php
src/Composer/Command/AuditCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Advisory\AuditConfig; use Composer\Composer; use Composer\Repository\RepositorySet; use Composer\Repository\RepositoryUtils; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepository; use Composer\Advisory\Auditor; use Composer\Console\Input\InputOption; class AuditCommand extends BaseCommand { protected function configure(): void { $this ->setName('audit') ->setDescription('Checks for security vulnerability advisories for installed packages') ->setDefinition([ new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables auditing of require-dev packages.'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_TABLE, Auditor::FORMATS), new InputOption('locked', null, InputOption::VALUE_NONE, 'Audit based on the lock file instead of the installed packages.'), new InputOption('abandoned', null, InputOption::VALUE_REQUIRED, 'Behavior on abandoned packages. Must be "ignore", "report", or "fail".', null, Auditor::ABANDONEDS), new InputOption('ignore-severity', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Ignore advisories of a certain severity level.', [], ['low', 'medium', 'high', 'critical']), new InputOption('ignore-unreachable', null, InputOption::VALUE_NONE, 'Ignore repositories that are unreachable or return a non-200 status code.'), ]) ->setHelp( <<<EOT The <info>audit</info> command checks for security vulnerability advisories for installed packages. If you do not want to include dev dependencies in the audit you can omit them with --no-dev If you want to ignore repositories that are unreachable or return a non-200 status code, use --ignore-unreachable Read more at https://getcomposer.org/doc/03-cli.md#audit EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $packages = $this->getPackages($composer, $input); if (count($packages) === 0) { $this->getIO()->writeError('No packages - skipping audit.'); return 0; } $auditor = new Auditor(); $repoSet = new RepositorySet(); foreach ($composer->getRepositoryManager()->getRepositories() as $repo) { $repoSet->addRepository($repo); } $auditConfig = AuditConfig::fromConfig($composer->getConfig()); $abandoned = $input->getOption('abandoned'); if ($abandoned !== null && !in_array($abandoned, Auditor::ABANDONEDS, true)) { throw new \InvalidArgumentException('--abandoned must be one of '.implode(', ', Auditor::ABANDONEDS).'.'); } $abandoned = $abandoned ?? $auditConfig->auditAbandoned; $ignoreSeverities = array_merge(array_fill_keys($input->getOption('ignore-severity'), null), $auditConfig->ignoreSeverityForAudit); $ignoreUnreachable = $input->getOption('ignore-unreachable') || $auditConfig->ignoreUnreachable; return min(255, $auditor->audit( $this->getIO(), $repoSet, $packages, $this->getAuditFormat($input, 'format'), false, $auditConfig->ignoreListForAudit, $abandoned, $ignoreSeverities, $ignoreUnreachable, $auditConfig->ignoreAbandonedForAudit )); } /** * @return PackageInterface[] */ private function getPackages(Composer $composer, InputInterface $input): array { if ($input->getOption('locked')) { if (!$composer->getLocker()->isLocked()) { throw new \UnexpectedValueException('Valid composer.json and composer.lock files are required to run this command with --locked'); } $locker = $composer->getLocker(); return $locker->getLockedRepository(!$input->getOption('no-dev'))->getPackages(); } $rootPkg = $composer->getPackage(); $installedRepo = new InstalledRepository([$composer->getRepositoryManager()->getLocalRepository()]); if ($input->getOption('no-dev')) { return RepositoryUtils::filterRequiredPackages($installedRepo->getPackages(), $rootPkg); } return $installedRepo->getPackages(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/InstallCommand.php
src/Composer/Command/InstallCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Installer; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Advisory\Auditor; use Composer\Util\HttpDownloader; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> * @author Ryan Weaver <ryan@knplabs.com> * @author Konstantin Kudryashov <ever.zet@gmail.com> * @author Nils Adermann <naderman@naderman.de> */ class InstallCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('install') ->setAliases(['i']) ->setDescription('Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json') ->setDefinition([ new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'), new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('download-only', null, InputOption::VALUE_NONE, 'Download only, do not install packages.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'DEPRECATED: Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'DEPRECATED: This flag does not exist anymore.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('no-security-blocking', null, InputOption::VALUE_NONE, 'Allows installing packages with security advisories or that are abandoned (can also be set via the COMPOSER_NO_SECURITY_BLOCKING=1 env var). Only applies when no lock file is present.'), new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Do not use, only defined here to catch misuse of the install command.'), new InputOption('audit', null, InputOption::VALUE_NONE, 'Run an audit after installation is complete.'), new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS), new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Should not be provided, use composer require instead to add a given package to composer.json.'), ]) ->setHelp( <<<EOT The <info>install</info> command reads the composer.lock file from the current directory, processes it, and downloads and installs all the libraries and dependencies outlined in that file. If the file does not exist it will look for composer.json and do the same. <info>php composer.phar install</info> Read more at https://getcomposer.org/doc/03-cli.md#install-i EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $io = $this->getIO(); if ($input->getOption('dev')) { $io->writeError('<warning>You are using the deprecated option "--dev". It has no effect and will break in Composer 3.</warning>'); } if ($input->getOption('no-suggest')) { $io->writeError('<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>'); } $args = $input->getArgument('packages'); if (count($args) > 0) { $io->writeError('<error>Invalid argument '.implode(' ', $args).'. Use "composer require '.implode(' ', $args).'" instead to add packages to your composer.json.</error>'); return 1; } if ($input->getOption('no-install')) { $io->writeError('<error>Invalid option "--no-install". Use "composer update --no-install" instead if you are trying to update the composer.lock file.</error>'); return 1; } $composer = $this->requireComposer(); if (!$composer->getLocker()->isLocked() && !HttpDownloader::isCurlEnabled()) { $io->writeError('<warning>Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled.</warning>'); } $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'install', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $install = Installer::create($io, $composer); $config = $composer->getConfig(); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($config, $input); $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-autoloader-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $composer->getInstallationManager()->setOutputProgress(!$input->getOption('no-progress')); $install ->setDryRun($input->getOption('dry-run')) ->setDownloadOnly($input->getOption('download-only')) ->setVerbose($input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$input->getOption('no-dev')) ->setDumpAutoloader(!$input->getOption('no-autoloader')) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu, $apcuPrefix) ->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)) ->setAuditConfig($this->createAuditConfig($composer->getConfig(), $input)) ->setErrorOnAudit($input->getOption('audit')) ; if ($input->getOption('no-plugins')) { $install->disablePlugins(); } return $install->run(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/CheckPlatformReqsCommand.php
src/Composer/Command/CheckPlatformReqsCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Package\Link; use Composer\Semver\Constraint\Constraint; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Repository\PlatformRepository; use Composer\Repository\RootPackageRepository; use Composer\Repository\InstalledRepository; use Composer\Json\JsonFile; class CheckPlatformReqsCommand extends BaseCommand { protected function configure(): void { $this->setName('check-platform-reqs') ->setDescription('Check that platform requirements are satisfied') ->setDefinition([ new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables checking of require-dev packages requirements.'), new InputOption('lock', null, InputOption::VALUE_NONE, 'Checks requirements only from the lock file, not from installed packages.'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text', ['json', 'text']), ]) ->setHelp( <<<EOT Checks that your PHP and extensions versions match the platform requirements of the installed packages. Unlike update/install, this command will ignore config.platform settings and check the real platform packages so you can be certain you have the required platform dependencies. <info>php composer.phar check-platform-reqs</info> EOT ); } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $requires = []; $removePackages = []; if ($input->getOption('lock')) { $this->getIO()->writeError('<info>Checking '.($input->getOption('no-dev') ? 'non-dev ' : '').'platform requirements using the lock file</info>'); $installedRepo = $composer->getLocker()->getLockedRepository(!$input->getOption('no-dev')); } else { $installedRepo = $composer->getRepositoryManager()->getLocalRepository(); // fallback to lockfile if installed repo is empty if (!$installedRepo->getPackages()) { $this->getIO()->writeError('<warning>No vendor dir present, checking '.($input->getOption('no-dev') ? 'non-dev ' : '').'platform requirements from the lock file</warning>'); $installedRepo = $composer->getLocker()->getLockedRepository(!$input->getOption('no-dev')); } else { if ($input->getOption('no-dev')) { $removePackages = $installedRepo->getDevPackageNames(); } $this->getIO()->writeError('<info>Checking '.($input->getOption('no-dev') ? 'non-dev ' : '').'platform requirements for packages in the vendor dir</info>'); } } if (!$input->getOption('no-dev')) { foreach ($composer->getPackage()->getDevRequires() as $require => $link) { $requires[$require] = [$link]; } } $installedRepo = new InstalledRepository([$installedRepo, new RootPackageRepository(clone $composer->getPackage())]); foreach ($installedRepo->getPackages() as $package) { if (in_array($package->getName(), $removePackages, true)) { continue; } foreach ($package->getRequires() as $require => $link) { $requires[$require][] = $link; } } ksort($requires); $installedRepo->addRepository(new PlatformRepository([], [])); $results = []; $exitCode = 0; /** * @var Link[] $links */ foreach ($requires as $require => $links) { if (PlatformRepository::isPlatformPackage($require)) { $candidates = $installedRepo->findPackagesWithReplacersAndProviders($require); if ($candidates) { $reqResults = []; foreach ($candidates as $candidate) { $candidateConstraint = null; if ($candidate->getName() === $require) { $candidateConstraint = new Constraint('=', $candidate->getVersion()); $candidateConstraint->setPrettyString($candidate->getPrettyVersion()); } else { foreach (array_merge($candidate->getProvides(), $candidate->getReplaces()) as $link) { if ($link->getTarget() === $require) { $candidateConstraint = $link->getConstraint(); break; } } } // safety check for phpstan, but it should not be possible to get a candidate out of findPackagesWithReplacersAndProviders without a constraint matching $require if (!$candidateConstraint) { continue; } foreach ($links as $link) { if (!$link->getConstraint()->matches($candidateConstraint)) { $reqResults[] = [ $candidate->getName() === $require ? $candidate->getPrettyName() : $require, $candidateConstraint->getPrettyString(), $link, '<error>failed</error>', $candidate->getName() === $require ? '' : '<comment>provided by '.$candidate->getPrettyName().'</comment>', ]; // skip to next candidate continue 2; } } $results[] = [ $candidate->getName() === $require ? $candidate->getPrettyName() : $require, $candidateConstraint->getPrettyString(), null, '<info>success</info>', $candidate->getName() === $require ? '' : '<comment>provided by '.$candidate->getPrettyName().'</comment>', ]; // candidate matched, skip to next requirement continue 2; } // show the first error from every failed candidate $results = array_merge($results, $reqResults); $exitCode = max($exitCode, 1); continue; } $results[] = [ $require, 'n/a', $links[0], '<error>missing</error>', '', ]; $exitCode = max($exitCode, 2); } } $this->printTable($output, $results, $input->getOption('format')); return $exitCode; } /** * @param mixed[] $results */ protected function printTable(OutputInterface $output, array $results, string $format): void { $rows = []; foreach ($results as $result) { /** * @var Link|null $link */ [$platformPackage, $version, $link, $status, $provider] = $result; if ('json' === $format) { $rows[] = [ "name" => $platformPackage, "version" => $version, "status" => strip_tags($status), "failed_requirement" => $link instanceof Link ? [ 'source' => $link->getSource(), 'type' => $link->getDescription(), 'target' => $link->getTarget(), 'constraint' => $link->getPrettyConstraint(), ] : null, "provider" => $provider === '' ? null : strip_tags($provider), ]; } else { $rows[] = [ $platformPackage, $version, $link, $link ? sprintf('%s %s %s (%s)', $link->getSource(), $link->getDescription(), $link->getTarget(), $link->getPrettyConstraint()) : '', rtrim($status.' '.$provider), ]; } } if ('json' === $format) { $this->getIO()->write(JsonFile::encode($rows)); } else { $this->renderTable($rows, $output); } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/RemoveCommand.php
src/Composer/Command/RemoveCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Config\JsonConfigSource; use Composer\DependencyResolver\Request; use Composer\Installer; use Composer\Pcre\Preg; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Json\JsonFile; use Composer\Factory; use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; use Composer\Package\BasePackage; use Composer\Advisory\Auditor; /** * @author Pierre du Plessis <pdples@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class RemoveCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('remove') ->setAliases(['rm', 'uninstall']) ->setDescription('Removes a package from the require or require-dev') ->setDefinition([ new InputArgument('packages', InputArgument::IS_ARRAY, 'Packages that should be removed.', null, $this->suggestRootRequirement()), new InputOption('dev', null, InputOption::VALUE_NONE, 'Removes a package from the require-dev section.'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies (implies --no-install).'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Skip the install step after updating the composer.lock file.'), new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Skip the audit step after updating the composer.lock file (can also be set via the COMPOSER_NO_AUDIT=1 env var).'), new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS), new InputOption('no-security-blocking', null, InputOption::VALUE_NONE, 'Allows installing packages with security advisories or that are abandoned (can also be set via the COMPOSER_NO_SECURITY_BLOCKING=1 env var).'), new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'), new InputOption('update-with-dependencies', 'w', InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies (can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var). (Deprecated, is now default behavior)'), new InputOption('update-with-all-dependencies', 'W', InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements (can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var).'), new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-all-dependencies'), new InputOption('no-update-with-dependencies', null, InputOption::VALUE_NONE, 'Does not allow inherited dependencies to be updated with explicit dependencies.'), new InputOption('minimal-changes', 'm', InputOption::VALUE_NONE, 'During an update with -w/-W, only perform absolutely necessary changes to transitive dependencies (can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var).'), new InputOption('unused', null, InputOption::VALUE_NONE, 'Remove all packages which are locked but not required by any other package.'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'), ]) ->setHelp( <<<EOT The <info>remove</info> command removes a package from the current list of installed packages <info>php composer.phar remove</info> Read more at https://getcomposer.org/doc/03-cli.md#remove-rm EOT ) ; } /** * @throws \Seld\JsonLint\ParsingException */ protected function execute(InputInterface $input, OutputInterface $output): int { if ($input->getArgument('packages') === [] && !$input->getOption('unused')) { throw new InvalidArgumentException('Not enough arguments (missing: "packages").'); } $packages = $input->getArgument('packages'); $packages = array_map('strtolower', $packages); if ($input->getOption('unused')) { $composer = $this->requireComposer(); $locker = $composer->getLocker(); if (!$locker->isLocked()) { throw new \UnexpectedValueException('A valid composer.lock file is required to run this command with --unused'); } $lockedPackages = $locker->getLockedRepository()->getPackages(); $required = []; foreach (array_merge($composer->getPackage()->getRequires(), $composer->getPackage()->getDevRequires()) as $link) { $required[$link->getTarget()] = true; } do { $found = false; foreach ($lockedPackages as $index => $package) { foreach ($package->getNames() as $name) { if (isset($required[$name])) { foreach ($package->getRequires() as $link) { $required[$link->getTarget()] = true; } $found = true; unset($lockedPackages[$index]); break; } } } } while ($found); $unused = []; foreach ($lockedPackages as $package) { $unused[] = $package->getName(); } $packages = array_merge($packages, $unused); if (count($packages) === 0) { $this->getIO()->writeError('<info>No unused packages to remove</info>'); return 0; } } $file = Factory::getComposerFile(); $jsonFile = new JsonFile($file); /** @var array{require?: array<string, string>, require-dev?: array<string, string>} $composer */ $composer = $jsonFile->read(); $composerBackup = file_get_contents($jsonFile->getPath()); $json = new JsonConfigSource($jsonFile); $type = $input->getOption('dev') ? 'require-dev' : 'require'; $altType = !$input->getOption('dev') ? 'require-dev' : 'require'; $io = $this->getIO(); if ($input->getOption('update-with-dependencies')) { $io->writeError('<warning>You are using the deprecated option "update-with-dependencies". This is now default behaviour. The --no-update-with-dependencies option can be used to remove a package without its dependencies.</warning>'); } // make sure name checks are done case insensitively foreach (['require', 'require-dev'] as $linkType) { if (isset($composer[$linkType])) { foreach ($composer[$linkType] as $name => $version) { $composer[$linkType][strtolower($name)] = $name; } } } $dryRun = $input->getOption('dry-run'); $toRemove = []; foreach ($packages as $package) { if (isset($composer[$type][$package])) { if ($dryRun) { $toRemove[$type][] = $composer[$type][$package]; } else { $json->removeLink($type, $composer[$type][$package]); } } elseif (isset($composer[$altType][$package])) { $io->writeError('<warning>' . $composer[$altType][$package] . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>'); if ($io->isInteractive()) { if ($io->askConfirmation('Do you want to remove it from ' . $altType . ' [<comment>yes</comment>]? ')) { if ($dryRun) { $toRemove[$altType][] = $composer[$altType][$package]; } else { $json->removeLink($altType, $composer[$altType][$package]); } } } } elseif (isset($composer[$type]) && count($matches = Preg::grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$type]))) > 0) { foreach ($matches as $matchedPackage) { if ($dryRun) { $toRemove[$type][] = $matchedPackage; } else { $json->removeLink($type, $matchedPackage); } } } elseif (isset($composer[$altType]) && count($matches = Preg::grep(BasePackage::packageNameToRegexp($package), array_keys($composer[$altType]))) > 0) { foreach ($matches as $matchedPackage) { $io->writeError('<warning>' . $matchedPackage . ' could not be found in ' . $type . ' but it is present in ' . $altType . '</warning>'); if ($io->isInteractive()) { if ($io->askConfirmation('Do you want to remove it from ' . $altType . ' [<comment>yes</comment>]? ')) { if ($dryRun) { $toRemove[$altType][] = $matchedPackage; } else { $json->removeLink($altType, $matchedPackage); } } } } } else { $io->writeError('<warning>'.$package.' is not required in your composer.json and has not been removed</warning>'); } } $io->writeError('<info>'.$file.' has been updated</info>'); if ($input->getOption('no-update')) { return 0; } if ($composer = $this->tryComposer()) { $composer->getPluginManager()->deactivateInstalledPlugins(); } // Update packages $this->resetComposer(); $composer = $this->requireComposer(); if ($dryRun) { $rootPackage = $composer->getPackage(); $links = [ 'require' => $rootPackage->getRequires(), 'require-dev' => $rootPackage->getDevRequires(), ]; foreach ($toRemove as $type => $names) { foreach ($names as $name) { unset($links[$type][$name]); } } $rootPackage->setRequires($links['require']); $rootPackage->setDevRequires($links['require-dev']); } $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $allowPlugins = $composer->getConfig()->get('allow-plugins'); $removedPlugins = is_array($allowPlugins) ? array_intersect(array_keys($allowPlugins), $packages) : []; if (!$dryRun && is_array($allowPlugins) && count($removedPlugins) > 0) { if (count($allowPlugins) === count($removedPlugins)) { $json->removeConfigSetting('allow-plugins'); } else { foreach ($removedPlugins as $plugin) { $json->removeConfigSetting('allow-plugins.'.$plugin); } } } $composer->getInstallationManager()->setOutputProgress(!$input->getOption('no-progress')); $install = Installer::create($io, $composer); $updateDevMode = !$input->getOption('update-no-dev'); $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-autoloader-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader'); $minimalChanges = $input->getOption('minimal-changes') || $composer->getConfig()->get('update-with-minimal-changes'); $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE; $flags = ''; if ($input->getOption('update-with-all-dependencies') || $input->getOption('with-all-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS; $flags .= ' --with-all-dependencies'; } elseif ($input->getOption('no-update-with-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED; $flags .= ' --with-dependencies'; } $io->writeError('<info>Running composer update '.implode(' ', $packages).$flags.'</info>'); $install ->setVerbose($input->getOption('verbose')) ->setDevMode($updateDevMode) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu, $apcuPrefix) ->setUpdate(true) ->setInstall(!$input->getOption('no-install')) ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies) ->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)) ->setDryRun($dryRun) ->setAuditConfig($this->createAuditConfig($composer->getConfig(), $input)) ->setMinimalUpdate($minimalChanges) ; // if no lock is present, we do not do a partial update as // this is not supported by the Installer if ($composer->getLocker()->isLocked()) { $install->setUpdateAllowList($packages); } $status = $install->run(); if ($status !== 0) { $io->writeError("\n".'<error>Removal failed, reverting '.$file.' to its original content.</error>'); file_put_contents($jsonFile->getPath(), $composerBackup); } if (!$dryRun) { foreach ($packages as $package) { if ($composer->getRepositoryManager()->getLocalRepository()->findPackages($package)) { $io->writeError('<error>Removal failed, '.$package.' is still present, it may be required by another package. See `composer why '.$package.'`.</error>'); return 2; } } } return $status; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/DumpAutoloadCommand.php
src/Composer/Command/DumpAutoloadCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class DumpAutoloadCommand extends BaseCommand { protected function configure(): void { $this ->setName('dump-autoload') ->setAliases(['dumpautoload']) ->setDescription('Dumps the autoloader') ->setDefinition([ new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize`.'), new InputOption('apcu', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables autoload-dev rules. Composer will by default infer this automatically according to the last install or update --no-dev state.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables autoload-dev rules. Composer will by default infer this automatically according to the last install or update --no-dev state.'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('strict-psr', null, InputOption::VALUE_NONE, 'Return a failed status code (1) if PSR-4 or PSR-0 mapping errors are present. Requires --optimize to work.'), new InputOption('strict-ambiguous', null, InputOption::VALUE_NONE, 'Return a failed status code (2) if the same class is found in multiple files. Requires --optimize to work.'), ]) ->setHelp( <<<EOT <info>php composer.phar dump-autoload</info> Read more at https://getcomposer.org/doc/03-cli.md#dump-autoload-dumpautoload EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'dump-autoload', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $installationManager = $composer->getInstallationManager(); $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $package = $composer->getPackage(); $config = $composer->getConfig(); $missingDependencies = false; foreach ($localRepo->getCanonicalPackages() as $localPkg) { $installPath = $installationManager->getInstallPath($localPkg); if ($installPath !== null && file_exists($installPath) === false) { $missingDependencies = true; $this->getIO()->write('<warning>Not all dependencies are installed. Make sure to run a "composer install" to install missing dependencies</warning>'); break; } } $optimize = $input->getOption('optimize') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu') || $config->get('apcu-autoloader'); if ($input->getOption('strict-psr') && !$optimize && !$authoritative) { throw new \InvalidArgumentException('--strict-psr mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.'); } if ($input->getOption('strict-ambiguous') && !$optimize && !$authoritative) { throw new \InvalidArgumentException('--strict-ambiguous mode only works with optimized autoloader, use --optimize or --classmap-authoritative if you want a strict return value.'); } if ($authoritative) { $this->getIO()->write('<info>Generating optimized autoload files (authoritative)</info>'); } elseif ($optimize) { $this->getIO()->write('<info>Generating optimized autoload files</info>'); } else { $this->getIO()->write('<info>Generating autoload files</info>'); } $generator = $composer->getAutoloadGenerator(); if ($input->getOption('dry-run')) { $generator->setDryRun(true); } if ($input->getOption('no-dev')) { $generator->setDevMode(false); } if ($input->getOption('dev')) { if ($input->getOption('no-dev')) { throw new \InvalidArgumentException('You can not use both --no-dev and --dev as they conflict with each other.'); } $generator->setDevMode(true); } $generator->setClassMapAuthoritative($authoritative); $generator->setRunScripts(true); $generator->setApcu($apcu, $apcuPrefix); $generator->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)); $classMap = $generator->dump( $config, $localRepo, $package, $installationManager, 'composer', $optimize, null, $composer->getLocker(), $input->getOption('strict-ambiguous') ); $numberOfClasses = count($classMap); if ($authoritative) { $this->getIO()->write('<info>Generated optimized autoload files (authoritative) containing '. $numberOfClasses .' classes</info>'); } elseif ($optimize) { $this->getIO()->write('<info>Generated optimized autoload files containing '. $numberOfClasses .' classes</info>'); } else { $this->getIO()->write('<info>Generated autoload files</info>'); } if ($missingDependencies || ($input->getOption('strict-psr') && count($classMap->getPsrViolations()) > 0)) { return 1; } if ($input->getOption('strict-ambiguous') && count($classMap->getAmbiguousClasses(false)) > 0) { return 2; } return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/SearchCommand.php
src/Composer/Command/SearchCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Json\JsonFile; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryInterface; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; /** * @author Robert Schönthal <seroscho@googlemail.com> */ class SearchCommand extends BaseCommand { protected function configure(): void { $this ->setName('search') ->setDescription('Searches for packages') ->setDefinition([ new InputOption('only-name', 'N', InputOption::VALUE_NONE, 'Search only in package names'), new InputOption('only-vendor', 'O', InputOption::VALUE_NONE, 'Search only for vendor / organization names, returns only "vendor" as result'), new InputOption('type', 't', InputOption::VALUE_REQUIRED, 'Search for a specific package type'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text', ['json', 'text']), new InputArgument('tokens', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'tokens to search for'), ]) ->setHelp( <<<EOT The search command searches for packages by its name <info>php composer.phar search symfony composer</info> Read more at https://getcomposer.org/doc/03-cli.md#search EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { // init repos $platformRepo = new PlatformRepository; $io = $this->getIO(); $format = $input->getOption('format'); if (!in_array($format, ['text', 'json'])) { $io->writeError(sprintf('Unsupported format "%s". See help for supported formats.', $format)); return 1; } if (!($composer = $this->tryComposer())) { $composer = $this->createComposerInstance($input, $this->getIO(), []); } $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $installedRepo = new CompositeRepository([$localRepo, $platformRepo]); $repos = new CompositeRepository(array_merge([$installedRepo], $composer->getRepositoryManager()->getRepositories())); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'search', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $mode = RepositoryInterface::SEARCH_FULLTEXT; if ($input->getOption('only-name') === true) { if ($input->getOption('only-vendor') === true) { throw new \InvalidArgumentException('--only-name and --only-vendor cannot be used together'); } $mode = RepositoryInterface::SEARCH_NAME; } elseif ($input->getOption('only-vendor') === true) { $mode = RepositoryInterface::SEARCH_VENDOR; } $type = $input->getOption('type'); $query = implode(' ', $input->getArgument('tokens')); if ($mode !== RepositoryInterface::SEARCH_FULLTEXT) { $query = preg_quote($query); } $results = $repos->search($query, $mode, $type); if (\count($results) > 0 && $format === 'text') { $width = $this->getTerminalWidth(); $nameLength = 0; foreach ($results as $result) { $nameLength = max(strlen($result['name']), $nameLength); } $nameLength += 1; foreach ($results as $result) { $description = $result['description'] ?? ''; $warning = !empty($result['abandoned']) ? '<warning>! Abandoned !</warning> ' : ''; $remaining = $width - $nameLength - strlen($warning) - 2; if (strlen($description) > $remaining) { $description = substr($description, 0, $remaining - 3) . '...'; } $link = $result['url'] ?? null; if ($link !== null) { $io->write('<href='.OutputFormatter::escape($link).'>'.$result['name'].'</>'. str_repeat(' ', $nameLength - strlen($result['name'])) . $warning . $description); } else { $io->write(str_pad($result['name'], $nameLength, ' ') . $warning . $description); } } } elseif ($format === 'json') { $io->write(JsonFile::encode($results)); } return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/PackageDiscoveryTrait.php
src/Composer/Command/PackageDiscoveryTrait.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\IO\IOInterface; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionParser; use Composer\Package\Version\VersionSelector; use Composer\Pcre\Preg; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Repository\RepositorySet; use Composer\Semver\Constraint\Constraint; use Composer\Util\Filesystem; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @internal */ trait PackageDiscoveryTrait { /** @var ?CompositeRepository */ private $repos; /** @var RepositorySet[] */ private $repositorySets; protected function getRepos(): CompositeRepository { if (null === $this->repos) { $this->repos = new CompositeRepository(array_merge( [new PlatformRepository], RepositoryFactory::defaultReposWithDefaultManager($this->getIO()) )); } return $this->repos; } /** * @param key-of<BasePackage::STABILITIES>|null $minimumStability */ private function getRepositorySet(InputInterface $input, ?string $minimumStability = null): RepositorySet { $key = $minimumStability ?? 'default'; if (!isset($this->repositorySets[$key])) { $this->repositorySets[$key] = $repositorySet = new RepositorySet($minimumStability ?? $this->getMinimumStability($input)); $repositorySet->addRepository($this->getRepos()); } return $this->repositorySets[$key]; } /** * @return key-of<BasePackage::STABILITIES> */ private function getMinimumStability(InputInterface $input): string { if ($input->hasOption('stability')) { // @phpstan-ignore-line as InitCommand does have this option but not all classes using this trait do return VersionParser::normalizeStability($input->getOption('stability') ?? 'stable'); } // @phpstan-ignore-next-line as RequireCommand does not have the option above so this code is reachable there $file = Factory::getComposerFile(); if (is_file($file) && Filesystem::isReadable($file) && is_array($composer = json_decode((string) file_get_contents($file), true))) { if (isset($composer['minimum-stability'])) { return VersionParser::normalizeStability($composer['minimum-stability']); } } return 'stable'; } /** * @param array<string> $requires * * @return array<string> * @throws \Exception */ final protected function determineRequirements(InputInterface $input, OutputInterface $output, array $requires = [], ?PlatformRepository $platformRepo = null, string $preferredStability = 'stable', bool $useBestVersionConstraint = true, bool $fixed = false): array { if (count($requires) > 0) { $requires = $this->normalizeRequirements($requires); $result = []; $io = $this->getIO(); foreach ($requires as $requirement) { if (isset($requirement['version']) && Preg::isMatch('{^\d+(\.\d+)?$}', $requirement['version'])) { $io->writeError('<warning>The "'.$requirement['version'].'" constraint for "'.$requirement['name'].'" appears too strict and will likely not match what you want. See https://getcomposer.org/constraints</warning>'); } if (!isset($requirement['version'])) { // determine the best version automatically [$name, $version] = $this->findBestVersionAndNameForPackage($this->getIO(), $input, $requirement['name'], $platformRepo, $preferredStability, $fixed); // replace package name from packagist.org $requirement['name'] = $name; if ($useBestVersionConstraint) { $requirement['version'] = $version; $io->writeError(sprintf( 'Using version <info>%s</info> for <info>%s</info>', $requirement['version'], $requirement['name'] )); } else { $requirement['version'] = 'guess'; } } $result[] = $requirement['name'] . ' ' . $requirement['version']; } return $result; } $versionParser = new VersionParser(); // Collect existing packages $composer = $this->tryComposer(); $installedRepo = null; if (null !== $composer) { $installedRepo = $composer->getRepositoryManager()->getLocalRepository(); } $existingPackages = []; if (null !== $installedRepo) { foreach ($installedRepo->getPackages() as $package) { $existingPackages[] = $package->getName(); } } unset($composer, $installedRepo); $io = $this->getIO(); while (null !== $package = $io->ask('Search for a package: ')) { $matches = $this->getRepos()->search($package); if (count($matches) > 0) { // Remove existing packages from search results. foreach ($matches as $position => $foundPackage) { if (in_array($foundPackage['name'], $existingPackages, true)) { unset($matches[$position]); } } $matches = array_values($matches); $exactMatch = false; foreach ($matches as $match) { if ($match['name'] === $package) { $exactMatch = true; break; } } // no match, prompt which to pick if (!$exactMatch) { $providers = $this->getRepos()->getProviders($package); if (count($providers) > 0) { array_unshift($matches, ['name' => $package, 'description' => '']); } $choices = []; foreach ($matches as $position => $foundPackage) { $abandoned = ''; if (isset($foundPackage['abandoned'])) { if (is_string($foundPackage['abandoned'])) { $replacement = sprintf('Use %s instead', $foundPackage['abandoned']); } else { $replacement = 'No replacement was suggested'; } $abandoned = sprintf('<warning>Abandoned. %s.</warning>', $replacement); } $choices[] = sprintf(' <info>%5s</info> %s %s', "[$position]", $foundPackage['name'], $abandoned); } $io->writeError([ '', sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package), '', ]); $io->writeError($choices); $io->writeError(''); $validator = static function (string $selection) use ($matches, $versionParser) { if ('' === $selection) { return false; } if (is_numeric($selection) && isset($matches[(int) $selection])) { $package = $matches[(int) $selection]; return $package['name']; } if (Preg::isMatch('{^\s*(?P<name>[\S/]+)(?:\s+(?P<version>\S+))?\s*$}', $selection, $packageMatches)) { if (isset($packageMatches['version'])) { // parsing `acme/example ~2.3` // validate version constraint $versionParser->parseConstraints($packageMatches['version']); return $packageMatches['name'].' '.$packageMatches['version']; } // parsing `acme/example` return $packageMatches['name']; } throw new \Exception('Not a valid selection'); }; $package = $io->askAndValidate( 'Enter package # to add, or the complete package name if it is not listed: ', $validator, 3, '' ); } // no constraint yet, determine the best version automatically if (false !== $package && false === strpos($package, ' ')) { $validator = static function (string $input) { $input = trim($input); return strlen($input) > 0 ? $input : false; }; $constraint = $io->askAndValidate( 'Enter the version constraint to require (or leave blank to use the latest version): ', $validator, 3, '' ); if (false === $constraint) { [, $constraint] = $this->findBestVersionAndNameForPackage($this->getIO(), $input, $package, $platformRepo, $preferredStability); $io->writeError(sprintf( 'Using version <info>%s</info> for <info>%s</info>', $constraint, $package )); } $package .= ' '.$constraint; } if (false !== $package) { $requires[] = $package; $existingPackages[] = explode(' ', $package)[0]; } } } return $requires; } /** * Given a package name, this determines the best version to use in the require key. * * This returns a version with the ~ operator prefixed when possible. * * @throws \InvalidArgumentException * @return array{string, string} name version */ private function findBestVersionAndNameForPackage(IOInterface $io, InputInterface $input, string $name, ?PlatformRepository $platformRepo = null, string $preferredStability = 'stable', bool $fixed = false): array { // handle ignore-platform-reqs flag if present if ($input->hasOption('ignore-platform-reqs') && $input->hasOption('ignore-platform-req')) { $platformRequirementFilter = $this->getPlatformRequirementFilter($input); } else { $platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing(); } // find the latest version allowed in this repo set $repoSet = $this->getRepositorySet($input); $versionSelector = new VersionSelector($repoSet, $platformRepo); $effectiveMinimumStability = $this->getMinimumStability($input); $package = $versionSelector->findBestCandidate($name, null, $preferredStability, $platformRequirementFilter, 0, $this->getIO()); if (false === $package) { // platform packages can not be found in the pool in versions other than the local platform's has // so if platform reqs are ignored we just take the user's word for it if ($platformRequirementFilter->isIgnored($name)) { return [$name, '*']; } // Check if it is a virtual package provided by others $providers = $repoSet->getProviders($name); if (count($providers) > 0) { $constraint = '*'; if ($input->isInteractive()) { $constraint = $this->getIO()->askAndValidate('Package "<info>'.$name.'</info>" does not exist but is provided by '.count($providers).' packages. Which version constraint would you like to use? [<info>*</info>] ', static function ($value) { $parser = new VersionParser(); $parser->parseConstraints($value); return $value; }, 3, '*'); } return [$name, $constraint]; } // Check whether the package requirements were the problem if (!($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter) && false !== ($candidate = $versionSelector->findBestCandidate($name, null, $preferredStability, PlatformRequirementFilterFactory::ignoreAll()))) { throw new \InvalidArgumentException(sprintf( 'Package %s has requirements incompatible with your PHP version, PHP extensions and Composer version' . $this->getPlatformExceptionDetails($candidate, $platformRepo), $name )); } // Check whether the minimum stability was the problem but the package exists if (false !== ($package = $versionSelector->findBestCandidate($name, null, $preferredStability, $platformRequirementFilter, RepositorySet::ALLOW_UNACCEPTABLE_STABILITIES))) { // we must first verify if a valid package would be found in a lower priority repository if (false !== ($allReposPackage = $versionSelector->findBestCandidate($name, null, $preferredStability, $platformRequirementFilter, RepositorySet::ALLOW_SHADOWED_REPOSITORIES))) { throw new \InvalidArgumentException( 'Package '.$name.' exists in '.$allReposPackage->getRepository()->getRepoName().' and '.$package->getRepository()->getRepoName().' which has a higher repository priority. The packages from the higher priority repository do not match your minimum-stability and are therefore not installable. That repository is canonical so the lower priority repo\'s packages are not installable. See https://getcomposer.org/repoprio for details and assistance.' ); } throw new \InvalidArgumentException(sprintf( 'Could not find a version of package %s matching your minimum-stability (%s). Require it with an explicit version constraint allowing its desired stability.', $name, $effectiveMinimumStability )); } // Check whether the PHP version was the problem for all versions if (!$platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter && false !== ($candidate = $versionSelector->findBestCandidate($name, null, $preferredStability, PlatformRequirementFilterFactory::ignoreAll(), RepositorySet::ALLOW_UNACCEPTABLE_STABILITIES))) { $additional = ''; if (false === $versionSelector->findBestCandidate($name, null, $preferredStability, PlatformRequirementFilterFactory::ignoreAll())) { $additional = PHP_EOL.PHP_EOL.'Additionally, the package was only found with a stability of "'.$candidate->getStability().'" while your minimum stability is "'.$effectiveMinimumStability.'".'; } throw new \InvalidArgumentException(sprintf( 'Could not find package %s in any version matching your PHP version, PHP extensions and Composer version' . $this->getPlatformExceptionDetails($candidate, $platformRepo) . '%s', $name, $additional )); } // Check for similar names/typos $similar = $this->findSimilar($name); if (count($similar) > 0) { if (in_array($name, $similar, true)) { throw new \InvalidArgumentException(sprintf( "Could not find package %s. It was however found via repository search, which indicates a consistency issue with the repository.", $name )); } if ($input->isInteractive()) { $result = $io->select("<error>Could not find package $name.</error>\nPick one of these or leave empty to abort:", $similar, false, 1); if ($result !== false) { return $this->findBestVersionAndNameForPackage($io, $input, $similar[$result], $platformRepo, $preferredStability, $fixed); } } throw new \InvalidArgumentException(sprintf( "Could not find package %s.\n\nDid you mean " . (count($similar) > 1 ? 'one of these' : 'this') . "?\n %s", $name, implode("\n ", $similar) )); } throw new \InvalidArgumentException(sprintf( 'Could not find a matching version of package %s. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (%s).', $name, $effectiveMinimumStability )); } return [ $package->getPrettyName(), $fixed ? $package->getPrettyVersion() : $versionSelector->findRecommendedRequireVersion($package), ]; } /** * @return array<string> */ private function findSimilar(string $package): array { try { if (null === $this->repos) { throw new \LogicException('findSimilar was called before $this->repos was initialized'); } $results = $this->repos->search($package); } catch (\Throwable $e) { if ($e instanceof \LogicException) { throw $e; } // ignore search errors return []; } $similarPackages = []; $installedRepo = $this->requireComposer()->getRepositoryManager()->getLocalRepository(); foreach ($results as $result) { if (null !== $installedRepo->findPackage($result['name'], '*')) { // Ignore installed package continue; } $similarPackages[$result['name']] = levenshtein($package, $result['name']); } asort($similarPackages); return array_keys(array_slice($similarPackages, 0, 5)); } private function getPlatformExceptionDetails(PackageInterface $candidate, ?PlatformRepository $platformRepo = null): string { $details = []; if (null === $platformRepo) { return ''; } foreach ($candidate->getRequires() as $link) { if (!PlatformRepository::isPlatformPackage($link->getTarget())) { continue; } $platformPkg = $platformRepo->findPackage($link->getTarget(), '*'); if (null === $platformPkg) { if ($platformRepo->isPlatformPackageDisabled($link->getTarget())) { $details[] = $candidate->getPrettyName().' '.$candidate->getPrettyVersion().' requires '.$link->getTarget().' '.$link->getPrettyConstraint().' but it is disabled by your platform config. Enable it again with "composer config platform.'.$link->getTarget().' --unset".'; } else { $details[] = $candidate->getPrettyName().' '.$candidate->getPrettyVersion().' requires '.$link->getTarget().' '.$link->getPrettyConstraint().' but it is not present.'; } continue; } if (!$link->getConstraint()->matches(new Constraint('==', $platformPkg->getVersion()))) { $platformPkgVersion = $platformPkg->getPrettyVersion(); $platformExtra = $platformPkg->getExtra(); if (isset($platformExtra['config.platform']) && $platformPkg instanceof CompletePackageInterface) { $platformPkgVersion .= ' ('.$platformPkg->getDescription().')'; } $details[] = $candidate->getPrettyName().' '.$candidate->getPrettyVersion().' requires '.$link->getTarget().' '.$link->getPrettyConstraint().' which does not match your installed version '.$platformPkgVersion.'.'; } } if (count($details) === 0) { return ''; } return ':'.PHP_EOL.' - ' . implode(PHP_EOL.' - ', $details); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ClearCacheCommand.php
src/Composer/Command/ClearCacheCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Cache; use Composer\Factory; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author David Neilsen <petah.p@gmail.com> */ class ClearCacheCommand extends BaseCommand { protected function configure(): void { $this ->setName('clear-cache') ->setAliases(['clearcache', 'cc']) ->setDescription('Clears composer\'s internal package cache') ->setDefinition([ new InputOption('gc', null, InputOption::VALUE_NONE, 'Only run garbage collection, not a full cache clear'), ]) ->setHelp( <<<EOT The <info>clear-cache</info> deletes all cached packages from composer's cache directory. Read more at https://getcomposer.org/doc/03-cli.md#clear-cache-clearcache-cc EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->tryComposer(); if ($composer !== null) { $config = $composer->getConfig(); } else { $config = Factory::createConfig(); } $io = $this->getIO(); $cachePaths = [ 'cache-vcs-dir' => $config->get('cache-vcs-dir'), 'cache-repo-dir' => $config->get('cache-repo-dir'), 'cache-files-dir' => $config->get('cache-files-dir'), 'cache-dir' => $config->get('cache-dir'), ]; foreach ($cachePaths as $key => $cachePath) { // only individual dirs get garbage collected if ($key === 'cache-dir' && $input->getOption('gc')) { continue; } $cachePath = realpath($cachePath); if (!$cachePath) { $io->writeError("<info>Cache directory does not exist ($key): $cachePath</info>"); continue; } $cache = new Cache($io, $cachePath); $cache->setReadOnly($config->get('cache-read-only')); if (!$cache->isEnabled()) { $io->writeError("<info>Cache is not enabled ($key): $cachePath</info>"); continue; } if ($input->getOption('gc')) { $io->writeError("<info>Garbage-collecting cache ($key): $cachePath</info>"); if ($key === 'cache-files-dir') { $cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize')); } elseif ($key === 'cache-repo-dir') { $cache->gc($config->get('cache-ttl'), 1024 * 1024 * 1024 /* 1GB, this should almost never clear anything that is not outdated */); } elseif ($key === 'cache-vcs-dir') { $cache->gcVcsCache($config->get('cache-ttl')); } } else { $io->writeError("<info>Clearing cache ($key): $cachePath</info>"); $cache->clear(); } } if ($input->getOption('gc')) { $io->writeError('<info>All caches garbage-collected.</info>'); } else { $io->writeError('<info>All caches cleared.</info>'); } return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/SuggestsCommand.php
src/Composer/Command/SuggestsCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Repository\PlatformRepository; use Composer\Repository\RootPackageRepository; use Composer\Repository\InstalledRepository; use Composer\Installer\SuggestedPackagesReporter; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class SuggestsCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('suggests') ->setDescription('Shows package suggestions') ->setDefinition([ new InputOption('by-package', null, InputOption::VALUE_NONE, 'Groups output by suggesting package (default)'), new InputOption('by-suggestion', null, InputOption::VALUE_NONE, 'Groups output by suggested package'), new InputOption('all', 'a', InputOption::VALUE_NONE, 'Show suggestions from all dependencies, including transitive ones'), new InputOption('list', null, InputOption::VALUE_NONE, 'Show only list of suggested package names'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Exclude suggestions from require-dev packages'), new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Packages that you want to list suggestions from.', null, $this->suggestInstalledPackage()), ]) ->setHelp( <<<EOT The <info>%command.name%</info> command shows a sorted list of suggested packages. Read more at https://getcomposer.org/doc/03-cli.md#suggests EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $installedRepos = [ new RootPackageRepository(clone $composer->getPackage()), ]; $locker = $composer->getLocker(); if ($locker->isLocked()) { $installedRepos[] = new PlatformRepository([], $locker->getPlatformOverrides()); $installedRepos[] = $locker->getLockedRepository(!$input->getOption('no-dev')); } else { $installedRepos[] = new PlatformRepository([], $composer->getConfig()->get('platform')); $installedRepos[] = $composer->getRepositoryManager()->getLocalRepository(); } $installedRepo = new InstalledRepository($installedRepos); $reporter = new SuggestedPackagesReporter($this->getIO()); $filter = $input->getArgument('packages'); $packages = $installedRepo->getPackages(); $packages[] = $composer->getPackage(); foreach ($packages as $package) { if (!empty($filter) && !in_array($package->getName(), $filter)) { continue; } $reporter->addSuggestionsFromPackage($package); } // Determine output mode, default is by-package $mode = SuggestedPackagesReporter::MODE_BY_PACKAGE; // if by-suggestion is given we override the default if ($input->getOption('by-suggestion')) { $mode = SuggestedPackagesReporter::MODE_BY_SUGGESTION; } // unless by-package is also present then we enable both if ($input->getOption('by-package')) { $mode |= SuggestedPackagesReporter::MODE_BY_PACKAGE; } // list is exclusive and overrides everything else if ($input->getOption('list')) { $mode = SuggestedPackagesReporter::MODE_LIST; } $reporter->output($mode, $installedRepo, empty($filter) && !$input->getOption('all') ? $composer->getPackage() : null); return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ExecCommand.php
src/Composer/Command/ExecCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Console\Input\InputArgument; /** * @author Davey Shafik <me@daveyshafik.com> */ class ExecCommand extends BaseCommand { protected function configure(): void { $this ->setName('exec') ->setDescription('Executes a vendored binary/script') ->setDefinition([ new InputOption('list', 'l', InputOption::VALUE_NONE), new InputArgument('binary', InputArgument::OPTIONAL, 'The binary to run, e.g. phpunit', null, function () { return $this->getBinaries(false); }), new InputArgument( 'args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Arguments to pass to the binary. Use <info>--</info> to separate from composer arguments' ), ]) ->setHelp( <<<EOT Executes a vendored binary/script. Read more at https://getcomposer.org/doc/03-cli.md#exec EOT ) ; } protected function interact(InputInterface $input, OutputInterface $output): void { $binaries = $this->getBinaries(false); if (count($binaries) === 0) { return; } if ($input->getArgument('binary') !== null || $input->getOption('list')) { return; } $io = $this->getIO(); /** @var int $binary */ $binary = $io->select( 'Binary to run: ', $binaries, '', 1, 'Invalid binary name "%s"' ); $input->setArgument('binary', $binaries[$binary]); } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); if ($input->getOption('list') || null === $input->getArgument('binary')) { $bins = $this->getBinaries(true); if ([] === $bins) { $binDir = $composer->getConfig()->get('bin-dir'); throw new \RuntimeException("No binaries found in composer.json or in bin-dir ($binDir)"); } $this->getIO()->write( <<<EOT <comment>Available binaries:</comment> EOT ); foreach ($bins as $bin) { $this->getIO()->write( <<<EOT <info>- $bin</info> EOT ); } return 0; } $binary = $input->getArgument('binary'); $dispatcher = $composer->getEventDispatcher(); $dispatcher->addListener('__exec_command', $binary); // If the CWD was modified, we restore it to what it was initially, as it was // most likely modified by the global command, and we want exec to run in the local working directory // not the global one if (getcwd() !== $this->getApplication()->getInitialWorkingDirectory() && $this->getApplication()->getInitialWorkingDirectory() !== false) { try { chdir($this->getApplication()->getInitialWorkingDirectory()); } catch (\Exception $e) { throw new \RuntimeException('Could not switch back to working directory "'.$this->getApplication()->getInitialWorkingDirectory().'"', 0, $e); } } return $dispatcher->dispatchScript('__exec_command', true, $input->getArgument('args')); } /** * @return list<string> */ private function getBinaries(bool $forDisplay): array { $composer = $this->requireComposer(); $binDir = $composer->getConfig()->get('bin-dir'); $bins = glob($binDir . '/*'); $localBins = $composer->getPackage()->getBinaries(); if ($forDisplay) { $localBins = array_map(static function ($e) { return "$e (local)"; }, $localBins); } $binaries = []; foreach (array_merge($bins, $localBins) as $bin) { // skip .bat copies if (isset($previousBin) && $bin === $previousBin.'.bat') { continue; } $previousBin = $bin; $binaries[] = basename($bin); } return $binaries; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/RequireCommand.php
src/Composer/Command/RequireCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\DependencyResolver\Request; use Composer\Package\AliasPackage; use Composer\Package\CompletePackageInterface; use Composer\Package\Loader\RootPackageLoader; use Composer\Package\PackageInterface; use Composer\Package\Version\VersionSelector; use Composer\Pcre\Preg; use Composer\Repository\RepositorySet; use Composer\Util\Filesystem; use Composer\Util\PackageSorter; use Seld\Signal\SignalHandler; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Factory; use Composer\Installer; use Composer\Installer\InstallerEvents; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Package\Version\VersionParser; use Composer\Package\Loader\ArrayLoader; use Composer\Package\BasePackage; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\IO\IOInterface; use Composer\Advisory\Auditor; use Composer\Util\Silencer; /** * @author Jérémy Romey <jeremy@free-agent.fr> * @author Jordi Boggiano <j.boggiano@seld.be> */ class RequireCommand extends BaseCommand { use CompletionTrait; use PackageDiscoveryTrait; /** @var bool */ private $newlyCreated; /** @var bool */ private $firstRequire; /** @var JsonFile */ private $json; /** @var string */ private $file; /** @var string */ private $composerBackup; /** @var string file name */ private $lock; /** @var ?string contents before modification if the lock file exists */ private $lockBackup; /** @var bool */ private $dependencyResolutionCompleted = false; protected function configure(): void { $this ->setName('require') ->setAliases(['r']) ->setDescription('Adds required packages to your composer.json and installs them') ->setDefinition([ new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name can also include a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"', null, $this->suggestAvailablePackageInclPlatform()), new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'), new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()), new InputOption('fixed', null, InputOption::VALUE_NONE, 'Write fixed version to the composer.json.'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'DEPRECATED: This flag does not exist anymore.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies (implies --no-install).'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Skip the install step after updating the composer.lock file.'), new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Skip the audit step after updating the composer.lock file (can also be set via the COMPOSER_NO_AUDIT=1 env var).'), new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS), new InputOption('no-security-blocking', null, InputOption::VALUE_NONE, 'Allows installing packages with security advisories or that are abandoned (can also be set via the COMPOSER_NO_SECURITY_BLOCKING=1 env var).'), new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'), new InputOption('update-with-dependencies', 'w', InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated, except those that are root requirements (can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var).'), new InputOption('update-with-all-dependencies', 'W', InputOption::VALUE_NONE, 'Allows all inherited dependencies to be updated, including those that are root requirements (can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var).'), new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-dependencies'), new InputOption('with-all-dependencies', null, InputOption::VALUE_NONE, 'Alias for --update-with-all-dependencies'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies (can also be set via the COMPOSER_PREFER_STABLE=1 env var).'), new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies (can also be set via the COMPOSER_PREFER_LOWEST=1 env var).'), new InputOption('minimal-changes', 'm', InputOption::VALUE_NONE, 'During an update with -w/-W, only perform absolutely necessary changes to transitive dependencies (can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var).'), new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'), ]) ->setHelp( <<<EOT The require command adds required packages to your composer.json and installs them. If you do not specify a package, composer will prompt you to search for a package, and given results, provide a list of matches to require. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions. If you do not want to install the new dependencies immediately you can call it with --no-update Read more at https://getcomposer.org/doc/03-cli.md#require-r EOT ) ; } /** * @throws \Seld\JsonLint\ParsingException */ protected function execute(InputInterface $input, OutputInterface $output): int { $this->file = Factory::getComposerFile(); $io = $this->getIO(); if ($input->getOption('no-suggest')) { $io->writeError('<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>'); } $this->newlyCreated = !file_exists($this->file); if ($this->newlyCreated && !file_put_contents($this->file, "{\n}\n")) { $io->writeError('<error>'.$this->file.' could not be created.</error>'); return 1; } if (!Filesystem::isReadable($this->file)) { $io->writeError('<error>'.$this->file.' is not readable.</error>'); return 1; } if (filesize($this->file) === 0) { file_put_contents($this->file, "{\n}\n"); } $this->json = new JsonFile($this->file); $this->lock = Factory::getLockFile($this->file); $this->composerBackup = file_get_contents($this->json->getPath()); $this->lockBackup = file_exists($this->lock) ? file_get_contents($this->lock) : null; $signalHandler = SignalHandler::create([SignalHandler::SIGINT, SignalHandler::SIGTERM, SignalHandler::SIGHUP], function (string $signal, SignalHandler $handler) { $this->getIO()->writeError('Received '.$signal.', aborting', true, IOInterface::DEBUG); $this->revertComposerFile(); $handler->exitWithLastSignal(); }); // check for writability by writing to the file as is_writable can not be trusted on network-mounts // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926 if (!is_writable($this->file) && false === Silencer::call('file_put_contents', $this->file, $this->composerBackup)) { $io->writeError('<error>'.$this->file.' is not writable.</error>'); return 1; } if ($input->getOption('fixed') === true) { $config = $this->json->read(); $packageType = empty($config['type']) ? 'library' : $config['type']; /** * @see https://github.com/composer/composer/pull/8313#issuecomment-532637955 */ if ($packageType !== 'project' && !$input->getOption('dev')) { $io->writeError('<error>The "--fixed" option is only allowed for packages with a "project" type or for dev dependencies to prevent possible misuses.</error>'); if (!isset($config['type'])) { $io->writeError('<error>If your package is not a library, you can explicitly specify the "type" by using "composer config type project".</error>'); } return 1; } } $composer = $this->requireComposer(); $repos = $composer->getRepositoryManager()->getRepositories(); $platformOverrides = $composer->getConfig()->get('platform'); // initialize $this->repos as it is used by the PackageDiscoveryTrait $this->repos = new CompositeRepository(array_merge( [$platformRepo = new PlatformRepository([], $platformOverrides)], $repos )); if ($composer->getPackage()->getPreferStable()) { $preferredStability = 'stable'; } else { $preferredStability = $composer->getPackage()->getMinimumStability(); } try { $requirements = $this->determineRequirements( $input, $output, $input->getArgument('packages'), $platformRepo, $preferredStability, $input->getOption('no-update'), // if there is no update, we need to use the best possible version constraint directly as we cannot rely on the solver to guess the best constraint $input->getOption('fixed') ); } catch (\Exception $e) { if ($this->newlyCreated) { $this->revertComposerFile(); throw new \RuntimeException('No composer.json present in the current directory ('.$this->file.'), this may be the cause of the following exception.', 0, $e); } throw $e; } $requirements = $this->formatRequirements($requirements); if (!$input->getOption('dev') && $io->isInteractive() && !$composer->isGlobal()) { $devPackages = []; $devTags = ['dev', 'testing', 'static analysis']; $currentRequiresByKey = $this->getPackagesByRequireKey(); foreach ($requirements as $name => $version) { // skip packages which are already in the composer.json as those have already been decided if (isset($currentRequiresByKey[$name])) { continue; } $pkg = PackageSorter::getMostCurrentVersion($this->getRepos()->findPackages($name)); if ($pkg instanceof CompletePackageInterface) { $pkgDevTags = array_intersect($devTags, array_map('strtolower', $pkg->getKeywords())); if (count($pkgDevTags) > 0) { $devPackages[] = $pkgDevTags; } } } if (count($devPackages) === count($requirements)) { $plural = count($requirements) > 1 ? 's' : ''; $plural2 = count($requirements) > 1 ? 'are' : 'is'; $plural3 = count($requirements) > 1 ? 'they are' : 'it is'; $pkgDevTags = array_unique(array_merge(...$devPackages)); $io->warning('The package'.$plural.' you required '.$plural2.' recommended to be placed in require-dev (because '.$plural3.' tagged as "'.implode('", "', $pkgDevTags).'") but you did not use --dev.'); if ($io->askConfirmation('<info>Do you want to re-run the command with --dev?</> [<comment>yes</>]? ')) { $input->setOption('dev', true); } } unset($devPackages, $pkgDevTags); } $requireKey = $input->getOption('dev') ? 'require-dev' : 'require'; $removeKey = $input->getOption('dev') ? 'require' : 'require-dev'; // check which requirements need the version guessed $requirementsToGuess = []; foreach ($requirements as $package => $constraint) { if ($constraint === 'guess') { $requirements[$package] = '*'; $requirementsToGuess[] = $package; } } // validate requirements format $versionParser = new VersionParser(); foreach ($requirements as $package => $constraint) { if (strtolower($package) === $composer->getPackage()->getName()) { $io->writeError(sprintf('<error>Root package \'%s\' cannot require itself in its composer.json</error>', $package)); return 1; } if ($constraint === 'self.version') { continue; } $versionParser->parseConstraints($constraint); } $inconsistentRequireKeys = $this->getInconsistentRequireKeys($requirements, $requireKey); if (count($inconsistentRequireKeys) > 0) { foreach ($inconsistentRequireKeys as $package) { $io->warning(sprintf( '%s is currently present in the %s key and you ran the command %s the --dev flag, which will move it to the %s key.', $package, $removeKey, $input->getOption('dev') ? 'with' : 'without', $requireKey )); } if ($io->isInteractive()) { if (!$io->askConfirmation(sprintf('<info>Do you want to move %s?</info> [<comment>no</comment>]? ', count($inconsistentRequireKeys) > 1 ? 'these requirements' : 'this requirement'), false)) { if (!$io->askConfirmation(sprintf('<info>Do you want to re-run the command %s --dev?</info> [<comment>yes</comment>]? ', $input->getOption('dev') ? 'without' : 'with'), true)) { return 0; } $input->setOption('dev', true); [$requireKey, $removeKey] = [$removeKey, $requireKey]; } } } $sortPackages = $input->getOption('sort-packages') || $composer->getConfig()->get('sort-packages'); $this->firstRequire = $this->newlyCreated; if (!$this->firstRequire) { $composerDefinition = $this->json->read(); if (count($composerDefinition['require'] ?? []) === 0 && count($composerDefinition['require-dev'] ?? []) === 0) { $this->firstRequire = true; } } if (!$input->getOption('dry-run')) { $this->updateFile($this->json, $requirements, $requireKey, $removeKey, $sortPackages); } $io->writeError('<info>'.$this->file.' has been '.($this->newlyCreated ? 'created' : 'updated').'</info>'); if ($input->getOption('no-update')) { return 0; } $composer->getPluginManager()->deactivateInstalledPlugins(); try { $result = $this->doUpdate($input, $output, $io, $requirements, $requireKey, $removeKey); if ($result === 0 && count($requirementsToGuess) > 0) { $result = $this->updateRequirementsAfterResolution($requirementsToGuess, $requireKey, $removeKey, $sortPackages, $input->getOption('dry-run'), $input->getOption('fixed')); } return $result; } catch (\Exception $e) { if (!$this->dependencyResolutionCompleted) { $this->revertComposerFile(); } throw $e; } finally { if ($input->getOption('dry-run') && $this->newlyCreated) { @unlink($this->json->getPath()); } $signalHandler->unregister(); } } /** * @param array<string, string> $newRequirements * @return string[] */ private function getInconsistentRequireKeys(array $newRequirements, string $requireKey): array { $requireKeys = $this->getPackagesByRequireKey(); $inconsistentRequirements = []; foreach ($requireKeys as $package => $packageRequireKey) { if (!isset($newRequirements[$package])) { continue; } if ($requireKey !== $packageRequireKey) { $inconsistentRequirements[] = $package; } } return $inconsistentRequirements; } /** * @return array<string, string> */ private function getPackagesByRequireKey(): array { $composerDefinition = $this->json->read(); $require = []; $requireDev = []; if (isset($composerDefinition['require'])) { $require = $composerDefinition['require']; } if (isset($composerDefinition['require-dev'])) { $requireDev = $composerDefinition['require-dev']; } return array_merge( array_fill_keys(array_keys($require), 'require'), array_fill_keys(array_keys($requireDev), 'require-dev') ); } /** * @param array<string, string> $requirements * @param 'require'|'require-dev' $requireKey * @param 'require'|'require-dev' $removeKey * @throws \Exception */ private function doUpdate(InputInterface $input, OutputInterface $output, IOInterface $io, array $requirements, string $requireKey, string $removeKey): int { // Update packages $this->resetComposer(); $composer = $this->requireComposer(); $this->dependencyResolutionCompleted = false; $composer->getEventDispatcher()->addListener(InstallerEvents::PRE_OPERATIONS_EXEC, function (): void { $this->dependencyResolutionCompleted = true; }, 10000); if ($input->getOption('dry-run')) { $rootPackage = $composer->getPackage(); $links = [ 'require' => $rootPackage->getRequires(), 'require-dev' => $rootPackage->getDevRequires(), ]; $loader = new ArrayLoader(); $newLinks = $loader->parseLinks($rootPackage->getName(), $rootPackage->getPrettyVersion(), BasePackage::$supportedLinkTypes[$requireKey]['method'], $requirements); $links[$requireKey] = array_merge($links[$requireKey], $newLinks); foreach ($requirements as $package => $constraint) { unset($links[$removeKey][$package]); } $rootPackage->setRequires($links['require']); $rootPackage->setDevRequires($links['require-dev']); // extract stability flags & references as they weren't present when loading the unmodified composer.json $references = $rootPackage->getReferences(); $references = RootPackageLoader::extractReferences($requirements, $references); $rootPackage->setReferences($references); $stabilityFlags = $rootPackage->getStabilityFlags(); $stabilityFlags = RootPackageLoader::extractStabilityFlags($requirements, $rootPackage->getMinimumStability(), $stabilityFlags); $rootPackage->setStabilityFlags($stabilityFlags); unset($stabilityFlags, $references); } $updateDevMode = !$input->getOption('update-no-dev'); $optimize = $input->getOption('optimize-autoloader') || $composer->getConfig()->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $composer->getConfig()->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-autoloader-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $composer->getConfig()->get('apcu-autoloader'); $minimalChanges = $input->getOption('minimal-changes') || $composer->getConfig()->get('update-with-minimal-changes'); $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED; $flags = ''; if ($input->getOption('update-with-all-dependencies') || $input->getOption('with-all-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS; $flags .= ' --with-all-dependencies'; } elseif ($input->getOption('update-with-dependencies') || $input->getOption('with-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE; $flags .= ' --with-dependencies'; } $io->writeError('<info>Running composer update '.implode(' ', array_keys($requirements)).$flags.'</info>'); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $composer->getInstallationManager()->setOutputProgress(!$input->getOption('no-progress')); $install = Installer::create($io, $composer); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($composer->getConfig(), $input); $install ->setDryRun($input->getOption('dry-run')) ->setVerbose($input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode($updateDevMode) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu, $apcuPrefix) ->setUpdate(true) ->setInstall(!$input->getOption('no-install')) ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies) ->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)) ->setPreferStable($input->getOption('prefer-stable')) ->setPreferLowest($input->getOption('prefer-lowest')) ->setAuditConfig($this->createAuditConfig($composer->getConfig(), $input)) ->setMinimalUpdate($minimalChanges) ; // if no lock is present, or the file is brand new, we do not do a // partial update as this is not supported by the Installer if (!$this->firstRequire && $composer->getLocker()->isLocked()) { $install->setUpdateAllowList(array_keys($requirements)); } $status = $install->run(); if ($status !== 0 && $status !== Installer::ERROR_AUDIT_FAILED) { if ($status === Installer::ERROR_DEPENDENCY_RESOLUTION_FAILED) { foreach ($this->normalizeRequirements($input->getArgument('packages')) as $req) { if (!isset($req['version'])) { $io->writeError('You can also try re-running composer require with an explicit version constraint, e.g. "composer require '.$req['name'].':*" to figure out if any version is installable, or "composer require '.$req['name'].':^2.1" if you know which you need.'); break; } } } $this->revertComposerFile(); } return $status; } /** * @param list<string> $requirementsToUpdate */ private function updateRequirementsAfterResolution(array $requirementsToUpdate, string $requireKey, string $removeKey, bool $sortPackages, bool $dryRun, bool $fixed): int { $composer = $this->requireComposer(); $locker = $composer->getLocker(); $requirements = []; $versionSelector = new VersionSelector(new RepositorySet()); $repo = $locker->isLocked() ? $composer->getLocker()->getLockedRepository(true) : $composer->getRepositoryManager()->getLocalRepository(); foreach ($requirementsToUpdate as $packageName) { $package = $repo->findPackage($packageName, '*'); while ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } if (!$package instanceof PackageInterface) { continue; } if ($fixed) { $requirements[$packageName] = $package->getPrettyVersion(); } else { $requirements[$packageName] = $versionSelector->findRecommendedRequireVersion($package); } $this->getIO()->writeError(sprintf( 'Using version <info>%s</info> for <info>%s</info>', $requirements[$packageName], $packageName )); if (Preg::isMatch('{^dev-(?!main$|master$|trunk$|latest$)}', $requirements[$packageName])) { $this->getIO()->warning('Version '.$requirements[$packageName].' looks like it may be a feature branch which is unlikely to keep working in the long run and may be in an unstable state'); if ($this->getIO()->isInteractive() && !$this->getIO()->askConfirmation('Are you sure you want to use this constraint (<comment>y</comment>) or would you rather abort (<comment>n</comment>) the whole operation [<comment>y,n</comment>]? ')) { $this->revertComposerFile(); return 1; } } } if (!$dryRun) { $this->updateFile($this->json, $requirements, $requireKey, $removeKey, $sortPackages); if ($locker->isLocked() && $composer->getConfig()->get('lock')) { $stabilityFlags = RootPackageLoader::extractStabilityFlags($requirements, $composer->getPackage()->getMinimumStability(), []); $locker->updateHash($this->json, static function (array $lockData) use ($stabilityFlags) { foreach ($stabilityFlags as $packageName => $flag) { $lockData['stability-flags'][$packageName] = $flag; } return $lockData; }); } } return 0; } /** * @param array<string, string> $new */ private function updateFile(JsonFile $json, array $new, string $requireKey, string $removeKey, bool $sortPackages): void { if ($this->updateFileCleanly($json, $new, $requireKey, $removeKey, $sortPackages)) { return; } $composerDefinition = $this->json->read(); foreach ($new as $package => $version) { $composerDefinition[$requireKey][$package] = $version; unset($composerDefinition[$removeKey][$package]); if (isset($composerDefinition[$removeKey]) && count($composerDefinition[$removeKey]) === 0) { unset($composerDefinition[$removeKey]); } } $this->json->write($composerDefinition); } /** * @param array<string, string> $new */ private function updateFileCleanly(JsonFile $json, array $new, string $requireKey, string $removeKey, bool $sortPackages): bool { $contents = file_get_contents($json->getPath()); $manipulator = new JsonManipulator($contents); foreach ($new as $package => $constraint) { if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) { return false; } if (!$manipulator->removeSubNode($removeKey, $package)) { return false; } } $manipulator->removeMainKeyIfEmpty($removeKey); file_put_contents($json->getPath(), $manipulator->getContents()); return true; } protected function interact(InputInterface $input, OutputInterface $output): void { } private function revertComposerFile(): void { $io = $this->getIO(); if ($this->newlyCreated) { $io->writeError("\n".'<error>Installation failed, deleting '.$this->file.'.</error>'); unlink($this->json->getPath()); if (file_exists($this->lock)) { unlink($this->lock); } } else { $msg = ' to its '; if ($this->lockBackup) { $msg = ' and '.$this->lock.' to their '; } $io->writeError("\n".'<error>Installation failed, reverting '.$this->file.$msg.'original content.</error>'); file_put_contents($this->json->getPath(), $this->composerBackup); if ($this->lockBackup) { file_put_contents($this->lock, $this->lockBackup); } } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/BaseCommand.php
src/Composer/Command/BaseCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Config; use Composer\Console\Application; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; use Composer\Factory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\IO\IOInterface; use Composer\IO\NullIO; use Composer\Plugin\PreCommandRunEvent; use Composer\Package\Version\VersionParser; use Composer\Plugin\PluginEvents; use Composer\Advisory\Auditor; use Composer\Advisory\AuditConfig; use Composer\Util\Platform; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Helper\TableSeparator; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Terminal; /** * Base class for Composer commands * * @author Ryan Weaver <ryan@knplabs.com> * @author Konstantin Kudryashov <ever.zet@gmail.com> */ abstract class BaseCommand extends Command { /** * @var Composer|null */ private $composer; /** * @var IOInterface */ private $io; /** * Gets the application instance for this command. */ public function getApplication(): Application { $application = parent::getApplication(); if (!$application instanceof Application) { throw new \RuntimeException('Composer commands can only work with an '.Application::class.' instance set'); } return $application; } /** * @param bool $required Should be set to false, or use `requireComposer` instead * @param bool|null $disablePlugins If null, reads --no-plugins as default * @param bool|null $disableScripts If null, reads --no-scripts as default * @throws \RuntimeException * @return Composer|null * @deprecated since Composer 2.3.0 use requireComposer or tryComposer depending on whether you have $required set to true or false */ public function getComposer(bool $required = true, ?bool $disablePlugins = null, ?bool $disableScripts = null) { if ($required) { return $this->requireComposer($disablePlugins, $disableScripts); } return $this->tryComposer($disablePlugins, $disableScripts); } /** * Retrieves the default Composer\Composer instance or throws * * Use this instead of getComposer if you absolutely need an instance * * @param bool|null $disablePlugins If null, reads --no-plugins as default * @param bool|null $disableScripts If null, reads --no-scripts as default * @throws \RuntimeException */ public function requireComposer(?bool $disablePlugins = null, ?bool $disableScripts = null): Composer { if (null === $this->composer) { $application = parent::getApplication(); if ($application instanceof Application) { $this->composer = $application->getComposer(true, $disablePlugins, $disableScripts); assert($this->composer instanceof Composer); } else { throw new \RuntimeException( 'Could not create a Composer\Composer instance, you must inject '. 'one if this command is not used with a Composer\Console\Application instance' ); } } return $this->composer; } /** * Retrieves the default Composer\Composer instance or null * * Use this instead of getComposer(false) * * @param bool|null $disablePlugins If null, reads --no-plugins as default * @param bool|null $disableScripts If null, reads --no-scripts as default */ public function tryComposer(?bool $disablePlugins = null, ?bool $disableScripts = null): ?Composer { if (null === $this->composer) { $application = parent::getApplication(); if ($application instanceof Application) { $this->composer = $application->getComposer(false, $disablePlugins, $disableScripts); } } return $this->composer; } /** * @return void */ public function setComposer(Composer $composer) { $this->composer = $composer; } /** * Removes the cached composer instance * * @return void */ public function resetComposer() { $this->composer = null; $this->getApplication()->resetComposer(); } /** * Whether or not this command is meant to call another command. * * This is mainly needed to avoid duplicated warnings messages. * * @return bool */ public function isProxyCommand() { return false; } /** * @return IOInterface */ public function getIO() { if (null === $this->io) { $application = parent::getApplication(); if ($application instanceof Application) { $this->io = $application->getIO(); } else { $this->io = new NullIO(); } } return $this->io; } /** * @return void */ public function setIO(IOInterface $io) { $this->io = $io; } /** * @inheritdoc * * Backport suggested values definition from symfony/console 6.1+ * * TODO drop when PHP 8.1 / symfony 6.1+ can be required */ public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void { $definition = $this->getDefinition(); $name = (string) $input->getCompletionName(); if (CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType() && $definition->hasOption($name) && ($option = $definition->getOption($name)) instanceof InputOption ) { $option->complete($input, $suggestions); } elseif (CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() && $definition->hasArgument($name) && ($argument = $definition->getArgument($name)) instanceof InputArgument ) { $argument->complete($input, $suggestions); } else { parent::complete($input, $suggestions); } } /** * @inheritDoc */ protected function initialize(InputInterface $input, OutputInterface $output): void { // initialize a plugin-enabled Composer instance, either local or global $disablePlugins = $input->hasParameterOption('--no-plugins'); $disableScripts = $input->hasParameterOption('--no-scripts'); $application = parent::getApplication(); if ($application instanceof Application && $application->getDisablePluginsByDefault()) { $disablePlugins = true; } if ($application instanceof Application && $application->getDisableScriptsByDefault()) { $disableScripts = true; } if ($this instanceof SelfUpdateCommand) { $disablePlugins = true; $disableScripts = true; } $composer = $this->tryComposer($disablePlugins, $disableScripts); $io = $this->getIO(); if (null === $composer) { $composer = Factory::createGlobal($this->getIO(), $disablePlugins, $disableScripts); } if ($composer) { $preCommandRunEvent = new PreCommandRunEvent(PluginEvents::PRE_COMMAND_RUN, $input, $this->getName()); $composer->getEventDispatcher()->dispatch($preCommandRunEvent->getName(), $preCommandRunEvent); } if (true === $input->hasParameterOption(['--no-ansi']) && $input->hasOption('no-progress')) { $input->setOption('no-progress', true); } $envOptions = [ 'COMPOSER_NO_AUDIT' => ['no-audit'], 'COMPOSER_NO_DEV' => ['no-dev', 'update-no-dev'], 'COMPOSER_PREFER_STABLE' => ['prefer-stable'], 'COMPOSER_PREFER_LOWEST' => ['prefer-lowest'], 'COMPOSER_MINIMAL_CHANGES' => ['minimal-changes'], 'COMPOSER_WITH_DEPENDENCIES' => ['with-dependencies'], 'COMPOSER_WITH_ALL_DEPENDENCIES' => ['with-all-dependencies'], 'COMPOSER_NO_SECURITY_BLOCKING' => ['no-security-blocking'], ]; foreach ($envOptions as $envName => $optionNames) { foreach ($optionNames as $optionName) { if (true === $input->hasOption($optionName)) { if (false === $input->getOption($optionName) && (bool) Platform::getEnv($envName)) { $input->setOption($optionName, true); } } } } if (true === $input->hasOption('ignore-platform-reqs')) { if (!$input->getOption('ignore-platform-reqs') && (bool) Platform::getEnv('COMPOSER_IGNORE_PLATFORM_REQS')) { $input->setOption('ignore-platform-reqs', true); $io->writeError('<warning>COMPOSER_IGNORE_PLATFORM_REQS is set. You may experience unexpected errors.</warning>'); } } if (true === $input->hasOption('ignore-platform-req') && (!$input->hasOption('ignore-platform-reqs') || !$input->getOption('ignore-platform-reqs'))) { $ignorePlatformReqEnv = Platform::getEnv('COMPOSER_IGNORE_PLATFORM_REQ'); if (0 === count($input->getOption('ignore-platform-req')) && is_string($ignorePlatformReqEnv) && '' !== $ignorePlatformReqEnv) { $input->setOption('ignore-platform-req', explode(',', $ignorePlatformReqEnv)); $io->writeError('<warning>COMPOSER_IGNORE_PLATFORM_REQ is set to ignore '.$ignorePlatformReqEnv.'. You may experience unexpected errors.</warning>'); } } parent::initialize($input, $output); } /** * Calls {@see Factory::create()} with the given arguments, taking into account flags and default states for disabling scripts and plugins * * @param mixed $config either a configuration array or a filename to read from, if null it will read from * the default filename */ protected function createComposerInstance(InputInterface $input, IOInterface $io, $config = null, ?bool $disablePlugins = null, ?bool $disableScripts = null): Composer { $disablePlugins = $disablePlugins === true || $input->hasParameterOption('--no-plugins'); $disableScripts = $disableScripts === true || $input->hasParameterOption('--no-scripts'); $application = parent::getApplication(); if ($application instanceof Application && $application->getDisablePluginsByDefault()) { $disablePlugins = true; } if ($application instanceof Application && $application->getDisableScriptsByDefault()) { $disableScripts = true; } return Factory::create($io, $config, $disablePlugins, $disableScripts); } /** * Returns preferSource and preferDist values based on the configuration. * * @return bool[] An array composed of the preferSource and preferDist values */ protected function getPreferredInstallOptions(Config $config, InputInterface $input, bool $keepVcsRequiresPreferSource = false) { $preferSource = false; $preferDist = false; switch ($config->get('preferred-install')) { case 'source': $preferSource = true; break; case 'dist': $preferDist = true; break; case 'auto': default: // noop break; } if (!$input->hasOption('prefer-dist') || !$input->hasOption('prefer-source')) { return [$preferSource, $preferDist]; } if ($input->hasOption('prefer-install') && is_string($input->getOption('prefer-install'))) { if ($input->getOption('prefer-source')) { throw new \InvalidArgumentException('--prefer-source can not be used together with --prefer-install'); } if ($input->getOption('prefer-dist')) { throw new \InvalidArgumentException('--prefer-dist can not be used together with --prefer-install'); } switch ($input->getOption('prefer-install')) { case 'dist': $input->setOption('prefer-dist', true); break; case 'source': $input->setOption('prefer-source', true); break; case 'auto': $preferDist = false; $preferSource = false; break; default: throw new \UnexpectedValueException('--prefer-install accepts one of "dist", "source" or "auto", got '.$input->getOption('prefer-install')); } } if ($input->getOption('prefer-source') || $input->getOption('prefer-dist') || ($keepVcsRequiresPreferSource && $input->hasOption('keep-vcs') && $input->getOption('keep-vcs'))) { $preferSource = $input->getOption('prefer-source') || ($keepVcsRequiresPreferSource && $input->hasOption('keep-vcs') && $input->getOption('keep-vcs')); $preferDist = $input->getOption('prefer-dist'); } return [$preferSource, $preferDist]; } protected function getPlatformRequirementFilter(InputInterface $input): PlatformRequirementFilterInterface { if (!$input->hasOption('ignore-platform-reqs') || !$input->hasOption('ignore-platform-req')) { throw new \LogicException('Calling getPlatformRequirementFilter from a command which does not define the --ignore-platform-req[s] flags is not permitted.'); } if (true === $input->getOption('ignore-platform-reqs')) { return PlatformRequirementFilterFactory::ignoreAll(); } $ignores = $input->getOption('ignore-platform-req'); if (count($ignores) > 0) { return PlatformRequirementFilterFactory::fromBoolOrList($ignores); } return PlatformRequirementFilterFactory::ignoreNothing(); } /** * @param array<string> $requirements * * @return array<string, string> */ protected function formatRequirements(array $requirements) { $requires = []; $requirements = $this->normalizeRequirements($requirements); foreach ($requirements as $requirement) { if (!isset($requirement['version'])) { throw new \UnexpectedValueException('Option '.$requirement['name'] .' is missing a version constraint, use e.g. '.$requirement['name'].':^1.0'); } $requires[$requirement['name']] = $requirement['version']; } return $requires; } /** * @param array<string> $requirements * * @return list<array{name: string, version?: string}> */ protected function normalizeRequirements(array $requirements) { $parser = new VersionParser(); return $parser->parseNameVersionPairs($requirements); } /** * @param array<TableSeparator|mixed[]> $table * * @return void */ protected function renderTable(array $table, OutputInterface $output) { $renderer = new Table($output); $renderer->setStyle('compact'); $renderer->setRows($table)->render(); } /** * @return int */ protected function getTerminalWidth() { $terminal = new Terminal(); $width = $terminal->getWidth(); if (Platform::isWindows()) { $width--; } else { $width = max(80, $width); } return $width; } /** * @internal * @param 'format'|'audit-format' $optName * @return Auditor::FORMAT_* */ protected function getAuditFormat(InputInterface $input, string $optName = 'audit-format'): string { if (!$input->hasOption($optName)) { throw new \LogicException('This should not be called on a Command which has no '.$optName.' option defined.'); } $val = $input->getOption($optName); if (!in_array($val, Auditor::FORMATS, true)) { throw new \InvalidArgumentException('--'.$optName.' must be one of '.implode(', ', Auditor::FORMATS).'.'); } return $val; } /** * Creates an AuditConfig from the Config object, optionally overriding security blocking based on input options * * @internal */ protected function createAuditConfig(Config $config, InputInterface $input): AuditConfig { // Handle both --audit and --no-audit flags if ($input->hasOption('audit')) { $audit = (bool) $input->getOption('audit'); } else { $audit = !($input->hasOption('no-audit') && $input->getOption('no-audit')); } $auditFormat = $input->hasOption('audit-format') ? $this->getAuditFormat($input) : Auditor::FORMAT_SUMMARY; $auditConfig = AuditConfig::fromConfig($config, $audit, $auditFormat); if ((bool) Platform::getEnv('COMPOSER_NO_SECURITY_BLOCKING') || ($input->hasOption('no-security-blocking') && $input->getOption('no-security-blocking'))) { $auditConfig = new AuditConfig( $auditConfig->audit, $auditConfig->auditFormat, $auditConfig->auditAbandoned, false, // blockInsecure $auditConfig->blockAbandoned, $auditConfig->ignoreUnreachable, $auditConfig->ignoreListForAudit, $auditConfig->ignoreListForBlocking, $auditConfig->ignoreSeverityForAudit, $auditConfig->ignoreSeverityForBlocking, $auditConfig->ignoreAbandonedForAudit, $auditConfig->ignoreAbandonedForBlocking ); } return $auditConfig; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/AboutCommand.php
src/Composer/Command/AboutCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class AboutCommand extends BaseCommand { protected function configure(): void { $this ->setName('about') ->setDescription('Shows a short information about Composer') ->setHelp( <<<EOT <info>php composer.phar about</info> EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composerVersion = Composer::getVersion(); $this->getIO()->write( <<<EOT <info>Composer - Dependency Manager for PHP - version $composerVersion</info> <comment>Composer is a dependency manager tracking local dependencies of your projects and libraries. See https://getcomposer.org/ for more information.</comment> EOT ); return 0; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/DependsCommand.php
src/Composer/Command/DependsCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; /** * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class DependsCommand extends BaseDependencyCommand { use CompletionTrait; /** * Configure command metadata. */ protected function configure(): void { $this ->setName('depends') ->setAliases(['why']) ->setDescription('Shows which packages cause the given package to be installed') ->setDefinition([ new InputArgument(self::ARGUMENT_PACKAGE, InputArgument::REQUIRED, 'Package to inspect', null, $this->suggestInstalledPackage(true, true)), new InputOption(self::OPTION_RECURSIVE, 'r', InputOption::VALUE_NONE, 'Recursively resolves up to the root package'), new InputOption(self::OPTION_TREE, 't', InputOption::VALUE_NONE, 'Prints the results as a nested tree'), new InputOption('locked', null, InputOption::VALUE_NONE, 'Read dependency information from composer.lock'), ]) ->setHelp( <<<EOT Displays detailed information about where a package is referenced. <info>php composer.phar depends composer/composer</info> Read more at https://getcomposer.org/doc/03-cli.md#depends-why EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { return parent::doExecute($input, $output); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/CompletionTrait.php
src/Composer/Command/CompletionTrait.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\Package\BasePackage; use Composer\Package\PackageInterface; use Composer\Pcre\Preg; use Composer\Repository\CompositeRepository; use Composer\Repository\InstalledRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryInterface; use Composer\Repository\RootPackageRepository; use Symfony\Component\Console\Completion\CompletionInput; /** * Adds completion to arguments and options. * * @internal */ trait CompletionTrait { /** * @see BaseCommand::requireComposer() */ abstract public function requireComposer(?bool $disablePlugins = null, ?bool $disableScripts = null): Composer; /** * Suggestion values for "prefer-install" option * * @return list<string> */ private function suggestPreferInstall(): array { return ['dist', 'source', 'auto']; } /** * Suggest package names from root requirements. */ private function suggestRootRequirement(): \Closure { return function (CompletionInput $input): array { $composer = $this->requireComposer(); return array_merge(array_keys($composer->getPackage()->getRequires()), array_keys($composer->getPackage()->getDevRequires())); }; } /** * Suggest package names from installed. */ private function suggestInstalledPackage(bool $includeRootPackage = true, bool $includePlatformPackages = false): \Closure { return function (CompletionInput $input) use ($includeRootPackage, $includePlatformPackages): array { $composer = $this->requireComposer(); $installedRepos = []; if ($includeRootPackage) { $installedRepos[] = new RootPackageRepository(clone $composer->getPackage()); } $locker = $composer->getLocker(); if ($locker->isLocked()) { $installedRepos[] = $locker->getLockedRepository(true); } else { $installedRepos[] = $composer->getRepositoryManager()->getLocalRepository(); } $platformHint = []; if ($includePlatformPackages) { if ($locker->isLocked()) { $platformRepo = new PlatformRepository([], $locker->getPlatformOverrides()); } else { $platformRepo = new PlatformRepository([], $composer->getConfig()->get('platform')); } if ($input->getCompletionValue() === '') { // to reduce noise, when no text is yet entered we list only two entries for ext- and lib- prefixes $hintsToFind = ['ext-' => 0, 'lib-' => 0, 'php' => 99, 'composer' => 99]; foreach ($platformRepo->getPackages() as $pkg) { foreach ($hintsToFind as $hintPrefix => $hintCount) { if (str_starts_with($pkg->getName(), $hintPrefix)) { if ($hintCount === 0 || $hintCount >= 99) { $platformHint[] = $pkg->getName(); $hintsToFind[$hintPrefix]++; } elseif ($hintCount === 1) { unset($hintsToFind[$hintPrefix]); $platformHint[] = substr($pkg->getName(), 0, max(strlen($pkg->getName()) - 3, strlen($hintPrefix) + 1)).'...'; } continue 2; } } } } else { $installedRepos[] = $platformRepo; } } $installedRepo = new InstalledRepository($installedRepos); return array_merge( array_map(static function (PackageInterface $package) { return $package->getName(); }, $installedRepo->getPackages()), $platformHint ); }; } /** * Suggest package names from installed. */ private function suggestInstalledPackageTypes(bool $includeRootPackage = true): \Closure { return function (CompletionInput $input) use ($includeRootPackage): array { $composer = $this->requireComposer(); $installedRepos = []; if ($includeRootPackage) { $installedRepos[] = new RootPackageRepository(clone $composer->getPackage()); } $locker = $composer->getLocker(); if ($locker->isLocked()) { $installedRepos[] = $locker->getLockedRepository(true); } else { $installedRepos[] = $composer->getRepositoryManager()->getLocalRepository(); } $installedRepo = new InstalledRepository($installedRepos); return array_values(array_unique( array_map(static function (PackageInterface $package) { return $package->getType(); }, $installedRepo->getPackages()) )); }; } /** * Suggest package names available on all configured repositories. */ private function suggestAvailablePackage(int $max = 99): \Closure { return function (CompletionInput $input) use ($max): array { if ($max < 1) { return []; } $composer = $this->requireComposer(); $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories()); $results = []; $showVendors = false; if (!str_contains($input->getCompletionValue(), '/')) { $results = $repos->search('^' . preg_quote($input->getCompletionValue()), RepositoryInterface::SEARCH_VENDOR); $showVendors = true; } // if we get a single vendor, we expand it into its contents already if (\count($results) <= 1) { $results = $repos->search('^'.preg_quote($input->getCompletionValue()), RepositoryInterface::SEARCH_NAME); $showVendors = false; } $results = array_column($results, 'name'); if ($showVendors) { $results = array_map(static function (string $name): string { return $name.'/'; }, $results); // sort shorter results first to avoid auto-expanding the completion to a longer string than needed usort($results, static function (string $a, string $b) { $lenA = \strlen($a); $lenB = \strlen($b); if ($lenA === $lenB) { return $a <=> $b; } return $lenA - $lenB; }); $pinned = []; // ensure if the input is an exact match that it is always in the result set $completionInput = $input->getCompletionValue().'/'; if (false !== ($exactIndex = array_search($completionInput, $results, true))) { $pinned[] = $completionInput; array_splice($results, $exactIndex, 1); } return array_merge($pinned, array_slice($results, 0, $max - \count($pinned))); } return array_slice($results, 0, $max); }; } /** * Suggest package names available on all configured repositories or * platform packages from the ones available on the currently-running PHP */ private function suggestAvailablePackageInclPlatform(): \Closure { return function (CompletionInput $input): array { if (Preg::isMatch('{^(ext|lib|php)(-|$)|^com}', $input->getCompletionValue())) { $matches = $this->suggestPlatformPackage()($input); } else { $matches = []; } return array_merge($matches, $this->suggestAvailablePackage(99 - \count($matches))($input)); }; } /** * Suggest platform packages from the ones available on the currently-running PHP */ private function suggestPlatformPackage(): \Closure { return function (CompletionInput $input): array { $repos = new PlatformRepository([], $this->requireComposer()->getConfig()->get('platform')); $pattern = BasePackage::packageNameToRegexp($input->getCompletionValue().'*'); return array_filter(array_map(static function (PackageInterface $package) { return $package->getName(); }, $repos->getPackages()), static function (string $name) use ($pattern): bool { return Preg::isMatch($pattern, $name); }); }; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/RunScriptCommand.php
src/Composer/Command/RunScriptCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Script\Event as ScriptEvent; use Composer\Script\ScriptEvents; use Composer\Util\ProcessExecutor; use Composer\Util\Platform; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Fabien Potencier <fabien.potencier@gmail.com> */ class RunScriptCommand extends BaseCommand { /** * @var string[] Array with command events */ protected $scriptEvents = [ ScriptEvents::PRE_INSTALL_CMD, ScriptEvents::POST_INSTALL_CMD, ScriptEvents::PRE_UPDATE_CMD, ScriptEvents::POST_UPDATE_CMD, ScriptEvents::PRE_STATUS_CMD, ScriptEvents::POST_STATUS_CMD, ScriptEvents::POST_ROOT_PACKAGE_INSTALL, ScriptEvents::POST_CREATE_PROJECT_CMD, ScriptEvents::PRE_ARCHIVE_CMD, ScriptEvents::POST_ARCHIVE_CMD, ScriptEvents::PRE_AUTOLOAD_DUMP, ScriptEvents::POST_AUTOLOAD_DUMP, ]; protected function configure(): void { $this ->setName('run-script') ->setAliases(['run']) ->setDescription('Runs the scripts defined in composer.json') ->setDefinition([ new InputArgument('script', InputArgument::OPTIONAL, 'Script name to run.', null, function () { return array_map(static function ($script) { return $script['name']; }, $this->getScripts()); }), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), new InputOption('timeout', null, InputOption::VALUE_REQUIRED, 'Sets script timeout in seconds, or 0 for never.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'), new InputOption('list', 'l', InputOption::VALUE_NONE, 'List scripts.'), ]) ->setHelp( <<<EOT The <info>run-script</info> command runs scripts defined in composer.json: <info>php composer.phar run-script post-update-cmd</info> Read more at https://getcomposer.org/doc/03-cli.md#run-script-run EOT ) ; } protected function interact(InputInterface $input, OutputInterface $output): void { $scripts = $this->getScripts(); if (count($scripts) === 0) { return; } if ($input->getArgument('script') !== null || $input->getOption('list')) { return; } $options = []; foreach ($scripts as $script) { $options[$script['name']] = $script['description']; } $io = $this->getIO(); $script = $io->select( 'Script to run: ', $options, '', 1, 'Invalid script name "%s"' ); $input->setArgument('script', $script); } protected function execute(InputInterface $input, OutputInterface $output): int { if ($input->getOption('list')) { return $this->listScripts($output); } $script = $input->getArgument('script'); if ($script === null) { throw new \RuntimeException('Missing required argument "script"'); } if (!in_array($script, $this->scriptEvents)) { if (defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) { throw new \InvalidArgumentException(sprintf('Script "%s" cannot be run with this command', $script)); } } $composer = $this->requireComposer(); $devMode = $input->getOption('dev') || !$input->getOption('no-dev'); $event = new ScriptEvent($script, $composer, $this->getIO(), $devMode); $hasListeners = $composer->getEventDispatcher()->hasEventListeners($event); if (!$hasListeners) { throw new \InvalidArgumentException(sprintf('Script "%s" is not defined in this package', $script)); } $args = $input->getArgument('args'); if (null !== $timeout = $input->getOption('timeout')) { if (!ctype_digit($timeout)) { throw new \RuntimeException('Timeout value must be numeric and positive if defined, or 0 for forever'); } // Override global timeout set before in Composer by environment or config ProcessExecutor::setTimeout((int) $timeout); } Platform::putEnv('COMPOSER_DEV_MODE', $devMode ? '1' : '0'); return $composer->getEventDispatcher()->dispatchScript($script, $devMode, $args); } protected function listScripts(OutputInterface $output): int { $scripts = $this->getScripts(); if (count($scripts) === 0) { return 0; } $io = $this->getIO(); $io->writeError('<info>scripts:</info>'); $table = []; foreach ($scripts as $script) { $table[] = [' '.$script['name'], $script['description']]; } $this->renderTable($table, $output); return 0; } /** * @return list<array{name: string, description: string}> */ private function getScripts(): array { $scripts = $this->requireComposer()->getPackage()->getScripts(); if (count($scripts) === 0) { return []; } $result = []; foreach ($scripts as $name => $script) { $description = ''; try { $cmd = $this->getApplication()->find($name); $description = $cmd->getDescription(); } catch (\Symfony\Component\Console\Exception\CommandNotFoundException $e) { // ignore scripts that have no command associated, like native Composer script listeners } $result[] = ['name' => $name, 'description' => $description]; } return $result; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/UpdateCommand.php
src/Composer/Command/UpdateCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Composer; use Composer\DependencyResolver\Request; use Composer\Installer; use Composer\IO\IOInterface; use Composer\Package\BasePackage; use Composer\Package\Loader\RootPackageLoader; use Composer\Package\Version\VersionSelector; use Composer\Pcre\Preg; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Package\Version\VersionParser; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryInterface; use Composer\Repository\RepositorySet; use Composer\Semver\Constraint\MultiConstraint; use Composer\Semver\Intervals; use Composer\Util\HttpDownloader; use Composer\Advisory\Auditor; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> * @author Nils Adermann <naderman@naderman.de> */ class UpdateCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('update') ->setAliases(['u', 'upgrade']) ->setDescription('Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file') ->setDefinition([ new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Packages that should be updated, if not provided all packages are.', null, $this->suggestInstalledPackage(false)), new InputOption('with', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Temporary version constraint to add, e.g. foo/bar:1.0.0 or foo/bar=1.0.0'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'), new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'), new InputOption('dev', null, InputOption::VALUE_NONE, 'DEPRECATED: Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('lock', null, InputOption::VALUE_NONE, 'Overwrites the lock file hash to suppress warning about the lock file being out of date without updating package versions. Package metadata like mirrors and URLs are updated if they changed.'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Skip the install step after updating the composer.lock file.'), new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Skip the audit step after updating the composer.lock file (can also be set via the COMPOSER_NO_AUDIT=1 env var).'), new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json", or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS), new InputOption('no-security-blocking', null, InputOption::VALUE_NONE, 'Allows installing packages with security advisories or that are abandoned (can also be set via the COMPOSER_NO_SECURITY_BLOCKING=1 env var).'), new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'), new InputOption('no-suggest', null, InputOption::VALUE_NONE, 'DEPRECATED: This flag does not exist anymore.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('with-dependencies', 'w', InputOption::VALUE_NONE, 'Update also dependencies of packages in the argument list, except those which are root requirements (can also be set via the COMPOSER_WITH_DEPENDENCIES=1 env var).'), new InputOption('with-all-dependencies', 'W', InputOption::VALUE_NONE, 'Update also dependencies of packages in the argument list, including those which are root requirements (can also be set via the COMPOSER_WITH_ALL_DEPENDENCIES=1 env var).'), new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'), new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump.'), new InputOption('classmap-authoritative', 'a', InputOption::VALUE_NONE, 'Autoload classes from the classmap only. Implicitly enables `--optimize-autoloader`.'), new InputOption('apcu-autoloader', null, InputOption::VALUE_NONE, 'Use APCu to cache found/not-found classes.'), new InputOption('apcu-autoloader-prefix', null, InputOption::VALUE_REQUIRED, 'Use a custom prefix for the APCu autoloader cache. Implicitly enables --apcu-autoloader'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies (can also be set via the COMPOSER_PREFER_STABLE=1 env var).'), new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies (can also be set via the COMPOSER_PREFER_LOWEST=1 env var).'), new InputOption('minimal-changes', 'm', InputOption::VALUE_NONE, 'Only perform absolutely necessary changes to dependencies. If packages cannot be kept at their currently locked version they are updated. For partial updates the allow-listed packages are always updated fully. (can also be set via the COMPOSER_MINIMAL_CHANGES=1 env var).'), new InputOption('patch-only', null, InputOption::VALUE_NONE, 'Only allow patch version updates for currently installed dependencies.'), new InputOption('interactive', 'i', InputOption::VALUE_NONE, 'Interactive interface with autocompletion to select the packages to update.'), new InputOption('root-reqs', null, InputOption::VALUE_NONE, 'Restricts the update to your first degree dependencies.'), new InputOption('bump-after-update', null, InputOption::VALUE_OPTIONAL, 'Runs bump after performing the update.', false, ['dev', 'no-dev', 'all']), ]) ->setHelp( <<<EOT The <info>update</info> command reads the composer.json file from the current directory, processes it, and updates, removes or installs all the dependencies. <info>php composer.phar update</info> To limit the update operation to a few packages, you can list the package(s) you want to update as such: <info>php composer.phar update vendor/package1 foo/mypackage [...]</info> You may also use an asterisk (*) pattern to limit the update operation to package(s) from a specific vendor: <info>php composer.phar update vendor/package1 foo/* [...]</info> To run an update with more restrictive constraints you can use: <info>php composer.phar update --with vendor/package:1.0.*</info> To run a partial update with more restrictive constraints you can use the shorthand: <info>php composer.phar update vendor/package:1.0.*</info> To select packages names interactively with auto-completion use <info>-i</info>. Read more at https://getcomposer.org/doc/03-cli.md#update-u-upgrade EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $io = $this->getIO(); if ($input->getOption('dev')) { $io->writeError('<warning>You are using the deprecated option "--dev". It has no effect and will break in Composer 3.</warning>'); } if ($input->getOption('no-suggest')) { $io->writeError('<warning>You are using the deprecated option "--no-suggest". It has no effect and will break in Composer 3.</warning>'); } $composer = $this->requireComposer(); if (!HttpDownloader::isCurlEnabled()) { $io->writeError('<warning>Composer is operating significantly slower than normal because you do not have the PHP curl extension enabled.</warning>'); } $packages = $input->getArgument('packages'); $reqs = $this->formatRequirements($input->getOption('with')); // extract --with shorthands from the allowlist if (count($packages) > 0) { $allowlistPackagesWithRequirements = array_filter($packages, static function ($pkg): bool { return Preg::isMatch('{\S+[ =:]\S+}', $pkg); }); foreach ($this->formatRequirements($allowlistPackagesWithRequirements) as $package => $constraint) { $reqs[$package] = $constraint; } // replace the foo/bar:req by foo/bar in the allowlist foreach ($allowlistPackagesWithRequirements as $package) { $packageName = Preg::replace('{^([^ =:]+)[ =:].*$}', '$1', $package); $index = array_search($package, $packages); $packages[$index] = $packageName; } } $rootPackage = $composer->getPackage(); $rootPackage->setReferences(RootPackageLoader::extractReferences($reqs, $rootPackage->getReferences())); $rootPackage->setStabilityFlags(RootPackageLoader::extractStabilityFlags($reqs, $rootPackage->getMinimumStability(), $rootPackage->getStabilityFlags())); $parser = new VersionParser; $temporaryConstraints = []; $rootRequirements = array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires()); foreach ($reqs as $package => $constraint) { $package = strtolower($package); $parsedConstraint = $parser->parseConstraints($constraint); $temporaryConstraints[$package] = $parsedConstraint; if (isset($rootRequirements[$package]) && !Intervals::haveIntersections($parsedConstraint, $rootRequirements[$package]->getConstraint())) { $io->writeError('<error>The temporary constraint "'.$constraint.'" for "'.$package.'" must be a subset of the constraint in your composer.json ('.$rootRequirements[$package]->getPrettyConstraint().')</error>'); $io->write('<info>Run `composer require '.$package.'` or `composer require '.$package.':'.$constraint.'` instead to replace the constraint</info>'); return self::FAILURE; } } if ($input->getOption('patch-only')) { if (!$composer->getLocker()->isLocked()) { throw new \InvalidArgumentException('patch-only can only be used with a lock file present'); } foreach ($composer->getLocker()->getLockedRepository(true)->getCanonicalPackages() as $package) { if ($package->isDev()) { continue; } if (!Preg::isMatch('{^(\d+\.\d+\.\d+)}', $package->getVersion(), $match)) { continue; } $constraint = $parser->parseConstraints('~'.$match[1]); if (isset($temporaryConstraints[$package->getName()])) { $temporaryConstraints[$package->getName()] = MultiConstraint::create([$temporaryConstraints[$package->getName()], $constraint], true); } else { $temporaryConstraints[$package->getName()] = $constraint; } } } if ($input->getOption('interactive')) { $packages = $this->getPackagesInteractively($io, $input, $output, $composer, $packages); } if ($input->getOption('root-reqs')) { $requires = array_keys($rootPackage->getRequires()); if (!$input->getOption('no-dev')) { $requires = array_merge($requires, array_keys($rootPackage->getDevRequires())); } if (!empty($packages)) { $packages = array_intersect($packages, $requires); } else { $packages = $requires; } } // 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, static function ($package): bool { return !in_array($package, ['lock', 'nothing', 'mirrors'], true); }); $updateMirrors = $input->getOption('lock') || count($filteredPackages) !== count($packages); $packages = $filteredPackages; if ($updateMirrors && !empty($packages)) { $io->writeError('<error>You cannot simultaneously update only a selection of packages and regenerate the lock file metadata.</error>'); return -1; } $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'update', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $composer->getInstallationManager()->setOutputProgress(!$input->getOption('no-progress')); $install = Installer::create($io, $composer); $config = $composer->getConfig(); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($config, $input); $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader'); $authoritative = $input->getOption('classmap-authoritative') || $config->get('classmap-authoritative'); $apcuPrefix = $input->getOption('apcu-autoloader-prefix'); $apcu = $apcuPrefix !== null || $input->getOption('apcu-autoloader') || $config->get('apcu-autoloader'); $minimalChanges = $input->getOption('minimal-changes') || $config->get('update-with-minimal-changes'); $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED; if ($input->getOption('with-all-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS; } elseif ($input->getOption('with-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE; } $install ->setDryRun($input->getOption('dry-run')) ->setVerbose($input->getOption('verbose')) ->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode(!$input->getOption('no-dev')) ->setDumpAutoloader(!$input->getOption('no-autoloader')) ->setOptimizeAutoloader($optimize) ->setClassMapAuthoritative($authoritative) ->setApcuAutoloader($apcu, $apcuPrefix) ->setUpdate(true) ->setInstall(!$input->getOption('no-install')) ->setUpdateMirrors($updateMirrors) ->setUpdateAllowList($packages) ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies) ->setPlatformRequirementFilter($this->getPlatformRequirementFilter($input)) ->setPreferStable($input->getOption('prefer-stable')) ->setPreferLowest($input->getOption('prefer-lowest')) ->setTemporaryConstraints($temporaryConstraints) ->setAuditConfig($this->createAuditConfig($composer->getConfig(), $input)) ->setMinimalUpdate($minimalChanges) ; if ($input->getOption('no-plugins')) { $install->disablePlugins(); } $result = $install->run(); if ($result === 0 && !$input->getOption('lock')) { $bumpAfterUpdate = $input->getOption('bump-after-update'); if (false === $bumpAfterUpdate) { $bumpAfterUpdate = $composer->getConfig()->get('bump-after-update'); } if (false !== $bumpAfterUpdate) { $io->writeError('<info>Bumping dependencies</info>'); $bumpCommand = new BumpCommand(); $bumpCommand->setComposer($composer); $result = $bumpCommand->doBump( $io, $bumpAfterUpdate === 'dev', $bumpAfterUpdate === 'no-dev', $input->getOption('dry-run'), $input->getArgument('packages'), '--bump-after-update=dev' ); } } return $result; } /** * @param array<string> $packages * @return array<string> */ 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.'); } $platformReqFilter = $this->getPlatformRequirementFilter($input); $stabilityFlags = $composer->getPackage()->getStabilityFlags(); $requires = array_merge( $composer->getPackage()->getRequires(), $composer->getPackage()->getDevRequires() ); $filter = \count($packages) > 0 ? BasePackage::packageNamesToRegexp($packages) : null; $io->writeError('<info>Loading packages that can be updated...</info>'); $autocompleterValues = []; $installedPackages = $composer->getLocker()->isLocked() ? $composer->getLocker()->getLockedRepository(true)->getPackages() : $composer->getRepositoryManager()->getLocalRepository()->getPackages(); $versionSelector = $this->createVersionSelector($composer); foreach ($installedPackages as $package) { if ($filter !== null && !Preg::isMatch($filter, $package->getName())) { continue; } $currentVersion = $package->getPrettyVersion(); $constraint = isset($requires[$package->getName()]) ? $requires[$package->getName()]->getPrettyConstraint() : null; $stability = isset($stabilityFlags[$package->getName()]) ? (string) array_search($stabilityFlags[$package->getName()], BasePackage::STABILITIES, true) : $composer->getPackage()->getMinimumStability(); $latestVersion = $versionSelector->findBestCandidate($package->getName(), $constraint, $stability, $platformReqFilter); if ($latestVersion !== false && ($package->getVersion() !== $latestVersion->getVersion() || $latestVersion->isDev())) { $autocompleterValues[$package->getName()] = '<comment>' . $currentVersion . '</comment> => <comment>' . $latestVersion->getPrettyVersion() . '</comment>'; } } if (0 === \count($installedPackages)) { foreach ($requires as $req => $constraint) { if (PlatformRepository::isPlatformPackage($req)) { continue; } $autocompleterValues[$req] = ''; } } if (0 === \count($autocompleterValues)) { throw new \RuntimeException('Could not find any package with new versions available'); } $packages = $io->select( 'Select packages: (Select more than one value separated by comma) ', $autocompleterValues, false, 1, 'No package named "%s" is installed.', true ); $table = new Table($output); $table->setHeaders(['Selected packages']); foreach ($packages as $package) { $table->addRow([$package]); } $table->render(); if ($io->askConfirmation(sprintf( 'Would you like to continue and update the above package%s [<comment>yes</comment>]? ', 1 === count($packages) ? '' : 's' ))) { return $packages; } throw new \RuntimeException('Installation aborted.'); } private function createVersionSelector(Composer $composer): VersionSelector { $repositorySet = new RepositorySet(); $repositorySet->addRepository(new CompositeRepository(array_filter($composer->getRepositoryManager()->getRepositories(), static function (RepositoryInterface $repository) { return !$repository instanceof PlatformRepository; }))); return new VersionSelector($repositorySet); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ProhibitsCommand.php
src/Composer/Command/ProhibitsCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; /** * @author Niels Keurentjes <niels.keurentjes@omines.com> */ class ProhibitsCommand extends BaseDependencyCommand { use CompletionTrait; /** * Configure command metadata. */ protected function configure(): void { $this ->setName('prohibits') ->setAliases(['why-not']) ->setDescription('Shows which packages prevent the given package from being installed') ->setDefinition([ new InputArgument(self::ARGUMENT_PACKAGE, InputArgument::REQUIRED, 'Package to inspect', null, $this->suggestAvailablePackage()), new InputArgument(self::ARGUMENT_CONSTRAINT, InputArgument::REQUIRED, 'Version constraint, which version you expected to be installed'), new InputOption(self::OPTION_RECURSIVE, 'r', InputOption::VALUE_NONE, 'Recursively resolves up to the root package'), new InputOption(self::OPTION_TREE, 't', InputOption::VALUE_NONE, 'Prints the results as a nested tree'), new InputOption('locked', null, InputOption::VALUE_NONE, 'Read dependency information from composer.lock'), ]) ->setHelp( <<<EOT Displays detailed information about why a package cannot be installed. <info>php composer.phar prohibits composer/composer</info> Read more at https://getcomposer.org/doc/03-cli.md#prohibits-why-not EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { return parent::doExecute($input, $output, true); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/BumpCommand.php
src/Composer/Command/BumpCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\IO\IOInterface; use Composer\Package\AliasPackage; use Composer\Package\BasePackage; use Composer\Package\Version\VersionBumper; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Composer\Factory; use Composer\Json\JsonFile; use Composer\Json\JsonManipulator; use Composer\Repository\PlatformRepository; use Composer\Util\Silencer; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ final class BumpCommand extends BaseCommand { private const ERROR_GENERIC = 1; private const ERROR_LOCK_OUTDATED = 2; use CompletionTrait; protected function configure(): void { $this ->setName('bump') ->setDescription('Increases the lower limit of your composer.json requirements to the currently installed versions') ->setDefinition([ new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Optional package name(s) to restrict which packages are bumped.', null, $this->suggestRootRequirement()), new InputOption('dev-only', 'D', InputOption::VALUE_NONE, 'Only bump requirements in "require-dev".'), new InputOption('no-dev-only', 'R', InputOption::VALUE_NONE, 'Only bump requirements in "require".'), new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the packages to bump, but will not execute anything.'), ]) ->setHelp( <<<EOT The <info>bump</info> command increases the lower limit of your composer.json requirements to the currently installed versions. This helps to ensure your dependencies do not accidentally get downgraded due to some other conflict, and can slightly improve dependency resolution performance as it limits the amount of package versions Composer has to look at. Running this blindly on libraries is **NOT** recommended as it will narrow down your allowed dependencies, which may cause dependency hell for your users. Running it with <info>--dev-only</info> on libraries may be fine however as dev requirements are local to the library and do not affect consumers of the package. EOT ) ; } /** * @throws \Seld\JsonLint\ParsingException */ protected function execute(InputInterface $input, OutputInterface $output): int { return $this->doBump( $this->getIO(), $input->getOption('dev-only'), $input->getOption('no-dev-only'), $input->getOption('dry-run'), $input->getArgument('packages') ); } /** * @internal * @param string[] $packagesFilter * @throws \Seld\JsonLint\ParsingException */ public function doBump( IOInterface $io, bool $devOnly, bool $noDevOnly, bool $dryRun, array $packagesFilter, string $devOnlyFlagHint = '--dev-only' ): int { /** @readonly */ $composerJsonPath = Factory::getComposerFile(); if (!Filesystem::isReadable($composerJsonPath)) { $io->writeError('<error>'.$composerJsonPath.' is not readable.</error>'); return self::ERROR_GENERIC; } $composerJson = new JsonFile($composerJsonPath); $contents = file_get_contents($composerJson->getPath()); if (false === $contents) { $io->writeError('<error>'.$composerJsonPath.' is not readable.</error>'); return self::ERROR_GENERIC; } // check for writability by writing to the file as is_writable can not be trusted on network-mounts // see https://github.com/composer/composer/issues/8231 and https://bugs.php.net/bug.php?id=68926 if (!is_writable($composerJsonPath) && false === Silencer::call('file_put_contents', $composerJsonPath, $contents)) { $io->writeError('<error>'.$composerJsonPath.' is not writable.</error>'); return self::ERROR_GENERIC; } unset($contents); $composer = $this->requireComposer(); $hasLockfileDisabled = !$composer->getConfig()->has('lock') || $composer->getConfig()->get('lock'); if (!$hasLockfileDisabled) { $repo = $composer->getLocker()->getLockedRepository(true); } elseif ($composer->getLocker()->isLocked()) { if (!$composer->getLocker()->isFresh()) { $io->writeError('<error>The lock file is not up to date with the latest changes in composer.json. Run the appropriate `update` to fix that before you use the `bump` command.</error>'); return self::ERROR_LOCK_OUTDATED; } $repo = $composer->getLocker()->getLockedRepository(true); } else { $repo = $composer->getRepositoryManager()->getLocalRepository(); } if ($composer->getPackage()->getType() !== 'project' && !$devOnly) { $io->writeError('<warning>Warning: Bumping dependency constraints is not recommended for libraries as it will narrow down your dependencies and may cause problems for your users.</warning>'); $contents = $composerJson->read(); if (!isset($contents['type'])) { $io->writeError('<warning>If your package is not a library, you can explicitly specify the "type" by using "composer config type project".</warning>'); $io->writeError('<warning>Alternatively you can use '.$devOnlyFlagHint.' to only bump dependencies within "require-dev".</warning>'); } unset($contents); } $bumper = new VersionBumper(); $tasks = []; if (!$devOnly) { $tasks['require'] = $composer->getPackage()->getRequires(); } if (!$noDevOnly) { $tasks['require-dev'] = $composer->getPackage()->getDevRequires(); } if (count($packagesFilter) > 0) { // support proxied args from the update command that contain constraints together with the package names $packagesFilter = array_map(static function ($constraint) { return Preg::replace('{[:= ].+}', '', $constraint); }, $packagesFilter); $pattern = BasePackage::packageNamesToRegexp(array_unique(array_map('strtolower', $packagesFilter))); foreach ($tasks as $key => $reqs) { foreach ($reqs as $pkgName => $link) { if (!Preg::isMatch($pattern, $pkgName)) { unset($tasks[$key][$pkgName]); } } } } $updates = []; foreach ($tasks as $key => $reqs) { foreach ($reqs as $pkgName => $link) { if (PlatformRepository::isPlatformPackage($pkgName)) { continue; } $currentConstraint = $link->getPrettyConstraint(); $package = $repo->findPackage($pkgName, '*'); // name must be provided or replaced if (null === $package) { continue; } while ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } $bumped = $bumper->bumpRequirement($link->getConstraint(), $package); if ($bumped === $currentConstraint) { continue; } $updates[$key][$pkgName] = $bumped; } } if (!$dryRun && !$this->updateFileCleanly($composerJson, $updates)) { $composerDefinition = $composerJson->read(); foreach ($updates as $key => $packages) { foreach ($packages as $package => $version) { $composerDefinition[$key][$package] = $version; } } $composerJson->write($composerDefinition); } $changeCount = array_sum(array_map('count', $updates)); if ($changeCount > 0) { if ($dryRun) { $io->write('<info>' . $composerJsonPath . ' would be updated with:</info>'); foreach ($updates as $requireType => $packages) { foreach ($packages as $package => $version) { $io->write(sprintf('<info> - %s.%s: %s</info>', $requireType, $package, $version)); } } } else { $io->write('<info>' . $composerJsonPath . ' has been updated (' . $changeCount . ' changes).</info>'); } } else { $io->write('<info>No requirements to update in '.$composerJsonPath.'.</info>'); } if (!$dryRun && $composer->getLocker()->isLocked() && $composer->getConfig()->get('lock') && $changeCount > 0) { $composer->getLocker()->updateHash($composerJson); } if ($dryRun && $changeCount > 0) { return self::ERROR_GENERIC; } return 0; } /** * @param array<'require'|'require-dev', array<string, string>> $updates */ private function updateFileCleanly(JsonFile $json, array $updates): bool { $contents = file_get_contents($json->getPath()); if (false === $contents) { throw new \RuntimeException('Unable to read '.$json->getPath().' contents.'); } $manipulator = new JsonManipulator($contents); foreach ($updates as $key => $packages) { foreach ($packages as $package => $version) { if (!$manipulator->addLink($key, $package, $version)) { return false; } } } if (false === file_put_contents($json->getPath(), $manipulator->getContents())) { throw new \RuntimeException('Unable to write new '.$json->getPath().' contents.'); } return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/GlobalCommand.php
src/Composer/Command/GlobalCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Platform; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Completion\CompletionSuggestions; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class GlobalCommand extends BaseCommand { public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void { $application = $this->getApplication(); if ($input->mustSuggestArgumentValuesFor('command-name')) { $suggestions->suggestValues(array_values(array_filter( array_map(static function (Command $command) { return $command->isHidden() ? null : $command->getName(); }, $application->all()), static function (?string $cmd) { return $cmd !== null; } ))); return; } if ($application->has($commandName = $input->getArgument('command-name'))) { $input = $this->prepareSubcommandInput($input, true); $input = CompletionInput::fromString($input->__toString(), 2); $command = $application->find($commandName); $command->mergeApplicationDefinition(); $input->bind($command->getDefinition()); $command->complete($input, $suggestions); } } protected function configure(): void { $this ->setName('global') ->setDescription('Allows running commands in the global composer dir ($COMPOSER_HOME)') ->setDefinition([ new InputArgument('command-name', InputArgument::REQUIRED, ''), new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''), ]) ->setHelp( <<<EOT Use this command as a wrapper to run other Composer commands within the global context of COMPOSER_HOME. You can use this to install CLI utilities globally, all you need is to add the COMPOSER_HOME/vendor/bin dir to your PATH env var. COMPOSER_HOME is c:\Users\<user>\AppData\Roaming\Composer on Windows and /home/<user>/.composer on unix systems. If your system uses freedesktop.org standards, then it will first check XDG_CONFIG_HOME or default to /home/<user>/.config/composer Note: This path may vary depending on customizations to bin-dir in composer.json or the environmental variable COMPOSER_BIN_DIR. Read more at https://getcomposer.org/doc/03-cli.md#global EOT ) ; } /** * @throws \Symfony\Component\Console\Exception\ExceptionInterface */ public function run(InputInterface $input, OutputInterface $output): int { // TODO remove for Symfony 6+ as it is then in the interface if (!method_exists($input, '__toString')) { // @phpstan-ignore-line throw new \LogicException('Expected an Input instance that is stringable, got '.get_class($input)); } // extract real command name $tokens = Preg::split('{\s+}', $input->__toString()); $args = []; foreach ($tokens as $token) { if ($token && $token[0] !== '-') { $args[] = $token; if (count($args) >= 2) { break; } } } // show help for this command if no command was found if (count($args) < 2) { return parent::run($input, $output); } $input = $this->prepareSubcommandInput($input); return $this->getApplication()->run($input, $output); } private function prepareSubcommandInput(InputInterface $input, bool $quiet = false): StringInput { // TODO remove for Symfony 6+ as it is then in the interface if (!method_exists($input, '__toString')) { // @phpstan-ignore-line throw new \LogicException('Expected an Input instance that is stringable, got '.get_class($input)); } // The COMPOSER env var should not apply to the global execution scope if (Platform::getEnv('COMPOSER')) { Platform::clearEnv('COMPOSER'); } // change to global dir $config = Factory::createConfig(); $home = $config->get('home'); if (!is_dir($home)) { $fs = new Filesystem(); $fs->ensureDirectoryExists($home); if (!is_dir($home)) { throw new \RuntimeException('Could not create home directory'); } } try { chdir($home); } catch (\Exception $e) { throw new \RuntimeException('Could not switch to home directory "'.$home.'"', 0, $e); } if (!$quiet) { $this->getIO()->writeError('<info>Changed current directory to '.$home.'</info>'); } // create new input without "global" command prefix $input = new StringInput(Preg::replace('{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}', '', $input->__toString(), 1)); $this->getApplication()->resetComposer(); return $input; } /** * @inheritDoc */ public function isProxyCommand(): bool { return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/BaseDependencyCommand.php
src/Composer/Command/BaseDependencyCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Package\Link; use Composer\Package\Package; use Composer\Package\PackageInterface; use Composer\Package\CompletePackageInterface; use Composer\Package\RootPackage; use Composer\Repository\InstalledArrayRepository; use Composer\Repository\CompositeRepository; use Composer\Repository\RootPackageRepository; use Composer\Repository\InstalledRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Semver\Constraint\Bound; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Formatter\OutputFormatterStyle; use Composer\Package\Version\VersionParser; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Composer\Util\PackageInfo; /** * Base implementation for commands mapping dependency relationships. * * @author Niels Keurentjes <niels.keurentjes@omines.com> */ abstract class BaseDependencyCommand extends BaseCommand { protected const ARGUMENT_PACKAGE = 'package'; protected const ARGUMENT_CONSTRAINT = 'version'; protected const OPTION_RECURSIVE = 'recursive'; protected const OPTION_TREE = 'tree'; /** @var string[] */ protected $colors; /** * Execute the command. * * @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, bool $inverted = false): int { // Emit command event on startup $composer = $this->requireComposer(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, $this->getName(), $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $repos = []; $repos[] = new RootPackageRepository(clone $composer->getPackage()); if ($input->getOption('locked')) { $locker = $composer->getLocker(); if (!$locker->isLocked()) { throw new \UnexpectedValueException('A valid composer.lock file is required to run this command with --locked'); } $repos[] = $locker->getLockedRepository(true); $repos[] = new PlatformRepository([], $locker->getPlatformOverrides()); } else { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); $rootPkg = $composer->getPackage(); if (count($localRepo->getPackages()) === 0 && (count($rootPkg->getRequires()) > 0 || count($rootPkg->getDevRequires()) > 0)) { $output->writeln('<warning>No dependencies installed. Try running composer install or update, or use --locked.</warning>'); return 1; } $repos[] = $localRepo; $platformOverrides = $composer->getConfig()->get('platform') ?: []; $repos[] = new PlatformRepository([], $platformOverrides); } $installedRepo = new InstalledRepository($repos); // Parse package name and constraint $needle = $input->getArgument(self::ARGUMENT_PACKAGE); $textConstraint = $input->hasArgument(self::ARGUMENT_CONSTRAINT) ? $input->getArgument(self::ARGUMENT_CONSTRAINT) : '*'; // Find packages that are or provide the requested package first $packages = $installedRepo->findPackagesWithReplacersAndProviders($needle); if (empty($packages)) { throw new \InvalidArgumentException(sprintf('Could not find package "%s" in your project', $needle)); } // If the version we ask for is not installed then we need to locate it in remote repos and add it. // This is needed for why-not to resolve conflicts from an uninstalled version against installed packages. $matchedPackage = $installedRepo->findPackage($needle, $textConstraint); if (!$matchedPackage) { $defaultRepos = new CompositeRepository(RepositoryFactory::defaultRepos($this->getIO(), $composer->getConfig(), $composer->getRepositoryManager())); if ($match = $defaultRepos->findPackage($needle, $textConstraint)) { $installedRepo->addRepository(new InstalledArrayRepository([clone $match])); } elseif (PlatformRepository::isPlatformPackage($needle)) { $parser = new VersionParser(); $constraint = $parser->parseConstraints($textConstraint); if ($constraint->getLowerBound() !== Bound::zero()) { $tempPlatformPkg = new Package($needle, $constraint->getLowerBound()->getVersion(), $constraint->getLowerBound()->getVersion()); $installedRepo->addRepository(new InstalledArrayRepository([$tempPlatformPkg])); } } else { $this->getIO()->writeError('<error>Package "'.$needle.'" could not be found with constraint "'.$textConstraint.'", results below will most likely be incomplete.</error>'); } } elseif (PlatformRepository::isPlatformPackage($needle)) { $extraNotice = ''; if (($matchedPackage->getExtra()['config.platform'] ?? false) === true) { $extraNotice = ' (version provided by config.platform)'; } $this->getIO()->writeError('<info>Package "'.$needle.' '.$textConstraint.'" found in version "'.$matchedPackage->getPrettyVersion().'"'.$extraNotice.'.</info>'); } elseif ($inverted) { $this->getIO()->write('<comment>Package "'.$needle.'" '.$matchedPackage->getPrettyVersion().' is already installed! To find out why, run `composer why '.$needle.'`</comment>'); return 0; } // Include replaced packages for inverted lookups as they are then the actual starting point to consider $needles = [$needle]; if ($inverted) { foreach ($packages as $package) { $needles = array_merge($needles, array_map(static function (Link $link): string { return $link->getTarget(); }, $package->getReplaces())); } } // Parse constraint if one was supplied if ('*' !== $textConstraint) { $versionParser = new VersionParser(); $constraint = $versionParser->parseConstraints($textConstraint); } else { $constraint = null; } // Parse rendering options $renderTree = $input->getOption(self::OPTION_TREE); $recursive = $renderTree || $input->getOption(self::OPTION_RECURSIVE); $return = $inverted ? 1 : 0; // Resolve dependencies $results = $installedRepo->getDependents($needles, $constraint, $inverted, $recursive); if (empty($results)) { $extra = (null !== $constraint) ? sprintf(' in versions %smatching %s', $inverted ? 'not ' : '', $textConstraint) : ''; $this->getIO()->writeError(sprintf( '<info>There is no installed package depending on "%s"%s</info>', $needle, $extra )); $return = $inverted ? 0 : 1; } elseif ($renderTree) { $this->initStyles($output); $root = $packages[0]; $this->getIO()->write(sprintf('<info>%s</info> %s %s', $root->getPrettyName(), $root->getPrettyVersion(), $root instanceof CompletePackageInterface ? $root->getDescription() : '')); $this->printTree($results); } else { $this->printTable($output, $results); } if ($inverted && $input->hasArgument(self::ARGUMENT_CONSTRAINT) && !PlatformRepository::isPlatformPackage($needle)) { $composerCommand = 'update'; foreach ($composer->getPackage()->getRequires() as $rootRequirement) { if ($rootRequirement->getTarget() === $needle) { $composerCommand = 'require'; break; } } foreach ($composer->getPackage()->getDevRequires() as $rootRequirement) { if ($rootRequirement->getTarget() === $needle) { $composerCommand = 'require --dev'; break; } } $this->getIO()->writeError('Not finding what you were looking for? Try calling `composer '.$composerCommand.' "'.$needle.':'.$textConstraint.'" --dry-run` to get another view on the problem.'); } return $return; } /** * Assembles and prints a bottom-up table of the dependencies. * * @param array{PackageInterface, Link, array<mixed>|false}[] $results */ protected function printTable(OutputInterface $output, array $results): void { $table = []; $doubles = []; do { $queue = []; $rows = []; foreach ($results as $result) { /** * @var PackageInterface $package * @var Link $link */ [$package, $link, $children] = $result; $unique = (string) $link; if (isset($doubles[$unique])) { continue; } $doubles[$unique] = true; $version = $package->getPrettyVersion() === RootPackage::DEFAULT_PRETTY_VERSION ? '-' : $package->getPrettyVersion(); $packageUrl = PackageInfo::getViewSourceOrHomepageUrl($package); $nameWithLink = $packageUrl !== null ? '<href=' . OutputFormatter::escape($packageUrl) . '>' . $package->getPrettyName() . '</>' : $package->getPrettyName(); $rows[] = [$nameWithLink, $version, $link->getDescription(), sprintf('%s (%s)', $link->getTarget(), $link->getPrettyConstraint())]; if (is_array($children)) { $queue = array_merge($queue, $children); } } $results = $queue; $table = array_merge($rows, $table); } while (\count($results) > 0); $this->renderTable($table, $output); } /** * Init styles for tree */ protected function initStyles(OutputInterface $output): void { $this->colors = [ 'green', 'yellow', 'cyan', 'magenta', 'blue', ]; foreach ($this->colors as $color) { $style = new OutputFormatterStyle($color); $output->getFormatter()->setStyle($color, $style); } } /** * Recursively prints a tree of the selected results. * * @param array{PackageInterface, Link, array<mixed>|false}[] $results Results to be printed at this level. * @param string $prefix Prefix of the current tree level. * @param int $level Current level of recursion. */ protected function printTree(array $results, string $prefix = '', int $level = 1): void { $count = count($results); $idx = 0; foreach ($results as $result) { [$package, $link, $children] = $result; $color = $this->colors[$level % count($this->colors)]; $prevColor = $this->colors[($level - 1) % count($this->colors)]; $isLast = (++$idx === $count); $versionText = $package->getPrettyVersion() === RootPackage::DEFAULT_PRETTY_VERSION ? '' : $package->getPrettyVersion(); $packageUrl = PackageInfo::getViewSourceOrHomepageUrl($package); $nameWithLink = $packageUrl !== null ? '<href=' . OutputFormatter::escape($packageUrl) . '>' . $package->getPrettyName() . '</>' : $package->getPrettyName(); $packageText = rtrim(sprintf('<%s>%s</%1$s> %s', $color, $nameWithLink, $versionText)); $linkText = sprintf('%s <%s>%s</%2$s> %s', $link->getDescription(), $prevColor, $link->getTarget(), $link->getPrettyConstraint()); $circularWarn = $children === false ? '(circular dependency aborted here)' : ''; $this->writeTreeLine(rtrim(sprintf("%s%s%s (%s) %s", $prefix, $isLast ? '└──' : '├──', $packageText, $linkText, $circularWarn))); if (is_array($children)) { $this->printTree($children, $prefix . ($isLast ? ' ' : '│ '), $level + 1); } } } private function writeTreeLine(string $line): void { $io = $this->getIO(); if (!$io->isDecorated()) { $line = str_replace(['└', '├', '──', '│'], ['`-', '|-', '-', '|'], $line); } $io->write($line); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/BaseConfigCommand.php
src/Composer/Command/BaseConfigCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Config; use Composer\Config\JsonConfigSource; use Composer\Json\JsonFile; use Composer\Factory; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; abstract class BaseConfigCommand extends BaseCommand { /** * @var Config */ protected $config; /** * @var JsonFile */ protected $configFile; /** * @var JsonConfigSource */ protected $configSource; protected function initialize(InputInterface $input, OutputInterface $output): void { parent::initialize($input, $output); if ($input->getOption('global') && null !== $input->getOption('file')) { throw new \RuntimeException('--file and --global can not be combined'); } $io = $this->getIO(); $this->config = Factory::createConfig($io); // When using --global flag, set baseDir to home directory for correct absolute path resolution if ($input->getOption('global')) { $this->config->setBaseDir($this->config->get('home')); } $configFile = $this->getComposerConfigFile($input, $this->config); // Create global composer.json if invoked using `composer global [config-cmd]` if ( ($configFile === 'composer.json' || $configFile === './composer.json') && !file_exists($configFile) && realpath(Platform::getCwd()) === realpath($this->config->get('home')) ) { file_put_contents($configFile, "{\n}\n"); } $this->configFile = new JsonFile($configFile, null, $io); $this->configSource = new JsonConfigSource($this->configFile); // Initialize the global file if it's not there, ignoring any warnings or notices if ($input->getOption('global') && !$this->configFile->exists()) { touch($this->configFile->getPath()); $this->configFile->write(['config' => new \ArrayObject]); Silencer::call('chmod', $this->configFile->getPath(), 0600); } if (!$this->configFile->exists()) { throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile)); } } /** * Get the local composer.json, global config.json, or the file passed by the user */ protected function getComposerConfigFile(InputInterface $input, Config $config): string { return $input->getOption('global') ? ($config->get('home') . '/config.json') : ($input->getOption('file') ?? Factory::getComposerFile()) ; } /** * Get the local auth.json or global auth.json, or if the user passed in a file to use, * the corresponding auth.json */ protected function getAuthConfigFile(InputInterface $input, Config $config): string { return $input->getOption('global') ? ($config->get('home') . '/auth.json') : dirname($this->getComposerConfigFile($input, $config)) . '/auth.json' ; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/FundCommand.php
src/Composer/Command/FundCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Json\JsonFile; use Composer\Package\AliasPackage; use Composer\Package\BasePackage; use Composer\Package\CompletePackageInterface; use Composer\Pcre\Preg; use Composer\Repository\CompositeRepository; use Composer\Semver\Constraint\MatchAllConstraint; use Symfony\Component\Console\Formatter\OutputFormatter; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Nicolas Grekas <p@tchwork.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class FundCommand extends BaseCommand { protected function configure(): void { $this->setName('fund') ->setDescription('Discover how to help fund the maintenance of your dependencies') ->setDefinition([ new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text', ['text', 'json']), ]) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->requireComposer(); $repo = $composer->getRepositoryManager()->getLocalRepository(); $remoteRepos = new CompositeRepository($composer->getRepositoryManager()->getRepositories()); $fundings = []; $packagesToLoad = []; foreach ($repo->getPackages() as $package) { if ($package instanceof AliasPackage) { continue; } $packagesToLoad[$package->getName()] = new MatchAllConstraint(); } // load all packages dev versions in parallel $result = $remoteRepos->loadPackages($packagesToLoad, ['dev' => BasePackage::STABILITY_DEV], []); // collect funding data from default branches foreach ($result['packages'] as $package) { if ( !$package instanceof AliasPackage && $package instanceof CompletePackageInterface && $package->isDefaultBranch() && $package->getFunding() && isset($packagesToLoad[$package->getName()]) ) { $fundings = $this->insertFundingData($fundings, $package); unset($packagesToLoad[$package->getName()]); } } // collect funding from installed packages if none was found in the default branch above foreach ($repo->getPackages() as $package) { if ($package instanceof AliasPackage || !isset($packagesToLoad[$package->getName()])) { continue; } if ($package instanceof CompletePackageInterface && $package->getFunding()) { $fundings = $this->insertFundingData($fundings, $package); } } ksort($fundings); $io = $this->getIO(); $format = $input->getOption('format'); if (!in_array($format, ['text', 'json'])) { $io->writeError(sprintf('Unsupported format "%s". See help for supported formats.', $format)); return 1; } if ($fundings && $format === 'text') { $prev = null; $io->write('The following packages were found in your dependencies which publish funding information:'); foreach ($fundings as $vendor => $links) { $io->write(''); $io->write(sprintf("<comment>%s</comment>", $vendor)); foreach ($links as $url => $packages) { $line = sprintf(' <info>%s</info>', implode(', ', $packages)); if ($prev !== $line) { $io->write($line); $prev = $line; } $io->write(sprintf(' <href=%s>%s</>', OutputFormatter::escape($url), $url)); } } $io->write(""); $io->write("Please consider following these links and sponsoring the work of package authors!"); $io->write("Thank you!"); } elseif ($format === 'json') { $io->write(JsonFile::encode($fundings)); } else { $io->write("No funding links were found in your package dependencies. This doesn't mean they don't need your support!"); } return 0; } /** * @param mixed[] $fundings * @return mixed[] */ private function insertFundingData(array $fundings, CompletePackageInterface $package): array { foreach ($package->getFunding() as $fundingOption) { [$vendor, $packageName] = explode('/', $package->getPrettyName()); // ignore malformed funding entries if (empty($fundingOption['url'])) { continue; } $url = $fundingOption['url']; if (!empty($fundingOption['type']) && $fundingOption['type'] === 'github' && Preg::isMatch('{^https://github.com/([^/]+)$}', $url, $match)) { $url = 'https://github.com/sponsors/'.$match[1]; } $fundings[$vendor][$url][] = $packageName; } return $fundings; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/DiagnoseCommand.php
src/Composer/Command/DiagnoseCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Advisory\Auditor; use Composer\Composer; use Composer\Factory; use Composer\Config; use Composer\Downloader\TransportException; use Composer\IO\BufferIO; use Composer\Json\JsonFile; use Composer\Json\JsonValidationException; use Composer\Package\Locker; use Composer\Package\RootPackage; use Composer\Package\Version\VersionParser; use Composer\Pcre\Preg; use Composer\Repository\ComposerRepository; use Composer\Repository\FilesystemRepository; use Composer\Repository\PlatformRepository; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Repository\RepositorySet; use Composer\Util\ConfigValidator; use Composer\Util\Git; use Composer\Util\IniHelper; use Composer\Util\ProcessExecutor; use Composer\Util\HttpDownloader; use Composer\Util\Platform; use Composer\SelfUpdate\Keys; use Composer\SelfUpdate\Versions; use Composer\IO\NullIO; use Composer\Package\CompletePackageInterface; use Composer\XdebugHandler\XdebugHandler; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\ExecutableFinder; use Composer\Util\Http\ProxyManager; use Composer\Util\Http\RequestProxy; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class DiagnoseCommand extends BaseCommand { /** @var HttpDownloader */ protected $httpDownloader; /** @var ProcessExecutor */ protected $process; /** @var int */ protected $exitCode = 0; protected function configure(): void { $this ->setName('diagnose') ->setDescription('Diagnoses the system to identify common errors') ->setHelp( <<<EOT The <info>diagnose</info> command checks common errors to help debugging problems. The process exit code will be 1 in case of warnings and 2 for errors. Read more at https://getcomposer.org/doc/03-cli.md#diagnose EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $composer = $this->tryComposer(); $io = $this->getIO(); if ($composer) { $config = $composer->getConfig(); $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output); $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); $this->process = $composer->getLoop()->getProcessExecutor() ?? new ProcessExecutor($io); } else { $config = Factory::createConfig(); $this->process = new ProcessExecutor($io); } $config->merge(['config' => ['secure-http' => false]], Config::SOURCE_COMMAND); $config->prohibitUrlByConfig('http://repo.packagist.org', new NullIO); $this->httpDownloader = Factory::createHttpDownloader($io, $config); if (strpos(__FILE__, 'phar:') === 0) { $io->write('Checking pubkeys: ', false); $this->outputResult($this->checkPubKeys($config)); $io->write('Checking Composer version: ', false); $this->outputResult($this->checkVersion($config)); } $io->write(sprintf('Composer version: <comment>%s</comment>', Composer::getVersion())); $io->write('Checking Composer and its dependencies for vulnerabilities: ', false); $this->outputResult($this->checkComposerAudit($config)); $platformOverrides = $config->get('platform') ?: []; $platformRepo = new PlatformRepository([], $platformOverrides); $phpPkg = $platformRepo->findPackage('php', '*'); $phpVersion = $phpPkg->getPrettyVersion(); if ($phpPkg instanceof CompletePackageInterface && str_contains((string) $phpPkg->getDescription(), 'overridden')) { $phpVersion .= ' - ' . $phpPkg->getDescription(); } $io->write(sprintf('PHP version: <comment>%s</comment>', $phpVersion)); if (defined('PHP_BINARY')) { $io->write(sprintf('PHP binary path: <comment>%s</comment>', PHP_BINARY)); } $io->write('OpenSSL version: ' . (defined('OPENSSL_VERSION_TEXT') ? '<comment>'.OPENSSL_VERSION_TEXT.'</comment>' : '<error>missing</error>')); $io->write('curl version: ' . $this->getCurlVersion()); $finder = new ExecutableFinder; $hasSystemUnzip = (bool) $finder->find('unzip'); $bin7zip = ''; if ($hasSystem7zip = (bool) $finder->find('7z', null, ['C:\Program Files\7-Zip'])) { $bin7zip = '7z'; } if (!Platform::isWindows() && !$hasSystem7zip && $hasSystem7zip = (bool) $finder->find('7zz')) { $bin7zip = '7zz'; } $io->write( 'zip: ' . (extension_loaded('zip') ? '<comment>extension present</comment>' : '<comment>extension not loaded</comment>') . ', ' . ($hasSystemUnzip ? '<comment>unzip present</comment>' : '<comment>unzip not available</comment>') . ', ' . ($hasSystem7zip ? '<comment>7-Zip present ('.$bin7zip.')</comment>' : '<comment>7-Zip not available</comment>') . (($hasSystem7zip || $hasSystemUnzip) && !function_exists('proc_open') ? ', <warning>proc_open is disabled or not present, unzip/7-z will not be usable</warning>' : '') ); if ($composer) { $io->write('Active plugins: '.implode(', ', $composer->getPluginManager()->getRegisteredPlugins())); $io->write('Checking composer.json: ', false); $this->outputResult($this->checkComposerSchema()); if ($composer->getLocker()->isLocked()) { $io->write('Checking composer.lock: ', false); $this->outputResult($this->checkComposerLockSchema($composer->getLocker())); } } $io->write('Checking platform settings: ', false); $this->outputResult($this->checkPlatform()); $io->write('Checking git settings: ', false); $this->outputResult($this->checkGit()); $io->write('Checking http connectivity to packagist: ', false); $this->outputResult($this->checkHttp('http', $config)); $io->write('Checking https connectivity to packagist: ', false); $this->outputResult($this->checkHttp('https', $config)); foreach ($config->getRepositories() as $repo) { if (($repo['type'] ?? null) === 'composer' && isset($repo['url'])) { $composerRepo = new ComposerRepository($repo, $this->getIO(), $config, $this->httpDownloader); $reflMethod = new \ReflectionMethod($composerRepo, 'getPackagesJsonUrl'); if (PHP_VERSION_ID < 80100) { $reflMethod->setAccessible(true); } $url = $reflMethod->invoke($composerRepo); if (!str_starts_with($url, 'http')) { continue; } if (str_starts_with($url, 'https://repo.packagist.org')) { continue; } $io->write('Checking connectivity to ' . $repo['url'].': ', false); $this->outputResult($this->checkComposerRepo($url, $config)); } } $proxyManager = ProxyManager::getInstance(); $protos = $config->get('disable-tls') === true ? ['http'] : ['http', 'https']; try { foreach ($protos as $proto) { $proxy = $proxyManager->getProxyForRequest($proto.'://repo.packagist.org'); if ($proxy->getStatus() !== '') { $type = $proxy->isSecure() ? 'HTTPS' : 'HTTP'; $io->write('Checking '.$type.' proxy with '.$proto.': ', false); $this->outputResult($this->checkHttpProxy($proxy, $proto)); } } } catch (TransportException $e) { $io->write('Checking HTTP proxy: ', false); $status = $this->checkConnectivityAndComposerNetworkHttpEnablement(); $this->outputResult(is_string($status) ? $status : $e); } if (count($oauth = $config->get('github-oauth')) > 0) { foreach ($oauth as $domain => $token) { $io->write('Checking '.$domain.' oauth access: ', false); $this->outputResult($this->checkGithubOauth($domain, $token)); } } else { $io->write('Checking github.com rate limit: ', false); try { $rate = $this->getGithubRateLimit('github.com'); if (!is_array($rate)) { $this->outputResult($rate); } elseif (10 > $rate['remaining']) { $io->write('<warning>WARNING</warning>'); $io->write(sprintf( '<comment>GitHub has a rate limit on their API. ' . 'You currently have <options=bold>%u</options=bold> ' . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>', $rate['remaining'], $rate['limit'] )); } else { $this->outputResult(true); } } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { $this->outputResult('<comment>The oauth token for github.com seems invalid, run "composer config --global --unset github-oauth.github.com" to remove it</comment>'); } else { $this->outputResult($e); } } } $io->write('Checking disk free space: ', false); $this->outputResult($this->checkDiskSpace($config)); return $this->exitCode; } /** * @return string|true */ private function checkComposerSchema() { $validator = new ConfigValidator($this->getIO()); [$errors, , $warnings] = $validator->validate(Factory::getComposerFile()); if ($errors || $warnings) { $messages = [ 'error' => $errors, 'warning' => $warnings, ]; $output = ''; foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL; } } return rtrim($output); } return true; } /** * @return string|true */ private function checkComposerLockSchema(Locker $locker) { $json = $locker->getJsonFile(); try { $json->validateSchema(JsonFile::LOCK_SCHEMA); } catch (JsonValidationException $e) { $output = ''; foreach ($e->getErrors() as $error) { $output .= '<error>'.$error.'</error>'.PHP_EOL; } return trim($output); } return true; } private function checkGit(): string { if (!function_exists('proc_open')) { return '<comment>proc_open is not available, git cannot be used</comment>'; } $this->process->execute(['git', 'config', 'color.ui'], $output); if (strtolower(trim($output)) === 'always') { return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>'; } $gitVersion = Git::getVersion($this->process); if (null === $gitVersion) { return '<comment>No git process found</>'; } if (version_compare('2.24.0', $gitVersion, '>')) { return '<warning>Your git version ('.$gitVersion.') is too old and possibly will cause issues. Please upgrade to git 2.24 or above</>'; } return '<info>OK</> <comment>git version '.$gitVersion.'</>'; } /** * @return string|string[]|true */ private function checkHttp(string $proto, Config $config) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } $result = []; if ($proto === 'https' && $config->get('disable-tls') === true) { $tlsWarning = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>'; } try { $this->httpDownloader->get($proto . '://repo.packagist.org/packages.json'); } catch (TransportException $e) { $hints = HttpDownloader::getExceptionHints($e); if (null !== $hints && count($hints) > 0) { foreach ($hints as $hint) { $result[] = $hint; } } $result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>'; } if (isset($tlsWarning)) { $result[] = $tlsWarning; } if (count($result) > 0) { return $result; } return true; } /** * @return string|string[]|true */ private function checkComposerRepo(string $url, Config $config) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } $result = []; if (str_starts_with($url, 'https://') && $config->get('disable-tls') === true) { $tlsWarning = '<warning>Composer is configured to disable SSL/TLS protection. This will leave remote HTTPS requests vulnerable to Man-In-The-Middle attacks.</warning>'; } try { $this->httpDownloader->get($url); } catch (TransportException $e) { $hints = HttpDownloader::getExceptionHints($e); if (null !== $hints && count($hints) > 0) { foreach ($hints as $hint) { $result[] = $hint; } } $result[] = '<error>[' . get_class($e) . '] ' . $e->getMessage() . '</error>'; } if (isset($tlsWarning)) { $result[] = $tlsWarning; } if (count($result) > 0) { return $result; } return true; } /** * @return string|\Exception */ private function checkHttpProxy(RequestProxy $proxy, string $protocol) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } try { $proxyStatus = $proxy->getStatus(); if ($proxy->isExcludedByNoProxy()) { return '<info>SKIP</> <comment>Because repo.packagist.org is '.$proxyStatus.'</>'; } $json = $this->httpDownloader->get($protocol.'://repo.packagist.org/packages.json')->decodeJson(); if (isset($json['provider-includes'])) { $hash = reset($json['provider-includes']); $hash = $hash['sha256']; $path = str_replace('%hash%', $hash, key($json['provider-includes'])); $provider = $this->httpDownloader->get($protocol.'://repo.packagist.org/'.$path)->getBody(); if (hash('sha256', $provider) !== $hash) { return '<warning>It seems that your proxy ('.$proxyStatus.') is modifying '.$protocol.' traffic on the fly</>'; } } return '<info>OK</> <comment>'.$proxyStatus.'</>'; } catch (\Exception $e) { return $e; } } /** * @return string|\Exception */ private function checkGithubOauth(string $domain, string $token) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); try { $url = $domain === 'github.com' ? 'https://api.'.$domain.'/' : 'https://'.$domain.'/api/v3/'; $response = $this->httpDownloader->get($url, [ 'retry-auth-failure' => false, ]); $expiration = $response->getHeader('github-authentication-token-expiration'); if ($expiration === null) { return '<info>OK</> <comment>does not expire</>'; } return '<info>OK</> <comment>expires on '. $expiration .'</>'; } catch (\Exception $e) { if ($e instanceof TransportException && $e->getCode() === 401) { return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>'; } return $e; } } /** * @throws TransportException * @return mixed|string */ private function getGithubRateLimit(string $domain, ?string $token = null) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } if ($token) { $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic'); } $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit'; $data = $this->httpDownloader->get($url, ['retry-auth-failure' => false])->decodeJson(); return $data['resources']['core']; } /** * @return string|true */ private function checkDiskSpace(Config $config) { if (!function_exists('disk_free_space')) { return true; } $minSpaceFree = 1024 * 1024; if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree) || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree) ) { return '<error>The disk hosting '.$dir.' is full</error>'; } return true; } /** * @return string[]|true */ private function checkPubKeys(Config $config) { $home = $config->get('home'); $errors = []; $io = $this->getIO(); if (file_exists($home.'/keys.tags.pub') && file_exists($home.'/keys.dev.pub')) { $io->write(''); } if (file_exists($home.'/keys.tags.pub')) { $io->write('Tags Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.tags.pub')); } else { $errors[] = '<error>Missing pubkey for tags verification</error>'; } if (file_exists($home.'/keys.dev.pub')) { $io->write('Dev Public Key Fingerprint: ' . Keys::fingerprint($home.'/keys.dev.pub')); } else { $errors[] = '<error>Missing pubkey for dev verification</error>'; } if ($errors) { $errors[] = '<error>Run composer self-update --update-keys to set them up</error>'; } return $errors ?: true; } /** * @return string|\Exception|true */ private function checkVersion(Config $config) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } $versionsUtil = new Versions($config, $this->httpDownloader); try { $latest = $versionsUtil->getLatest(); } catch (\Exception $e) { return $e; } if (Composer::VERSION !== $latest['version'] && Composer::VERSION !== '@package_version@') { return '<comment>You are not running the latest '.$versionsUtil->getChannel().' version, run `composer self-update` to update ('.Composer::VERSION.' => '.$latest['version'].')</comment>'; } return true; } /** * @return string|true */ private function checkComposerAudit(Config $config) { $result = $this->checkConnectivityAndComposerNetworkHttpEnablement(); if ($result !== true) { return $result; } $auditor = new Auditor(); $repoSet = new RepositorySet(); $installedJson = new JsonFile(__DIR__ . '/../../../vendor/composer/installed.json'); if (!$installedJson->exists()) { return '<warning>Could not find Composer\'s installed.json, this must be a non-standard Composer installation.</>'; } $localRepo = new FilesystemRepository($installedJson); $version = Composer::getVersion(); $packages = $localRepo->getCanonicalPackages(); if ($version !== '@package_version@') { $versionParser = new VersionParser(); $normalizedVersion = $versionParser->normalize($version); $rootPkg = new RootPackage('composer/composer', $normalizedVersion, $version); $packages[] = $rootPkg; } $repoSet->addRepository(new ComposerRepository(['type' => 'composer', 'url' => 'https://packagist.org'], new NullIO(), $config, $this->httpDownloader)); try { $io = new BufferIO(); $result = $auditor->audit($io, $repoSet, $packages, Auditor::FORMAT_TABLE, true, [], Auditor::ABANDONED_IGNORE); } catch (\Throwable $e) { return '<highlight>Failed performing audit: '.$e->getMessage().'</>'; } if ($result > 0) { return '<highlight>Audit found some issues:</>' . PHP_EOL . $io->getOutput(); } return true; } private function getCurlVersion(): string { if (extension_loaded('curl')) { if (!HttpDownloader::isCurlEnabled()) { return '<error>disabled via disable_functions, using php streams fallback, which reduces performance</error>'; } $version = curl_version(); $libzVersion = isset($version['libz_version']) && $version['libz_version'] !== '' ? $version['libz_version'] : 'missing'; $brotliVersion = isset($version['brotli_version']) && $version['brotli_version'] !== '' ? $version['brotli_version'] : 'missing'; $sslVersion = isset($version['ssl_version']) && $version['ssl_version'] !== '' ? $version['ssl_version'] : 'missing'; $hasZstd = isset($version['features']) && defined('CURL_VERSION_ZSTD') && 0 !== ($version['features'] & CURL_VERSION_ZSTD); $httpVersions = '1.0, 1.1'; if (isset($version['features']) && \defined('CURL_VERSION_HTTP2') && \defined('CURL_HTTP_VERSION_2_0') && (CURL_VERSION_HTTP2 & $version['features']) !== 0) { $httpVersions .= ', 2'; } if (isset($version['features']) && \defined('CURL_VERSION_HTTP3') && ($version['features'] & CURL_VERSION_HTTP3) !== 0) { $httpVersions .= ', 3'; } return '<comment>'.$version['version'].'</comment> '. 'libz <comment>'.$libzVersion.'</comment> '. 'brotli <comment>'.$brotliVersion.'</comment> '. 'zstd <comment>'.($hasZstd ? 'supported' : 'missing').'</comment> '. 'ssl <comment>'.$sslVersion.'</comment> '. 'HTTP <comment>'.$httpVersions.'</comment>'; } return '<error>missing, using php streams fallback, which reduces performance</error>'; } /** * @param bool|string|string[]|\Exception $result */ private function outputResult($result): void { $io = $this->getIO(); if (true === $result) { $io->write('<info>OK</info>'); return; } $hadError = false; $hadWarning = false; if ($result instanceof \Exception) { $result = '<error>['.get_class($result).'] '.$result->getMessage().'</error>'; } if (!$result) { // falsey results should be considered as an error, even if there is nothing to output $hadError = true; } else { if (!is_array($result)) { $result = [$result]; } foreach ($result as $message) { if (false !== strpos($message, '<error>')) { $hadError = true; } elseif (false !== strpos($message, '<warning>')) { $hadWarning = true; } } } if ($hadError) { $io->write('<error>FAIL</error>'); $this->exitCode = max($this->exitCode, 2); } elseif ($hadWarning) { $io->write('<warning>WARNING</warning>'); $this->exitCode = max($this->exitCode, 1); } if ($result) { foreach ($result as $message) { $io->write(trim($message)); } } } /** * @return string|true */ private function checkPlatform() { $output = ''; $out = static function ($msg, $style) use (&$output): void { $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL; }; // code below taken from getcomposer.org/installer, any changes should be made there and replicated here $errors = []; $warnings = []; $displayIniMessage = false; $iniMessage = PHP_EOL.PHP_EOL.IniHelper::getMessage(); $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.'; if (!function_exists('json_decode')) { $errors['json'] = true; } if (!extension_loaded('Phar')) { $errors['phar'] = true; } if (!extension_loaded('filter')) { $errors['filter'] = true; } if (!extension_loaded('hash')) { $errors['hash'] = true; } if (!extension_loaded('iconv') && !extension_loaded('mbstring')) { $errors['iconv_mbstring'] = true; } if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) { $errors['allow_url_fopen'] = true; } if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) { $errors['ioncube'] = ioncube_loader_version(); } if (\PHP_VERSION_ID < 70205) { $errors['php'] = PHP_VERSION; } if (!extension_loaded('openssl')) { $errors['openssl'] = true; } if (extension_loaded('openssl') && OPENSSL_VERSION_NUMBER < 0x1000100f) { $warnings['openssl_version'] = true; } if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && filter_var(ini_get('apc.enable_cli'), FILTER_VALIDATE_BOOLEAN)) { $warnings['apc_cli'] = true; } if (!extension_loaded('zlib')) { $warnings['zlib'] = true; } ob_start(); phpinfo(INFO_GENERAL); $phpinfo = ob_get_clean(); if (is_string($phpinfo) && Preg::isMatchStrictGroups('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) { $configure = $match[1]; if (str_contains($configure, '--enable-sigchild')) { $warnings['sigchild'] = true; } if (str_contains($configure, '--with-curlwrappers')) { $warnings['curlwrappers'] = true; } } if (filter_var(ini_get('xdebug.profiler_enabled'), FILTER_VALIDATE_BOOLEAN)) { $warnings['xdebug_profile'] = true; } elseif (XdebugHandler::isXdebugActive()) { $warnings['xdebug_loaded'] = true; } if (defined('PHP_WINDOWS_VERSION_BUILD') && (version_compare(PHP_VERSION, '7.2.23', '<') || (version_compare(PHP_VERSION, '7.3.0', '>=') && version_compare(PHP_VERSION, '7.3.10', '<')))) { $warnings['onedrive'] = PHP_VERSION; } if (extension_loaded('uopz') && !(filter_var(ini_get('uopz.disable'), FILTER_VALIDATE_BOOLEAN) || filter_var(ini_get('uopz.exit'), FILTER_VALIDATE_BOOLEAN))) { $warnings['uopz'] = true; } if (!empty($errors)) { foreach ($errors as $error => $current) { switch ($error) { case 'json': $text = PHP_EOL."The json extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-json"; break; case 'phar': $text = PHP_EOL."The phar extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-phar"; break; case 'filter': $text = PHP_EOL."The filter extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-filter"; break; case 'hash': $text = PHP_EOL."The hash extension is missing.".PHP_EOL; $text .= "Install it or recompile php without --disable-hash"; break; case 'iconv_mbstring': $text = PHP_EOL."The iconv OR mbstring extension is required and both are missing.".PHP_EOL; $text .= "Install either of them or recompile php without --disable-iconv"; break; case 'php': $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 7.2.5 or higher."; break; case 'allow_url_fopen': $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " allow_url_fopen = On"; $displayIniMessage = true; break; case 'ioncube': $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL; $text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL; $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so"; $displayIniMessage = true; break; case 'openssl': $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL; $text .= "If possible you should enable it or recompile php with --with-openssl"; break; default: throw new \InvalidArgumentException(sprintf("DiagnoseCommand: Unknown error type \"%s\". Please report at https://github.com/composer/composer/issues/new.", $error)); } $out($text, 'error'); } $output .= PHP_EOL; } if (!empty($warnings)) { foreach ($warnings as $warning => $current) { switch ($warning) { case 'apc_cli': $text = "The apc.enable_cli setting is incorrect.".PHP_EOL; $text .= "Add the following to the end of your `php.ini`:".PHP_EOL; $text .= " apc.enable_cli = Off"; $displayIniMessage = true; break; case 'zlib': $text = 'The zlib extension is not loaded, this can slow down Composer a lot.'.PHP_EOL; $text .= 'If possible, enable it or recompile php with --with-zlib'.PHP_EOL; $displayIniMessage = true; break; case 'sigchild':
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/InitCommand.php
src/Composer/Command/InitCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\Json\JsonFile; use Composer\Json\JsonValidationException; use Composer\Package\BasePackage; use Composer\Pcre\Preg; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\RepositoryFactory; use Composer\Spdx\SpdxLicenses; use Composer\Util\Filesystem; use Composer\Util\Silencer; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Composer\Util\ProcessExecutor; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Helper\FormatterHelper; /** * @author Justin Rainbow <justin.rainbow@gmail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class InitCommand extends BaseCommand { use CompletionTrait; use PackageDiscoveryTrait; /** @var array<string, string> */ private $gitConfig; /** * @inheritDoc */ protected function configure(): void { $this ->setName('init') ->setDescription('Creates a basic composer.json file in current directory') ->setDefinition([ new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'), new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'), new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'), new InputOption('type', null, InputOption::VALUE_REQUIRED, 'Type of package (e.g. library, project, metapackage, composer-plugin)'), new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'), new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"', null, $this->suggestAvailablePackageInclPlatform()), new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"', null, $this->suggestAvailablePackageInclPlatform()), new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::STABILITIES)).')'), new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'), new InputOption('repository', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add custom repositories, either by URL or using JSON arrays'), new InputOption('autoload', 'a', InputOption::VALUE_REQUIRED, 'Add PSR-4 autoload mapping. Maps your package\'s namespace to the provided directory. (Expects a relative path, e.g. src/)'), ]) ->setHelp( <<<EOT The <info>init</info> command creates a basic composer.json file in the current directory. <info>php composer.phar init</info> Read more at https://getcomposer.org/doc/03-cli.md#init EOT ) ; } /** * @throws \Seld\JsonLint\ParsingException */ protected function execute(InputInterface $input, OutputInterface $output): int { $io = $this->getIO(); $allowlist = ['name', 'description', 'author', 'type', 'homepage', 'require', 'require-dev', 'stability', 'license', 'autoload']; $options = array_filter(array_intersect_key($input->getOptions(), array_flip($allowlist)), static function ($val) { return $val !== null && $val !== []; }); if (isset($options['name']) && !Preg::isMatch('{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D', $options['name'])) { throw new \InvalidArgumentException( 'The package name '.$options['name'].' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+' ); } if (isset($options['author'])) { $options['authors'] = $this->formatAuthors($options['author']); unset($options['author']); } $repositories = $input->getOption('repository'); if (count($repositories) > 0) { $config = Factory::createConfig($io); foreach ($repositories as $repo) { $options['repositories'][] = RepositoryFactory::configFromString($io, $config, $repo, true); } } if (isset($options['stability'])) { $options['minimum-stability'] = $options['stability']; unset($options['stability']); } $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass; if ([] === $options['require']) { $options['require'] = new \stdClass; } if (isset($options['require-dev'])) { $options['require-dev'] = $this->formatRequirements($options['require-dev']); if ([] === $options['require-dev']) { $options['require-dev'] = new \stdClass; } } // --autoload - create autoload object $autoloadPath = null; if (isset($options['autoload'])) { $autoloadPath = $options['autoload']; $namespace = $this->namespaceFromPackageName((string) $input->getOption('name')); $options['autoload'] = (object) [ 'psr-4' => [ $namespace . '\\' => $autoloadPath, ], ]; } $file = new JsonFile(Factory::getComposerFile()); $json = JsonFile::encode($options); if ($input->isInteractive()) { $io->writeError(['', $json, '']); if (!$io->askConfirmation('Do you confirm generation [<comment>yes</comment>]? ')) { $io->writeError('<error>Command aborted</error>'); return 1; } } else { $io->writeError('Writing '.$file->getPath()); } $file->write($options); try { $file->validateSchema(JsonFile::LAX_SCHEMA); } catch (JsonValidationException $e) { $io->writeError('<error>Schema validation error, aborting</error>'); $errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors()); $io->writeError($e->getMessage() . ':' . PHP_EOL . $errors); Silencer::call('unlink', $file->getPath()); return 1; } // --autoload - Create src folder if ($autoloadPath) { $filesystem = new Filesystem(); $filesystem->ensureDirectoryExists($autoloadPath); // dump-autoload only for projects without added dependencies. if (!$this->hasDependencies($options)) { $this->runDumpAutoloadCommand($output); } } if ($input->isInteractive() && is_dir('.git')) { $ignoreFile = realpath('.gitignore'); if (false === $ignoreFile) { $ignoreFile = realpath('.') . '/.gitignore'; } if (!$this->hasVendorIgnore($ignoreFile)) { $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]? '; if ($io->askConfirmation($question)) { $this->addVendorIgnore($ignoreFile); } } } $question = 'Would you like to install dependencies now [<comment>yes</comment>]? '; if ($input->isInteractive() && $this->hasDependencies($options) && $io->askConfirmation($question)) { $this->updateDependencies($output); } // --autoload - Show post-install configuration info if ($autoloadPath) { $namespace = $this->namespaceFromPackageName((string) $input->getOption('name')); $io->writeError('PSR-4 autoloading configured. Use "<comment>namespace '.$namespace.';</comment>" in '.$autoloadPath); $io->writeError('Include the Composer autoloader with: <comment>require \'vendor/autoload.php\';</comment>'); } return 0; } protected function initialize(InputInterface $input, OutputInterface $output): void { parent::initialize($input, $output); if (!$input->isInteractive()) { if ($input->getOption('name') === null) { $input->setOption('name', $this->getDefaultPackageName()); } if ($input->getOption('author') === null) { $input->setOption('author', $this->getDefaultAuthor()); } } } /** * @inheritDoc */ protected function interact(InputInterface $input, OutputInterface $output): void { $io = $this->getIO(); /** @var FormatterHelper $formatter */ $formatter = $this->getHelperSet()->get('formatter'); // initialize repos if configured $repositories = $input->getOption('repository'); if (count($repositories) > 0) { $config = Factory::createConfig($io); $io->loadConfiguration($config); $repoManager = RepositoryFactory::manager($io, $config); $repos = [new PlatformRepository]; $createDefaultPackagistRepo = true; foreach ($repositories as $repo) { $repoConfig = RepositoryFactory::configFromString($io, $config, $repo, true); if ( (isset($repoConfig['packagist']) && $repoConfig === ['packagist' => false]) || (isset($repoConfig['packagist.org']) && $repoConfig === ['packagist.org' => false]) ) { $createDefaultPackagistRepo = false; continue; } $repos[] = RepositoryFactory::createRepo($io, $config, $repoConfig, $repoManager); } if ($createDefaultPackagistRepo) { $repos[] = RepositoryFactory::createRepo($io, $config, [ 'type' => 'composer', 'url' => 'https://repo.packagist.org', ], $repoManager); } $this->repos = new CompositeRepository($repos); unset($repos, $config, $repositories); } $io->writeError([ '', $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true), '', ]); // namespace $io->writeError([ '', 'This command will guide you through creating your composer.json config.', '', ]); $name = $input->getOption('name') ?? $this->getDefaultPackageName(); $name = $io->askAndValidate( 'Package name (<vendor>/<name>) [<comment>'.$name.'</comment>]: ', static function ($value) use ($name) { if (null === $value) { return $name; } if (!Preg::isMatch('{^[a-z0-9]([_.-]?[a-z0-9]+)*\/[a-z0-9](([_.]|-{1,2})?[a-z0-9]+)*$}D', $value)) { throw new \InvalidArgumentException( 'The package name '.$value.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+' ); } return $value; }, null, $name ); $input->setOption('name', $name); $description = $input->getOption('description') ?: null; $description = $io->ask( 'Description [<comment>'.$description.'</comment>]: ', $description ); $input->setOption('description', $description); $author = $input->getOption('author') ?? $this->getDefaultAuthor(); $author = $io->askAndValidate( 'Author ['.(is_string($author) ? '<comment>'.$author.'</comment>, ' : '') . 'n to skip]: ', function ($value) use ($author) { if ($value === 'n' || $value === 'no') { return; } $value = $value ?: $author; $author = $this->parseAuthorString($value ?? ''); if ($author['email'] === null) { return $author['name']; } return sprintf('%s <%s>', $author['name'], $author['email']); }, null, $author ); $input->setOption('author', $author); $minimumStability = $input->getOption('stability') ?: null; $minimumStability = $io->askAndValidate( 'Minimum Stability [<comment>'.$minimumStability.'</comment>]: ', static function ($value) use ($minimumStability) { if (null === $value) { return $minimumStability; } if (!isset(BasePackage::STABILITIES[$value])) { throw new \InvalidArgumentException( 'Invalid minimum stability "'.$value.'". Must be empty or one of: '. implode(', ', array_keys(BasePackage::STABILITIES)) ); } return $value; }, null, $minimumStability ); $input->setOption('stability', $minimumStability); $type = $input->getOption('type'); $type = $io->ask( 'Package Type (e.g. library, project, metapackage, composer-plugin) [<comment>'.$type.'</comment>]: ', $type ); if ($type === '' || $type === false) { $type = null; } $input->setOption('type', $type); if (null === $license = $input->getOption('license')) { if (!empty($_SERVER['COMPOSER_DEFAULT_LICENSE'])) { $license = $_SERVER['COMPOSER_DEFAULT_LICENSE']; } } $license = $io->ask( 'License [<comment>'.$license.'</comment>]: ', $license ); $spdx = new SpdxLicenses(); if (null !== $license && !$spdx->validate($license) && $license !== 'proprietary') { throw new \InvalidArgumentException('Invalid license provided: '.$license.'. Only SPDX license identifiers (https://spdx.org/licenses/) or "proprietary" are accepted.'); } $input->setOption('license', $license); $io->writeError(['', 'Define your dependencies.', '']); // prepare to resolve dependencies $repos = $this->getRepos(); $preferredStability = $minimumStability ?: 'stable'; $platformRepo = null; if ($repos instanceof CompositeRepository) { foreach ($repos->getRepositories() as $candidateRepo) { if ($candidateRepo instanceof PlatformRepository) { $platformRepo = $candidateRepo; break; } } } $question = 'Would you like to define your dependencies (require) interactively [<comment>yes</comment>]? '; $require = $input->getOption('require'); $requirements = []; if (count($require) > 0 || $io->askConfirmation($question)) { $requirements = $this->determineRequirements($input, $output, $require, $platformRepo, $preferredStability); } $input->setOption('require', $requirements); $question = 'Would you like to define your dev dependencies (require-dev) interactively [<comment>yes</comment>]? '; $requireDev = $input->getOption('require-dev'); $devRequirements = []; if (count($requireDev) > 0 || $io->askConfirmation($question)) { $devRequirements = $this->determineRequirements($input, $output, $requireDev, $platformRepo, $preferredStability); } $input->setOption('require-dev', $devRequirements); // --autoload - input and validation $autoload = $input->getOption('autoload') ?: 'src/'; $namespace = $this->namespaceFromPackageName((string) $input->getOption('name')); $autoload = $io->askAndValidate( 'Add PSR-4 autoload mapping? Maps namespace "'.$namespace.'" to the entered relative path. [<comment>'.$autoload.'</comment>, n to skip]: ', static function ($value) use ($autoload) { if (null === $value) { return $autoload; } if ($value === 'n' || $value === 'no') { return; } $value = $value ?: $autoload; if (!Preg::isMatch('{^[^/][A-Za-z0-9\-_/]+/$}', $value)) { throw new \InvalidArgumentException(sprintf( 'The src folder name "%s" is invalid. Please add a relative path with tailing forward slash. [A-Za-z0-9_-/]+/', $value )); } return $value; }, null, $autoload ); $input->setOption('autoload', $autoload); } /** * @return array{name: string, email: string|null} */ private function parseAuthorString(string $author): array { if (Preg::isMatch('/^(?P<name>[- .,\p{L}\p{N}\p{Mn}\'’"()]+)(?:\s+<(?P<email>.+?)>)?$/u', $author, $match)) { if (null !== $match['email'] && !$this->isValidEmail($match['email'])) { throw new \InvalidArgumentException('Invalid email "'.$match['email'].'"'); } return [ 'name' => trim($match['name']), 'email' => $match['email'], ]; } throw new \InvalidArgumentException( 'Invalid author string. Must be in the formats: '. 'Jane Doe or John Smith <john@example.com>' ); } /** * @return array<int, array{name: string, email?: string}> */ protected function formatAuthors(string $author): array { $author = $this->parseAuthorString($author); if (null === $author['email']) { unset($author['email']); } return [$author]; } /** * Extract namespace from package's vendor name. * * new_projects.acme-extra/package-name becomes "NewProjectsAcmeExtra\PackageName" */ public function namespaceFromPackageName(string $packageName): ?string { if (!$packageName || strpos($packageName, '/') === false) { return null; } $namespace = array_map( static function ($part): string { $part = Preg::replace('/[^a-z0-9]/i', ' ', $part); $part = ucwords($part); return str_replace(' ', '', $part); }, explode('/', $packageName) ); return implode('\\', $namespace); } /** * @return array<string, string> */ protected function getGitConfig(): array { if (null !== $this->gitConfig) { return $this->gitConfig; } $process = new ProcessExecutor($this->getIO()); if (0 === $process->execute(['git', 'config', '-l'], $output)) { $this->gitConfig = []; Preg::matchAllStrictGroups('{^([^=]+)=(.*)$}m', $output, $matches); foreach ($matches[1] as $key => $match) { $this->gitConfig[$match] = $matches[2][$key]; } return $this->gitConfig; } return $this->gitConfig = []; } /** * Checks the local .gitignore file for the Composer vendor directory. * * Tested patterns include: * "/$vendor" * "$vendor" * "$vendor/" * "/$vendor/" * "/$vendor/*" * "$vendor/*" */ protected function hasVendorIgnore(string $ignoreFile, string $vendor = 'vendor'): bool { if (!file_exists($ignoreFile)) { return false; } $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor)); $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES); foreach ($lines as $line) { if (Preg::isMatch($pattern, $line)) { return true; } } return false; } protected function addVendorIgnore(string $ignoreFile, string $vendor = '/vendor/'): void { $contents = ""; if (file_exists($ignoreFile)) { $contents = file_get_contents($ignoreFile); if (strpos($contents, "\n") !== 0) { $contents .= "\n"; } } file_put_contents($ignoreFile, $contents . $vendor. "\n"); } protected function isValidEmail(string $email): bool { // assume it's valid if we can't validate it if (!function_exists('filter_var')) { return true; } return false !== filter_var($email, FILTER_VALIDATE_EMAIL); } private function updateDependencies(OutputInterface $output): void { try { $updateCommand = $this->getApplication()->find('update'); $this->getApplication()->resetComposer(); $updateCommand->run(new ArrayInput([]), $output); } catch (\Exception $e) { $this->getIO()->writeError('Could not update dependencies. Run `composer update` to see more information.'); } } private function runDumpAutoloadCommand(OutputInterface $output): void { try { $command = $this->getApplication()->find('dump-autoload'); $this->getApplication()->resetComposer(); $command->run(new ArrayInput([]), $output); } catch (\Exception $e) { $this->getIO()->writeError('Could not run dump-autoload.'); } } /** * @param array<string, string|array<string>> $options */ private function hasDependencies(array $options): bool { $requires = (array) $options['require']; $devRequires = isset($options['require-dev']) ? (array) $options['require-dev'] : []; return !empty($requires) || !empty($devRequires); } private function sanitizePackageNameComponent(string $name): string { $name = Preg::replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name); $name = strtolower($name); $name = Preg::replace('{^[_.-]+|[_.-]+$|[^a-z0-9_.-]}u', '', $name); $name = Preg::replace('{([_.-]){2,}}u', '$1', $name); return $name; } private function getDefaultPackageName(): string { $git = $this->getGitConfig(); $cwd = realpath("."); $name = basename($cwd); $name = $this->sanitizePackageNameComponent($name); $vendor = $name; if (!empty($_SERVER['COMPOSER_DEFAULT_VENDOR'])) { $vendor = $_SERVER['COMPOSER_DEFAULT_VENDOR']; } elseif (isset($git['github.user'])) { $vendor = $git['github.user']; } elseif (!empty($_SERVER['USERNAME'])) { $vendor = $_SERVER['USERNAME']; } elseif (!empty($_SERVER['USER'])) { $vendor = $_SERVER['USER']; } elseif (get_current_user()) { $vendor = get_current_user(); } $vendor = $this->sanitizePackageNameComponent($vendor); return $vendor . '/' . $name; } private function getDefaultAuthor(): ?string { $git = $this->getGitConfig(); if (!empty($_SERVER['COMPOSER_DEFAULT_AUTHOR'])) { $author_name = $_SERVER['COMPOSER_DEFAULT_AUTHOR']; } elseif (isset($git['user.name'])) { $author_name = $git['user.name']; } if (!empty($_SERVER['COMPOSER_DEFAULT_EMAIL'])) { $author_email = $_SERVER['COMPOSER_DEFAULT_EMAIL']; } elseif (isset($git['user.email'])) { $author_email = $git['user.email']; } if (isset($author_name, $author_email)) { return sprintf('%s <%s>', $author_name, $author_email); } return null; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/OutdatedCommand.php
src/Composer/Command/OutdatedCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Input\ArrayInput; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * @author Jordi Boggiano <j.boggiano@seld.be> */ class OutdatedCommand extends BaseCommand { use CompletionTrait; protected function configure(): void { $this ->setName('outdated') ->setDescription('Shows a list of installed packages that have updates available, including their latest version') ->setDefinition([ new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect. Or a name including a wildcard (*) to filter lists of packages instead.', null, $this->suggestInstalledPackage(false)), new InputOption('outdated', 'o', InputOption::VALUE_NONE, 'Show only packages that are outdated (this is the default, but present here for compat with `show`'), new InputOption('all', 'a', InputOption::VALUE_NONE, 'Show all installed packages with their latest versions'), new InputOption('locked', null, InputOption::VALUE_NONE, 'Shows updates for packages from the lock file, regardless of what is currently in vendor dir'), new InputOption('direct', 'D', InputOption::VALUE_NONE, 'Shows only packages that are directly required by the root package'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code when there are outdated packages'), new InputOption('major-only', 'M', InputOption::VALUE_NONE, 'Show only packages that have major SemVer-compatible updates.'), new InputOption('minor-only', 'm', InputOption::VALUE_NONE, 'Show only packages that have minor SemVer-compatible updates.'), new InputOption('patch-only', 'p', InputOption::VALUE_NONE, 'Show only packages that have patch SemVer-compatible updates.'), new InputOption('sort-by-age', 'A', InputOption::VALUE_NONE, 'Displays the installed version\'s age, and sorts packages oldest first.'), new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text', ['json', 'text']), new InputOption('ignore', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore specified package(s). Can contain wildcards (*). Use it if you don\'t want to be informed about new versions of some packages.', null, $this->suggestInstalledPackage(false)), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables search in require-dev packages.'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages). Use with the --outdated option'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages). Use with the --outdated option'), ]) ->setHelp( <<<EOT The outdated command is just a proxy for `composer show -l` The color coding (or signage if you have ANSI colors disabled) for dependency versions is as such: - <info>green</info> (=): Dependency is in the latest version and is up to date. - <comment>yellow</comment> (~): Dependency has a new version available that includes backwards compatibility breaks according to semver, so upgrade when you can but it may involve work. - <highlight>red</highlight> (!): Dependency has a new version that is semver-compatible and you should upgrade it. Read more at https://getcomposer.org/doc/03-cli.md#outdated EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $args = [ 'command' => 'show', '--latest' => true, ]; if ($input->getOption('no-interaction')) { $args['--no-interaction'] = true; } if ($input->getOption('no-plugins')) { $args['--no-plugins'] = true; } if ($input->getOption('no-scripts')) { $args['--no-scripts'] = true; } if ($input->getOption('no-cache')) { $args['--no-cache'] = true; } if (!$input->getOption('all')) { $args['--outdated'] = true; } if ($input->getOption('direct')) { $args['--direct'] = true; } if (null !== $input->getArgument('package')) { $args['package'] = $input->getArgument('package'); } if ($input->getOption('strict')) { $args['--strict'] = true; } if ($input->getOption('major-only')) { $args['--major-only'] = true; } if ($input->getOption('minor-only')) { $args['--minor-only'] = true; } if ($input->getOption('patch-only')) { $args['--patch-only'] = true; } if ($input->getOption('locked')) { $args['--locked'] = true; } if ($input->getOption('no-dev')) { $args['--no-dev'] = true; } if ($input->getOption('sort-by-age')) { $args['--sort-by-age'] = true; } $args['--ignore-platform-req'] = $input->getOption('ignore-platform-req'); if ($input->getOption('ignore-platform-reqs')) { $args['--ignore-platform-reqs'] = true; } $args['--format'] = $input->getOption('format'); $args['--ignore'] = $input->getOption('ignore'); $input = new ArrayInput($args); return $this->getApplication()->run($input, $output); } /** * @inheritDoc */ public function isProxyCommand(): bool { return true; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/RepositoryCommand.php
src/Composer/Command/RepositoryCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\Json\JsonFile; use Composer\Pcre\Preg; use Composer\Console\Input\InputArgument; use Symfony\Component\Console\Completion\CompletionInput; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Manage repositories * * Examples: * - composer repo list * - composer repo add foo vcs https://github.com/acme/foo * - composer repo remove foo * - composer repo set-url foo https://git.example.org/acme/foo * - composer repo get-url foo * - composer repo disable packagist.org * - composer repo enable packagist.org */ class RepositoryCommand extends BaseConfigCommand { protected function configure(): void { $this ->setName('repository') ->setAliases(['repo']) ->setDescription('Manages repositories') ->setDefinition([ new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'), new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json'), new InputOption('append', null, InputOption::VALUE_NONE, 'When adding a repository, append it (lower priority) instead of prepending it'), new InputOption('before', null, InputOption::VALUE_REQUIRED, 'When adding a repository, insert it before the given repository name', null, $this->suggestRepoNames()), new InputOption('after', null, InputOption::VALUE_REQUIRED, 'When adding a repository, insert it after the given repository name', null, $this->suggestRepoNames()), new InputArgument('action', InputArgument::OPTIONAL, 'Action to perform: list, add, remove, set-url, get-url, enable, disable', 'list', ['list', 'add', 'remove', 'set-url', 'get-url', 'enable', 'disable']), new InputArgument('name', InputArgument::OPTIONAL, 'Repository name (or special name packagist.org for enable/disable)', null, $this->suggestRepoNames()), new InputArgument('arg1', InputArgument::OPTIONAL, 'Type for add, or new URL for set-url, or JSON config for add', null, $this->suggestTypeForAdd()), new InputArgument('arg2', InputArgument::OPTIONAL, 'URL for add (if not using JSON)'), ]) ->setHelp(<<<EOT This command lets you manage repositories in your composer.json. Examples: composer repo list composer repo add foo vcs https://github.com/acme/foo composer repo add bar composer https://repo.packagist.com/bar composer repo add zips '{"type":"artifact","url":"/path/to/dir/with/zips"}' composer repo add baz vcs https://example.org --before foo composer repo add qux vcs https://example.org --after bar composer repo remove foo composer repo set-url foo https://git.example.org/acme/foo composer repo get-url foo composer repo disable packagist.org composer repo enable packagist.org Use --global/-g to alter the global config.json instead. Use --file to alter a specific file. EOT ); } protected function execute(InputInterface $input, OutputInterface $output): int { $action = strtolower((string) $input->getArgument('action')); $name = $input->getArgument('name'); $arg1 = $input->getArgument('arg1'); $arg2 = $input->getArgument('arg2'); $this->config->merge($this->configFile->read(), $this->configFile->getPath()); $repos = $this->config->getRepositories(); switch ($action) { case 'list': case 'ls': case 'show': $this->listRepositories($repos); return 0; case 'add': if ($name === null) { throw new \RuntimeException('You must pass a repository name. Example: composer repo add foo vcs https://example.org'); } if ($arg1 === null) { throw new \RuntimeException('You must pass the type and a url, or a JSON string.'); } if (is_string($arg1) && Preg::isMatch('{^\s*\{}', $arg1)) { // JSON config $repoConfig = JsonFile::parseJson($arg1); } else { if ($arg2 === null) { throw new \RuntimeException('You must pass the type and a url. Example: composer repo add foo vcs https://example.org'); } $repoConfig = ['type' => (string) $arg1, 'url' => (string) $arg2]; } // ordering options $before = $input->getOption('before'); $after = $input->getOption('after'); if ($before !== null && $after !== null) { throw new \RuntimeException('You can not combine --before and --after'); } if ($before !== null || $after !== null) { if ($repoConfig === false) { throw new \RuntimeException('Cannot use --before/--after with boolean repository values'); } $this->configSource->insertRepository((string) $name, $repoConfig, $before ?? $after, $after !== null ? 1 : 0); return 0; } $this->configSource->addRepository((string) $name, $repoConfig, (bool) $input->getOption('append')); return 0; case 'remove': case 'rm': case 'delete': if ($name === null) { throw new \RuntimeException('You must pass the repository name to remove.'); } $this->configSource->removeRepository((string) $name); if (in_array($name, ['packagist', 'packagist.org'], true)) { $this->configSource->addRepository('packagist.org', false); } return 0; case 'set-url': case 'seturl': if ($name === null || $arg1 === null) { throw new \RuntimeException('Usage: composer repo set-url <name> <new-url>'); } $this->configSource->setRepositoryUrl($name, $arg1); return 0; case 'get-url': case 'geturl': if ($name === null) { throw new \RuntimeException('Usage: composer repo get-url <name>'); } if (isset($repos[$name]) && is_array($repos[$name])) { $url = $repos[$name]['url'] ?? null; if (!is_string($url)) { throw new \InvalidArgumentException('The '.$name.' repository does not have a URL'); } $this->getIO()->write($url); return 0; } // try named-list: find entry with matching name if (is_array($repos)) { foreach ($repos as $val) { if (is_array($val) && isset($val['name']) && $val['name'] === $name) { $url = $val['url'] ?? null; if (!is_string($url)) { throw new \InvalidArgumentException('The '.$name.' repository does not have a URL'); } $this->getIO()->write($url); return 0; } } } throw new \InvalidArgumentException('There is no '.$name.' repository defined'); case 'disable': if ($name === null) { throw new \RuntimeException('Usage: composer repo disable packagist.org'); } if (in_array($name, ['packagist', 'packagist.org'], true)) { // special handling mirrors ConfigCommand behavior $this->configSource->addRepository('packagist.org', false, (bool) $input->getOption('append')); return 0; } throw new \RuntimeException('Only packagist.org can be enabled/disabled using this command. Use add/remove for other repositories.'); case 'enable': if ($name === null) { throw new \RuntimeException('Usage: composer repo enable packagist.org'); } if (in_array($name, ['packagist', 'packagist.org'], true)) { // Remove a false flag by setting packagist.org to true via removing the key // Here we re-add the default by removing overrides $this->configSource->removeRepository('packagist.org'); return 0; } throw new \RuntimeException('Only packagist.org can be enabled/disabled using this command.'); default: throw new \InvalidArgumentException('Unknown action "'.$action.'". Use list, add, remove, set-url, get-url, enable, disable'); } } /** * @param array<int|string, mixed> $repos */ private function listRepositories(array $repos): void { $io = $this->getIO(); $packagistPresent = false; foreach ($repos as $key => $repo) { if (isset($repo['type'], $repo['url']) && $repo['type'] === 'composer' && str_ends_with((string) parse_url($repo['url'], PHP_URL_HOST), 'packagist.org')) { $packagistPresent = true; break; } } if (!$packagistPresent) { $repos[] = ['packagist.org' => false]; } if ($repos === []) { $io->write('No repositories configured'); return; } foreach ($repos as $key => $repo) { if ($repo === false) { $io->write('['.$key.'] <info>disabled</info>'); continue; } if (is_array($repo)) { if (1 === \count($repo) && false === current($repo)) { $io->write('['.array_key_first($repo).'] <info>disabled</info>'); continue; } $name = $repo['name'] ?? $key; $type = $repo['type'] ?? 'unknown'; $url = $repo['url'] ?? JsonFile::encode($repo); $io->write('['.$name.'] <info>'.$type.'</info> '.$url); } } } private function suggestTypeForAdd(): \Closure { return static function (CompletionInput $input): array { if ($input->getArgument('action') === 'add') { return ['composer', 'vcs', 'artifact', 'path']; } return []; }; } private function suggestRepoNames(): \Closure { return function (CompletionInput $input): array { if (in_array($input->getArgument('action'), ['enable', 'disable'], true)) { return ['packagist.org']; } if (!in_array($input->getArgument('action'), ['remove', 'set-url', 'get-url'], true)) { return []; } $config = Factory::createConfig(); $configFile = new JsonFile($this->getComposerConfigFile($input, $config)); $data = $configFile->read(); $repos = []; foreach (($data['repositories'] ?? []) as $repo) { if (isset($repo['name'])) { $repos[] = $repo['name']; } } sort($repos); return $repos; }; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/CreateProjectCommand.php
src/Composer/Command/CreateProjectCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Config; use Composer\Factory; use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface; use Composer\Installer; use Composer\Installer\ProjectInstaller; use Composer\Installer\SuggestedPackagesReporter; use Composer\IO\IOInterface; use Composer\Package\BasePackage; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\Package\Version\VersionSelector; use Composer\Package\AliasPackage; use Composer\Pcre\Preg; use Composer\Plugin\PluginBlockedException; use Composer\Repository\RepositoryFactory; use Composer\Repository\CompositeRepository; use Composer\Repository\PlatformRepository; use Composer\Repository\InstalledArrayRepository; use Composer\Repository\RepositorySet; use Composer\Script\ScriptEvents; use Composer\Console\Input\InputArgument; use Seld\Signal\SignalHandler; use Symfony\Component\Console\Input\InputInterface; use Composer\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Finder\Finder; use Composer\Json\JsonFile; use Composer\Config\JsonConfigSource; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\ProcessExecutor; use Composer\Package\Version\VersionParser; use Composer\Advisory\Auditor; /** * Install a package as new project into new directory. * * @author Benjamin Eberlei <kontakt@beberlei.de> * @author Jordi Boggiano <j.boggiano@seld.be> * @author Tobias Munk <schmunk@usrbin.de> * @author Nils Adermann <naderman@naderman.de> */ class CreateProjectCommand extends BaseCommand { use CompletionTrait; /** * @var SuggestedPackagesReporter */ protected $suggestedPackagesReporter; protected function configure(): void { $this ->setName('create-project') ->setDescription('Creates new project from a package into given directory') ->setDefinition([ new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed', null, $this->suggestAvailablePackage()), new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'), new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'), new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'), new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'), new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist (default behavior).'), new InputOption('prefer-install', null, InputOption::VALUE_REQUIRED, 'Forces installation from package dist|source|auto (auto chooses source for dev versions, dist for the rest).', null, $this->suggestPreferInstall()), new InputOption('repository', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Add custom repositories to look the package up, either by URL or using JSON arrays'), new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'DEPRECATED: Use --repository instead.'), new InputOption('add-repository', null, InputOption::VALUE_NONE, 'Add the custom repository in the composer.json. If a lock file is present it will be deleted and an update will be run instead of install.'), new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'), new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'), new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'), new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'), new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'), new InputOption('no-secure-http', null, InputOption::VALUE_NONE, 'Disable the secure-http config option temporarily while installing the root package. Use at your own risk. Using this flag is a bad idea.'), new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deleting the vcs folder.'), new InputOption('remove-vcs', null, InputOption::VALUE_NONE, 'Whether to force deletion of the vcs folder without prompting.'), new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'), new InputOption('no-audit', null, InputOption::VALUE_NONE, 'Whether to skip auditing of the installed package dependencies (can also be set via the COMPOSER_NO_AUDIT=1 env var).'), new InputOption('audit-format', null, InputOption::VALUE_REQUIRED, 'Audit output format. Must be "table", "plain", "json" or "summary".', Auditor::FORMAT_SUMMARY, Auditor::FORMATS), new InputOption('no-security-blocking', null, InputOption::VALUE_NONE, 'Allows installing packages with security advisories or that are abandoned (can also be set via the COMPOSER_NO_SECURITY_BLOCKING=1 env var).'), new InputOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Ignore a specific platform requirement (php & ext- packages).'), new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore all platform requirements (php & ext- packages).'), new InputOption('ask', null, InputOption::VALUE_NONE, 'Whether to ask for project directory.'), ]) ->setHelp( <<<EOT The <info>create-project</info> command creates a new project from a given package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project. You can use this command to bootstrap new projects or setup a clean version-controlled installation for developers of your project. <info>php composer.phar create-project vendor/project target-directory [version]</info> You can also specify the version with the package name using = or : as separator. <info>php composer.phar create-project vendor/project:version target-directory</info> To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev). To setup a developer workable version you should create the project using the source controlled code by appending the <info>'--prefer-source'</info> flag. To install a package from another repository than the default one you can pass the <info>'--repository=https://myrepository.org'</info> flag. Read more at https://getcomposer.org/doc/03-cli.md#create-project EOT ) ; } protected function execute(InputInterface $input, OutputInterface $output): int { $config = Factory::createConfig(); $io = $this->getIO(); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($config, $input, true); if ($input->getOption('dev')) { $io->writeError('<warning>You are using the deprecated option "dev". Dev packages are installed by default now.</warning>'); } if ($input->getOption('no-custom-installers')) { $io->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>'); $input->setOption('no-plugins', true); } if ($input->isInteractive() && $input->getOption('ask')) { $package = $input->getArgument('package'); if (null === $package) { throw new \RuntimeException('Not enough arguments (missing: "package").'); } $parts = explode("/", strtolower($package), 2); $input->setArgument('directory', $io->ask('New project directory [<comment>'.array_pop($parts).'</comment>]: ')); } return $this->installProject( $io, $config, $input, $input->getArgument('package'), $input->getArgument('directory'), $input->getArgument('version'), $input->getOption('stability'), $preferSource, $preferDist, !$input->getOption('no-dev'), \count($input->getOption('repository')) > 0 ? $input->getOption('repository') : $input->getOption('repository-url'), $input->getOption('no-plugins'), $input->getOption('no-scripts'), $input->getOption('no-progress'), $input->getOption('no-install'), $this->getPlatformRequirementFilter($input), !$input->getOption('no-secure-http'), $input->getOption('add-repository') ); } /** * @param string|array<string>|null $repositories * * @throws \Exception */ public function installProject(IOInterface $io, Config $config, InputInterface $input, ?string $packageName = null, ?string $directory = null, ?string $packageVersion = null, ?string $stability = 'stable', bool $preferSource = false, bool $preferDist = false, bool $installDevPackages = false, $repositories = null, bool $disablePlugins = false, bool $disableScripts = false, bool $noProgress = false, bool $noInstall = false, ?PlatformRequirementFilterInterface $platformRequirementFilter = null, bool $secureHttp = true, bool $addRepository = false): int { $oldCwd = Platform::getCwd(); if ($repositories !== null && !is_array($repositories)) { $repositories = (array) $repositories; } $platformRequirementFilter = $platformRequirementFilter ?? PlatformRequirementFilterFactory::ignoreNothing(); // we need to manually load the configuration to pass the auth credentials to the io interface! $io->loadConfiguration($config); $this->suggestedPackagesReporter = new SuggestedPackagesReporter($io); if ($packageName !== null) { $installedFromVcs = $this->installRootPackage($input, $io, $config, $packageName, $platformRequirementFilter, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositories, $disablePlugins, $disableScripts, $noProgress, $secureHttp); } else { $installedFromVcs = false; } if ($repositories !== null && $addRepository && is_file('composer.lock')) { unlink('composer.lock'); } $composer = $this->createComposerInstance($input, $io, null, $disablePlugins, $disableScripts); // add the repository to the composer.json and use it for the install run later if ($repositories !== null && $addRepository) { foreach ($repositories as $index => $repo) { $repoConfig = RepositoryFactory::configFromString($io, $composer->getConfig(), $repo, true); $composerJsonRepositoriesConfig = $composer->getConfig()->getRepositories(); $name = RepositoryFactory::generateRepositoryName($index, $repoConfig, $composerJsonRepositoriesConfig); $configSource = new JsonConfigSource(new JsonFile('composer.json')); if ( (isset($repoConfig['packagist']) && $repoConfig === ['packagist' => false]) || (isset($repoConfig['packagist.org']) && $repoConfig === ['packagist.org' => false]) ) { $configSource->addRepository('packagist.org', false); } else { $configSource->addRepository($name, $repoConfig, false); } $composer = $this->createComposerInstance($input, $io, null, $disablePlugins); } } $process = $composer->getLoop()->getProcessExecutor(); $fs = new Filesystem($process); // dispatch event $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages); // use the new config including the newly installed project $config = $composer->getConfig(); [$preferSource, $preferDist] = $this->getPreferredInstallOptions($config, $input); // install dependencies of the created project if ($noInstall === false) { $composer->getInstallationManager()->setOutputProgress(!$noProgress); $installer = Installer::create($io, $composer); $installer->setPreferSource($preferSource) ->setPreferDist($preferDist) ->setDevMode($installDevPackages) ->setPlatformRequirementFilter($platformRequirementFilter) ->setSuggestedPackagesReporter($this->suggestedPackagesReporter) ->setOptimizeAutoloader($config->get('optimize-autoloader')) ->setClassMapAuthoritative($config->get('classmap-authoritative')) ->setApcuAutoloader($config->get('apcu-autoloader')) ->setAuditConfig($this->createAuditConfig($config, $input)); if (!$composer->getLocker()->isLocked()) { $installer->setUpdate(true); } if ($disablePlugins) { $installer->disablePlugins(); } try { $status = $installer->run(); if (0 !== $status) { return $status; } } catch (PluginBlockedException $e) { $io->writeError('<error>Hint: To allow running the config command recommended below before dependencies are installed, run create-project with --no-install.</error>'); $io->writeError('<error>You can then cd into '.getcwd().', configure allow-plugins, and finally run a composer install to complete the process.</error>'); throw $e; } } $hasVcs = $installedFromVcs; if ( !$input->getOption('keep-vcs') && $installedFromVcs && ( $input->getOption('remove-vcs') || !$io->isInteractive() || $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>y,n</comment>]? ') ) ) { $finder = new Finder(); $finder->depth(0)->directories()->in(Platform::getCwd())->ignoreVCS(false)->ignoreDotFiles(false); foreach (['.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg', '.fslckout', '_FOSSIL_'] as $vcsName) { $finder->name($vcsName); } try { $dirs = iterator_to_array($finder); unset($finder); foreach ($dirs as $dir) { if (!$fs->removeDirectory((string) $dir)) { throw new \RuntimeException('Could not remove '.$dir); } } } catch (\Exception $e) { $io->writeError('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>'); } $hasVcs = false; } // rewriting self.version dependencies with explicit version numbers if the package's vcs metadata is gone if (!$hasVcs) { $package = $composer->getPackage(); $configSource = new JsonConfigSource(new JsonFile('composer.json')); foreach (BasePackage::$supportedLinkTypes as $type => $meta) { foreach ($package->{'get'.$meta['method']}() as $link) { if ($link->getPrettyConstraint() === 'self.version') { $configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion()); } } } } // dispatch event $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages); chdir($oldCwd); return 0; } /** * @param array<string>|null $repositories * * @throws \Exception */ protected function installRootPackage(InputInterface $input, IOInterface $io, Config $config, string $packageName, PlatformRequirementFilterInterface $platformRequirementFilter, ?string $directory = null, ?string $packageVersion = null, ?string $stability = 'stable', bool $preferSource = false, bool $preferDist = false, bool $installDevPackages = false, ?array $repositories = null, bool $disablePlugins = false, bool $disableScripts = false, bool $noProgress = false, bool $secureHttp = true): bool { $parser = new VersionParser(); $requirements = $parser->parseNameVersionPairs([$packageName]); $name = strtolower($requirements[0]['name']); if (!$packageVersion && isset($requirements[0]['version'])) { $packageVersion = $requirements[0]['version']; } // if no directory was specified, use the 2nd part of the package name if (null === $directory) { $parts = explode("/", $name, 2); $directory = Platform::getCwd() . DIRECTORY_SEPARATOR . array_pop($parts); } $directory = rtrim($directory, '/\\'); $process = new ProcessExecutor($io); $fs = new Filesystem($process); if (!$fs->isAbsolutePath($directory)) { $directory = Platform::getCwd() . DIRECTORY_SEPARATOR . $directory; } if ('' === $directory) { throw new \UnexpectedValueException('Got an empty target directory, something went wrong'); } // set the base dir to ensure $config->all() below resolves the correct absolute paths to vendor-dir etc $config->setBaseDir($directory); if (!$secureHttp) { $config->merge(['config' => ['secure-http' => false]], Config::SOURCE_COMMAND); } $io->writeError('<info>Creating a "' . $packageName . '" project at "' . $fs->findShortestPath(Platform::getCwd(), $directory, true) . '"</info>'); if (file_exists($directory)) { if (!is_dir($directory)) { throw new \InvalidArgumentException('Cannot create project directory at "'.$directory.'", it exists as a file.'); } if (!$fs->isDirEmpty($directory)) { throw new \InvalidArgumentException('Project directory "'.$directory.'" is not empty.'); } } if (null === $stability) { if (null === $packageVersion) { $stability = 'stable'; } elseif (Preg::isMatchStrictGroups('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::STABILITIES)).')$}i', $packageVersion, $match)) { $stability = $match[1]; } else { $stability = VersionParser::parseStability($packageVersion); } } $stability = VersionParser::normalizeStability($stability); if (!isset(BasePackage::STABILITIES[$stability])) { throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::STABILITIES))); } $composer = $this->createComposerInstance($input, $io, $config->all(), $disablePlugins, $disableScripts); $config = $composer->getConfig(); // set the base dir here again on the new config instance, as otherwise in case the vendor dir is defined in an env var for example it would still override the value set above by $config->all() $config->setBaseDir($directory); $rm = $composer->getRepositoryManager(); $repositorySet = new RepositorySet($stability); if (null === $repositories) { $repositorySet->addRepository(new CompositeRepository(RepositoryFactory::defaultRepos($io, $config, $rm))); } else { foreach ($repositories as $repo) { $repoConfig = RepositoryFactory::configFromString($io, $config, $repo, true); if ( (isset($repoConfig['packagist']) && $repoConfig === ['packagist' => false]) || (isset($repoConfig['packagist.org']) && $repoConfig === ['packagist.org' => false]) ) { continue; } // disable symlinking for the root package by default as that most likely makes no sense if (($repoConfig['type'] ?? null) === 'path' && !isset($repoConfig['options']['symlink'])) { $repoConfig['options']['symlink'] = false; } $repositorySet->addRepository(RepositoryFactory::createRepo($io, $config, $repoConfig, $rm)); } } $platformOverrides = $config->get('platform'); $platformRepo = new PlatformRepository([], $platformOverrides); // find the latest version if there are multiple $versionSelector = new VersionSelector($repositorySet, $platformRepo); $package = $versionSelector->findBestCandidate($name, $packageVersion, $stability, $platformRequirementFilter, 0, $io); if (!$package) { $errorMessage = "Could not find package $name with " . ($packageVersion ? "version $packageVersion" : "stability $stability"); if (!($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter) && $versionSelector->findBestCandidate($name, $packageVersion, $stability, PlatformRequirementFilterFactory::ignoreAll())) { throw new \InvalidArgumentException($errorMessage .' in a version installable using your PHP version, PHP extensions and Composer version.'); } throw new \InvalidArgumentException($errorMessage .'.'); } // handler Ctrl+C aborts gracefully @mkdir($directory, 0777, true); if (false !== ($realDir = realpath($directory))) { $signalHandler = SignalHandler::create([SignalHandler::SIGINT, SignalHandler::SIGTERM, SignalHandler::SIGHUP], function (string $signal, SignalHandler $handler) use ($realDir) { $this->getIO()->writeError('Received '.$signal.', aborting', true, IOInterface::DEBUG); $fs = new Filesystem(); $fs->removeDirectory($realDir); $handler->exitWithLastSignal(); }); } // avoid displaying 9999999-dev as version if default-branch was selected if ($package instanceof AliasPackage && $package->getPrettyVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) { $package = $package->getAliasOf(); } $io->writeError('<info>Installing ' . $package->getName() . ' (' . $package->getFullPrettyVersion(false) . ')</info>'); if ($disablePlugins) { $io->writeError('<info>Plugins have been disabled.</info>'); } if ($package instanceof AliasPackage) { $package = $package->getAliasOf(); } $dm = $composer->getDownloadManager(); $dm->setPreferSource($preferSource) ->setPreferDist($preferDist); $projectInstaller = new ProjectInstaller($directory, $dm, $fs); $im = $composer->getInstallationManager(); $im->setOutputProgress(!$noProgress); $im->addInstaller($projectInstaller); $im->execute(new InstalledArrayRepository(), [new InstallOperation($package)]); $im->notifyInstalls($io); // collect suggestions $this->suggestedPackagesReporter->addSuggestionsFromPackage($package); $installedFromVcs = 'source' === $package->getInstallationSource(); $io->writeError('<info>Created project in ' . $directory . '</info>'); chdir($directory); // ensure that the env var being set does not interfere with create-project // as it is probably not meant to be used here, so we do not use it if a composer.json can be found // in the project if (file_exists($directory.'/composer.json') && Platform::getEnv('COMPOSER') !== false) { Platform::clearEnv('COMPOSER'); } Platform::putEnv('COMPOSER_ROOT_VERSION', $package->getPrettyVersion()); // once the root project is fully initialized, we do not need to wipe everything on user abort anymore even if it happens during deps install if (isset($signalHandler)) { $signalHandler->unregister(); } return $installedFromVcs; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Command/ValidateCommand.php
src/Composer/Command/ValidateCommand.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Command; use Composer\Factory; use Composer\IO\IOInterface; use Composer\Package\Loader\ValidatingArrayLoader; use Composer\Plugin\CommandEvent; use Composer\Plugin\PluginEvents; use Composer\Util\ConfigValidator; use Composer\Util\Filesystem; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * ValidateCommand * * @author Robert Schönthal <seroscho@googlemail.com> * @author Jordi Boggiano <j.boggiano@seld.be> */ class ValidateCommand extends BaseCommand { /** * configure */ protected function configure(): void { $this ->setName('validate') ->setDescription('Validates a composer.json and composer.lock') ->setDefinition([ new InputOption('no-check-all', null, InputOption::VALUE_NONE, 'Do not validate requires for overly strict/loose constraints'), new InputOption('check-lock', null, InputOption::VALUE_NONE, 'Check if lock file is up to date (even when config.lock is false)'), new InputOption('no-check-lock', null, InputOption::VALUE_NONE, 'Do not check if lock file is up to date'), new InputOption('no-check-publish', null, InputOption::VALUE_NONE, 'Do not check for publish errors'), new InputOption('no-check-version', null, InputOption::VALUE_NONE, 'Do not report a warning if the version field is present'), new InputOption('with-dependencies', 'A', InputOption::VALUE_NONE, 'Also validate the composer.json of all installed dependencies'), new InputOption('strict', null, InputOption::VALUE_NONE, 'Return a non-zero exit code for warnings as well as errors'), new InputArgument('file', InputArgument::OPTIONAL, 'path to composer.json file'), ]) ->setHelp( <<<EOT The validate command validates a given composer.json and composer.lock Exit codes in case of errors are: 1 validation warning(s), only when --strict is given 2 validation error(s) 3 file unreadable or missing Read more at https://getcomposer.org/doc/03-cli.md#validate EOT ); } protected function execute(InputInterface $input, OutputInterface $output): int { $file = $input->getArgument('file') ?? Factory::getComposerFile(); $io = $this->getIO(); if (!file_exists($file)) { $io->writeError('<error>' . $file . ' not found.</error>'); return 3; } if (!Filesystem::isReadable($file)) { $io->writeError('<error>' . $file . ' is not readable.</error>'); return 3; } $validator = new ConfigValidator($io); $checkAll = $input->getOption('no-check-all') ? 0 : ValidatingArrayLoader::CHECK_ALL; $checkPublish = !$input->getOption('no-check-publish'); $checkLock = !$input->getOption('no-check-lock'); $checkVersion = $input->getOption('no-check-version') ? 0 : ConfigValidator::CHECK_VERSION; $isStrict = $input->getOption('strict'); [$errors, $publishErrors, $warnings] = $validator->validate($file, $checkAll, $checkVersion); $lockErrors = []; $composer = $this->createComposerInstance($input, $io, $file); // config.lock = false ~= implicit --no-check-lock; --check-lock overrides $checkLock = ($checkLock && $composer->getConfig()->get('lock')) || $input->getOption('check-lock'); $locker = $composer->getLocker(); if ($locker->isLocked() && !$locker->isFresh()) { $lockErrors[] = '- The lock file is not up to date with the latest changes in composer.json, it is recommended that you run `composer update` or `composer update <package name>`.'; } if ($locker->isLocked()) { $lockErrors = array_merge($lockErrors, $locker->getMissingRequirementInfo($composer->getPackage(), true)); } $this->outputResult($io, $file, $errors, $warnings, $checkPublish, $publishErrors, $checkLock, $lockErrors, true); // $errors include publish and lock errors when exists $exitCode = count($errors) > 0 ? 2 : (($isStrict && count($warnings) > 0) ? 1 : 0); if ($input->getOption('with-dependencies')) { $localRepo = $composer->getRepositoryManager()->getLocalRepository(); foreach ($localRepo->getPackages() as $package) { $path = $composer->getInstallationManager()->getInstallPath($package); if (null === $path) { continue; } $file = $path . '/composer.json'; if (is_dir($path) && file_exists($file)) { [$errors, $publishErrors, $warnings] = $validator->validate($file, $checkAll, $checkVersion); $this->outputResult($io, $package->getPrettyName(), $errors, $warnings, $checkPublish, $publishErrors); // $errors include publish errors when exists $depCode = count($errors) > 0 ? 2 : (($isStrict && count($warnings) > 0) ? 1 : 0); $exitCode = max($depCode, $exitCode); } } } $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'validate', $input, $output); $eventCode = $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent); return max($eventCode, $exitCode); } /** * @param string[] $errors * @param string[] $warnings * @param string[] $publishErrors * @param string[] $lockErrors */ private function outputResult(IOInterface $io, string $name, array &$errors, array &$warnings, bool $checkPublish = false, array $publishErrors = [], bool $checkLock = false, array $lockErrors = [], bool $printSchemaUrl = false): void { $doPrintSchemaUrl = false; if (\count($errors) > 0) { $io->writeError('<error>' . $name . ' is invalid, the following errors/warnings were found:</error>'); } elseif (\count($publishErrors) > 0 && $checkPublish) { $io->writeError('<info>' . $name . ' is valid for simple usage with Composer but has</info>'); $io->writeError('<info>strict errors that make it unable to be published as a package</info>'); $doPrintSchemaUrl = $printSchemaUrl; } elseif (\count($warnings) > 0) { $io->writeError('<info>' . $name . ' is valid, but with a few warnings</info>'); $doPrintSchemaUrl = $printSchemaUrl; } elseif (\count($lockErrors) > 0) { $io->write('<info>' . $name . ' is valid but your composer.lock has some '.($checkLock ? 'errors' : 'warnings').'</info>'); } else { $io->write('<info>' . $name . ' is valid</info>'); } if ($doPrintSchemaUrl) { $io->writeError('<warning>See https://getcomposer.org/doc/04-schema.md for details on the schema</warning>'); } if (\count($errors) > 0) { $errors = array_map(static function ($err): string { return '- ' . $err; }, $errors); array_unshift($errors, '# General errors'); } if (\count($warnings) > 0) { $warnings = array_map(static function ($err): string { return '- ' . $err; }, $warnings); array_unshift($warnings, '# General warnings'); } // Avoid setting the exit code to 1 in case --strict and --no-check-publish/--no-check-lock are combined $extraWarnings = []; // If checking publish errors, display them as errors, otherwise just show them as warnings if (\count($publishErrors) > 0 && $checkPublish) { $publishErrors = array_map(static function ($err): string { return '- ' . $err; }, $publishErrors); array_unshift($publishErrors, '# Publish errors'); $errors = array_merge($errors, $publishErrors); } // If checking lock errors, display them as errors, otherwise just show them as warnings if (\count($lockErrors) > 0) { if ($checkLock) { array_unshift($lockErrors, '# Lock file errors'); $errors = array_merge($errors, $lockErrors); } else { array_unshift($lockErrors, '# Lock file warnings'); $extraWarnings = array_merge($extraWarnings, $lockErrors); } } $messages = [ 'error' => $errors, 'warning' => array_merge($warnings, $extraWarnings), ]; foreach ($messages as $style => $msgs) { foreach ($msgs as $msg) { if (strpos($msg, '#') === 0) { $io->writeError('<' . $style . '>' . $msg . '</' . $style . '>'); } else { $io->writeError($msg); } } } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/console-application.php
tests/console-application.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ require __DIR__ . '/../vendor/autoload.php'; Composer\Util\Platform::putEnv('COMPOSER_TESTS_ARE_RUNNING', '1'); return new Composer\Console\Application();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/bootstrap.php
tests/bootstrap.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Composer\Util\Platform; error_reporting(E_ALL); if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) { date_default_timezone_set(@date_default_timezone_get()); } require __DIR__.'/../src/bootstrap.php'; // ensure we always use the latest InstalledVersions.php even if an older composer ran the install, but we need // to have it included from vendor dir and not from src/ otherwise some gated check in the code will not work copy(__DIR__.'/../src/Composer/InstalledVersions.php', __DIR__.'/../vendor/composer/InstalledVersions.php'); require __DIR__.'/../vendor/composer/InstalledVersions.php'; Platform::putEnv('COMPOSER_TESTS_ARE_RUNNING', '1'); // ensure Windows color support detection does not attempt to use colors // as this is dependent on env vars and not actual stream capabilities, see // https://github.com/composer/composer/issues/11598 Platform::putEnv('NO_COLOR', '1'); // symfony/phpunit-bridge sets some default env vars which we do not need polluting the test env Platform::clearEnv('COMPOSER'); Platform::clearEnv('COMPOSER_VENDOR_DIR'); Platform::clearEnv('COMPOSER_BIN_DIR');
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/ApplicationTest.php
tests/Composer/Test/ApplicationTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Console\Application; use Composer\Util\Platform; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\BufferedOutput; class ApplicationTest extends TestCase { protected function tearDown(): void { parent::tearDown(); Platform::clearEnv('COMPOSER_DISABLE_XDEBUG_WARN'); } protected function setUp(): void { parent::setUp(); Platform::putEnv('COMPOSER_DISABLE_XDEBUG_WARN', '1'); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testDevWarning(): void { $application = new Application; if (!defined('COMPOSER_DEV_WARNING_TIME')) { define('COMPOSER_DEV_WARNING_TIME', time() - 1); } $output = new BufferedOutput(); $application->doRun(new ArrayInput(['command' => 'about']), $output); $expectedOutput = sprintf('<warning>Warning: This development build of Composer is over 60 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']).PHP_EOL; self::assertStringContainsString($expectedOutput, $output->fetch()); } /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testDevWarningSuppressedForSelfUpdate(): void { if (Platform::isWindows()) { $this->markTestSkipped('Does not run on windows'); } $application = new Application; // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($application, 'addCommand') ? $application->addCommand(new \Composer\Command\SelfUpdateCommand) : $application->add(new \Composer\Command\SelfUpdateCommand); if (!defined('COMPOSER_DEV_WARNING_TIME')) { define('COMPOSER_DEV_WARNING_TIME', time() - 1); } $output = new BufferedOutput(); $application->doRun(new ArrayInput(['command' => 'self-update']), $output); self::assertSame( 'This instance of Composer does not have the self-update command.'.PHP_EOL. 'This could be due to a number of reasons, such as Composer being installed as a system package on your OS, or Composer being installed as a package in the current project.'.PHP_EOL, $output->fetch() ); } /** * @runInSeparateProcess * @see https://github.com/composer/composer/issues/12107 */ public function testProcessIsolationWorksMultipleTimes(): void { $application = new Application; // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($application, 'addCommand') ? $application->addCommand(new \Composer\Command\AboutCommand) : $application->add(new \Composer\Command\AboutCommand); self::assertSame(0, $application->doRun(new ArrayInput(['command' => 'about']), new BufferedOutput())); self::assertSame(0, $application->doRun(new ArrayInput(['command' => 'about']), new BufferedOutput())); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/CacheTest.php
tests/Composer/Test/CacheTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Cache; use Composer\Util\Filesystem; class CacheTest extends TestCase { /** @var array<\SplFileInfo> */ private $files; /** @var string */ private $root; /** @var \Symfony\Component\Finder\Finder&\PHPUnit\Framework\MockObject\MockObject */ private $finder; /** @var Filesystem&\PHPUnit\Framework\MockObject\MockObject */ private $filesystem; /** @var Cache&\PHPUnit\Framework\MockObject\MockObject */ private $cache; public function setUp(): void { $this->root = self::getUniqueTmpDirectory(); $this->files = []; $zeros = str_repeat('0', 1000); for ($i = 0; $i < 4; $i++) { file_put_contents("{$this->root}/cached.file{$i}.zip", $zeros); $this->files[] = new \SplFileInfo("{$this->root}/cached.file{$i}.zip"); } $this->finder = $this->getMockBuilder('Symfony\Component\Finder\Finder')->disableOriginalConstructor()->getMock(); $this->filesystem = $this->getMockBuilder('Composer\Util\Filesystem')->getMock(); $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $this->cache = $this->getMockBuilder('Composer\Cache') ->onlyMethods(['getFinder']) ->setConstructorArgs([$io, $this->root]) ->getMock(); $this->cache ->expects($this->any()) ->method('getFinder') ->will($this->returnValue($this->finder)); } protected function tearDown(): void { parent::tearDown(); if (is_dir($this->root)) { $fs = new Filesystem; $fs->removeDirectory($this->root); } } public function testRemoveOutdatedFiles(): void { $outdated = array_slice($this->files, 1); $this->finder ->expects($this->once()) ->method('getIterator') ->will($this->returnValue(new \ArrayIterator($outdated))); $this->finder ->expects($this->once()) ->method('date') ->will($this->returnValue($this->finder)); $this->cache->gc(600, 1024 * 1024 * 1024); for ($i = 1; $i < 4; $i++) { self::assertFileDoesNotExist("{$this->root}/cached.file{$i}.zip"); } self::assertFileExists("{$this->root}/cached.file0.zip"); } public function testRemoveFilesWhenCacheIsTooLarge(): void { $emptyFinder = $this->getMockBuilder('Symfony\Component\Finder\Finder')->disableOriginalConstructor()->getMock(); $emptyFinder ->expects($this->once()) ->method('getIterator') ->will($this->returnValue(new \EmptyIterator())); $this->finder ->expects($this->once()) ->method('date') ->will($this->returnValue($emptyFinder)); $this->finder ->expects($this->once()) ->method('getIterator') ->will($this->returnValue(new \ArrayIterator($this->files))); $this->finder ->expects($this->once()) ->method('sortByAccessedTime') ->will($this->returnValue($this->finder)); $this->cache->gc(600, 1500); for ($i = 0; $i < 3; $i++) { self::assertFileDoesNotExist("{$this->root}/cached.file{$i}.zip"); } self::assertFileExists("{$this->root}/cached.file3.zip"); } public function testClearCache(): void { $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $cache = new Cache($io, $this->root, 'a-z0-9.', $this->filesystem); self::assertTrue($cache->clear()); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/FactoryTest.php
tests/Composer/Test/FactoryTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Factory; use Composer\Util\Platform; class FactoryTest extends TestCase { public function tearDown(): void { parent::tearDown(); Platform::clearEnv('COMPOSER'); } /** * @group TLS */ public function testDefaultValuesAreAsExpected(): void { $ioMock = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $ioMock->expects($this->once()) ->method("writeError") ->with($this->equalTo('<warning>You are running Composer with SSL/TLS protection disabled.</warning>')); $config = $this ->getMockBuilder('Composer\Config') ->getMock(); $config->method('get') ->with($this->equalTo('disable-tls')) ->will($this->returnValue(true)); Factory::createHttpDownloader($ioMock, $config); } public function testGetComposerJsonPath(): void { self::assertSame('./composer.json', Factory::getComposerFile()); } public function testGetComposerJsonPathFailsIfDir(): void { Platform::putEnv('COMPOSER', __DIR__); self::expectException('RuntimeException'); self::expectExceptionMessage('The COMPOSER environment variable is set to '.__DIR__.' which is a directory, this variable should point to a composer.json or be left unset.'); Factory::getComposerFile(); } public function testGetComposerJsonPathFromEnv(): void { Platform::putEnv('COMPOSER', ' foo.json '); self::assertSame('foo.json', Factory::getComposerFile()); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/TestCase.php
tests/Composer/Test/TestCase.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Config; use Composer\Console\Application; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\Package\Locker; use Composer\Pcre\Preg; use Composer\Repository\InstalledFilesystemRepository; use Composer\Semver\VersionParser; use Composer\Package\PackageInterface; use Composer\Semver\Constraint\Constraint; use Composer\Test\Mock\FactoryMock; use Composer\Test\Mock\HttpDownloaderMock; use Composer\Test\Mock\IOMock; use Composer\Test\Mock\ProcessExecutorMock; use Composer\Util\Filesystem; use Composer\Util\Platform; use Composer\Util\Silencer; use Symfony\Component\Console\Tester\ApplicationTester; use Symfony\Component\Process\ExecutableFinder; use Composer\Package\Loader\ArrayLoader; use Composer\Package\BasePackage; use Composer\Package\RootPackage; use Composer\Package\AliasPackage; use Composer\Package\RootAliasPackage; use Composer\Package\CompletePackage; use Composer\Package\CompleteAliasPackage; use Composer\Package\Package; use Symfony\Component\Process\Process; abstract class TestCase extends \PHPUnit\Framework\TestCase { /** * @var ?VersionParser */ private static $parser; /** * @var array<string, bool> */ private static $executableCache = []; /** * @var list<HttpDownloaderMock> */ private $httpDownloaderMocks = []; /** * @var list<ProcessExecutorMock> */ private $processExecutorMocks = []; /** * @var list<IOMock> */ private $ioMocks = []; /** * @var list<string> */ private $tempComposerDirs = []; /** @var string|null */ private $prevCwd = null; protected function tearDown(): void { parent::tearDown(); foreach ($this->httpDownloaderMocks as $mock) { $mock->assertComplete(); } foreach ($this->processExecutorMocks as $mock) { $mock->assertComplete(); } foreach ($this->ioMocks as $mock) { $mock->assertComplete(); } if (null !== $this->prevCwd) { chdir($this->prevCwd); $this->prevCwd = null; Platform::clearEnv('COMPOSER_HOME'); Platform::clearEnv('COMPOSER_DISABLE_XDEBUG_WARN'); } $fs = new Filesystem(); foreach ($this->tempComposerDirs as $dir) { $fs->removeDirectory($dir); } } public static function getUniqueTmpDirectory(): string { $attempts = 5; $root = sys_get_temp_dir(); do { $unique = $root . DIRECTORY_SEPARATOR . 'composer-test-' . bin2hex(random_bytes(10)); if (!file_exists($unique) && Silencer::call('mkdir', $unique, 0777)) { return realpath($unique); } } while (--$attempts); throw new \RuntimeException('Failed to create a unique temporary directory.'); } /** * Creates a composer.json / auth.json inside a temp dir and chdir() into it * * The directory will be cleaned up on tearDown automatically. * * @see createInstalledJson * @see createComposerLock * @see getApplicationTester * @param mixed[] $composerJson * @param mixed[] $authJson * @param mixed[] $composerLock * @return string the newly created temp dir */ public function initTempComposer(array $composerJson = [], array $authJson = [], array $composerLock = [], bool $setupRepositories = true): string { $dir = self::getUniqueTmpDirectory(); $this->tempComposerDirs[] = $dir; $this->prevCwd = Platform::getCwd(); Platform::putEnv('COMPOSER_HOME', $dir.'/composer-home'); Platform::putEnv('COMPOSER_DISABLE_XDEBUG_WARN', '1'); if ($composerJson === []) { $composerJson = new \stdClass; } if ($authJson === []) { $authJson = new \stdClass; } if ($setupRepositories && is_array($composerJson) && isset($composerJson['repositories']) && !isset($composerJson['repositories']['packagist.org']) && !in_array(['packagist.org' => false], $composerJson['repositories'], true)) { if (array_is_list($composerJson['repositories'])) { $composerJson['repositories'][] = ['packagist.org' => false]; } else { $composerJson['repositories']['packagist.org'] = false; } } chdir($dir); file_put_contents($dir.'/composer.json', JsonFile::encode($composerJson, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); file_put_contents($dir.'/auth.json', JsonFile::encode($authJson, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); if ($composerLock !== []) { file_put_contents($dir.'/composer.lock', JsonFile::encode($composerLock, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); } return $dir; } /** * Creates a vendor/composer/installed.json in CWD with the given packages * * @param PackageInterface[] $packages * @param PackageInterface[] $devPackages */ protected function createInstalledJson(array $packages = [], array $devPackages = [], bool $devMode = true): void { mkdir('vendor/composer', 0777, true); $repo = new InstalledFilesystemRepository(new JsonFile('vendor/composer/installed.json')); $repo->setDevPackageNames(array_map(static function (PackageInterface $pkg) { return $pkg->getPrettyName(); }, $devPackages)); foreach ($packages as $pkg) { $repo->addPackage($pkg); mkdir('vendor/'.$pkg->getName(), 0777, true); } foreach ($devPackages as $pkg) { $repo->addPackage($pkg); mkdir('vendor/'.$pkg->getName(), 0777, true); } $factory = new FactoryMock(); $repo->write($devMode, $factory->createInstallationManager()); } /** * Creates a composer.lock in CWD with the given packages * * @param PackageInterface[] $packages * @param PackageInterface[] $devPackages */ protected function createComposerLock(array $packages = [], array $devPackages = []): void { $factory = new FactoryMock(); $locker = new Locker($this->getIOMock(), new JsonFile('./composer.lock'), $factory->createInstallationManager(), (string) file_get_contents('./composer.json')); $locker->setLockData($packages, $devPackages, [], [], [], 'dev', [], false, false, []); } public function getApplicationTester(): ApplicationTester { $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); if (method_exists($application, 'setCatchErrors')) { $application->setCatchErrors(false); } return new ApplicationTester($application); } /** * Trims the entire string but also the trailing spaces off of every line */ protected function trimLines(string $str): string { return trim(Preg::replace('{^(.*?) *$}m', '$1', $str)); } protected static function getVersionParser(): VersionParser { if (!self::$parser) { self::$parser = new VersionParser(); } return self::$parser; } /** * @param Constraint::STR_OP_* $operator */ protected static function getVersionConstraint($operator, string $version): Constraint { $constraint = new Constraint( $operator, self::getVersionParser()->normalize($version) ); $constraint->setPrettyString($operator.' '.$version); return $constraint; } /** * @template PackageClass of CompletePackage|CompleteAliasPackage * * @param string $class FQCN to be instantiated * * @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage * * @phpstan-param class-string<PackageClass> $class * @phpstan-return PackageClass */ protected static function getPackage(string $name = 'dummy/pkg', string $version = '1.0.0', string $class = 'Composer\Package\CompletePackage'): BasePackage { $normVersion = self::getVersionParser()->normalize($version); return new $class($name, $normVersion, $version); } protected static function getRootPackage(string $name = '__root__', string $version = '1.0.0'): RootPackage { $normVersion = self::getVersionParser()->normalize($version); return new RootPackage($name, $normVersion, $version); } /** * @return ($package is RootPackage ? RootAliasPackage : ($package is CompletePackage ? CompleteAliasPackage : AliasPackage)) */ protected static function getAliasPackage(Package $package, string $version): AliasPackage { $normVersion = self::getVersionParser()->normalize($version); if ($package instanceof RootPackage) { return new RootAliasPackage($package, $normVersion, $version); } if ($package instanceof CompletePackage) { return new CompleteAliasPackage($package, $normVersion, $version); } return new AliasPackage($package, $normVersion, $version); } /** * @param array<string, array<string, string>> $config */ protected static function configureLinks(PackageInterface $package, array $config): void { $arrayLoader = new ArrayLoader(); foreach (BasePackage::$supportedLinkTypes as $type => $opts) { if (isset($config[$type])) { $method = 'set'.ucfirst($opts['method']); $package->{$method}( $arrayLoader->parseLinks( $package->getName(), $package->getPrettyVersion(), $opts['method'], $config[$type] ) ); } } } /** * @param array<mixed> $configOptions */ protected function getConfig(array $configOptions = [], bool $useEnvironment = false): Config { $config = new Config($useEnvironment); $config->merge(['config' => $configOptions], 'test'); return $config; } protected static function ensureDirectoryExistsAndClear(string $directory): void { $fs = new Filesystem(); if (is_dir($directory)) { $fs->removeDirectory($directory); } mkdir($directory, 0777, true); } /** * Check whether or not the given name is an available executable. * * @param string $executableName The name of the binary to test. * * @throws \PHPUnit\Framework\SkippedTestError */ protected function skipIfNotExecutable(string $executableName): void { if (!isset(self::$executableCache[$executableName])) { $finder = new ExecutableFinder(); self::$executableCache[$executableName] = (bool) $finder->find($executableName); } if (false === self::$executableCache[$executableName]) { $this->markTestSkipped($executableName . ' is not found or not executable.'); } } /** * Transforms an escaped non-Windows command to match Windows escaping. * * @return string The transformed command */ protected static function getCmd(string $cmd): string { if (Platform::isWindows()) { $cmd = Preg::replaceCallback("/('[^']*')/", static function ($m) { // Double-quotes are used only when needed $char = (strpbrk($m[1], " \t^&|<>()") !== false || $m[1] === "''") ? '"' : ''; return str_replace("'", $char, $m[1]); }, $cmd); } return $cmd; } protected function getHttpDownloaderMock(?IOInterface $io = null, ?Config $config = null): HttpDownloaderMock { $this->httpDownloaderMocks[] = $mock = new HttpDownloaderMock($io, $config); return $mock; } protected function getProcessExecutorMock(): ProcessExecutorMock { $this->processExecutorMocks[] = $mock = new ProcessExecutorMock($this->getMockBuilder(Process::class)); return $mock; } /** * @param IOInterface::* $verbosity */ protected function getIOMock(int $verbosity = IOInterface::DEBUG): IOMock { $this->ioMocks[] = $mock = new IOMock($verbosity); return $mock; } protected function createTempFile(?string $dir = null): string { $dir = $dir ?? sys_get_temp_dir(); $name = tempnam($dir, 'c'); if ($name === false) { throw new \UnexpectedValueException('tempnam failed to create a temporary file in '.$dir); } return $name; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/InstalledVersionsTest.php
tests/Composer/Test/InstalledVersionsTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Autoload\ClassLoader; use Composer\InstalledVersions; use Composer\Semver\VersionParser; class InstalledVersionsTest extends TestCase { /** @var array<ClassLoader> */ private static $previousRegisteredLoaders; /** * @var string */ private $root; public static function setUpBeforeClass(): void { // disable multiple-ClassLoader-based checks of InstalledVersions by making it seem like no // class loaders are registered $prop = new \ReflectionProperty('Composer\Autoload\ClassLoader', 'registeredLoaders'); (\PHP_VERSION_ID < 80100) and $prop->setAccessible(true); self::$previousRegisteredLoaders = $prop->getValue(); $prop->setValue(null, []); } public static function tearDownAfterClass(): void { $prop = new \ReflectionProperty('Composer\Autoload\ClassLoader', 'registeredLoaders'); (\PHP_VERSION_ID < 80100) and $prop->setAccessible(true); $prop->setValue(null, self::$previousRegisteredLoaders); InstalledVersions::reload(null); // @phpstan-ignore argument.type } public function setUp(): void { $this->root = self::getUniqueTmpDirectory(); $dir = $this->root; InstalledVersions::reload(require __DIR__.'/Repository/Fixtures/installed_relative.php'); } public function testGetInstalledPackages(): void { $names = [ '__root__', 'a/provider', 'a/provider2', 'b/replacer', 'c/c', 'foo/impl', 'foo/impl2', 'foo/replaced', 'meta/package', ]; self::assertSame($names, InstalledVersions::getInstalledPackages()); } /** * @dataProvider isInstalledProvider */ public function testIsInstalled(bool $expected, string $name, bool $includeDevRequirements = true): void { self::assertSame($expected, InstalledVersions::isInstalled($name, $includeDevRequirements)); } public static function isInstalledProvider(): array { return [ [true, 'foo/impl'], [true, 'foo/replaced'], [true, 'c/c'], [false, 'c/c', false], [true, '__root__'], [true, 'b/replacer'], [false, 'not/there'], [true, 'meta/package'], ]; } /** * @dataProvider satisfiesProvider */ public function testSatisfies(bool $expected, string $name, string $constraint): void { self::assertSame($expected, InstalledVersions::satisfies(new VersionParser, $name, $constraint)); } public static function satisfiesProvider(): array { return [ [true, 'foo/impl', '1.5'], [true, 'foo/impl', '1.2'], [true, 'foo/impl', '^1.0'], [true, 'foo/impl', '^3 || ^2'], [false, 'foo/impl', '^3'], [true, 'foo/replaced', '3.5'], [true, 'foo/replaced', '^3.2'], [false, 'foo/replaced', '4.0'], [true, 'c/c', '3.0.0'], [true, 'c/c', '^3'], [false, 'c/c', '^3.1'], [true, '__root__', 'dev-master'], [true, '__root__', '^1.10'], [false, '__root__', '^2'], [true, 'b/replacer', '^2.1'], [false, 'b/replacer', '^2.3'], [true, 'a/provider2', '^1.2'], [true, 'a/provider2', '^1.4'], [false, 'a/provider2', '^1.5'], ]; } /** * @dataProvider getVersionRangesProvider */ public function testGetVersionRanges(string $expected, string $name): void { self::assertSame($expected, InstalledVersions::getVersionRanges($name)); } public static function getVersionRangesProvider(): array { return [ ['dev-master || 1.10.x-dev', '__root__'], ['^1.1 || 1.2 || 1.4 || 2.0', 'foo/impl'], ['2.2 || 2.0', 'foo/impl2'], ['^3.0', 'foo/replaced'], ['1.1', 'a/provider'], ['1.2 || 1.4', 'a/provider2'], ['2.2', 'b/replacer'], ['3.0', 'c/c'], ]; } /** * @dataProvider getVersionProvider */ public function testGetVersion(?string $expected, string $name): void { self::assertSame($expected, InstalledVersions::getVersion($name)); } public static function getVersionProvider(): array { return [ ['dev-master', '__root__'], [null, 'foo/impl'], [null, 'foo/impl2'], [null, 'foo/replaced'], ['1.1.0.0', 'a/provider'], ['1.2.0.0', 'a/provider2'], ['2.2.0.0', 'b/replacer'], ['3.0.0.0', 'c/c'], ]; } /** * @dataProvider getPrettyVersionProvider */ public function testGetPrettyVersion(?string $expected, string $name): void { self::assertSame($expected, InstalledVersions::getPrettyVersion($name)); } public static function getPrettyVersionProvider(): array { return [ ['dev-master', '__root__'], [null, 'foo/impl'], [null, 'foo/impl2'], [null, 'foo/replaced'], ['1.1', 'a/provider'], ['1.2', 'a/provider2'], ['2.2', 'b/replacer'], ['3.0', 'c/c'], ]; } public function testGetVersionOutOfBounds(): void { self::expectException('OutOfBoundsException'); InstalledVersions::getVersion('not/installed'); } public function testGetRootPackage(): void { self::assertSame([ 'name' => '__root__', 'pretty_version' => 'dev-master', 'version' => 'dev-master', 'reference' => 'sourceref-by-default', 'type' => 'library', 'install_path' => $this->root . '/./', 'aliases' => [ '1.10.x-dev', ], 'dev' => true, ], InstalledVersions::getRootPackage()); } /** * @group legacy */ public function testGetRawData(): void { $dir = $this->root; self::assertSame(require __DIR__.'/Repository/Fixtures/installed_relative.php', InstalledVersions::getRawData()); } /** * @dataProvider getReferenceProvider */ public function testGetReference(?string $expected, string $name): void { self::assertSame($expected, InstalledVersions::getReference($name)); } public static function getReferenceProvider(): array { return [ ['sourceref-by-default', '__root__'], [null, 'foo/impl'], [null, 'foo/impl2'], [null, 'foo/replaced'], ['distref-as-no-source', 'a/provider'], ['distref-as-installed-from-dist', 'a/provider2'], [null, 'b/replacer'], [null, 'c/c'], ]; } public function testGetInstalledPackagesByType(): void { $names = [ '__root__', 'a/provider', 'a/provider2', 'b/replacer', 'c/c', ]; self::assertSame($names, InstalledVersions::getInstalledPackagesByType('library')); } public function testGetInstallPath(): void { self::assertSame(realpath($this->root), realpath(InstalledVersions::getInstallPath('__root__'))); self::assertSame('/foo/bar/vendor/c/c', InstalledVersions::getInstallPath('c/c')); self::assertNull(InstalledVersions::getInstallPath('foo/impl')); } public function testWithClassLoaderLoaded(): void { // disable multiple-ClassLoader-based checks of InstalledVersions by making it seem like no // class loaders are registered $prop = new \ReflectionProperty(ClassLoader::class, 'registeredLoaders'); (\PHP_VERSION_ID < 80100) and $prop->setAccessible(true); $prop->setValue(null, array_slice(self::$previousRegisteredLoaders, 0, 1, true)); $prop2 = new \ReflectionProperty(InstalledVersions::class, 'installedIsLocalDir'); (\PHP_VERSION_ID < 80100) and $prop2->setAccessible(true); $prop2->setValue(null, true); self::assertFalse(InstalledVersions::isInstalled('foo/bar')); InstalledVersions::reload([ 'root' => InstalledVersions::getRootPackage(), 'versions' => [ 'foo/bar' => [ 'version' => '1.0.0', 'dev_requirement' => false, ], ], ]); self::assertTrue(InstalledVersions::isInstalled('foo/bar')); $prop->setValue(null, []); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/ComposerTest.php
tests/Composer/Test/ComposerTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Composer; class ComposerTest extends TestCase { public function testSetGetPackage(): void { $composer = new Composer(); $package = $this->getMockBuilder('Composer\Package\RootPackageInterface')->getMock(); $composer->setPackage($package); self::assertSame($package, $composer->getPackage()); } public function testSetGetLocker(): void { $composer = new Composer(); $locker = $this->getMockBuilder('Composer\Package\Locker')->disableOriginalConstructor()->getMock(); $composer->setLocker($locker); self::assertSame($locker, $composer->getLocker()); } public function testSetGetRepositoryManager(): void { $composer = new Composer(); $manager = $this->getMockBuilder('Composer\Repository\RepositoryManager')->disableOriginalConstructor()->getMock(); $composer->setRepositoryManager($manager); self::assertSame($manager, $composer->getRepositoryManager()); } public function testSetGetDownloadManager(): void { $composer = new Composer(); $io = $this->getMockBuilder('Composer\IO\IOInterface')->getMock(); $manager = $this->getMockBuilder('Composer\Downloader\DownloadManager')->setConstructorArgs([$io])->getMock(); $composer->setDownloadManager($manager); self::assertSame($manager, $composer->getDownloadManager()); } public function testSetGetInstallationManager(): void { $composer = new Composer(); $manager = $this->getMockBuilder('Composer\Installer\InstallationManager')->disableOriginalConstructor()->getMock(); $composer->setInstallationManager($manager); self::assertSame($manager, $composer->getInstallationManager()); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DefaultConfigTest.php
tests/Composer/Test/DefaultConfigTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Config; class DefaultConfigTest extends TestCase { /** * @group TLS */ public function testDefaultValuesAreAsExpected(): void { $config = new Config; self::assertFalse($config->get('disable-tls')); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/InstallerTest.php
tests/Composer/Test/InstallerTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Advisory\AuditConfig; use Composer\DependencyResolver\Request; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Installer; use Composer\Pcre\Preg; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Composer\IO\BufferIO; use Composer\Json\JsonFile; use Composer\Package\Dumper\ArrayDumper; use Composer\Util\Filesystem; use Composer\Repository\ArrayRepository; use Composer\Repository\RepositoryManager; use Composer\Repository\RepositoryInterface; use Composer\Repository\InstalledArrayRepository; use Composer\Package\RootPackageInterface; use Composer\Package\BasePackage; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Package\Locker; use Composer\Test\Mock\FactoryMock; use Composer\Test\Mock\InstalledFilesystemRepositoryMock; use Composer\Test\Mock\InstallationManagerMock; use Composer\Util\Platform; use Symfony\Component\Console\Input\StringInput; use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Formatter\OutputFormatter; class InstallerTest extends TestCase { /** @var string */ private $prevCwd; /** @var ?string */ protected $tempComposerHome; public function setUp(): void { $this->prevCwd = Platform::getCwd(); chdir(__DIR__); } protected function tearDown(): void { parent::tearDown(); Platform::clearEnv('COMPOSER_POOL_OPTIMIZER'); Platform::clearEnv('COMPOSER_FUND'); chdir($this->prevCwd); if (isset($this->tempComposerHome) && is_dir($this->tempComposerHome)) { $fs = new Filesystem; $fs->removeDirectory($this->tempComposerHome); } } /** * @dataProvider provideInstaller * @param RootPackageInterface&BasePackage $rootPackage * @param RepositoryInterface[] $repositories * @param mixed[] $options */ public function testInstaller(RootPackageInterface $rootPackage, array $repositories, array $options): void { $io = new BufferIO('', OutputInterface::VERBOSITY_NORMAL, new OutputFormatter(false)); $downloadManager = $this->getMockBuilder('Composer\Downloader\DownloadManager') ->setConstructorArgs([$io]) ->getMock(); $config = $this->getMockBuilder('Composer\Config')->getMock(); $config->expects($this->any()) ->method('get') ->will($this->returnCallback(static function ($key) { switch ($key) { case 'vendor-dir': return 'foo'; case 'lock': case 'notify-on-install': return true; case 'platform': case 'audit': return []; } throw new \UnexpectedValueException('Unknown key '.$key); })); $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(); $httpDownloader = $this->getMockBuilder('Composer\Util\HttpDownloader')->disableOriginalConstructor()->getMock(); $repositoryManager = new RepositoryManager($io, $config, $httpDownloader, $eventDispatcher); $repositoryManager->setLocalRepository(new InstalledArrayRepository()); foreach ($repositories as $repository) { $repositoryManager->addRepository($repository); } $installationManager = new InstallationManagerMock(); // emulate a writable lock file /** @var ?string $lockData */ $lockData = null; $lockJsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock(); $lockJsonMock->expects($this->any()) ->method('read') ->will($this->returnCallback(static function () use (&$lockData) { return json_decode($lockData, true); })); $lockJsonMock->expects($this->any()) ->method('exists') ->will($this->returnCallback(static function () use (&$lockData): bool { return $lockData !== null; })); $lockJsonMock->expects($this->any()) ->method('write') ->will($this->returnCallback(static function ($value, $options = 0) use (&$lockData): void { $lockData = json_encode($value, JSON_PRETTY_PRINT); })); $tempLockData = null; $locker = new Locker($io, $lockJsonMock, $installationManager, '{}'); $autoloadGenerator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator')->disableOriginalConstructor()->getMock(); $installer = new Installer($io, $config, clone $rootPackage, $downloadManager, $repositoryManager, $locker, $installationManager, $eventDispatcher, $autoloadGenerator); $installer->setAuditConfig(AuditConfig::fromConfig($config, false)); $result = $installer->run(); $output = str_replace("\r", '', $io->getOutput()); self::assertEquals(0, $result, $output); $expectedInstalled = $options['install'] ?? []; $expectedUpdated = $options['update'] ?? []; $expectedUninstalled = $options['uninstall'] ?? []; $installed = $installationManager->getInstalledPackages(); self::assertEquals($this->makePackagesComparable($expectedInstalled), $this->makePackagesComparable($installed)); $updated = $installationManager->getUpdatedPackages(); self::assertSame($expectedUpdated, $updated); $uninstalled = $installationManager->getUninstalledPackages(); self::assertSame($expectedUninstalled, $uninstalled); } /** * @param PackageInterface[] $packages * @return mixed[] */ protected function makePackagesComparable(array $packages): array { $dumper = new ArrayDumper(); $comparable = []; foreach ($packages as $package) { $comparable[] = $dumper->dump($package); } return $comparable; } public static function provideInstaller(): array { $cases = []; // when A requires B and B requires A, and A is a non-published root package // the install of B should succeed $a = self::getPackage('A', '1.0.0', 'Composer\Package\RootPackage'); $a->setRequires([ 'b' => new Link('A', 'B', $v = self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE, $v->getPrettyString()), ]); $b = self::getPackage('B', '1.0.0'); $b->setRequires([ 'a' => new Link('B', 'A', $v = self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE, $v->getPrettyString()), ]); $cases[] = [ $a, [new ArrayRepository([$b])], [ 'install' => [$b], ], ]; // #480: when A requires B and B requires A, and A is a published root package // only B should be installed, as A is the root $a = self::getPackage('A', '1.0.0', 'Composer\Package\RootPackage'); $a->setRequires([ 'b' => new Link('A', 'B', $v = self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE, $v->getPrettyString()), ]); $b = self::getPackage('B', '1.0.0'); $b->setRequires([ 'a' => new Link('B', 'A', $v = self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE, $v->getPrettyString()), ]); $cases[] = [ $a, [new ArrayRepository([$a, $b])], [ 'install' => [$b], ], ]; // TODO why are there not more cases with uninstall/update? return $cases; } /** * @group slow * @dataProvider provideSlowIntegrationTests * @param mixed[] $composerConfig * @param ?array<mixed> $lock * @param ?array<mixed> $installed * @param mixed[]|false $expectLock * @param ?array<mixed> $expectInstalled * @param int|class-string<\Throwable> $expectResult */ public function testSlowIntegration(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); $this->doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult); } /** * @dataProvider provideIntegrationTests * @param mixed[] $composerConfig * @param ?array<mixed> $lock * @param ?array<mixed> $installed * @param mixed[]|false $expectLock * @param ?array<mixed> $expectInstalled * @param int|class-string<\Throwable> $expectResult */ public function testIntegrationWithPoolOptimizer(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '1'); $this->doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutputOptimized ?: $expectOutput, $expect, $expectResult); } /** * @dataProvider provideIntegrationTests * @param mixed[] $composerConfig * @param ?array<mixed> $lock * @param ?array<mixed> $installed * @param mixed[]|false $expectLock * @param ?array<mixed> $expectInstalled * @param int|class-string<\Throwable> $expectResult */ public function testIntegrationWithRawPool(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, ?string $expectOutputOptimized, string $expect, $expectResult): void { Platform::putEnv('COMPOSER_POOL_OPTIMIZER', '0'); $this->doTestIntegration($file, $message, $condition, $composerConfig, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expect, $expectResult); } /** * @param mixed[] $composerConfig * @param ?array<mixed> $lock * @param ?array<mixed> $installed * @param mixed[]|false $expectLock * @param ?array<mixed> $expectInstalled * @param int|class-string<\Throwable> $expectResult */ private function doTestIntegration(string $file, string $message, ?string $condition, array $composerConfig, ?array $lock, ?array $installed, string $run, $expectLock, ?array $expectInstalled, ?string $expectOutput, string $expect, $expectResult): void { if ($condition) { eval('$res = '.$condition.';'); if (!$res) { // @phpstan-ignore variable.undefined $this->markTestSkipped($condition); } } $io = new BufferIO('', OutputInterface::VERBOSITY_NORMAL, new OutputFormatter(false)); // Prepare for exceptions if (!is_int($expectResult)) { $normalizedOutput = rtrim(str_replace("\n", PHP_EOL, $expect)); self::expectException($expectResult); self::expectExceptionMessage($normalizedOutput); } // Create Composer mock object according to configuration $composer = FactoryMock::create($io, $composerConfig); $this->tempComposerHome = $composer->getConfig()->get('home'); $jsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock(); $jsonMock->expects($this->any()) ->method('read') ->will($this->returnValue($installed)); $jsonMock->expects($this->any()) ->method('exists') ->will($this->returnValue(true)); $repositoryManager = $composer->getRepositoryManager(); $repositoryManager->setLocalRepository(new InstalledFilesystemRepositoryMock($jsonMock)); // emulate a writable lock file $lockData = $lock ? json_encode($lock, JSON_PRETTY_PRINT) : null; $lockJsonMock = $this->getMockBuilder('Composer\Json\JsonFile')->disableOriginalConstructor()->getMock(); $lockJsonMock->expects($this->any()) ->method('read') ->will($this->returnCallback(static function () use (&$lockData) { return json_decode($lockData, true); })); $lockJsonMock->expects($this->any()) ->method('exists') ->will($this->returnCallback(static function () use (&$lockData): bool { return $lockData !== null; })); $lockJsonMock->expects($this->any()) ->method('write') ->will($this->returnCallback(static function ($value, $options = 0) use (&$lockData): void { $lockData = json_encode($value, JSON_PRETTY_PRINT); })); if ($expectLock) { $actualLock = []; $lockJsonMock->expects($this->atLeastOnce()) ->method('write') ->will($this->returnCallback(static 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 assertion $actualLock = $hash; })); } elseif ($expectLock === false) { $lockJsonMock->expects($this->never()) ->method('write'); } $contents = json_encode($composerConfig); $locker = new Locker($io, $lockJsonMock, $composer->getInstallationManager(), $contents); $composer->setLocker($locker); $eventDispatcher = $this->getMockBuilder('Composer\EventDispatcher\EventDispatcher')->disableOriginalConstructor()->getMock(); $autoloadGenerator = $this->getMockBuilder('Composer\Autoload\AutoloadGenerator') ->setConstructorArgs([$eventDispatcher]) ->getMock(); $composer->setAutoloadGenerator($autoloadGenerator); $composer->setEventDispatcher($eventDispatcher); $installer = Installer::create($io, $composer); $application = new Application; $install = new Command('install'); $install->addOption('ignore-platform-reqs', null, InputOption::VALUE_NONE); $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(static function (InputInterface $input, OutputInterface $output) use ($installer, $composer): int { $ignorePlatformReqs = true === $input->getOption('ignore-platform-reqs') ?: ($input->getOption('ignore-platform-req') ?: false); $installer ->setDevMode(false === $input->getOption('no-dev')) ->setDryRun($input->getOption('dry-run')) ->setPlatformRequirementFilter(PlatformRequirementFilterFactory::fromBoolOrList($ignorePlatformReqs)) ->setAuditConfig(AuditConfig::fromConfig($composer->getConfig(), false)); return $installer->run(); }); // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($application, 'addCommand') ? $application->addCommand($install) : $application->add($install); $update = new Command('update'); $update->addOption('ignore-platform-reqs', null, InputOption::VALUE_NONE); $update->addOption('ignore-platform-req', null, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY); $update->addOption('no-dev', null, InputOption::VALUE_NONE); $update->addOption('no-install', null, InputOption::VALUE_NONE); $update->addOption('dry-run', null, InputOption::VALUE_NONE); $update->addOption('lock', null, InputOption::VALUE_NONE); $update->addOption('with-all-dependencies', null, InputOption::VALUE_NONE); $update->addOption('with-dependencies', null, InputOption::VALUE_NONE); $update->addOption('minimal-changes', null, InputOption::VALUE_NONE); $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(static function (InputInterface $input, OutputInterface $output) use ($installer, $composer): int { $packages = $input->getArgument('packages'); $filteredPackages = array_filter($packages, static function ($package): bool { return !in_array($package, ['lock', 'nothing', 'mirrors'], true); }); $updateMirrors = true === $input->getOption('lock') || count($filteredPackages) !== count($packages); $packages = $filteredPackages; $updateAllowTransitiveDependencies = Request::UPDATE_ONLY_LISTED; if (true === $input->getOption('with-all-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS; } elseif (true === $input->getOption('with-dependencies')) { $updateAllowTransitiveDependencies = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE; } $ignorePlatformReqs = true === $input->getOption('ignore-platform-reqs') ?: ($input->getOption('ignore-platform-req') ?: false); $installer ->setDevMode(false === $input->getOption('no-dev')) ->setUpdate(true) ->setInstall(false === $input->getOption('no-install')) ->setDryRun($input->getOption('dry-run')) ->setUpdateMirrors($updateMirrors) ->setUpdateAllowList($packages) ->setUpdateAllowTransitiveDependencies($updateAllowTransitiveDependencies) ->setPreferStable($input->getOption('prefer-stable')) ->setPreferLowest($input->getOption('prefer-lowest')) ->setPlatformRequirementFilter(PlatformRequirementFilterFactory::fromBoolOrList($ignorePlatformReqs)) ->setAuditConfig(AuditConfig::fromConfig($composer->getConfig(), false)) ->setMinimalUpdate($input->getOption('minimal-changes')); return $installer->run(); }); // Compatibility layer for symfony/console <7.4 // @phpstan-ignore method.notFound, function.alreadyNarrowedType method_exists($application, 'addCommand') ? $application->addCommand($update) : $application->add($update); if (!Preg::isMatch('{^(install|update)\b}', $run)) { throw new \UnexpectedValueException('The run command only supports install and update'); } $application->setAutoExit(false); $appOutput = fopen('php://memory', 'w+'); if (false === $appOutput) { self::fail('Failed to open memory stream'); } $input = new StringInput($run.' -vvv'); $input->setInteractive(false); $result = $application->run($input, new StreamOutput($appOutput)); fseek($appOutput, 0); // Shouldn't check output and results if an exception was expected by this point if (!is_int($expectResult)) { return; } $output = str_replace("\r", '', $io->getOutput()); self::assertEquals($expectResult, $result, $output . stream_get_contents($appOutput)); if ($expectLock && isset($actualLock)) { unset($actualLock['hash'], $actualLock['content-hash'], $actualLock['_readme'], $actualLock['plugin-api-version']); foreach (['stability-flags', 'platform', 'platform-dev'] as $key) { if ($expectLock[$key] === []) { $expectLock[$key] = new \stdClass; } } self::assertEquals($expectLock, $actualLock); } if ($expectInstalled !== null) { $actualInstalled = []; $dumper = new ArrayDumper(); foreach ($repositoryManager->getLocalRepository()->getCanonicalPackages() as $package) { $package = $dumper->dump($package); unset($package['version_normalized']); $actualInstalled[] = $package; } usort($actualInstalled, static function ($a, $b): int { return strcmp($a['name'], $b['name']); }); self::assertSame($expectInstalled, $actualInstalled); } /** @var InstallationManagerMock $installationManager */ $installationManager = $composer->getInstallationManager(); self::assertSame(rtrim($expect), implode("\n", $installationManager->getTrace())); if ($expectOutput) { $output = Preg::replace('{^ - .*?\.ini$}m', '__inilist__', $output); $output = Preg::replace('{(__inilist__\r?\n)+}', "__inilist__\n", $output); self::assertStringMatchesFormat(rtrim($expectOutput), rtrim($output)); } } public static function provideSlowIntegrationTests(): array { return self::loadIntegrationTests('installer-slow/'); } public static function provideIntegrationTests(): array { return self::loadIntegrationTests('installer/'); } /** * @return mixed[] */ public static function loadIntegrationTests(string $path): array { $fixturesDir = (string) realpath(__DIR__.'/Fixtures/'.$path); $tests = []; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $file = (string) $file; if (!Preg::isMatch('/\.test$/', $file)) { continue; } try { $testData = self::readTestFile($file, $fixturesDir); // skip 64bit related tests on 32bit if (str_contains($testData['EXPECT-OUTPUT'] ?? '', 'php-64bit') && PHP_INT_SIZE === 4) { continue; } $installed = []; $installedDev = []; $lock = []; $expectLock = []; $expectInstalled = null; $expectResult = 0; $message = $testData['TEST']; $condition = !empty($testData['CONDITION']) ? $testData['CONDITION'] : null; $composer = JsonFile::parseJson($testData['COMPOSER']); if (isset($composer['repositories'])) { foreach ($composer['repositories'] as &$repo) { if ($repo['type'] !== 'composer') { continue; } // Change paths like file://foobar to file:///path/to/fixtures if (Preg::isMatch('{^file://[^/]}', $repo['url'])) { $repo['url'] = 'file://' . strtr($fixturesDir, '\\', '/') . '/' . substr($repo['url'], 7); } unset($repo); } } if (!empty($testData['LOCK'])) { $lock = JsonFile::parseJson($testData['LOCK']); if (!isset($lock['hash'])) { $lock['hash'] = hash('md5', JsonFile::encode($composer, 0)); } } if (!empty($testData['INSTALLED'])) { $installed = JsonFile::parseJson($testData['INSTALLED']); } $run = $testData['RUN']; if (!empty($testData['EXPECT-LOCK'])) { if ($testData['EXPECT-LOCK'] === 'false') { $expectLock = false; } else { $expectLock = JsonFile::parseJson($testData['EXPECT-LOCK']); } } if (!empty($testData['EXPECT-INSTALLED'])) { $expectInstalled = JsonFile::parseJson($testData['EXPECT-INSTALLED']); } $expectOutput = $testData['EXPECT-OUTPUT'] ?? null; $expectOutputOptimized = $testData['EXPECT-OUTPUT-OPTIMIZED'] ?? null; $expect = $testData['EXPECT']; if (!empty($testData['EXPECT-EXCEPTION'])) { $expectResult = $testData['EXPECT-EXCEPTION']; if (!empty($testData['EXPECT-EXIT-CODE'])) { throw new \LogicException('EXPECT-EXCEPTION and EXPECT-EXIT-CODE are mutually exclusive'); } } elseif (!empty($testData['EXPECT-EXIT-CODE'])) { $expectResult = (int) $testData['EXPECT-EXIT-CODE']; } else { $expectResult = 0; } } catch (\Exception $e) { die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file))); } $tests[basename($file)] = [str_replace($fixturesDir.'/', '', $file), $message, $condition, $composer, $lock, $installed, $run, $expectLock, $expectInstalled, $expectOutput, $expectOutputOptimized, $expect, $expectResult]; } return $tests; } /** * @return mixed[] */ protected static function readTestFile(string $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); $sectionInfo = [ 'TEST' => true, 'CONDITION' => false, 'COMPOSER' => true, 'LOCK' => false, 'INSTALLED' => false, 'RUN' => true, 'EXPECT-LOCK' => false, 'EXPECT-INSTALLED' => false, 'EXPECT-OUTPUT' => false, 'EXPECT-OUTPUT-OPTIMIZED' => false, 'EXPECT-EXIT-CODE' => false, 'EXPECT-EXCEPTION' => false, 'EXPECT' => true, ]; $section = null; $data = []; foreach ($tokens as $i => $token) { if (null === $section && empty($token)) { continue; // skip leading blank } if (null === $section) { if (!isset($sectionInfo[$token])) { throw new \RuntimeException(sprintf( 'The test file "%s" must not contain a section named "%s".', str_replace($fixturesDir.'/', '', $file), $token )); } $section = $token; continue; } $sectionData = $token; $data[$section] = $sectionData; $section = $sectionData = null; } foreach ($sectionInfo as $section => $required) { if ($required && !isset($data[$section])) { throw new \RuntimeException(sprintf( 'The test file "%s" must have a section named "%s".', str_replace($fixturesDir.'/', '', $file), $section )); } } return $data; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/AllFunctionalTest.php
tests/Composer/Test/AllFunctionalTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Pcre\Preg; use Composer\Util\Filesystem; use Composer\Util\Platform; use Symfony\Component\Finder\Finder; use Symfony\Component\Process\Process; /** * @group slow */ class AllFunctionalTest extends TestCase { /** @var string|false */ protected $oldcwd; /** @var ?string */ protected $testDir; /** * @var string */ private static $pharPath; public function setUp(): void { $this->oldcwd = Platform::getCwd(); chdir(__DIR__.'/Fixtures/functional'); } protected function tearDown(): void { parent::tearDown(); if ($this->oldcwd) { chdir($this->oldcwd); } if ($this->testDir) { $fs = new Filesystem; $fs->removeDirectory($this->testDir); $this->testDir = null; } } public static function setUpBeforeClass(): void { self::$pharPath = self::getUniqueTmpDirectory() . '/composer.phar'; } public static function tearDownAfterClass(): void { $fs = new Filesystem; $fs->removeDirectory(dirname(self::$pharPath)); } public function testBuildPhar(): void { if (defined('HHVM_VERSION')) { $this->markTestSkipped('Building the phar does not work on HHVM.'); } $target = dirname(self::$pharPath); $fs = new Filesystem(); chdir($target); $it = new \RecursiveDirectoryIterator(__DIR__.'/../../../', \RecursiveDirectoryIterator::SKIP_DOTS); $ri = new \RecursiveIteratorIterator($it, \RecursiveIteratorIterator::SELF_FIRST); foreach ($ri as $file) { $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathname(); if ($file->isDir()) { $fs->ensureDirectoryExists($targetPath); } else { copy($file->getPathname(), $targetPath); } } $proc = new Process([PHP_BINARY, '-dphar.readonly=0', './bin/compile'], $target); $proc->setTimeout(300); $exitcode = $proc->run(); if ($exitcode !== 0 || trim($proc->getOutput()) !== '') { $this->fail($proc->getOutput()); } self::assertFileExists(self::$pharPath); copy(self::$pharPath, __DIR__.'/../../composer-test.phar'); chmod(__DIR__.'/../../composer-test.phar', 0777); } /** * @dataProvider getTestFiles * @depends testBuildPhar */ public function testIntegration(string $testFile): void { $testData = $this->parseTestFile($testFile); $this->testDir = self::getUniqueTmpDirectory(); // if a dir is present with the name of the .test file (without .test), we // copy all its contents in the $testDir to be used to run the test with $testFileSetupDir = substr($testFile, 0, -5); if (is_dir($testFileSetupDir)) { $fs = new Filesystem(); $fs->copy($testFileSetupDir, $this->testDir); } $env = [ 'COMPOSER_HOME' => $this->testDir.'home', 'COMPOSER_CACHE_DIR' => $this->testDir.'cache', ]; $proc = Process::fromShellCommandline(escapeshellcmd(PHP_BINARY).' '.escapeshellarg(self::$pharPath).' --no-ansi '.$testData['RUN'], $this->testDir, $env, null, 300); $output = ''; $exitCode = $proc->run(static function ($type, $buffer) use (&$output): void { $output .= $buffer; }); if (isset($testData['EXPECT'])) { $output = trim($this->cleanOutput($output)); $expected = $testData['EXPECT']; $line = 1; for ($i = 0, $j = 0; $i < strlen($expected);) { if ($expected[$i] === "\n") { $line++; } if ($expected[$i] === '%') { if (!Preg::isMatchStrictGroups('{%(.+?)%}', substr($expected, $i), $match)) { throw new \LogicException('Failed to match %...% in '.substr($expected, $i)); } $regex = $match[1]; if (Preg::isMatch('{'.$regex.'}', substr($output, $j), $match)) { $i += strlen($regex) + 2; $j += strlen((string) $match[0]); continue; } else { $this->fail( 'Failed to match pattern '.$regex.' at line '.$line.' / abs offset '.$i.': ' .substr($output, $j, min(((int) strpos($output, "\n", $j)) - $j, 100)).PHP_EOL.PHP_EOL. 'Output:'.PHP_EOL.$output ); } } if ($expected[$i] !== $output[$j]) { $this->fail( 'Output does not match expectation at line '.$line.' / abs offset '.$i.': '.PHP_EOL .'-'.substr($expected, $i, min(((int) strpos($expected, "\n", $i)) - $i, 100)).PHP_EOL .'+'.substr($output, $j, min(((int) strpos($output, "\n", $j)) - $j, 100)).PHP_EOL.PHP_EOL .'Output:'.PHP_EOL.$output ); } $i++; $j++; } } if (isset($testData['EXPECT-REGEX'])) { self::assertMatchesRegularExpression($testData['EXPECT-REGEX'], $this->cleanOutput($output)); } if (isset($testData['EXPECT-REGEXES'])) { $cleanOutput = $this->cleanOutput($output); foreach (explode("\n", $testData['EXPECT-REGEXES']) as $regex) { self::assertMatchesRegularExpression($regex, $cleanOutput, 'Output: '.$output); } } if (isset($testData['EXPECT-EXIT-CODE'])) { self::assertSame($testData['EXPECT-EXIT-CODE'], $exitCode); } } /** * @return array<string, array<string>> */ public static function getTestFiles(): array { $tests = []; foreach (Finder::create()->in(__DIR__.'/Fixtures/functional')->name('*.test')->files() as $file) { $tests[$file->getFilename()] = [(string) $file]; } return $tests; } /** * @return array{RUN: string, EXPECT?: string, EXPECT-EXIT-CODE?: int, EXPECT-REGEX?: string, EXPECT-REGEXES?: string, TEST?: string} */ private function parseTestFile(string $file): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', (string) file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); $data = []; $section = null; foreach ($tokens as $token) { if ('' === $token && null === $section) { continue; } // Handle section headers. if (null === $section) { $section = $token; continue; } $sectionData = $token; // Allow sections to validate, or modify their section data. switch ($section) { case 'EXPECT-EXIT-CODE': $sectionData = (int) $sectionData; break; case 'RUN': case 'EXPECT': case 'EXPECT-REGEX': case 'EXPECT-REGEXES': $sectionData = trim($sectionData); break; case 'TEST': break; default: throw new \RuntimeException(sprintf( 'Unknown section "%s". Allowed sections: "RUN", "EXPECT", "EXPECT-EXIT-CODE", "EXPECT-REGEX", "EXPECT-REGEXES". ' .'Section headers must be written as "--HEADER_NAME--".', $section )); } $data[$section] = $sectionData; $section = $sectionData = null; } // validate data if (!isset($data['RUN'])) { throw new \RuntimeException('The test file must have a section named "RUN".'); } if (!isset($data['EXPECT']) && !isset($data['EXPECT-REGEX']) && !isset($data['EXPECT-REGEXES'])) { throw new \RuntimeException('The test file must have a section named "EXPECT", "EXPECT-REGEX", or "EXPECT-REGEXES".'); } return $data; // @phpstan-ignore return.type } private function cleanOutput(string $output): string { $processed = ''; for ($i = 0; $i < strlen($output); $i++) { if ($output[$i] === "\x08") { $processed = substr($processed, 0, -1); } elseif ($output[$i] !== "\r") { $processed .= $output[$i]; } } return $processed; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/ConfigTest.php
tests/Composer/Test/ConfigTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Advisory\Auditor; use Composer\Config; use Composer\Util\Platform; class ConfigTest extends TestCase { /** * @dataProvider dataAddPackagistRepository * @param mixed[] $expected * @param mixed[] $localConfig * @param ?array<mixed> $systemConfig */ public function testAddPackagistRepository(array $expected, array $localConfig, ?array $systemConfig = null): void { $config = new Config(false); if ($systemConfig) { $config->merge(['repositories' => $systemConfig]); } $config->merge(['repositories' => $localConfig]); self::assertEquals($expected, $config->getRepositories()); } public static function dataAddPackagistRepository(): array { $data = []; $data['local config inherits system defaults'] = [ [ 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], [], ]; $data['local config can disable system config by name'] = [ [], [ ['packagist.org' => false], ], ]; $data['local config can disable system config by name bc'] = [ [], [ ['packagist' => false], ], ]; $data['local config adds above defaults'] = [ [ 0 => ['type' => 'vcs', 'url' => 'git://github.com/composer/composer.git'], 1 => ['type' => 'pear', 'url' => 'http://pear.composer.org'], 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], [ ['type' => 'vcs', 'url' => 'git://github.com/composer/composer.git'], ['type' => 'pear', 'url' => 'http://pear.composer.org'], ], ]; $data['system config adds above core defaults'] = [ [ 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], [], [ 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], ], ]; $data['local config can disable repos by name and re-add them anonymously to bring them above system config'] = [ [ 1 => ['type' => 'composer', 'url' => 'http://packagist.org'], 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], ], [ ['packagist.org' => false], ['type' => 'composer', 'url' => 'http://packagist.org'], ], [ 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], ], ]; $data['local config can override by name to bring a repo above system config'] = [ [ 'packagist.org' => ['type' => 'composer', 'url' => 'http://packagistnew.org'], 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], ], [ 'packagist.org' => ['type' => 'composer', 'url' => 'http://packagistnew.org'], ], [ 'example.com' => ['type' => 'composer', 'url' => 'http://example.com'], ], ]; $data['local config redefining packagist.org by URL override it if no named keys are used'] = [ [ ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], [ ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], ]; $data['local config redefining packagist.org by URL override it also with named keys'] = [ [ 'example' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], [ 'example' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], ], ]; $data['incorrect local config does not cause ErrorException'] = [ [ 'packagist.org' => ['type' => 'composer', 'url' => 'https://repo.packagist.org'], 'type' => 'vcs', 'url' => 'http://example.com', ], [ 'type' => 'vcs', 'url' => 'http://example.com', ], ]; return $data; } public function testPreferredInstallAsString(): void { $config = new Config(false); $config->merge(['config' => ['preferred-install' => 'source']]); $config->merge(['config' => ['preferred-install' => 'dist']]); self::assertEquals('dist', $config->get('preferred-install')); } public function testMergePreferredInstall(): void { $config = new Config(false); $config->merge(['config' => ['preferred-install' => 'dist']]); $config->merge(['config' => ['preferred-install' => ['foo/*' => 'source']]]); // This assertion needs to make sure full wildcard preferences are placed last // Handled by composer because we convert string preferences for BC, all other // care for ordering and collision prevention is up to the user self::assertEquals(['foo/*' => 'source', '*' => 'dist'], $config->get('preferred-install')); } public function testMergeGithubOauth(): void { $config = new Config(false); $config->merge(['config' => ['github-oauth' => ['foo' => 'bar']]]); $config->merge(['config' => ['github-oauth' => ['bar' => 'baz']]]); self::assertEquals(['foo' => 'bar', 'bar' => 'baz'], $config->get('github-oauth')); } public function testVarReplacement(): void { $config = new Config(false); $config->merge(['config' => ['a' => 'b', 'c' => '{$a}']]); $config->merge(['config' => ['bin-dir' => '$HOME', 'cache-dir' => '~/foo/']]); $home = rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '\\/'); self::assertEquals('b', $config->get('c')); self::assertEquals($home, $config->get('bin-dir')); self::assertEquals($home.'/foo', $config->get('cache-dir')); } public function testRealpathReplacement(): void { $config = new Config(false, '/foo/bar'); $config->merge(['config' => [ 'bin-dir' => '$HOME/foo', 'cache-dir' => '/baz/', 'vendor-dir' => 'vendor', ]]); $home = rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '\\/'); self::assertEquals('/foo/bar/vendor', $config->get('vendor-dir')); self::assertEquals($home.'/foo', $config->get('bin-dir')); self::assertEquals('/baz', $config->get('cache-dir')); } public function testStreamWrapperDirs(): void { $config = new Config(false, '/foo/bar'); $config->merge(['config' => [ 'cache-dir' => 's3://baz/', ]]); self::assertEquals('s3://baz', $config->get('cache-dir')); } public function testFetchingRelativePaths(): void { $config = new Config(false, '/foo/bar'); $config->merge(['config' => [ 'bin-dir' => '{$vendor-dir}/foo', 'vendor-dir' => 'vendor', ]]); self::assertEquals('/foo/bar/vendor', $config->get('vendor-dir')); self::assertEquals('/foo/bar/vendor/foo', $config->get('bin-dir')); self::assertEquals('vendor', $config->get('vendor-dir', Config::RELATIVE_PATHS)); self::assertEquals('vendor/foo', $config->get('bin-dir', Config::RELATIVE_PATHS)); } public function testOverrideGithubProtocols(): void { $config = new Config(false); $config->merge(['config' => ['github-protocols' => ['https', 'ssh']]]); $config->merge(['config' => ['github-protocols' => ['https']]]); self::assertEquals(['https'], $config->get('github-protocols')); } public function testGitDisabledByDefaultInGithubProtocols(): void { $config = new Config(false); $config->merge(['config' => ['github-protocols' => ['https', 'git']]]); self::assertEquals(['https'], $config->get('github-protocols')); $config->merge(['config' => ['secure-http' => false]]); self::assertEquals(['https', 'git'], $config->get('github-protocols')); } /** * @dataProvider allowedUrlProvider * @doesNotPerformAssertions */ public function testAllowedUrlsPass(string $url): void { $config = new Config(false); $config->prohibitUrlByConfig($url); } /** * @dataProvider prohibitedUrlProvider */ public function testProhibitedUrlsThrowException(string $url): void { self::expectException('Composer\Downloader\TransportException'); self::expectExceptionMessage('Your configuration does not allow connections to ' . $url); $config = new Config(false); $config->prohibitUrlByConfig($url); } /** * @return string[][] List of test URLs that should pass strict security */ public static function allowedUrlProvider(): array { $urls = [ 'https://packagist.org', 'git@github.com:composer/composer.git', 'hg://user:pass@my.satis/satis', '\\myserver\myplace.git', 'file://myserver.localhost/mygit.git', 'file://example.org/mygit.git', 'git:Department/Repo.git', 'ssh://[user@]host.xz[:port]/path/to/repo.git/', ]; return array_combine($urls, array_map(static function ($e): array { return [$e]; }, $urls)); } /** * @return string[][] List of test URLs that should not pass strict security */ public static function prohibitedUrlProvider(): array { $urls = [ 'http://packagist.org', 'http://10.1.0.1/satis', 'http://127.0.0.1/satis', 'http://💛@example.org', 'svn://localhost/trunk', 'svn://will.not.resolve/trunk', 'svn://192.168.0.1/trunk', 'svn://1.2.3.4/trunk', 'git://5.6.7.8/git.git', ]; return array_combine($urls, array_map(static function ($e): array { return [$e]; }, $urls)); } public function testProhibitedUrlsWarningVerifyPeer(): void { $io = $this->getIOMock(); $io->expects([['text' => '<warning>Warning: Accessing example.org with verify_peer and verify_peer_name disabled.</warning>']], true); $config = new Config(false); $config->prohibitUrlByConfig('https://example.org', $io, [ 'ssl' => [ 'verify_peer' => false, 'verify_peer_name' => false, ], ]); } /** * @group TLS */ public function testDisableTlsCanBeOverridden(): void { $config = new Config; $config->merge( ['config' => ['disable-tls' => 'false']] ); self::assertFalse($config->get('disable-tls')); $config->merge( ['config' => ['disable-tls' => 'true']] ); self::assertTrue($config->get('disable-tls')); } public function testProcessTimeout(): void { Platform::putEnv('COMPOSER_PROCESS_TIMEOUT', '0'); $config = new Config(true); $result = $config->get('process-timeout'); Platform::clearEnv('COMPOSER_PROCESS_TIMEOUT'); self::assertEquals(0, $result); } public function testHtaccessProtect(): void { Platform::putEnv('COMPOSER_HTACCESS_PROTECT', '0'); $config = new Config(true); $result = $config->get('htaccess-protect'); Platform::clearEnv('COMPOSER_HTACCESS_PROTECT'); self::assertEquals(0, $result); } public function testGetSourceOfValue(): void { Platform::clearEnv('COMPOSER_PROCESS_TIMEOUT'); $config = new Config; self::assertSame(Config::SOURCE_DEFAULT, $config->getSourceOfValue('process-timeout')); $config->merge( ['config' => ['process-timeout' => 1]], 'phpunit-test' ); self::assertSame('phpunit-test', $config->getSourceOfValue('process-timeout')); } public function testGetSourceOfValueEnvVariables(): void { Platform::putEnv('COMPOSER_HTACCESS_PROTECT', '0'); $config = new Config; $result = $config->getSourceOfValue('htaccess-protect'); Platform::clearEnv('COMPOSER_HTACCESS_PROTECT'); self::assertEquals('COMPOSER_HTACCESS_PROTECT', $result); } public function testAudit(): void { $config = new Config(true); $result = $config->get('audit'); self::assertArrayHasKey('abandoned', $result); self::assertArrayHasKey('ignore', $result); self::assertSame(Auditor::ABANDONED_FAIL, $result['abandoned']); self::assertSame([], $result['ignore']); Platform::putEnv('COMPOSER_AUDIT_ABANDONED', Auditor::ABANDONED_IGNORE); $result = $config->get('audit'); Platform::clearEnv('COMPOSER_AUDIT_ABANDONED'); self::assertArrayHasKey('abandoned', $result); self::assertArrayHasKey('ignore', $result); self::assertSame(Auditor::ABANDONED_IGNORE, $result['abandoned']); self::assertSame([], $result['ignore']); $config->merge(['config' => ['audit' => ['ignore' => ['A', 'B']]]]); $config->merge(['config' => ['audit' => ['ignore' => ['A', 'C']]]]); $result = $config->get('audit'); self::assertArrayHasKey('ignore', $result); self::assertSame(['A', 'B', 'A', 'C'], $result['ignore']); // Test COMPOSER_SECURITY_BLOCKING_ABANDONED env var Platform::putEnv('COMPOSER_SECURITY_BLOCKING_ABANDONED', '1'); $result = $config->get('audit'); Platform::clearEnv('COMPOSER_SECURITY_BLOCKING_ABANDONED'); self::assertArrayHasKey('block-abandoned', $result); self::assertSame(true, $result['block-abandoned']); Platform::putEnv('COMPOSER_SECURITY_BLOCKING_ABANDONED', '0'); $result = $config->get('audit'); Platform::clearEnv('COMPOSER_SECURITY_BLOCKING_ABANDONED'); self::assertArrayHasKey('block-abandoned', $result); self::assertSame(false, $result['block-abandoned']); } public function testGetDefaultsToAnEmptyArray(): void { $config = new Config; $keys = [ 'bitbucket-oauth', 'github-oauth', 'gitlab-oauth', 'gitlab-token', 'forgejo-token', 'http-basic', 'bearer', ]; foreach ($keys as $key) { $value = $config->get($key); self::assertIsArray($value); self::assertCount(0, $value); } } public function testMergesPluginConfig(): void { $config = new Config(false); $config->merge(['config' => ['allow-plugins' => ['some/plugin' => true]]]); self::assertEquals(['some/plugin' => true], $config->get('allow-plugins')); $config->merge(['config' => ['allow-plugins' => ['another/plugin' => true]]]); self::assertEquals(['some/plugin' => true, 'another/plugin' => true], $config->get('allow-plugins')); } public function testOverridesGlobalBooleanPluginsConfig(): void { $config = new Config(false); $config->merge(['config' => ['allow-plugins' => true]]); self::assertEquals(true, $config->get('allow-plugins')); $config->merge(['config' => ['allow-plugins' => ['another/plugin' => true]]]); self::assertEquals(['another/plugin' => true], $config->get('allow-plugins')); } public function testAllowsAllPluginsFromLocalBoolean(): void { $config = new Config(false); $config->merge(['config' => ['allow-plugins' => ['some/plugin' => true]]]); self::assertEquals(['some/plugin' => true], $config->get('allow-plugins')); $config->merge(['config' => ['allow-plugins' => true]]); self::assertEquals(true, $config->get('allow-plugins')); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DocumentationTest.php
tests/Composer/Test/DocumentationTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Descriptor\ApplicationDescription; class DocumentationTest extends TestCase { /** * @dataProvider provideCommandCases */ public function testCommand(Command $command): void { static $docContent = null; if ($docContent === null) { $docContent = file_get_contents(__DIR__ . '/../../../doc/03-cli.md'); } self::assertStringContainsString( sprintf( "\n## %s\n\n", $this->getCommandName($command) // TODO: test description // TODO: test options ), $docContent ); } private function getCommandName(Command $command): string { $name = (string) $command->getName(); foreach ($command->getAliases() as $alias) { $name .= ' / ' . $alias; } return $name; } public static function provideCommandCases(): \Generator { $application = new Application(); $application->setAutoExit(false); if (method_exists($application, 'setCatchErrors')) { $application->setCatchErrors(false); } $application->setCatchExceptions(false); $description = new ApplicationDescription($application); foreach ($description->getCommands() as $command) { if (in_array($command->getName(), ['about', 'completion', 'list'], true)) { continue; } yield [$command]; } } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/CompletionFunctionalTest.php
tests/Composer/Test/CompletionFunctionalTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test; use Composer\Console\Application; use Symfony\Component\Console\Tester\CommandCompletionTester; /** * Validate autocompletion for all commands. * * @author Jérôme Tamarelle <jerome@tamarelle.net> */ class CompletionFunctionalTest extends TestCase { /** * @return iterable<array<string|string[]|null>> */ public static function getCommandSuggestions(): iterable { $randomVendor = 'a/'; $installedPackages = ['composer/semver', 'psr/log']; $preferInstall = ['dist', 'source', 'auto']; yield ['archive ', [$randomVendor]]; yield ['archive symfony/http-', ['symfony/http-kernel', 'symfony/http-foundation']]; yield ['archive --format ', ['tar', 'zip']]; yield ['create-project ', [$randomVendor]]; yield ['create-project symfony/skeleton --prefer-install ', $preferInstall]; yield ['depends ', $installedPackages]; yield ['why ', $installedPackages]; yield ['exec ', ['composer', 'jsonlint', 'phpstan', 'phpstan.phar', 'simple-phpunit', 'validate-json']]; yield ['browse ', $installedPackages]; yield ['home -H ', $installedPackages]; yield ['init --require ', [$randomVendor]]; yield ['init --require-dev foo/bar --require-dev ', [$randomVendor]]; yield ['install --prefer-install ', $preferInstall]; yield ['install ', null]; yield ['outdated ', $installedPackages]; yield ['prohibits ', [$randomVendor]]; yield ['why-not symfony/http-ker', ['symfony/http-kernel']]; yield ['reinstall --prefer-install ', $preferInstall]; yield ['reinstall ', $installedPackages]; yield ['remove ', $installedPackages]; yield ['require --prefer-install ', $preferInstall]; yield ['require ', [$randomVendor]]; yield ['require --dev symfony/http-', ['symfony/http-kernel', 'symfony/http-foundation']]; yield ['run-script ', ['compile', 'test', 'phpstan']]; yield ['run-script test ', null]; yield ['search --format ', ['text', 'json']]; yield ['show --format ', ['text', 'json']]; yield ['info ', $installedPackages]; yield ['suggests ', $installedPackages]; yield ['update --prefer-install ', $preferInstall]; yield ['update ', $installedPackages]; yield ['config --list ', null]; yield ['config --editor ', null]; yield ['config --auth ', null]; yield ['config ', ['bin-compat', 'extra', 'extra.branch-alias', 'home', 'name', 'repositories', 'repositories.packagist.org', 'suggest', 'suggest.ext-zip', 'type', 'version']]; yield ['config bin', ['bin-dir']]; // global setting yield ['config nam', ['name']]; // existing package-property yield ['config ver', ['version']]; // non-existing package-property yield ['config repo', ['repositories', 'repositories.packagist.org']]; yield ['config repositories.', ['repositories.packagist.org']]; yield ['config sug', ['suggest', 'suggest.ext-zip']]; yield ['config suggest.ext-', ['suggest.ext-zip']]; yield ['config ext', ['extra', 'extra.branch-alias', 'extra.branch-alias.dev-main']]; // as this test does not use a fixture (yet?), the completion // of setting authentication settings can have varying results // yield ['config http-basic.', […]]; yield ['config --unset ', ['extra', 'extra.branch-alias', 'extra.branch-alias.dev-main', 'name', 'suggest', 'suggest.ext-zip', 'type']]; yield ['config --unset bin-dir', null]; // global setting yield ['config --unset nam', ['name']]; // existing package-property yield ['config --unset version', null]; // non-existing package-property yield ['config --unset extra.', ['extra.branch-alias', 'extra.branch-alias.dev-main']]; // as this test does not use a fixture (yet?), the completion // of unsetting authentication settings can have varying results // yield ['config --unset http-basic.', […]]; yield ['config --global ', ['bin-compat', 'home', 'repositories', 'repositories.packagist.org']]; yield ['config --global repo', ['repositories', 'repositories.packagist.org']]; yield ['config --global repositories.', ['repositories.packagist.org']]; // as this test does not use a fixture (yet?), the completion // of unsetting global settings can have varying results // yield ['config --global --unset ', null]; // as this test does not use a fixture (yet?), the completion of // unsetting global authentication settings can have varying results // yield ['config --global --unset http-basic.', […]]; } /** * @dataProvider getCommandSuggestions * * @param string $input The command that is typed * @param string[]|null $expectedSuggestions Sample expected suggestions. Null if nothing is expected. */ public function testComplete(string $input, ?array $expectedSuggestions): void { $input = explode(' ', $input); $commandName = array_shift($input); $command = $this->getApplication()->get($commandName); $tester = new CommandCompletionTester($command); $suggestions = $tester->complete($input); if (null === $expectedSuggestions) { self::assertEmpty($suggestions); return; } $diff = array_diff($expectedSuggestions, $suggestions); self::assertEmpty($diff, sprintf('Suggestions must contain "%s". Got "%s".', implode('", "', $diff), implode('", "', $suggestions))); } private function getApplication(): Application { return new Application(); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php
tests/Composer/Test/DependencyResolver/RuleSetIteratorTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\GenericRule; use Composer\DependencyResolver\Rule; use Composer\DependencyResolver\RuleSet; use Composer\DependencyResolver\RuleSetIterator; use Composer\DependencyResolver\Pool; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Test\TestCase; class RuleSetIteratorTest extends TestCase { /** @var array<RuleSet::TYPE_*, Rule[]> */ protected $rules; /** @var Pool */ protected $pool; protected function setUp(): void { $this->pool = new Pool(); $this->rules = [ RuleSet::TYPE_REQUEST => [ new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), ], RuleSet::TYPE_LEARNED => [ new GenericRule([], Rule::RULE_LEARNED, 1), ], RuleSet::TYPE_PACKAGE => [], ]; } public function testForeach(): void { $ruleSetIterator = new RuleSetIterator($this->rules); $result = []; foreach ($ruleSetIterator as $rule) { $result[] = $rule; } $expected = [ $this->rules[RuleSet::TYPE_REQUEST][0], $this->rules[RuleSet::TYPE_REQUEST][1], $this->rules[RuleSet::TYPE_LEARNED][0], ]; self::assertEquals($expected, $result); } public function testKeys(): void { $ruleSetIterator = new RuleSetIterator($this->rules); $result = []; foreach ($ruleSetIterator as $key => $rule) { $result[] = $key; } $expected = [ RuleSet::TYPE_REQUEST, RuleSet::TYPE_REQUEST, RuleSet::TYPE_LEARNED, ]; self::assertEquals($expected, $result); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/PoolTest.php
tests/Composer/Test/DependencyResolver/PoolTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\Pool; use Composer\Test\TestCase; class PoolTest extends TestCase { public function testPool(): void { $package = self::getPackage('foo', '1'); $pool = $this->createPool([$package]); self::assertEquals([$package], $pool->whatProvides('foo')); self::assertEquals([$package], $pool->whatProvides('foo')); } public function testWhatProvidesPackageWithConstraint(): void { $firstPackage = self::getPackage('foo', '1'); $secondPackage = self::getPackage('foo', '2'); $pool = $this->createPool([ $firstPackage, $secondPackage, ]); self::assertEquals([$firstPackage, $secondPackage], $pool->whatProvides('foo')); self::assertEquals([$secondPackage], $pool->whatProvides('foo', self::getVersionConstraint('==', '2'))); } public function testPackageById(): void { $package = self::getPackage('foo', '1'); $pool = $this->createPool([$package]); self::assertSame($package, $pool->packageById(1)); } public function testWhatProvidesWhenPackageCannotBeFound(): void { $pool = $this->createPool(); self::assertEquals([], $pool->whatProvides('foo')); } /** * @param array<\Composer\Package\BasePackage>|null $packages */ protected function createPool(?array $packages = []): Pool { return new Pool($packages); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php
tests/Composer/Test/DependencyResolver/PoolOptimizerTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\DefaultPolicy; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\PoolOptimizer; use Composer\DependencyResolver\Request; use Composer\Json\JsonFile; use Composer\Package\AliasPackage; use Composer\Package\BasePackage; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Version\VersionParser; use Composer\Pcre\Preg; use Composer\Repository\LockArrayRepository; use Composer\Test\TestCase; class PoolOptimizerTest extends TestCase { /** * @dataProvider provideIntegrationTests * @param mixed[] $requestData * @param BasePackage[] $packagesBefore * @param BasePackage[] $expectedPackages */ public function testPoolOptimizer(array $requestData, array $packagesBefore, array $expectedPackages, string $message): void { $lockedRepo = new LockArrayRepository(); $request = new Request($lockedRepo); $parser = new VersionParser(); if (isset($requestData['locked'])) { foreach ($requestData['locked'] as $package) { $request->lockPackage(self::loadPackage($package)); } } if (isset($requestData['fixed'])) { foreach ($requestData['fixed'] as $package) { $request->fixPackage(self::loadPackage($package)); } } foreach ($requestData['require'] as $package => $constraint) { $request->requireName($package, $parser->parseConstraints($constraint)); } $preferStable = $requestData['preferStable'] ?? false; $preferLowest = $requestData['preferLowest'] ?? false; $pool = new Pool($packagesBefore); $poolOptimizer = new PoolOptimizer(new DefaultPolicy($preferStable, $preferLowest)); $pool = $poolOptimizer->optimize($request, $pool); self::assertSame( $this->reducePackagesInfoForComparison($expectedPackages), $this->reducePackagesInfoForComparison($pool->getPackages()), $message ); } public static function provideIntegrationTests(): array { $fixturesDir = (string) realpath(__DIR__.'/Fixtures/pooloptimizer/'); $tests = []; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $file = (string) $file; if (!Preg::isMatch('/\.test$/', $file)) { continue; } try { $testData = self::readTestFile($file, $fixturesDir); $message = $testData['TEST']; $requestData = JsonFile::parseJson($testData['REQUEST']); $packagesBefore = self::loadPackages(JsonFile::parseJson($testData['POOL-BEFORE'])); $expectedPackages = self::loadPackages(JsonFile::parseJson($testData['POOL-AFTER'])); } catch (\Exception $e) { die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file))); } $tests[basename($file)] = [$requestData, $packagesBefore, $expectedPackages, $message]; } return $tests; } /** * @return mixed[] */ protected static function readTestFile(string $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); /** @var array<string, bool> $sectionInfo */ $sectionInfo = [ 'TEST' => true, 'REQUEST' => true, 'POOL-BEFORE' => true, 'POOL-AFTER' => true, ]; $section = null; $data = []; foreach ($tokens as $i => $token) { if (null === $section && empty($token)) { continue; // skip leading blank } if (null === $section) { if (!isset($sectionInfo[$token])) { throw new \RuntimeException(sprintf( 'The test file "%s" must not contain a section named "%s".', str_replace($fixturesDir.'/', '', $file), $token )); } $section = $token; continue; } $sectionData = $token; $data[$section] = $sectionData; $section = $sectionData = null; } foreach ($sectionInfo as $section => $required) { if ($required && !isset($data[$section])) { throw new \RuntimeException(sprintf( 'The test file "%s" must have a section named "%s".', str_replace($fixturesDir.'/', '', $file), $section )); } } return $data; } /** * @param BasePackage[] $packages * @return string[] */ private function reducePackagesInfoForComparison(array $packages): array { $packagesInfo = []; foreach ($packages as $package) { $packagesInfo[] = $package->getName() . '@' . $package->getVersion() . ($package instanceof AliasPackage ? ' (alias of '.$package->getAliasOf()->getVersion().')' : ''); } sort($packagesInfo); return $packagesInfo; } /** * @param mixed[][] $packagesData * @return BasePackage[] */ private static function loadPackages(array $packagesData): array { $packages = []; foreach ($packagesData as $packageData) { $packages[] = $package = self::loadPackage($packageData); if ($package instanceof AliasPackage) { $packages[] = $package->getAliasOf(); } } return $packages; } /** * @param mixed[] $packageData */ private static function loadPackage(array $packageData): BasePackage { $loader = new ArrayLoader(); return $loader->load($packageData); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/RuleTest.php
tests/Composer/Test/DependencyResolver/RuleTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\GenericRule; use Composer\DependencyResolver\Rule; use Composer\DependencyResolver\RuleSet; use Composer\DependencyResolver\Pool; use Composer\Package\Link; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Test\TestCase; class RuleTest extends TestCase { public function testGetHash(): void { $rule = new GenericRule([123], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $hash = unpack('ihash', (string) hash(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', '123', true)); self::assertEquals($hash['hash'], $rule->getHash()); } public function testEqualsForRulesWithDifferentHashes(): void { $rule = new GenericRule([1, 2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([1, 3], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); self::assertFalse($rule->equals($rule2)); } public function testEqualsForRulesWithDifferLiteralsQuantity(): void { $rule = new GenericRule([1, 12], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); self::assertFalse($rule->equals($rule2)); } public function testEqualsForRulesWithSameLiterals(): void { $rule = new GenericRule([1, 12], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([1, 12], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); self::assertTrue($rule->equals($rule2)); } public function testSetAndGetType(): void { $rule = new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule->setType(RuleSet::TYPE_REQUEST); self::assertEquals(RuleSet::TYPE_REQUEST, $rule->getType()); } public function testEnable(): void { $rule = new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule->disable(); $rule->enable(); self::assertTrue($rule->isEnabled()); self::assertFalse($rule->isDisabled()); } public function testDisable(): void { $rule = new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule->enable(); $rule->disable(); self::assertTrue($rule->isDisabled()); self::assertFalse($rule->isEnabled()); } public function testIsAssertions(): void { $rule = new GenericRule([1, 12], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); self::assertFalse($rule->isAssertion()); self::assertTrue($rule2->isAssertion()); } public function testPrettyString(): void { $pool = new Pool([ $p1 = self::getPackage('foo', '2.1'), $p2 = self::getPackage('baz', '1.1'), ]); $repositorySetMock = $this->getMockBuilder('Composer\Repository\RepositorySet')->disableOriginalConstructor()->getMock(); $requestMock = $this->getMockBuilder('Composer\DependencyResolver\Request')->disableOriginalConstructor()->getMock(); $emptyConstraint = new MatchAllConstraint(); $emptyConstraint->setPrettyString('*'); $rule = new GenericRule([$p1->getId(), -$p2->getId()], Rule::RULE_PACKAGE_REQUIRES, new Link('baz', 'foo', $emptyConstraint)); self::assertEquals('baz 1.1 relates to foo * -> satisfiable by foo[2.1].', $rule->getPrettyString($repositorySetMock, $requestMock, $pool, false)); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/PoolBuilderTest.php
tests/Composer/Test/DependencyResolver/PoolBuilderTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\DefaultPolicy; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\PoolOptimizer; use Composer\Config; use Composer\IO\NullIO; use Composer\Pcre\Preg; use Composer\Repository\ArrayRepository; use Composer\Repository\FilterRepository; use Composer\Repository\LockArrayRepository; use Composer\DependencyResolver\Request; use Composer\Package\BasePackage; use Composer\Package\AliasPackage; use Composer\Json\JsonFile; use Composer\Package\Loader\ArrayLoader; use Composer\Package\Version\VersionParser; use Composer\Repository\RepositoryFactory; use Composer\Repository\RepositorySet; use Composer\Test\TestCase; use Composer\Util\Platform; class PoolBuilderTest extends TestCase { /** * @dataProvider getIntegrationTests * @param string[] $expect * @param string[] $expectOptimized * @param mixed[] $root * @param mixed[] $requestData * @param mixed[] $packageRepos * @param mixed[] $fixed */ public function testPoolBuilder(string $file, string $message, array $expect, array $expectOptimized, array $root, array $requestData, array $packageRepos, array $fixed): void { $rootAliases = !empty($root['aliases']) ? $root['aliases'] : []; $minimumStability = !empty($root['minimum-stability']) ? $root['minimum-stability'] : 'stable'; $stabilityFlags = !empty($root['stability-flags']) ? $root['stability-flags'] : []; $rootReferences = !empty($root['references']) ? $root['references'] : []; $stabilityFlags = array_map(static function ($stability): int { if (!isset(BasePackage::STABILITIES[$stability])) { throw new \LogicException('Invalid stability given: '.$stability); } return BasePackage::STABILITIES[$stability]; }, $stabilityFlags); $parser = new VersionParser(); foreach ($rootAliases as $index => $alias) { $rootAliases[$index]['version'] = $parser->normalize($alias['version']); $rootAliases[$index]['alias_normalized'] = $parser->normalize($alias['alias']); } $loader = new ArrayLoader(null, true); $packageIds = []; $loadPackage = static function ($data) use ($loader, &$packageIds): \Composer\Package\PackageInterface { /** @var ?int $id */ $id = null; if (!empty($data['id'])) { $id = $data['id']; unset($data['id']); } $pkg = $loader->load($data); if (!empty($id)) { if (!empty($packageIds[$id])) { throw new \LogicException('Duplicate package id '.$id.' defined'); } $packageIds[$id] = $pkg; } return $pkg; }; $oldCwd = Platform::getCwd(); chdir(__DIR__.'/Fixtures/poolbuilder/'); $repositorySet = new RepositorySet($minimumStability, $stabilityFlags, $rootAliases, $rootReferences); $config = new Config(false); $rm = RepositoryFactory::manager($io = new NullIO(), $config); foreach ($packageRepos as $packages) { if (isset($packages['type'])) { $repo = RepositoryFactory::createRepo($io, $config, $packages, $rm); $repositorySet->addRepository($repo); continue; } $repo = new ArrayRepository(); if (isset($packages['canonical']) || isset($packages['only']) || isset($packages['exclude'])) { $options = $packages; $packages = $options['packages']; unset($options['packages']); $repositorySet->addRepository(new FilterRepository($repo, $options)); } else { $repositorySet->addRepository($repo); } foreach ($packages as $package) { $repo->addPackage($loadPackage($package)); } } $repositorySet->addRepository($lockedRepo = new LockArrayRepository()); if (isset($requestData['locked'])) { foreach ($requestData['locked'] as $package) { $lockedRepo->addPackage($loadPackage($package)); } } $request = new Request($lockedRepo); foreach ($requestData['require'] as $package => $constraint) { $request->requireName($package, $parser->parseConstraints($constraint)); } if (isset($requestData['allowList'])) { $transitiveDeps = Request::UPDATE_ONLY_LISTED; if (isset($requestData['allowTransitiveDepsNoRootRequire']) && $requestData['allowTransitiveDepsNoRootRequire']) { $transitiveDeps = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS_NO_ROOT_REQUIRE; } if (isset($requestData['allowTransitiveDeps']) && $requestData['allowTransitiveDeps']) { $transitiveDeps = Request::UPDATE_LISTED_WITH_TRANSITIVE_DEPS; } $request->setUpdateAllowList($requestData['allowList'], $transitiveDeps); } foreach ($fixed as $fixedPackage) { $request->fixPackage($loadPackage($fixedPackage)); } $pool = $repositorySet->createPool($request, new NullIO()); $result = $this->getPackageResultSet($pool, $packageIds); sort($expect); sort($result); self::assertSame($expect, $result, 'Unoptimized pool does not match expected package set'); $optimizer = new PoolOptimizer(new DefaultPolicy()); $result = $this->getPackageResultSet($optimizer->optimize($request, $pool), $packageIds); sort($expectOptimized); sort($result); self::assertSame($expectOptimized, $result, 'Optimized pool does not match expected package set'); chdir($oldCwd); } /** * @param array<int, BasePackage> $packageIds * @return list<string|int> */ private function getPackageResultSet(Pool $pool, array $packageIds): array { $result = []; for ($i = 1, $count = count($pool); $i <= $count; $i++) { $result[] = $pool->packageById($i); } return array_map(static function (BasePackage $package) use ($packageIds) { if ($id = array_search($package, $packageIds, true)) { return $id; } $suffix = ''; if ($package->getSourceReference()) { $suffix = '#'.$package->getSourceReference(); } if ($package->getRepository() instanceof LockArrayRepository) { $suffix .= ' (locked)'; } if ($package instanceof AliasPackage) { if ($id = array_search($package->getAliasOf(), $packageIds, true)) { return (string) $package->getName().'-'.$package->getVersion() . $suffix . ' (alias of '.$id . ')'; } return (string) $package->getName().'-'.$package->getVersion() . $suffix . ' (alias of '.$package->getAliasOf()->getVersion().')'; } return (string) $package->getName().'-'.$package->getVersion() . $suffix; }, $result); } /** * @return array<string, array<string>> */ public static function getIntegrationTests(): array { $fixturesDir = (string) realpath(__DIR__.'/Fixtures/poolbuilder/'); $tests = []; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $file = (string) $file; if (!Preg::isMatch('/\.test$/', $file)) { continue; } try { $testData = self::readTestFile($file, $fixturesDir); $message = $testData['TEST']; $request = JsonFile::parseJson($testData['REQUEST']); $root = !empty($testData['ROOT']) ? JsonFile::parseJson($testData['ROOT']) : []; $packageRepos = JsonFile::parseJson($testData['PACKAGE-REPOS']); $fixed = []; if (!empty($testData['FIXED'])) { $fixed = JsonFile::parseJson($testData['FIXED']); } $expect = JsonFile::parseJson($testData['EXPECT']); $expectOptimized = !empty($testData['EXPECT-OPTIMIZED']) ? JsonFile::parseJson($testData['EXPECT-OPTIMIZED']) : $expect; } catch (\Exception $e) { die(sprintf('Test "%s" is not valid: '.$e->getMessage(), str_replace($fixturesDir.'/', '', $file))); } $tests[basename($file)] = [str_replace($fixturesDir.'/', '', $file), $message, $expect, $expectOptimized, $root, $request, $packageRepos, $fixed]; } return $tests; } /** * @return array<string, string> */ protected static function readTestFile(string $file, string $fixturesDir): array { $tokens = Preg::split('#(?:^|\n*)--([A-Z-]+)--\n#', file_get_contents($file), -1, PREG_SPLIT_DELIM_CAPTURE); $sectionInfo = [ 'TEST' => true, 'ROOT' => false, 'REQUEST' => true, 'FIXED' => false, 'PACKAGE-REPOS' => true, 'EXPECT' => true, 'EXPECT-OPTIMIZED' => false, ]; $section = null; $data = []; foreach ($tokens as $i => $token) { if (null === $section && empty($token)) { continue; // skip leading blank } if (null === $section) { if (!isset($sectionInfo[$token])) { throw new \RuntimeException(sprintf( 'The test file "%s" must not contain a section named "%s".', str_replace($fixturesDir.'/', '', $file), $token )); } $section = $token; continue; } $sectionData = $token; $data[$section] = $sectionData; $section = $sectionData = null; } foreach ($sectionInfo as $section => $required) { if ($required && !isset($data[$section])) { throw new \RuntimeException(sprintf( 'The test file "%s" must have a section named "%s".', str_replace($fixturesDir.'/', '', $file), $section )); } } return $data; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/SolverTest.php
tests/Composer/Test/DependencyResolver/SolverTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\IO\NullIO; use Composer\Repository\ArrayRepository; use Composer\Repository\LockArrayRepository; use Composer\DependencyResolver\DefaultPolicy; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation; use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Request; use Composer\DependencyResolver\Solver; use Composer\DependencyResolver\SolverProblemsException; use Composer\Package\PackageInterface; use Composer\Package\Link; use Composer\Repository\RepositorySet; use Composer\Test\TestCase; use Composer\Semver\Constraint\MultiConstraint; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\DependencyResolver\Pool; class SolverTest extends TestCase { /** @var RepositorySet */ protected $repoSet; /** @var ArrayRepository */ protected $repo; /** @var LockArrayRepository */ protected $repoLocked; /** @var Request */ protected $request; /** @var DefaultPolicy */ protected $policy; /** @var Solver|null */ protected $solver; /** @var Pool */ protected $pool; public function setUp(): void { $this->repoSet = new RepositorySet(); $this->repo = new ArrayRepository; $this->repoLocked = new LockArrayRepository; $this->request = new Request($this->repoLocked); $this->policy = new DefaultPolicy; } public function testSolverInstallSingle(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageA], ]); } public function testSolverRemoveIfNotRequested(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->reposComplete(); $this->checkSolverResult([ ['job' => 'remove', 'package' => $packageA], ]); } public function testInstallNonExistingPackageFails(): void { $this->repo->addPackage(self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->requireName('B', self::getVersionConstraint('==', '1')); $this->createSolver(); try { $transaction = $this->solver->solve($this->request); $this->fail('Unsolvable conflict did not result in exception.'); } catch (SolverProblemsException $e) { $problems = $e->getProblems(); self::assertCount(1, $problems); self::assertEquals(2, $e->getCode()); self::assertEquals("\n - Root composer.json requires b, it could not be found in any version, there may be a typo in the package name.", $problems[0]->getPrettyString($this->repoSet, $this->request, $this->pool, false)); } } public function testSolverInstallSamePackageFromDifferentRepositories(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; $repo1->addPackage($foo1 = self::getPackage('foo', '1')); $repo2->addPackage($foo2 = self::getPackage('foo', '1')); $this->repoSet->addRepository($repo1); $this->repoSet->addRepository($repo2); $this->request->requireName('foo'); $this->checkSolverResult([ ['job' => 'install', 'package' => $foo1], ]); } public function testSolverInstallWithDeps(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageB = self::getPackage('B', '1.1')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('<', '1.1'), Link::TYPE_REQUIRE)]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageB], ['job' => 'install', 'package' => $packageA], ]); } public function testSolverInstallHonoursNotEqualOperator(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageB11 = self::getPackage('B', '1.1')); $this->repo->addPackage($newPackageB12 = self::getPackage('B', '1.2')); $this->repo->addPackage($newPackageB13 = self::getPackage('B', '1.3')); $packageA->setRequires([ 'b' => new Link('A', 'B', new MultiConstraint([ self::getVersionConstraint('<=', '1.3'), self::getVersionConstraint('<>', '1.3'), self::getVersionConstraint('!=', '1.2'), ]), Link::TYPE_REQUIRE), ]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $newPackageB11], ['job' => 'install', 'package' => $packageA], ]); } public function testSolverInstallWithDepsInOrder(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($packageC = self::getPackage('C', '1.0')); $packageB->setRequires([ 'a' => new Link('B', 'A', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE), 'c' => new Link('B', 'C', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE), ]); $packageC->setRequires([ 'a' => new Link('C', 'A', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE), ]); $this->reposComplete(); $this->request->requireName('A'); $this->request->requireName('B'); $this->request->requireName('C'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageA], ['job' => 'install', 'package' => $packageC], ['job' => 'install', 'package' => $packageB], ]); } /** * This test covers a particular behavior of the solver related to packages with the same name and version, * but different requirements on other packages. * Imagine you had multiple instances of packages (same name/version) with e.g. different dists depending on what other related package they were "built" for. * * An example people can probably relate to, so it was chosen here for better readability: * - PHP versions 8.0.10 and 7.4.23 could be a package * - ext-foobar 1.0.0 could be a package, but it must be built separately for each PHP x.y series * - thus each of the ext-foobar packages lists the "PHP" package as a dependency * * This is not something that can happen with packages on e.g. Packagist, but custom installers with custom repositories might do something like this; * in fact, some PaaSes do the exact thing above, installing binary builds of PHP and extensions as Composer packages with a custom installer in a separate step before the "userland" `composer install`. * * If version selectors are sufficiently permissive (e.g. "ourcustom/php":"*", "ourcustom/ext-foobar":"*"), then it may happen that the Solver won't pick the highest possible PHP version, as it has already settled on an "ext-foobar" (they're all the same version to the Solver, it doesn't know about the different requirements in each of the otherwise identical packages) if that was listed in "require" before "php". * That's "unfixable", and not even broken, behavior (what if the "ext-foobar" has higher versions for the lower "PHP"? who wins then? any combination of the packages is "correct"), but it shouldn't randomly change. * This test asserts this behavior to prevent regressions. * * CAUTION: IF THIS TEST EVER FAILS, SOLVER BEHAVIOR HAS CHANGED AND MAY BREAK DOWNSTREAM USERS */ public function testSolverMultiPackageNameVersionResolutionDependsOnRequireOrder(): void { $this->repo->addPackage($php74 = self::getPackage('ourcustom/PHP', '7.4.23')); $this->repo->addPackage($php80 = self::getPackage('ourcustom/PHP', '8.0.10')); $this->repo->addPackage($extForPhp74 = self::getPackage('ourcustom/ext-foobar', '1.0')); $this->repo->addPackage($extForPhp80 = self::getPackage('ourcustom/ext-foobar', '1.0')); $extForPhp74->setRequires([ 'ourcustom/php' => new Link('ourcustom/ext-foobar', 'ourcustom/PHP', new MultiConstraint([ self::getVersionConstraint('>=', '7.4.0'), self::getVersionConstraint('<', '7.5.0'), ]), Link::TYPE_REQUIRE), ]); $extForPhp80->setRequires([ 'ourcustom/php' => new Link('ourcustom/ext-foobar', 'ourcustom/PHP', new MultiConstraint([ self::getVersionConstraint('>=', '8.0.0'), self::getVersionConstraint('<', '8.1.0'), ]), Link::TYPE_REQUIRE), ]); $this->reposComplete(); $this->request->requireName('ourcustom/PHP'); $this->request->requireName('ourcustom/ext-foobar'); $this->checkSolverResult([ ['job' => 'install', 'package' => $php80], ['job' => 'install', 'package' => $extForPhp80], ]); // now we flip the requirements around: we request "ext-foobar" before "php" // because the ext-foobar package that requires php74 comes first in the repo, and the one that requires php80 second, the solver will pick the one for php74, and then, as it is a dependency, also php74 // this is because both packages have the same name and version; just their requirements differ // and because no other constraint forces a particular version of package "php" $this->request = new Request($this->repoLocked); $this->request->requireName('ourcustom/ext-foobar'); $this->request->requireName('ourcustom/PHP'); $this->checkSolverResult([ ['job' => 'install', 'package' => $php74], ['job' => 'install', 'package' => $extForPhp74], ]); } /** * This test is almost the same as above, except we're inserting the package with the requirement on the other package in a different order, asserting that if that is done, the order of requirements no longer matters * * CAUTION: IF THIS TEST EVER FAILS, SOLVER BEHAVIOR HAS CHANGED AND MAY BREAK DOWNSTREAM USERS */ public function testSolverMultiPackageNameVersionResolutionIsIndependentOfRequireOrderIfOrderedDescendingByRequirement(): void { $this->repo->addPackage($php74 = self::getPackage('ourcustom/PHP', '7.4')); $this->repo->addPackage($php80 = self::getPackage('ourcustom/PHP', '8.0')); $this->repo->addPackage($extForPhp80 = self::getPackage('ourcustom/ext-foobar', '1.0')); // note we are inserting this one into the repo first, unlike in the previous test $this->repo->addPackage($extForPhp74 = self::getPackage('ourcustom/ext-foobar', '1.0')); $extForPhp80->setRequires([ 'ourcustom/php' => new Link('ourcustom/ext-foobar', 'ourcustom/PHP', new MultiConstraint([ self::getVersionConstraint('>=', '8.0.0'), self::getVersionConstraint('<', '8.1.0'), ]), Link::TYPE_REQUIRE), ]); $extForPhp74->setRequires([ 'ourcustom/php' => new Link('ourcustom/ext-foobar', 'ourcustom/PHP', new MultiConstraint([ self::getVersionConstraint('>=', '7.4.0'), self::getVersionConstraint('<', '7.5.0'), ]), Link::TYPE_REQUIRE), ]); $this->reposComplete(); $this->request->requireName('ourcustom/PHP'); $this->request->requireName('ourcustom/ext-foobar'); $this->checkSolverResult([ ['job' => 'install', 'package' => $php80], ['job' => 'install', 'package' => $extForPhp80], ]); // unlike in the previous test, the order of requirements no longer matters now $this->request = new Request($this->repoLocked); $this->request->requireName('ourcustom/ext-foobar'); $this->request->requireName('ourcustom/PHP'); $this->checkSolverResult([ ['job' => 'install', 'package' => $php80], ['job' => 'install', 'package' => $extForPhp80], ]); } public function testSolverFixLocked(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->fixPackage($packageA); $this->checkSolverResult([]); } public function testSolverFixLockedWithAlternative(): void { $this->repo->addPackage(self::getPackage('A', '1.0')); $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->fixPackage($packageA); $this->checkSolverResult([]); } public function testSolverUpdateDoesOnlyUpdate(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageB = self::getPackage('B', '1.1')); $this->reposComplete(); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0.0.0'), Link::TYPE_REQUIRE)]); $this->request->fixPackage($packageA); $this->request->requireName('B', self::getVersionConstraint('=', '1.1.0.0')); $this->checkSolverResult([ ['job' => 'update', 'from' => $packageB, 'to' => $newPackageB], ]); } public function testSolverUpdateSingle(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '1.1')); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'update', 'from' => $packageA, 'to' => $newPackageA], ]); } public function testSolverUpdateAll(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '1.1')); $this->repo->addPackage($newPackageB = self::getPackage('B', '1.1')); $packageA->setRequires(['b' => new Link('A', 'B', new MatchAllConstraint(), Link::TYPE_REQUIRE)]); $newPackageA->setRequires(['b' => new Link('A', 'B', new MatchAllConstraint(), Link::TYPE_REQUIRE)]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'update', 'from' => $packageB, 'to' => $newPackageB], ['job' => 'update', 'from' => $packageA, 'to' => $newPackageA], ]); } public function testSolverUpdateCurrent(): void { $this->repoLocked->addPackage(self::getPackage('A', '1.0')); $this->repo->addPackage(self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([]); } public function testSolverUpdateOnlyUpdatesSelectedPackage(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($packageAnewer = self::getPackage('A', '1.1')); $this->repo->addPackage($packageBnewer = self::getPackage('B', '1.1')); $this->reposComplete(); $this->request->requireName('A'); $this->request->fixPackage($packageB); $this->checkSolverResult([ ['job' => 'update', 'from' => $packageA, 'to' => $packageAnewer], ]); } public function testSolverUpdateConstrained(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '1.2')); $this->repo->addPackage(self::getPackage('A', '2.0')); $this->reposComplete(); $this->request->requireName('A', self::getVersionConstraint('<', '2.0.0.0')); $this->checkSolverResult([[ 'job' => 'update', 'from' => $packageA, 'to' => $newPackageA, ]]); } public function testSolverUpdateFullyConstrained(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '1.2')); $this->repo->addPackage(self::getPackage('A', '2.0')); $this->reposComplete(); $this->request->requireName('A', self::getVersionConstraint('<', '2.0.0.0')); $this->checkSolverResult([[ 'job' => 'update', 'from' => $packageA, 'to' => $newPackageA, ]]); } public function testSolverUpdateFullyConstrainedPrunesInstalledPackages(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repoLocked->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '1.2')); $this->repo->addPackage(self::getPackage('A', '2.0')); $this->reposComplete(); $this->request->requireName('A', self::getVersionConstraint('<', '2.0.0.0')); $this->checkSolverResult([ [ 'job' => 'remove', 'package' => $packageB, ], [ 'job' => 'update', 'from' => $packageA, 'to' => $newPackageA, ], ]); } public function testSolverAllJobs(): void { $this->repoLocked->addPackage($packageD = self::getPackage('D', '1.0')); $this->repoLocked->addPackage($oldPackageC = self::getPackage('C', '1.0')); $this->repo->addPackage($packageA = self::getPackage('A', '2.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageB = self::getPackage('B', '1.1')); $this->repo->addPackage($packageC = self::getPackage('C', '1.1')); $this->repo->addPackage(self::getPackage('D', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('<', '1.1'), Link::TYPE_REQUIRE)]); $this->reposComplete(); $this->request->requireName('A'); $this->request->requireName('C'); $this->checkSolverResult([ ['job' => 'remove', 'package' => $packageD], ['job' => 'install', 'package' => $packageB], ['job' => 'install', 'package' => $packageA], ['job' => 'update', 'from' => $oldPackageC, 'to' => $packageC], ]); } public function testSolverThreeAlternativeRequireAndConflict(): void { $this->repo->addPackage($packageA = self::getPackage('A', '2.0')); $this->repo->addPackage($middlePackageB = self::getPackage('B', '1.0')); $this->repo->addPackage($newPackageB = self::getPackage('B', '1.1')); $this->repo->addPackage($oldPackageB = self::getPackage('B', '0.9')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('<', '1.1'), Link::TYPE_REQUIRE)]); $packageA->setConflicts(['b' => new Link('A', 'B', self::getVersionConstraint('<', '1.0'), Link::TYPE_CONFLICT)]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $middlePackageB], ['job' => 'install', 'package' => $packageA], ]); } public function testSolverObsolete(): void { $this->repoLocked->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $packageB->setReplaces(['a' => new Link('B', 'A', new MatchAllConstraint())]); $this->reposComplete(); $this->request->requireName('B'); $this->checkSolverResult([ ['job' => 'remove', 'package' => $packageA], ['job' => 'install', 'package' => $packageB], ]); } public function testInstallOneOfTwoAlternatives(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('A', '1.0')); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageA], ]); } public function testInstallProvider(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageQ = self::getPackage('Q', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageQ->setProvides(['b' => new Link('Q', 'B', self::getVersionConstraint('=', '1.0'), Link::TYPE_PROVIDE)]); $this->reposComplete(); $this->request->requireName('A'); // must explicitly pick the provider, so error in this case self::expectException('Composer\DependencyResolver\SolverProblemsException'); $this->createSolver(); $this->solver->solve($this->request); } public function testSkipReplacerOfExistingPackage(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageQ = self::getPackage('Q', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageQ->setReplaces(['b' => new Link('Q', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE)]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageB], ['job' => 'install', 'package' => $packageA], ]); } public function testNoInstallReplacerOfMissingPackage(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageQ = self::getPackage('Q', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageQ->setReplaces(['b' => new Link('Q', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE)]); $this->reposComplete(); $this->request->requireName('A'); self::expectException('Composer\DependencyResolver\SolverProblemsException'); $this->createSolver(); $this->solver->solve($this->request); } public function testSkipReplacedPackageIfReplacerIsSelected(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageQ = self::getPackage('Q', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageQ->setReplaces(['b' => new Link('Q', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE)]); $this->reposComplete(); $this->request->requireName('A'); $this->request->requireName('Q'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageQ], ['job' => 'install', 'package' => $packageA], ]); } public function testPickOlderIfNewerConflicts(): void { $this->repo->addPackage($packageX = self::getPackage('X', '1.0')); $packageX->setRequires([ 'a' => new Link('X', 'A', self::getVersionConstraint('>=', '2.0.0.0'), Link::TYPE_REQUIRE), 'b' => new Link('X', 'B', self::getVersionConstraint('>=', '2.0.0.0'), Link::TYPE_REQUIRE), ]); $this->repo->addPackage($packageA = self::getPackage('A', '2.0.0')); $this->repo->addPackage($newPackageA = self::getPackage('A', '2.1.0')); $this->repo->addPackage($newPackageB = self::getPackage('B', '2.1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '2.0.0.0'), Link::TYPE_REQUIRE)]); // new package A depends on version of package B that does not exist // => new package A is not installable $newPackageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '2.2.0.0'), Link::TYPE_REQUIRE)]); // add a package S replacing both A and B, so that S and B or S and A cannot be simultaneously installed // but an alternative option for A and B both exists // this creates a more difficult so solve conflict $this->repo->addPackage($packageS = self::getPackage('S', '2.0.0')); $packageS->setReplaces([ 'a' => new Link('S', 'A', self::getVersionConstraint('>=', '2.0.0.0'), Link::TYPE_REPLACE), 'b' => new Link('S', 'B', self::getVersionConstraint('>=', '2.0.0.0'), Link::TYPE_REPLACE), ]); $this->reposComplete(); $this->request->requireName('X'); $this->checkSolverResult([ ['job' => 'install', 'package' => $newPackageB], ['job' => 'install', 'package' => $packageA], ['job' => 'install', 'package' => $packageX], ]); } public function testInstallCircularRequire(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB1 = self::getPackage('B', '0.9')); $this->repo->addPackage($packageB2 = self::getPackage('B', '1.1')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageB2->setRequires(['a' => new Link('B', 'A', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $this->reposComplete(); $this->request->requireName('A'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageB2], ['job' => 'install', 'package' => $packageA], ]); } public function testInstallAlternativeWithCircularRequire(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($packageC = self::getPackage('C', '1.0')); $this->repo->addPackage($packageD = self::getPackage('D', '1.0')); $packageA->setRequires(['b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageB->setRequires(['virtual' => new Link('B', 'Virtual', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE)]); $packageC->setProvides(['virtual' => new Link('C', 'Virtual', self::getVersionConstraint('==', '1.0'), Link::TYPE_PROVIDE)]); $packageD->setProvides(['virtual' => new Link('D', 'Virtual', self::getVersionConstraint('==', '1.0'), Link::TYPE_PROVIDE)]); $packageC->setRequires(['a' => new Link('C', 'A', self::getVersionConstraint('==', '1.0'), Link::TYPE_REQUIRE)]); $packageD->setRequires(['a' => new Link('D', 'A', self::getVersionConstraint('==', '1.0'), Link::TYPE_REQUIRE)]); $this->reposComplete(); $this->request->requireName('A'); $this->request->requireName('C'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageB], ['job' => 'install', 'package' => $packageA], ['job' => 'install', 'package' => $packageC], ]); } /** * 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(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $this->repo->addPackage($packageD = self::getPackage('D', '1.0')); $this->repo->addPackage($packageD2 = self::getPackage('D', '1.1')); $packageA->setRequires([ 'b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE), 'c' => new Link('A', 'C', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REQUIRE), ]); $packageD->setReplaces([ 'b' => new Link('D', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE), 'c' => new Link('D', 'C', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE), ]); $packageD2->setReplaces([ 'b' => new Link('D', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE), 'c' => new Link('D', 'C', self::getVersionConstraint('>=', '1.0'), Link::TYPE_REPLACE), ]); $this->reposComplete(); $this->request->requireName('A'); $this->request->requireName('D'); $this->checkSolverResult([ ['job' => 'install', 'package' => $packageD2], ['job' => 'install', 'package' => $packageA], ]); } public function testIssue265(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '2.0.999999-dev')); $this->repo->addPackage($packageA2 = self::getPackage('A', '2.1-dev')); $this->repo->addPackage($packageA3 = self::getPackage('A', '2.2-dev')); $this->repo->addPackage($packageB1 = self::getPackage('B', '2.0.10')); $this->repo->addPackage($packageB2 = self::getPackage('B', '2.0.9')); $this->repo->addPackage($packageC = self::getPackage('C', '2.0-dev')); $this->repo->addPackage($packageD = self::getPackage('D', '2.0.9')); $packageC->setRequires([ 'a' => new Link('C', 'A', self::getVersionConstraint('>=', '2.0'), Link::TYPE_REQUIRE), 'd' => new Link('C', 'D', self::getVersionConstraint('>=', '2.0'), Link::TYPE_REQUIRE), ]); $packageD->setRequires([ 'a' => new Link('D', 'A', self::getVersionConstraint('>=', '2.1'), Link::TYPE_REQUIRE), 'b' => new Link('D', 'B', self::getVersionConstraint('>=', '2.0-dev'), Link::TYPE_REQUIRE), ]); $packageB1->setRequires(['a' => new Link('B', 'A', self::getVersionConstraint('==', '2.1.0.0-dev'), Link::TYPE_REQUIRE)]); $packageB2->setRequires(['a' => new Link('B', 'A', self::getVersionConstraint('==', '2.1.0.0-dev'), Link::TYPE_REQUIRE)]); $packageB2->setReplaces(['d' => new Link('B', 'D', self::getVersionConstraint('==', '2.0.9.0'), Link::TYPE_REPLACE)]); $this->reposComplete(); $this->request->requireName('C', self::getVersionConstraint('==', '2.0.0.0-dev')); self::expectException('Composer\DependencyResolver\SolverProblemsException'); $this->createSolver(); $this->solver->solve($this->request); } public function testConflictResultEmpty(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '1.0')); $packageA->setConflicts([ 'b' => new Link('A', 'B', self::getVersionConstraint('>=', '1.0'), Link::TYPE_CONFLICT), ]); $this->reposComplete(); $emptyConstraint = new MatchAllConstraint(); $emptyConstraint->setPrettyString('*'); $this->request->requireName('A', $emptyConstraint);
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/RuleSetTest.php
tests/Composer/Test/DependencyResolver/RuleSetTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\GenericRule; use Composer\DependencyResolver\Rule; use Composer\DependencyResolver\RuleSet; use Composer\DependencyResolver\Pool; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Semver\Constraint\MatchNoneConstraint; use Composer\Test\TestCase; class RuleSetTest extends TestCase { public function testAdd(): void { $rules = [ RuleSet::TYPE_PACKAGE => [], RuleSet::TYPE_REQUEST => [ new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), new GenericRule([2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), ], RuleSet::TYPE_LEARNED => [ new GenericRule([], Rule::RULE_LEARNED, 1), ], ]; $ruleSet = new RuleSet; $ruleSet->add($rules[RuleSet::TYPE_REQUEST][0], RuleSet::TYPE_REQUEST); $ruleSet->add($rules[RuleSet::TYPE_LEARNED][0], RuleSet::TYPE_LEARNED); $ruleSet->add($rules[RuleSet::TYPE_REQUEST][1], RuleSet::TYPE_REQUEST); self::assertEquals($rules, $ruleSet->getRules()); } public function testAddIgnoresDuplicates(): void { $rules = [ RuleSet::TYPE_REQUEST => [ new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), ], ]; $ruleSet = new RuleSet; $ruleSet->add($rules[RuleSet::TYPE_REQUEST][0], RuleSet::TYPE_REQUEST); $ruleSet->add($rules[RuleSet::TYPE_REQUEST][1], RuleSet::TYPE_REQUEST); $ruleSet->add($rules[RuleSet::TYPE_REQUEST][2], RuleSet::TYPE_REQUEST); self::assertCount(1, $ruleSet->getIteratorFor([RuleSet::TYPE_REQUEST])); } public function testAddWhenTypeIsNotRecognized(): void { $ruleSet = new RuleSet; self::expectException('OutOfBoundsException'); // @phpstan-ignore argument.type $ruleSet->add(new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), 7); } public function testCount(): void { $ruleSet = new RuleSet; $ruleSet->add(new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), RuleSet::TYPE_REQUEST); $ruleSet->add(new GenericRule([2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]), RuleSet::TYPE_REQUEST); self::assertEquals(2, $ruleSet->count()); } public function testRuleById(): void { $ruleSet = new RuleSet; $rule = new GenericRule([], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $ruleSet->add($rule, RuleSet::TYPE_REQUEST); self::assertSame($rule, $ruleSet->ruleById[0]); } public function testGetIterator(): void { $ruleSet = new RuleSet; $rule1 = new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $ruleSet->add($rule1, RuleSet::TYPE_REQUEST); $ruleSet->add($rule2, RuleSet::TYPE_LEARNED); $iterator = $ruleSet->getIterator(); self::assertSame($rule1, $iterator->current()); $iterator->next(); self::assertSame($rule2, $iterator->current()); } public function testGetIteratorFor(): void { $ruleSet = new RuleSet; $rule1 = new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $ruleSet->add($rule1, RuleSet::TYPE_REQUEST); $ruleSet->add($rule2, RuleSet::TYPE_LEARNED); $iterator = $ruleSet->getIteratorFor(RuleSet::TYPE_LEARNED); self::assertSame($rule2, $iterator->current()); } public function testGetIteratorWithout(): void { $ruleSet = new RuleSet; $rule1 = new GenericRule([1], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $rule2 = new GenericRule([2], Rule::RULE_ROOT_REQUIRE, ['packageName' => '', 'constraint' => new MatchAllConstraint]); $ruleSet->add($rule1, RuleSet::TYPE_REQUEST); $ruleSet->add($rule2, RuleSet::TYPE_LEARNED); $iterator = $ruleSet->getIteratorWithout(RuleSet::TYPE_REQUEST); self::assertSame($rule2, $iterator->current()); } public function testPrettyString(): void { $pool = new Pool([ $p = self::getPackage('foo', '2.1'), ]); $repositorySetMock = $this->getMockBuilder('Composer\Repository\RepositorySet')->disableOriginalConstructor()->getMock(); $requestMock = $this->getMockBuilder('Composer\DependencyResolver\Request')->disableOriginalConstructor()->getMock(); $ruleSet = new RuleSet; $literal = $p->getId(); $rule = new GenericRule([$literal], Rule::RULE_ROOT_REQUIRE, ['packageName' => 'foo/bar', 'constraint' => new MatchNoneConstraint]); $ruleSet->add($rule, RuleSet::TYPE_REQUEST); self::assertStringContainsString('REQUEST : No package found to satisfy root composer.json require foo/bar', $ruleSet->getPrettyString($repositorySetMock, $requestMock, $pool)); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php
tests/Composer/Test/DependencyResolver/DefaultPolicyTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\Repository\ArrayRepository; use Composer\Repository\LockArrayRepository; use Composer\DependencyResolver\DefaultPolicy; use Composer\Package\Link; use Composer\Package\AliasPackage; use Composer\Repository\RepositorySet; use Composer\Semver\Constraint\Constraint; use Composer\Test\TestCase; use Composer\Util\Platform; class DefaultPolicyTest extends TestCase { /** @var RepositorySet */ protected $repositorySet; /** @var ArrayRepository */ protected $repo; /** @var LockArrayRepository */ protected $repoLocked; /** @var DefaultPolicy */ protected $policy; public function setUp(): void { $this->repositorySet = new RepositorySet('dev'); $this->repo = new ArrayRepository; $this->repoLocked = new LockArrayRepository; $this->policy = new DefaultPolicy; } protected function tearDown(): void { Platform::clearEnv('COMPOSER_PREFER_DEV_OVER_PRERELEASE'); } public function testSelectSingle(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA->getId()]; $expected = [$packageA->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewest(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '2.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA2->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestPicksLatest(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.0.1-alpha')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA2->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestPicksLatestStableWithPreferStable(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.0.1-alpha')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA1->getId()]; $policy = new DefaultPolicy(true); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } /** * @testWith ["alpha1"] * ["beta1"] * ["RC1"] */ public function testSelectLowestWithPreferDevOverPrerelease(string $stability): void { Platform::putEnv('COMPOSER_PREFER_DEV_OVER_PRERELEASE', '1'); $this->repo->addPackage($devPackage = self::getPackage('A', 'dev-master')); $this->repo->addPackage($prereleasePackage = self::getPackage('A', '1.0.0-' . $stability)); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$devPackage->getId(), $prereleasePackage->getId()]; $expected = [$devPackage->getId()]; $policy = new DefaultPolicy(true, true); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } /** * @testWith ["alpha1"] * ["beta1"] * ["RC1"] */ public function testSelectLowestPrefersPrereleaseOverDev(string $stability): void { $this->repo->addPackage($devPackage = self::getPackage('A', 'dev-master')); $this->repo->addPackage($prereleasePackage = self::getPackage('A', '1.0.0-' . $stability)); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$prereleasePackage->getId(), $devPackage->getId()]; $expected = [$prereleasePackage->getId()]; $policy = new DefaultPolicy(true, true); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectLowestWithPreferStableStillPrefersStable(): void { Platform::putEnv('COMPOSER_PREFER_DEV_OVER_PRERELEASE', '1'); $this->repo->addPackage($stablePackage = self::getPackage('A', '1.0.0')); $this->repo->addPackage($devPackage = self::getPackage('A', 'dev-master')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$stablePackage->getId(), $devPackage->getId()]; $expected = [$stablePackage->getId()]; $policy = new DefaultPolicy(true, true); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestWithDevPicksNonDev(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', 'dev-foo')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.0.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA2->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestWithPreferredVersionPicksPreferredVersionIfAvailable(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.1.0')); $this->repo->addPackage($packageA2b = self::getPackage('A', '1.1.0')); $this->repo->addPackage($packageA3 = self::getPackage('A', '1.2.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId(), $packageA2b->getId(), $packageA3->getId()]; $expected = [$packageA2->getId(), $packageA2b->getId()]; $policy = new DefaultPolicy(false, false, ['a' => '1.1.0.0']); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestWithPreferredVersionPicksNewestOtherwise(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.2.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA2->getId()]; $policy = new DefaultPolicy(false, false, ['a' => '1.1.0.0']); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectNewestWithPreferredVersionPicksLowestIfPreferLowest(): void { $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '1.2.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA1->getId()]; $policy = new DefaultPolicy(false, true, ['a' => '1.1.0.0']); $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testRepositoryOrderingAffectsPriority(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; $repo1->addPackage($package1 = self::getPackage('A', '1.0')); $repo1->addPackage($package2 = self::getPackage('A', '1.1')); $repo2->addPackage($package3 = self::getPackage('A', '1.1')); $repo2->addPackage($package4 = self::getPackage('A', '1.2')); $this->repositorySet->addRepository($repo1); $this->repositorySet->addRepository($repo2); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$package1->getId(), $package2->getId(), $package3->getId(), $package4->getId()]; $expected = [$package2->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); $this->repositorySet = new RepositorySet('dev'); $this->repositorySet->addRepository($repo2); $this->repositorySet->addRepository($repo1); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $expected = [$package4->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectLocalReposFirst(): void { $repoImportant = new ArrayRepository; $this->repo->addPackage($packageA = self::getPackage('A', 'dev-master')); $this->repo->addPackage($packageAAlias = new AliasPackage($packageA, '2.1.9999999.9999999-dev', '2.1.x-dev')); $repoImportant->addPackage($packageAImportant = self::getPackage('A', 'dev-feature-a')); $repoImportant->addPackage($packageAAliasImportant = new AliasPackage($packageAImportant, '2.1.9999999.9999999-dev', '2.1.x-dev')); $repoImportant->addPackage($packageA2Important = self::getPackage('A', 'dev-master')); $repoImportant->addPackage($packageA2AliasImportant = new AliasPackage($packageA2Important, '2.1.9999999.9999999-dev', '2.1.x-dev')); $packageAAliasImportant->setRootPackageAlias(true); $this->repositorySet->addRepository($repoImportant); $this->repositorySet->addRepository($this->repo); $this->repositorySet->addRepository($this->repoLocked); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $packages = $pool->whatProvides('a', new Constraint('=', '2.1.9999999.9999999-dev')); self::assertNotEmpty($packages); $literals = []; foreach ($packages as $package) { $literals[] = $package->getId(); } $expected = [$packageAAliasImportant->getId()]; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testSelectAllProviders(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '2.0')); $packageA->setProvides(['x' => new Link('A', 'X', new Constraint('==', '1.0'), Link::TYPE_PROVIDE)]); $packageB->setProvides(['x' => new Link('B', 'X', new Constraint('==', '1.0'), Link::TYPE_PROVIDE)]); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackages(['A', 'B'], $this->repoLocked); $literals = [$packageA->getId(), $packageB->getId()]; $expected = $literals; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testPreferNonReplacingFromSameRepo(): void { $this->repo->addPackage($packageA = self::getPackage('A', '1.0')); $this->repo->addPackage($packageB = self::getPackage('B', '2.0')); $packageB->setReplaces(['a' => new Link('B', 'A', new Constraint('==', '1.0'), Link::TYPE_REPLACE)]); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackages(['A', 'B'], $this->repoLocked); $literals = [$packageA->getId(), $packageB->getId()]; $expected = $literals; $selected = $this->policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } public function testPreferReplacingPackageFromSameVendor(): void { // test with default order $this->repo->addPackage($packageB = self::getPackage('vendor-b/replacer', '1.0')); $this->repo->addPackage($packageA = self::getPackage('vendor-a/replacer', '1.0')); $packageA->setReplaces(['vendor-a/package' => new Link('vendor-a/replacer', 'vendor-a/package', new Constraint('==', '1.0'), Link::TYPE_REPLACE)]); $packageB->setReplaces(['vendor-a/package' => new Link('vendor-b/replacer', 'vendor-a/package', new Constraint('==', '1.0'), Link::TYPE_REPLACE)]); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackages(['vendor-a/replacer', 'vendor-b/replacer'], $this->repoLocked); $literals = [$packageA->getId(), $packageB->getId()]; $expected = $literals; $selected = $this->policy->selectPreferredPackages($pool, $literals, 'vendor-a/package'); self::assertEquals($expected, $selected); // test with reversed order in repo $repo = new ArrayRepository; $repo->addPackage($packageA = clone $packageA); $repo->addPackage($packageB = clone $packageB); $repositorySet = new RepositorySet('dev'); $repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackages(['vendor-a/replacer', 'vendor-b/replacer'], $this->repoLocked); $literals = [$packageA->getId(), $packageB->getId()]; $expected = $literals; $selected = $this->policy->selectPreferredPackages($pool, $literals, 'vendor-a/package'); self::assertSame($expected, $selected); } public function testSelectLowest(): void { $policy = new DefaultPolicy(false, true); $this->repo->addPackage($packageA1 = self::getPackage('A', '1.0')); $this->repo->addPackage($packageA2 = self::getPackage('A', '2.0')); $this->repositorySet->addRepository($this->repo); $pool = $this->repositorySet->createPoolForPackage('A', $this->repoLocked); $literals = [$packageA1->getId(), $packageA2->getId()]; $expected = [$packageA1->getId()]; $selected = $policy->selectPreferredPackages($pool, $literals); self::assertSame($expected, $selected); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/RequestTest.php
tests/Composer/Test/DependencyResolver/RequestTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\Request; use Composer\Repository\ArrayRepository; use Composer\Semver\Constraint\MatchAllConstraint; use Composer\Test\TestCase; class RequestTest extends TestCase { public function testRequestInstall(): void { $repo = new ArrayRepository; $foo = self::getPackage('foo', '1'); $bar = self::getPackage('bar', '1'); $foobar = self::getPackage('foobar', '1'); $repo->addPackage($foo); $repo->addPackage($bar); $repo->addPackage($foobar); $request = new Request(); $request->requireName('foo'); self::assertEquals( [ 'foo' => new MatchAllConstraint(), ], $request->getRequires() ); } public function testRequestInstallSamePackageFromDifferentRepositories(): void { $repo1 = new ArrayRepository; $repo2 = new ArrayRepository; $foo1 = self::getPackage('foo', '1'); $foo2 = self::getPackage('foo', '1'); $repo1->addPackage($foo1); $repo2->addPackage($foo2); $request = new Request(); $request->requireName('foo', $constraint = self::getVersionConstraint('=', '1')); self::assertEquals( [ 'foo' => $constraint, ], $request->getRequires() ); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/SecurityAdvisoryPoolFilterTest.php
tests/Composer/Test/DependencyResolver/SecurityAdvisoryPoolFilterTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\Advisory\AuditConfig; use Composer\Advisory\Auditor; use Composer\DependencyResolver\Pool; use Composer\DependencyResolver\Request; use Composer\DependencyResolver\SecurityAdvisoryPoolFilter; use Composer\Package\CompletePackage; use Composer\Package\Package; use Composer\Repository\PackageRepository; use Composer\Semver\Constraint\Constraint; use Composer\Test\TestCase; class SecurityAdvisoryPoolFilterTest extends TestCase { public function testFilterPackagesByAdvisories(): void { $auditConfig = new AuditConfig(true, Auditor::FORMAT_SUMMARY, Auditor::ABANDONED_FAIL, true, true, false, [], [], [], [], [], []); $filter = new SecurityAdvisoryPoolFilter(new Auditor(), $auditConfig); $repository = new PackageRepository([ 'package' => [], 'security-advisories' => [ 'acme/package' => [ $advisory1 = $this->generateSecurityAdvisory('acme/package', 'CVE-1999-1000', '>=1.0.0,<1.1.0'), $advisory2 = $this->generateSecurityAdvisory('acme/package', 'CVE-1999-1001', '>=1.0.0,<1.1.0'), ], ], ]); $pool = new Pool([ new Package('acme/package', '1.0.0.0', '1.0'), $expectedPackage1 = new Package('acme/package', '2.0.0.0', '2.0'), $expectedPackage2 = new Package('acme/other', '1.0.0.0', '1.0'), ]); $filteredPool = $filter->filter($pool, [$repository], new Request()); $this->assertSame([$expectedPackage1, $expectedPackage2], $filteredPool->getPackages()); $this->assertTrue($filteredPool->isSecurityRemovedPackageVersion('acme/package', new Constraint('==', '1.0.0.0'))); $this->assertCount(0, $filteredPool->getAllAbandonedRemovedPackageVersions()); $advisoryMap = $filteredPool->getAllSecurityRemovedPackageVersions(); $this->assertArrayHasKey('acme/package', $advisoryMap); $this->assertArrayHasKey('1.0.0.0', $advisoryMap['acme/package']); $this->assertSame([$advisory1['advisoryId'], $advisory2['advisoryId']], $filteredPool->getSecurityAdvisoryIdentifiersForPackageVersion('acme/package', new Constraint('==', '1.0.0.0'))); } public function testDontFilterPackagesByIgnoredAdvisories(): void { $auditConfig = new AuditConfig(true, Auditor::FORMAT_SUMMARY, Auditor::ABANDONED_FAIL, true, true, false, ['CVE-2024-1234' => null], ['CVE-2024-1234' => null], [], [], [], []); $filter = new SecurityAdvisoryPoolFilter(new Auditor(), $auditConfig); $repository = new PackageRepository([ 'package' => [], 'security-advisories' => [ 'acme/package' => [$this->generateSecurityAdvisory('acme/package', 'CVE-2024-1234', '>=1.0.0,<1.1.0')], ], ]); $pool = new Pool([ $expectedPackage1 = new Package('acme/package', '1.0.0.0', '1.0'), $expectedPackage2 = new Package('acme/package', '1.1.0.0', '1.1'), ]); $filteredPool = $filter->filter($pool, [$repository], new Request()); $this->assertSame([$expectedPackage1, $expectedPackage2], $filteredPool->getPackages()); $this->assertCount(0, $filteredPool->getAllAbandonedRemovedPackageVersions()); $this->assertCount(0, $filteredPool->getAllSecurityRemovedPackageVersions()); } public function testDontFilterPackagesWithBlockInsecureDisabled(): void { $auditConfig = new AuditConfig(true, Auditor::FORMAT_SUMMARY, Auditor::ABANDONED_FAIL, false, true, false, [], [], [], [], [], []); $filter = new SecurityAdvisoryPoolFilter(new Auditor(), $auditConfig); $repository = new PackageRepository([ 'package' => [], 'security-advisories' => [ 'acme/package' => [$this->generateSecurityAdvisory('acme/package', 'CVE-2024-1234', '>=1.0.0,<1.1.0')], ], ]); $pool = new Pool([ $expectedPackage1 = new Package('acme/package', '1.0.0.0', '1.0'), $expectedPackage2 = new Package('acme/package', '1.1.0.0', '1.1'), ]); $filteredPool = $filter->filter($pool, [$repository], new Request()); $this->assertSame([$expectedPackage1, $expectedPackage2], $filteredPool->getPackages()); $this->assertCount(0, $filteredPool->getAllAbandonedRemovedPackageVersions()); $this->assertCount(0, $filteredPool->getAllSecurityRemovedPackageVersions()); } public function testDontFilterPackagesWithAbandonedPackage(): void { $packageNameIgnoreAbandoned = 'acme/ignore-abandoned'; $auditConfig = new AuditConfig(true, Auditor::FORMAT_SUMMARY, Auditor::ABANDONED_FAIL, true, true, false, [], [], [], [], [$packageNameIgnoreAbandoned => null], [$packageNameIgnoreAbandoned => null]); $filter = new SecurityAdvisoryPoolFilter(new Auditor(), $auditConfig); $abandonedPackage = new CompletePackage('acme/package', '1.0.0.0', '1.0'); $abandonedPackage->setAbandoned(true); $ignoreAbandonedPackage = new CompletePackage($packageNameIgnoreAbandoned, '1.0.0.0', '1.0'); $ignoreAbandonedPackage->setAbandoned(true); $expectedPackage = new Package('acme/other', '1.1.0.0', '1.1'); $pool = new Pool([ $expectedPackage, $abandonedPackage, $ignoreAbandonedPackage, ]); $filteredPool = $filter->filter($pool, [], new Request()); $this->assertSame([$expectedPackage, $ignoreAbandonedPackage], $filteredPool->getPackages()); $this->assertCount(1, $filteredPool->getAllAbandonedRemovedPackageVersions()); $this->assertCount(0, $filteredPool->getAllSecurityRemovedPackageVersions()); } /** * @return array<string, mixed> */ private function generateSecurityAdvisory(string $packageName, ?string $cve, string $affectedVersions): array { return [ 'advisoryId' => uniqid('PKSA-'), 'packageName' => $packageName, 'remoteId' => 'test', 'title' => 'Security Advisory', 'link' => null, 'cve' => $cve, 'affectedVersions' => $affectedVersions, 'source' => 'Tests', 'reportedAt' => '2024-04-31 12:37:47', 'composerRepository' => 'Package Repository', 'severity' => 'high', 'sources' => [ [ 'name' => 'Security Advisory', 'remoteId' => 'test', ], ], ]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/DependencyResolver/TransactionTest.php
tests/Composer/Test/DependencyResolver/TransactionTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\DependencyResolver; use Composer\DependencyResolver\Operation\InstallOperation; use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation; use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation; use Composer\DependencyResolver\Operation\UninstallOperation; use Composer\DependencyResolver\Operation\UpdateOperation; use Composer\DependencyResolver\Transaction; use Composer\Package\Link; use Composer\Package\PackageInterface; use Composer\Test\TestCase; class TransactionTest extends TestCase { public function setUp(): void { } public function testTransactionGenerationAndSorting(): void { $presentPackages = [ $packageA = self::getPackage('a/a', 'dev-master'), $packageAalias = self::getAliasPackage($packageA, '1.0.x-dev'), $packageB = self::getPackage('b/b', '1.0.0'), $packageE = self::getPackage('e/e', 'dev-foo'), $packageEalias = self::getAliasPackage($packageE, '1.0.x-dev'), $packageC = self::getPackage('c/c', '1.0.0'), ]; $resultPackages = [ $packageA, $packageAalias, $packageBnew = self::getPackage('b/b', '2.1.3'), $packageD = self::getPackage('d/d', '1.2.3'), $packageF = self::getPackage('f/f', '1.0.0'), $packageFalias1 = self::getAliasPackage($packageF, 'dev-foo'), $packageG = self::getPackage('g/g', '1.0.0'), $packageA0first = self::getPackage('a0/first', '1.2.3'), $packageFalias2 = self::getAliasPackage($packageF, 'dev-bar'), $plugin = self::getPackage('x/plugin', '1.0.0'), $plugin2Dep = self::getPackage('x/plugin2-dep', '1.0.0'), $plugin2 = self::getPackage('x/plugin2', '1.0.0'), $dlModifyingPlugin = self::getPackage('x/downloads-modifying', '1.0.0'), $dlModifyingPlugin2Dep = self::getPackage('x/downloads-modifying2-dep', '1.0.0'), $dlModifyingPlugin2 = self::getPackage('x/downloads-modifying2', '1.0.0'), ]; $plugin->setType('composer-installer'); foreach ([$plugin2, $dlModifyingPlugin, $dlModifyingPlugin2] as $pluginPackage) { $pluginPackage->setType('composer-plugin'); } $plugin2->setRequires([ 'x/plugin2-dep' => new Link('x/plugin2', 'x/plugin2-dep', self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE), ]); $dlModifyingPlugin2->setRequires([ 'x/downloads-modifying2-dep' => new Link('x/downloads-modifying2', 'x/downloads-modifying2-dep', self::getVersionConstraint('=', '1.0.0'), Link::TYPE_REQUIRE), ]); $dlModifyingPlugin->setExtra(['plugin-modifies-downloads' => true]); $dlModifyingPlugin2->setExtra(['plugin-modifies-downloads' => true]); $packageD->setRequires([ 'f/f' => new Link('d/d', 'f/f', self::getVersionConstraint('>', '0.2'), Link::TYPE_REQUIRE), 'g/provider' => new Link('d/d', 'g/provider', self::getVersionConstraint('>', '0.2'), Link::TYPE_REQUIRE), ]); $packageG->setProvides(['g/provider' => new Link('g/g', 'g/provider', self::getVersionConstraint('==', '1.0.0'), Link::TYPE_PROVIDE)]); $expectedOperations = [ ['job' => 'uninstall', 'package' => $packageC], ['job' => 'uninstall', 'package' => $packageE], ['job' => 'markAliasUninstalled', 'package' => $packageEalias], ['job' => 'install', 'package' => $dlModifyingPlugin], ['job' => 'install', 'package' => $dlModifyingPlugin2Dep], ['job' => 'install', 'package' => $dlModifyingPlugin2], ['job' => 'install', 'package' => $plugin], ['job' => 'install', 'package' => $plugin2Dep], ['job' => 'install', 'package' => $plugin2], ['job' => 'install', 'package' => $packageA0first], ['job' => 'update', 'from' => $packageB, 'to' => $packageBnew], ['job' => 'install', 'package' => $packageG], ['job' => 'install', 'package' => $packageF], ['job' => 'markAliasInstalled', 'package' => $packageFalias2], ['job' => 'markAliasInstalled', 'package' => $packageFalias1], ['job' => 'install', 'package' => $packageD], ]; $transaction = new Transaction($presentPackages, $resultPackages); $this->checkTransactionOperations($transaction, $expectedOperations); } /** * @param array<array{job: string, package?: PackageInterface, from?: PackageInterface, to?: PackageInterface}> $expected */ protected function checkTransactionOperations(Transaction $transaction, array $expected): void { $result = []; foreach ($transaction->getOperations() as $operation) { if ($operation instanceof UpdateOperation) { $result[] = [ 'job' => 'update', 'from' => $operation->getInitialPackage(), 'to' => $operation->getTargetPackage(), ]; } elseif ($operation instanceof InstallOperation || $operation instanceof UninstallOperation || $operation instanceof MarkAliasInstalledOperation || $operation instanceof MarkAliasUninstalledOperation) { $result[] = [ 'job' => $operation->getOperationType(), 'package' => $operation->getPackage(), ]; } else { throw new \UnexpectedValueException('Unknown operation type: '.get_class($operation)); } } self::assertEquals($expected, $result); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Advisory/AuditConfigTest.php
tests/Composer/Test/Advisory/AuditConfigTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Advisory; use Composer\Advisory\AuditConfig; use Composer\Advisory\Auditor; use Composer\Config; use Composer\Test\TestCase; class AuditConfigTest extends TestCase { public function testSimpleFormat(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore' => ['CVE-2024-1234', 'CVE-2024-5678'], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['CVE-2024-1234' => null, 'CVE-2024-5678' => null], $auditConfig->ignoreListForAudit); $this->assertSame(['CVE-2024-1234' => null, 'CVE-2024-5678' => null], $auditConfig->ignoreListForBlocking); } public function testDetailedFormatAuditOnly(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore' => [ 'CVE-2024-1234' => [ 'apply' => 'audit', 'reason' => 'Only ignore for auditing', ], ], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['CVE-2024-1234' => 'Only ignore for auditing'], $auditConfig->ignoreListForAudit); $this->assertSame([], $auditConfig->ignoreListForBlocking); } public function testDetailedFormatBlockOnly(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore' => [ 'CVE-2024-1234' => [ 'apply' => 'block', 'reason' => 'Only ignore for blocking', ], ], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame([], $auditConfig->ignoreListForAudit); $this->assertSame(['CVE-2024-1234' => 'Only ignore for blocking'], $auditConfig->ignoreListForBlocking); } public function testMixedFormats(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore' => [ 'CVE-2024-1234', 'CVE-2024-5678' => 'Simple reason', 'CVE-2024-9999' => [ 'apply' => 'audit', 'reason' => 'Detailed reason', ], 'CVE-2024-8888' => [ 'apply' => 'block', ], ], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame([ 'CVE-2024-1234' => null, 'CVE-2024-5678' => 'Simple reason', 'CVE-2024-9999' => 'Detailed reason', ], $auditConfig->ignoreListForAudit); $this->assertSame([ 'CVE-2024-1234' => null, 'CVE-2024-5678' => 'Simple reason', 'CVE-2024-8888' => null, ], $auditConfig->ignoreListForBlocking); } public function testIgnoreSeveritySimpleArray(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore-severity' => ['low', 'medium'], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['low' => null, 'medium' => null], $auditConfig->ignoreSeverityForAudit); $this->assertSame(['low' => null, 'medium' => null], $auditConfig->ignoreSeverityForBlocking); } public function testIgnoreSeverityDetailedFormat(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore-severity' => [ 'low' => [ 'apply' => 'audit', 'reason' => 'We accept low severity issues', ], 'medium' => [ 'apply' => 'block', ], ], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['low' => 'We accept low severity issues'], $auditConfig->ignoreSeverityForAudit); $this->assertSame(['medium' => null], $auditConfig->ignoreSeverityForBlocking); } public function testIgnoreAbandonedSimpleFormat(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore-abandoned' => ['vendor/package1', 'vendor/package2'], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['vendor/package1' => null, 'vendor/package2' => null], $auditConfig->ignoreAbandonedForAudit); $this->assertSame(['vendor/package1' => null, 'vendor/package2' => null], $auditConfig->ignoreAbandonedForBlocking); } public function testIgnoreAbandonedDetailedFormat(): void { $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore-abandoned' => [ 'vendor/package1' => [ 'apply' => 'audit', 'reason' => 'Report but do not block', ], 'vendor/package2' => [ 'apply' => 'block', 'reason' => 'Block but do not report', ], ], ], ], ]); $auditConfig = AuditConfig::fromConfig($config); $this->assertSame(['vendor/package1' => 'Report but do not block'], $auditConfig->ignoreAbandonedForAudit); $this->assertSame(['vendor/package2' => 'Block but do not report'], $auditConfig->ignoreAbandonedForBlocking); } public function testInvalidApplyValue(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Invalid 'apply' value for 'CVE-2024-1234': invalid. Expected 'audit', 'block', or 'all'."); $config = new Config(); $config->merge([ 'config' => [ 'audit' => [ 'ignore' => [ 'CVE-2024-1234' => [ 'apply' => 'invalid', ], ], ], ], ]); AuditConfig::fromConfig($config); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Advisory/AuditorTest.php
tests/Composer/Test/Advisory/AuditorTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Advisory; use Composer\Advisory\AuditConfig; use Composer\Advisory\PartialSecurityAdvisory; use Composer\Advisory\SecurityAdvisory; use Composer\IO\BufferIO; use Composer\Package\CompletePackage; use Composer\Package\Package; use Composer\Package\Version\VersionParser; use Composer\Repository\ComposerRepository; use Composer\Repository\RepositorySet; use Composer\Semver\Constraint\Constraint; use Composer\Test\TestCase; use Composer\Advisory\Auditor; use DateTimeImmutable; use InvalidArgumentException; class AuditorTest extends TestCase { public static function auditProvider() { yield 'Test no advisories returns 0' => [ 'data' => [ 'packages' => [ new Package('vendor1/package2', '9.0.0', '9.0.0'), new Package('vendor1/package1', '9.0.0', '9.0.0'), new Package('vendor3/package1', '9.0.0', '9.0.0'), ], 'warningOnly' => true, ], 'expected' => Auditor::STATUS_OK, 'output' => 'No security vulnerability advisories found.', ]; yield 'Test with advisories returns 1' => [ 'data' => [ 'packages' => [ new Package('vendor1/package2', '9.0.0', '9.0.0'), new Package('vendor1/package1', '8.2.1', '8.2.1'), new Package('vendor3/package1', '9.0.0', '9.0.0'), ], 'warningOnly' => true, ], 'expected' => Auditor::STATUS_VULNERABLE, 'output' => '<warning>Found 2 security vulnerability advisories affecting 1 package:</warning> Package: vendor1/package1 Severity: high Advisory ID: ID4 CVE: CVE3 Title: advisory4 URL: https://advisory.example.com/advisory4 Affected versions: >=8,<8.2.2|>=1,<2.5.6 Reported at: 2022-05-25T13:21:00+00:00 -------- Package: vendor1/package1 Severity: medium Advisory ID: ID5 CVE: '.' Title: advisory5 URL: https://advisory.example.com/advisory5 Affected versions: >=8,<8.2.2|>=1,<2.5.6 Reported at: 2022-05-25T13:21:00+00:00', ]; $abandonedWithReplacement = new CompletePackage('vendor/abandoned', '1.0.0', '1.0.0'); $abandonedWithReplacement->setAbandoned('foo/bar'); $abandonedNoReplacement = new CompletePackage('vendor/abandoned2', '1.0.0', '1.0.0'); $abandonedNoReplacement->setAbandoned(true); yield 'abandoned packages ignored' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_IGNORE, ], 'expected' => Auditor::STATUS_OK, 'output' => 'No security vulnerability advisories found.', ]; yield 'abandoned packages individually ignored via full vendor' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'ignore-abandoned' => ['vendor/*' => null], ], 'expected' => Auditor::STATUS_OK, 'output' => 'No security vulnerability advisories found.', ]; yield 'abandoned packages individually ignored via package name' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'ignore-abandoned' => [$abandonedWithReplacement->getName() => null, $abandonedNoReplacement->getName() => null], ], 'expected' => Auditor::STATUS_OK, 'output' => 'No security vulnerability advisories found.', ]; yield 'abandoned packages individually ignored not matching package name' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'ignore-abandoned' => ['acme/test' => 'ignoring because yolo'], ], 'expected' => Auditor::STATUS_ABANDONED, 'output' => 'No security vulnerability advisories found. Found 2 abandoned packages: vendor/abandoned is abandoned. Use foo/bar instead. vendor/abandoned2 is abandoned. No replacement was suggested.', ]; yield 'abandoned packages reported only' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => true, 'abandoned' => Auditor::ABANDONED_REPORT, ], 'expected' => Auditor::STATUS_OK, 'output' => 'No security vulnerability advisories found. Found 2 abandoned packages: vendor/abandoned is abandoned. Use foo/bar instead. vendor/abandoned2 is abandoned. No replacement was suggested.', ]; yield 'abandoned packages fails' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'format' => Auditor::FORMAT_TABLE, ], 'expected' => Auditor::STATUS_ABANDONED, 'output' => 'No security vulnerability advisories found. Found 2 abandoned packages: +-------------------+----------------------------------------------------------------------------------+ | Abandoned Package | Suggested Replacement | +-------------------+----------------------------------------------------------------------------------+ | vendor/abandoned | foo/bar | | vendor/abandoned2 | none | +-------------------+----------------------------------------------------------------------------------+', ]; yield 'vulnerable and abandoned packages fails' => [ 'data' => [ 'packages' => [ new Package('vendor1/package1', '8.2.1', '8.2.1'), $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'format' => Auditor::FORMAT_TABLE, ], 'expected' => Auditor::STATUS_VULNERABLE | Auditor::STATUS_ABANDONED, 'output' => 'Found 2 security vulnerability advisories affecting 1 package: +-------------------+----------------------------------------------------------------------------------+ | Package | vendor1/package1 | | Severity | high | | Advisory ID | ID4 | | CVE | CVE3 | | Title | advisory4 | | URL | https://advisory.example.com/advisory4 | | Affected versions | >=8,<8.2.2|>=1,<2.5.6 | | Reported at | 2022-05-25T13:21:00+00:00 | +-------------------+----------------------------------------------------------------------------------+ +-------------------+----------------------------------------------------------------------------------+ | Package | vendor1/package1 | | Severity | medium | | Advisory ID | ID5 | | CVE | | | Title | advisory5 | | URL | https://advisory.example.com/advisory5 | | Affected versions | >=8,<8.2.2|>=1,<2.5.6 | | Reported at | 2022-05-25T13:21:00+00:00 | +-------------------+----------------------------------------------------------------------------------+ Found 2 abandoned packages: +-------------------+----------------------------------------------------------------------------------+ | Abandoned Package | Suggested Replacement | +-------------------+----------------------------------------------------------------------------------+ | vendor/abandoned | foo/bar | | vendor/abandoned2 | none | +-------------------+----------------------------------------------------------------------------------+', ]; yield 'abandoned packages fails with json format' => [ 'data' => [ 'packages' => [ $abandonedWithReplacement, $abandonedNoReplacement, ], 'warningOnly' => false, 'abandoned' => Auditor::ABANDONED_FAIL, 'format' => Auditor::FORMAT_JSON, ], 'expected' => Auditor::STATUS_ABANDONED, 'output' => '{ "advisories": [], "abandoned": { "vendor/abandoned": "foo/bar", "vendor/abandoned2": null } }', ]; } /** * @dataProvider auditProvider * @phpstan-param array<string, mixed> $data */ public function testAudit(array $data, int $expected, string $output): void { if (count($data['packages']) === 0) { $this->expectException(InvalidArgumentException::class); } $auditor = new Auditor(); $result = $auditor->audit($io = new BufferIO(), $this->getRepoSet(), $data['packages'], $data['format'] ?? Auditor::FORMAT_PLAIN, $data['warningOnly'], [], $data['abandoned'] ?? Auditor::ABANDONED_IGNORE, [], false, $data['ignore-abandoned'] ?? []); self::assertSame($expected, $result); self::assertSame($output, trim(str_replace("\r", '', $io->getOutput()))); } public function ignoredIdsProvider(): \Generator { yield 'ignore by CVE' => [ [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ], ['CVE1' => null], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID1'], ['text' => 'CVE: CVE1'], ['text' => 'Title: advisory1'], ['text' => 'URL: https://advisory.example.com/advisory1'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ], ]; yield 'ignore by CVE with reasoning' => [ [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ], ['CVE1' => 'A good reason'], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID1'], ['text' => 'CVE: CVE1'], ['text' => 'Title: advisory1'], ['text' => 'URL: https://advisory.example.com/advisory1'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ['text' => 'Ignore reason: A good reason'], ], ]; yield 'ignore by advisory id' => [ [ new Package('vendor1/package2', '3.0.0.0', '3.0.0'), ], ['ID2' => null], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package2'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID2'], ['text' => 'CVE: '], ['text' => 'Title: advisory2'], ['text' => 'URL: https://advisory.example.com/advisory2'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ], ]; yield 'ignore by remote id' => [ [ new Package('vendorx/packagex', '3.0.0.0', '3.0.0'), ], ['RemoteIDx' => null], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendorx/packagex'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: IDx'], ['text' => 'CVE: CVE5'], ['text' => 'Title: advisory17'], ['text' => 'URL: https://advisory.example.com/advisory17'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2015-05-25T13:21:00+00:00'], ], ]; yield 'ignore by package name' => [ [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ], ['vendor1/package1' => null], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID1'], ['text' => 'CVE: CVE1'], ['text' => 'Title: advisory1'], ['text' => 'URL: https://advisory.example.com/advisory1'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ], ]; yield 'ignore by package name with reasoning' => [ [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ], ['vendor1/package1' => 'Package has known safe usage'], 0, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID1'], ['text' => 'CVE: CVE1'], ['text' => 'Title: advisory1'], ['text' => 'URL: https://advisory.example.com/advisory1'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ['text' => 'Ignore reason: Package has known safe usage'], ], ]; yield '1 vulnerability, 0 ignored' => [ [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ], [], 1, [ ['text' => 'Found 1 security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor1/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID1'], ['text' => 'CVE: CVE1'], ['text' => 'Title: advisory1'], ['text' => 'URL: https://advisory.example.com/advisory1'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ], ]; yield '1 vulnerability, 3 ignored affecting 2 packages' => [ [ new Package('vendor3/package1', '3.0.0.0', '3.0.0'), // RemoteIDx new Package('vendorx/packagex', '3.0.0.0', '3.0.0'), // ID3, ID6 new Package('vendor2/package1', '3.0.0.0', '3.0.0'), ], ['RemoteIDx' => null, 'ID3' => null, 'ID6' => null], 1, [ ['text' => 'Found 3 ignored security vulnerability advisories affecting 2 packages:'], ['text' => 'Package: vendor2/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID3'], ['text' => 'CVE: CVE2'], ['text' => 'Title: advisory3'], ['text' => 'URL: https://advisory.example.com/advisory3'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2022-05-25T13:21:00+00:00'], ['text' => 'Ignore reason: None specified'], ['text' => '--------'], ['text' => 'Package: vendor2/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID6'], ['text' => 'CVE: CVE4'], ['text' => 'Title: advisory6'], ['text' => 'URL: https://advisory.example.com/advisory6'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2015-05-25T13:21:00+00:00'], ['text' => 'Ignore reason: None specified'], ['text' => '--------'], ['text' => 'Package: vendorx/packagex'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: IDx'], ['text' => 'CVE: CVE5'], ['text' => 'Title: advisory17'], ['text' => 'URL: https://advisory.example.com/advisory17'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2015-05-25T13:21:00+00:00'], ['text' => 'Ignore reason: None specified'], ['text' => 'Found 1 security vulnerability advisory affecting 1 package:'], ['text' => 'Package: vendor3/package1'], ['text' => 'Severity: medium'], ['text' => 'Advisory ID: ID7'], ['text' => 'CVE: CVE5'], ['text' => 'Title: advisory7'], ['text' => 'URL: https://advisory.example.com/advisory7'], ['text' => 'Affected versions: >=3,<3.4.3|>=1,<2.5.6'], ['text' => 'Reported at: 2015-05-25T13:21:00+00:00'], ], ]; } /** * @dataProvider ignoredIdsProvider * @phpstan-param array<Package> $packages * @phpstan-param array<string>|array<string,string> $ignoredIds * @phpstan-param 0|positive-int $exitCode * @phpstan-param list<array{text: string, verbosity?: \Composer\IO\IOInterface::*, regex?: true}|array{ask: string, reply: string}|array{auth: array{string, string, string|null}}> $expectedOutput */ public function testAuditWithIgnore($packages, $ignoredIds, $exitCode, $expectedOutput): void { $auditor = new Auditor(); $result = $auditor->audit($io = $this->getIOMock(), $this->getRepoSet(), $packages, Auditor::FORMAT_PLAIN, false, $ignoredIds); $io->expects($expectedOutput, true); self::assertSame($exitCode, $result); } public function ignoreSeverityProvider(): \Generator { yield 'ignore medium' => [ [ new Package('vendor1/package1', '2.0.0.0', '2.0.0'), ], ['medium' => null], 1, [ ['text' => 'Found 2 ignored security vulnerability advisories affecting 1 package:'], ], ]; yield 'ignore high' => [ [ new Package('vendor1/package1', '2.0.0.0', '2.0.0'), ], ['high' => null], 1, [ ['text' => 'Found 1 ignored security vulnerability advisory affecting 1 package:'], ], ]; yield 'ignore high and medium' => [ [ new Package('vendor1/package1', '2.0.0.0', '2.0.0'), ], ['high' => null, 'medium' => null], 0, [ ['text' => 'Found 3 ignored security vulnerability advisories affecting 1 package:'], ], ]; } public function testAuditWithIgnoreUnreachable(): void { $packages = [ new Package('vendor1/package1', '3.0.0.0', '3.0.0'), ]; $errorMessage = 'The "https://example.org/packages.json" file could not be downloaded: HTTP/1.1 404 Not Found'; // Create a mock RepositorySet that simulates multiple repositories with the middle one being unreachable $repoSet = $this->getMockBuilder(RepositorySet::class) ->disableOriginalConstructor() ->onlyMethods(['getMatchingSecurityAdvisories']) ->getMock(); $repoSet->method('getMatchingSecurityAdvisories') ->willReturnCallback(static function ($packages, $allowPartialAdvisories, $ignoreUnreachable) use ($errorMessage) { if (!$ignoreUnreachable) { throw new \Composer\Downloader\TransportException($errorMessage, 404); } // Simulate multiple repositories with the middle one being unreachable // First and third repositories have advisories, middle one is unreachable return [ 'advisories' => [ 'vendor1/package1' => [ new SecurityAdvisory( 'vendor1/package1', 'CVE-2023-12345', new \Composer\Semver\Constraint\Constraint('=', '3.0.0.0'), 'First repo advisory', [['name' => 'test', 'remoteId' => '1']], new \DateTimeImmutable('2023-01-01', new \DateTimeZone('UTC')), 'CVE-2023-12345', 'https://example.com/advisory/1', 'medium' ), new SecurityAdvisory( 'vendor1/package1', 'CVE-2023-67890', new \Composer\Semver\Constraint\Constraint('=', '3.0.0.0'), 'Third repo advisory', [['name' => 'test', 'remoteId' => '3']], new \DateTimeImmutable('2023-01-01', new \DateTimeZone('UTC')), 'CVE-2023-67890', 'https://example.com/advisory/3', 'high' ), ], ], 'unreachableRepos' => [$errorMessage], ]; }); $auditor = new Auditor(); // Test without ignoreUnreachable flag try { $auditor->audit(new BufferIO(), $repoSet, $packages, Auditor::FORMAT_PLAIN, false); self::fail('Expected TransportException was not thrown'); } catch (\Composer\Downloader\TransportException $e) { self::assertStringContainsString('HTTP/1.1 404 Not Found', $e->getMessage()); } // Test with ignoreUnreachable flag $io = new BufferIO(); $result = $auditor->audit($io, $repoSet, $packages, Auditor::FORMAT_PLAIN, false, [], Auditor::ABANDONED_IGNORE, [], true); // Should find advisories from the reachable repositories self::assertSame(Auditor::STATUS_VULNERABLE, $result); $output = $io->getOutput(); self::assertStringContainsString('The following repositories were unreachable:', $output); self::assertStringContainsString('HTTP/1.1 404 Not Found', $output); // Verify that advisories from reachable repositories were found self::assertStringContainsString('First repo advisory', $output); self::assertStringContainsString('Third repo advisory', $output); self::assertStringContainsString('CVE-2023-12345', $output); self::assertStringContainsString('CVE-2023-67890', $output); // Test with JSON format $io = new BufferIO(); $result = $auditor->audit($io, $repoSet, $packages, Auditor::FORMAT_JSON, false, [], Auditor::ABANDONED_IGNORE, [], true); self::assertSame(Auditor::STATUS_VULNERABLE, $result); $json = json_decode($io->getOutput(), true); self::assertArrayHasKey('unreachable-repositories', $json); self::assertCount(1, $json['unreachable-repositories']); self::assertStringContainsString('HTTP/1.1 404 Not Found', $json['unreachable-repositories'][0]); // Verify that advisories from reachable repositories were included in JSON output self::assertArrayHasKey('advisories', $json); self::assertArrayHasKey('vendor1/package1', $json['advisories']); self::assertCount(2, $json['advisories']['vendor1/package1']); // Check first advisory self::assertSame('CVE-2023-12345', $json['advisories']['vendor1/package1'][0]['cve']); self::assertSame('First repo advisory', $json['advisories']['vendor1/package1'][0]['title']); // Check second advisory self::assertSame('CVE-2023-67890', $json['advisories']['vendor1/package1'][1]['cve']); self::assertSame('Third repo advisory', $json['advisories']['vendor1/package1'][1]['title']); } /** * @dataProvider ignoreSeverityProvider * @phpstan-param array<Package> $packages * @phpstan-param array<string> $ignoredSeverities * @phpstan-param 0|positive-int $exitCode * @phpstan-param list<array{text: string, verbosity?: \Composer\IO\IOInterface::*, regex?: true}|array{ask: string, reply: string}|array{auth: array{string, string, string|null}}> $expectedOutput */ public function testAuditWithIgnoreSeverity($packages, $ignoredSeverities, $exitCode, $expectedOutput): void { $auditor = new Auditor(); $result = $auditor->audit($io = $this->getIOMock(), $this->getRepoSet(), $packages, Auditor::FORMAT_PLAIN, false, [], Auditor::ABANDONED_IGNORE, $ignoredSeverities); $io->expects($expectedOutput, true); self::assertSame($exitCode, $result); } private function getRepoSet(): RepositorySet { $repo = $this ->getMockBuilder(ComposerRepository::class) ->disableOriginalConstructor() ->onlyMethods(['hasSecurityAdvisories', 'getSecurityAdvisories']) ->getMock(); $repoSet = new RepositorySet(); $repoSet->addRepository($repo); $repo ->method('hasSecurityAdvisories') ->willReturn(true); $repo ->method('getSecurityAdvisories') ->willReturnCallback(static function (array $packageConstraintMap, bool $allowPartialAdvisories) { $advisories = []; $parser = new VersionParser(); /** * @param array<mixed> $data * @param string $name * @return ($allowPartialAdvisories is false ? SecurityAdvisory|null : PartialSecurityAdvisory|SecurityAdvisory|null) */ $create = static function (array $data, string $name) use ($parser, $allowPartialAdvisories, $packageConstraintMap): ?PartialSecurityAdvisory { $advisory = PartialSecurityAdvisory::create($name, $data, $parser); if (!$allowPartialAdvisories && !$advisory instanceof SecurityAdvisory) { throw new \RuntimeException('Advisory for '.$name.' could not be loaded as a full advisory from test repo'); } if (!$advisory->affectedVersions->matches($packageConstraintMap[$name])) { return null; } return $advisory; }; foreach (self::getMockAdvisories() as $package => $list) { if (!isset($packageConstraintMap[$package])) { continue; } $advisories[$package] = array_filter(array_map( static function ($data) use ($package, $create) { return $create($data, $package); }, $list )); } return ['namesFound' => array_keys($packageConstraintMap), 'advisories' => array_filter($advisories)]; }); return $repoSet; } /** * @return array<mixed> */ public static function getMockAdvisories(): array { $advisories = [ 'vendor1/package1' => [ [ 'advisoryId' => 'ID1', 'packageName' => 'vendor1/package1', 'title' => 'advisory1', 'link' => 'https://advisory.example.com/advisory1', 'cve' => 'CVE1', 'affectedVersions' => '>=3,<3.4.3|>=1,<2.5.6', 'sources' => [ [ 'name' => 'source1', 'remoteId' => 'RemoteID1', ], ], 'reportedAt' => '2022-05-25 13:21:00', 'composerRepository' => 'https://packagist.org', 'severity' => 'medium', ], [ 'advisoryId' => 'ID4', 'packageName' => 'vendor1/package1', 'title' => 'advisory4', 'link' => 'https://advisory.example.com/advisory4', 'cve' => 'CVE3', 'affectedVersions' => '>=8,<8.2.2|>=1,<2.5.6', 'sources' => [ [ 'name' => 'source2', 'remoteId' => 'RemoteID4', ], ], 'reportedAt' => '2022-05-25 13:21:00', 'composerRepository' => 'https://packagist.org', 'severity' => 'high', ], [ 'advisoryId' => 'ID5', 'packageName' => 'vendor1/package1', 'title' => 'advisory5', 'link' => 'https://advisory.example.com/advisory5', 'cve' => '', 'affectedVersions' => '>=8,<8.2.2|>=1,<2.5.6', 'sources' => [ [ 'name' => 'source1', 'remoteId' => 'RemoteID3', ], ], 'reportedAt' => '2022-05-25 13:21:00',
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
true
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php
tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreAllPlatformRequirementFilterTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Filter\PlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter; use Composer\Test\TestCase; final class IgnoreAllPlatformRequirementFilterTest extends TestCase { /** * @dataProvider dataIsIgnored */ public function testIsIgnored(string $req, bool $expectIgnored): void { $platformRequirementFilter = new IgnoreAllPlatformRequirementFilter(); self::assertSame($expectIgnored, $platformRequirementFilter->isIgnored($req)); self::assertSame($expectIgnored, $platformRequirementFilter->isUpperBoundIgnored($req)); } /** * @return array<string, mixed[]> */ public static function dataIsIgnored(): array { return [ 'php is ignored' => ['php', true], 'monolog/monolog is not ignored' => ['monolog/monolog', false], ]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php
tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreListPlatformRequirementFilterTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Filter\PlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter; use Composer\Test\TestCase; final class IgnoreListPlatformRequirementFilterTest extends TestCase { /** * @dataProvider dataIsIgnored * * @param string[] $reqList */ public function testIsIgnored(array $reqList, string $req, bool $expectIgnored): void { $platformRequirementFilter = new IgnoreListPlatformRequirementFilter($reqList); self::assertSame($expectIgnored, $platformRequirementFilter->isIgnored($req)); } /** * @return array<string, mixed[]> */ public static function dataIsIgnored(): array { return [ 'ext-json is ignored if listed' => [['ext-json', 'monolog/monolog'], 'ext-json', true], 'php is not ignored if not listed' => [['ext-json', 'monolog/monolog'], 'php', false], 'monolog/monolog is not ignored even if listed' => [['ext-json', 'monolog/monolog'], 'monolog/monolog', false], 'ext-json is ignored if ext-* is listed' => [['ext-*'], 'ext-json', true], 'php is ignored if php* is listed' => [['ext-*', 'php*'], 'php', true], 'ext-json is ignored if * is listed' => [['foo', '*'], 'ext-json', true], 'php is ignored if * is listed' => [['*', 'foo'], 'php', true], 'monolog/monolog is not ignored even if * or monolog/* are listed' => [['*', 'monolog/*'], 'monolog/monolog', false], 'empty list entry does not ignore' => [[''], 'ext-foo', false], 'empty array does not ignore' => [[], 'ext-foo', false], 'list entries are not completing each other' => [['ext-', 'foo'], 'ext-foo', false], ]; } /** * @dataProvider dataIsUpperBoundIgnored * * @param string[] $reqList */ public function testIsUpperBoundIgnored(array $reqList, string $req, bool $expectIgnored): void { $platformRequirementFilter = new IgnoreListPlatformRequirementFilter($reqList); self::assertSame($expectIgnored, $platformRequirementFilter->isUpperBoundIgnored($req)); } /** * @return array<string, mixed[]> */ public static function dataIsUpperBoundIgnored(): array { return [ 'ext-json is ignored if listed and fully ignored' => [['ext-json', 'monolog/monolog'], 'ext-json', true], 'ext-json is ignored if listed and upper bound ignored' => [['ext-json+', 'monolog/monolog'], 'ext-json', true], 'php is not ignored if not listed' => [['ext-json+', 'monolog/monolog'], 'php', false], 'monolog/monolog is not ignored even if listed' => [['monolog/monolog'], 'monolog/monolog', false], 'ext-json is ignored if ext-* is listed' => [['ext-*+'], 'ext-json', true], 'php is ignored if php* is listed' => [['ext-*+', 'php*+'], 'php', true], 'ext-json is ignored if * is listed' => [['foo', '*+'], 'ext-json', true], 'php is ignored if * is listed' => [['*+', 'foo'], 'php', true], 'monolog/monolog is not ignored even if * or monolog/* are listed' => [['*+', 'monolog/*+'], 'monolog/monolog', false], 'empty list entry does not ignore' => [[''], 'ext-foo', false], 'empty array does not ignore' => [[], 'ext-foo', false], 'list entries are not completing each other' => [['ext-', 'foo'], 'ext-foo', false], ]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php
tests/Composer/Test/Filter/PlatformRequirementFilter/PlatformRequirementFilterFactoryTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Filter\PlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory; use Composer\Test\TestCase; final class PlatformRequirementFilterFactoryTest extends TestCase { /** * @dataProvider dataFromBoolOrList * * @param mixed $boolOrList * @param class-string $expectedInstance */ public function testFromBoolOrList($boolOrList, $expectedInstance): void { self::assertInstanceOf($expectedInstance, PlatformRequirementFilterFactory::fromBoolOrList($boolOrList)); } /** * @return array<string, mixed[]> */ public static function dataFromBoolOrList(): array { return [ 'true creates IgnoreAllFilter' => [true, 'Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter'], 'false creates IgnoreNothingFilter' => [false, 'Composer\Filter\PlatformRequirementFilter\IgnoreNothingPlatformRequirementFilter'], 'list creates IgnoreListFilter' => [['php', 'ext-json'], 'Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter'], ]; } public function testFromBoolThrowsExceptionIfTypeIsUnknown(): void { self::expectException('InvalidArgumentException'); self::expectExceptionMessage('PlatformRequirementFilter: Unknown $boolOrList parameter null. Please report at https://github.com/composer/composer/issues/new.'); PlatformRequirementFilterFactory::fromBoolOrList(null); } public function testIgnoreAll(): void { $platformRequirementFilter = PlatformRequirementFilterFactory::ignoreAll(); self::assertInstanceOf('Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter', $platformRequirementFilter); } public function testIgnoreNothing(): void { $platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing(); self::assertInstanceOf('Composer\Filter\PlatformRequirementFilter\IgnoreNothingPlatformRequirementFilter', $platformRequirementFilter); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php
tests/Composer/Test/Filter/PlatformRequirementFilter/IgnoreNothingPlatformRequirementFilterTest.php
<?php declare(strict_types=1); /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Test\Filter\PlatformRequirementFilter; use Composer\Filter\PlatformRequirementFilter\IgnoreNothingPlatformRequirementFilter; use Composer\Test\TestCase; final class IgnoreNothingPlatformRequirementFilterTest extends TestCase { /** * @dataProvider dataIsIgnored */ public function testIsIgnored(string $req): void { $platformRequirementFilter = new IgnoreNothingPlatformRequirementFilter(); self::assertFalse($platformRequirementFilter->isIgnored($req)); self::assertFalse($platformRequirementFilter->isUpperBoundIgnored($req)); } /** * @return array<string, mixed[]> */ public static function dataIsIgnored(): array { return [ 'php is not ignored' => ['php'], 'monolog/monolog is not ignored' => ['monolog/monolog'], ]; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/Hooks.php
tests/Composer/Test/Fixtures/functional/installed-versions2/Hooks.php
<?php use Composer\Json\JsonFile; use Composer\InstalledVersions; use Composer\Script\Event; class Hooks { public static function preUpdate(Event $event) { fwrite(STDERR, '!!PreUpdate:'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); } public static function postUpdate(Event $event) { fwrite(STDERR, '!!PostUpdate:'.JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"); fwrite(STDERR, '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"); fwrite(STDERR, '!!PluginA:'.InstalledVersions::getVersion('plugin/a')."\n"); fwrite(STDERR, '!!PluginB:'.InstalledVersions::getVersion('plugin/b')."\n"); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/autoload.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/autoload.php
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer/autoload_real.php'; return ComposerAutoloaderInit46489d6835a727203ffccd612295440e::getLoader();
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/plugin/a/PluginA.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/plugin/a/PluginA.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginA implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { echo '!!PluginA:'.InstalledVersions::getVersion('plugin/a').JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"; echo '!!PluginB:'.(InstalledVersions::isInstalled('plugin/b') ? InstalledVersions::getVersion('plugin/b') : 'null')."\n"; echo '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"; } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/plugin/b/PluginB.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/plugin/b/PluginB.php
<?php use Composer\Plugin\PluginInterface; use Composer\Composer; use Composer\IO\IOInterface; use Composer\Json\JsonFile; use Composer\InstalledVersions; class PluginB implements PluginInterface { public function activate(Composer $composer, IOInterface $io) { echo '!!PluginB:'.InstalledVersions::getVersion('plugin/b').JsonFile::encode(InstalledVersions::getInstalledPackages(), 320)."\n"; echo '!!PluginA:'.(InstalledVersions::isInstalled('plugin/a') ? InstalledVersions::getVersion('plugin/a') : 'null')."\n"; echo '!!Versions:console:'.InstalledVersions::getVersion('symfony/console').';process:'.InstalledVersions::getVersion('symfony/process').';filesystem:'.InstalledVersions::getVersion('symfony/filesystem')."\n"; } public function deactivate(Composer $composer, IOInterface $io) { } public function uninstall(Composer $composer, IOInterface $io) { } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/InstalledVersions.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/InstalledVersions.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer; use Composer\Autoload\ClassLoader; use Composer\Semver\VersionParser; /** * This class is copied in every Composer installed project and available to all * * To require its presence, you can require `composer-runtime-api ^2.0` */ class InstalledVersions { private static $installed = array ( 'root' => array ( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'aliases' => array ( ), 'reference' => NULL, 'name' => 'root/pkg', ), 'versions' => array ( 'plugin/a' => array ( 'pretty_version' => '1.1.1', 'version' => '1.1.1.0', 'aliases' => array ( ), 'reference' => 'da71e7f842e61910f596935057e4690a3546392e', ), 'plugin/b' => array ( 'pretty_version' => '2.2.2', 'version' => '2.2.2.0', 'aliases' => array ( ), 'reference' => '398c3abfb6c73bc2bdd4f4f046845ffc180e2229', ), 'root/pkg' => array ( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'aliases' => array ( ), 'reference' => NULL, ), 'symfony/console' => array ( 'pretty_version' => '99999.1.2', 'version' => '99999.1.2.0', 'aliases' => array ( ), 'reference' => '53e6291b8b80838b227aa86da61656ea7ba25901', ), 'symfony/filesystem' => array ( 'pretty_version' => 'v2.8.2', 'version' => '2.8.2.0', 'aliases' => array ( ), 'reference' => '262d033b57c73e8b59cd6e68a45c528318b15038', ), 'symfony/polyfill-ctype' => array ( 'pretty_version' => 'v1.22.0', 'version' => '1.22.0.0', 'aliases' => array ( ), 'reference' => 'c6c942b1ac76c82448322025e084cadc56048b4e', ), 'symfony/process' => array ( 'pretty_version' => '12345.1.2', 'version' => '12345.1.2.0', 'aliases' => array ( ), 'reference' => '28ebf252e9e21386d873e48b302b9fa044a96e5f', ), ), ); private static $canGetVendors; private static $installedByVendor = array(); /** * Returns a list of all package names which are present, either by being installed, replaced or provided * * @return string[] * @psalm-return list<string> */ public static function getInstalledPackages() { $packages = array(); foreach (self::getInstalled() as $installed) { $packages[] = array_keys($installed['versions']); } if (1 === \count($packages)) { return $packages[0]; } return array_keys(array_flip(\call_user_func_array('array_merge', $packages))); } /** * Checks whether the given package is installed * * This also returns true if the package name is provided or replaced by another package * * @param string $packageName * @return bool */ public static function isInstalled($packageName) { foreach (self::getInstalled() as $installed) { if (isset($installed['versions'][$packageName])) { return true; } } return false; } /** * Checks whether the given package satisfies a version constraint * * e.g. If you want to know whether version 2.3+ of package foo/bar is installed, you would call: * * Composer\InstalledVersions::satisfies(new VersionParser, 'foo/bar', '^2.3') * * @param VersionParser $parser Install composer/semver to have access to this class and functionality * @param string $packageName * @param string|null $constraint A version constraint to check for, if you pass one you have to make sure composer/semver is required by your package * * @return bool */ public static function satisfies(VersionParser $parser, $packageName, $constraint) { $constraint = $parser->parseConstraints($constraint); $provided = $parser->parseConstraints(self::getVersionRanges($packageName)); return $provided->matches($constraint); } /** * Returns a version constraint representing all the range(s) which are installed for a given package * * It is easier to use this via isInstalled() with the $constraint argument if you need to check * whether a given version of a package is installed, and not just whether it exists * * @param string $packageName * @return string Version constraint usable with composer/semver */ public static function getVersionRanges($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } $ranges = array(); if (isset($installed['versions'][$packageName]['pretty_version'])) { $ranges[] = $installed['versions'][$packageName]['pretty_version']; } if (array_key_exists('aliases', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['aliases']); } if (array_key_exists('replaced', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['replaced']); } if (array_key_exists('provided', $installed['versions'][$packageName])) { $ranges = array_merge($ranges, $installed['versions'][$packageName]['provided']); } return implode(' || ', $ranges); } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['version'])) { return null; } return $installed['versions'][$packageName]['version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as version, use satisfies or getVersionRanges if you need to know if a given version is present */ public static function getPrettyVersion($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['pretty_version'])) { return null; } return $installed['versions'][$packageName]['pretty_version']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @param string $packageName * @return string|null If the package is being replaced or provided but is not really installed, null will be returned as reference */ public static function getReference($packageName) { foreach (self::getInstalled() as $installed) { if (!isset($installed['versions'][$packageName])) { continue; } if (!isset($installed['versions'][$packageName]['reference'])) { return null; } return $installed['versions'][$packageName]['reference']; } throw new \OutOfBoundsException('Package "' . $packageName . '" is not installed'); } /** * @return array * @psalm-return array{name: string, version: string, reference: string, pretty_version: string, aliases: string[]} */ public static function getRootPackage() { $installed = self::getInstalled(); return $installed[0]['root']; } /** * Returns the raw installed.php data for custom implementations * * @return array[] * @psalm-return array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[]}, versions: list<string, array{pretty_version: ?string, version: ?string, aliases: ?string[], reference: ?string, replaced: ?string[], provided: ?string[]}>} */ public static function getRawData() { return self::$installed; } /** * Lets you reload the static array from another file * * This is only useful for complex integrations in which a project needs to use * this class but then also needs to execute another project's autoloader in process, * and wants to ensure both projects have access to their version of installed.php. * * A typical case would be PHPUnit, where it would need to make sure it reads all * the data it needs from this class, then call reload() with * `require $CWD/vendor/composer/installed.php` (or similar) as input to make sure * the project in which it runs can then also use this class safely, without * interference between PHPUnit's dependencies and the project's dependencies. * * @param array[] $data A vendor/composer/installed.php data set * @return void * * @psalm-param array{root: array{name: string, version: string, reference: string, pretty_version: string, aliases: string[]}, versions: list<string, array{pretty_version: ?string, version: ?string, aliases: ?string[], reference: ?string, replaced: ?string[], provided: ?string[]}>} $data */ public static function reload($data) { self::$installed = $data; self::$installedByVendor = array(); } /** * @return array[] */ private static function getInstalled() { if (null === self::$canGetVendors) { self::$canGetVendors = method_exists('Composer\Autoload\ClassLoader', 'getRegisteredLoaders'); } $installed = array(); if (self::$canGetVendors) { foreach (ClassLoader::getRegisteredLoaders() as $vendorDir => $loader) { if (isset(self::$installedByVendor[$vendorDir])) { $installed[] = self::$installedByVendor[$vendorDir]; } elseif (is_file($vendorDir.'/composer/installed.php')) { $installed[] = self::$installedByVendor[$vendorDir] = require $vendorDir.'/composer/installed.php'; } } } $installed[] = self::$installed; return $installed; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_files.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_files.php
<?php // autoload_files.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( '320cde22f66dd4f5d3fd621d3e88b98f' => $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_real.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_real.php
<?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit46489d6835a727203ffccd612295440e { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } /** * @return \Composer\Autoload\ClassLoader */ public static function getLoader() { if (null !== self::$loader) { return self::$loader; } require __DIR__ . '/platform_check.php'; spl_autoload_register(array('ComposerAutoloaderInit46489d6835a727203ffccd612295440e', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__))); spl_autoload_unregister(array('ComposerAutoloaderInit46489d6835a727203ffccd612295440e', 'loadClassLoader')); $useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); if ($useStaticLoader) { require __DIR__ . '/autoload_static.php'; call_user_func(\Composer\Autoload\ComposerStaticInit46489d6835a727203ffccd612295440e::getInitializer($loader)); } else { $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } } $loader->register(true); if ($useStaticLoader) { $includeFiles = Composer\Autoload\ComposerStaticInit46489d6835a727203ffccd612295440e::$files; } else { $includeFiles = require __DIR__ . '/autoload_files.php'; } foreach ($includeFiles as $fileIdentifier => $file) { composerRequire46489d6835a727203ffccd612295440e($fileIdentifier, $file); } return $loader; } } function composerRequire46489d6835a727203ffccd612295440e($fileIdentifier, $file) { if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; require $file; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_namespaces.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_namespaces.php
<?php // autoload_namespaces.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_psr4.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_psr4.php
<?php // autoload_psr4.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), 'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_static.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_static.php
<?php // autoload_static.php @generated by Composer namespace Composer\Autoload; class ComposerStaticInit46489d6835a727203ffccd612295440e { public static $files = array ( '320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', ); public static $prefixLengthsPsr4 = array ( 'S' => array ( 'Symfony\\Polyfill\\Ctype\\' => 23, 'Symfony\\Component\\Filesystem\\' => 29, ), ); public static $prefixDirsPsr4 = array ( 'Symfony\\Polyfill\\Ctype\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', ), 'Symfony\\Component\\Filesystem\\' => array ( 0 => __DIR__ . '/..' . '/symfony/filesystem', ), ); public static $classMap = array ( 'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php', 'Hooks' => __DIR__ . '/../..' . '/Hooks.php', 'PluginA' => __DIR__ . '/..' . '/plugin/a/PluginA.php', 'PluginB' => __DIR__ . '/..' . '/plugin/b/PluginB.php', ); public static function getInitializer(ClassLoader $loader) { return \Closure::bind(function () use ($loader) { $loader->prefixLengthsPsr4 = ComposerStaticInit46489d6835a727203ffccd612295440e::$prefixLengthsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit46489d6835a727203ffccd612295440e::$prefixDirsPsr4; $loader->classMap = ComposerStaticInit46489d6835a727203ffccd612295440e::$classMap; }, null, ClassLoader::class); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/installed.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/installed.php
<?php return array ( 'root' => array ( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'aliases' => array ( ), 'reference' => NULL, 'name' => 'root/pkg', ), 'versions' => array ( 'plugin/a' => array ( 'pretty_version' => '1.1.1', 'version' => '1.1.1.0', 'aliases' => array ( ), 'reference' => 'da71e7f842e61910f596935057e4690a3546392e', ), 'plugin/b' => array ( 'pretty_version' => '2.2.2', 'version' => '2.2.2.0', 'aliases' => array ( ), 'reference' => '398c3abfb6c73bc2bdd4f4f046845ffc180e2229', ), 'root/pkg' => array ( 'pretty_version' => '1.2.3', 'version' => '1.2.3.0', 'aliases' => array ( ), 'reference' => NULL, ), 'symfony/console' => array ( 'pretty_version' => '99999.1.2', 'version' => '99999.1.2.0', 'aliases' => array ( ), 'reference' => '53e6291b8b80838b227aa86da61656ea7ba25901', ), 'symfony/filesystem' => array ( 'pretty_version' => 'v2.8.2', 'version' => '2.8.2.0', 'aliases' => array ( ), 'reference' => '262d033b57c73e8b59cd6e68a45c528318b15038', ), 'symfony/polyfill-ctype' => array ( 'pretty_version' => 'v1.22.0', 'version' => '1.22.0.0', 'aliases' => array ( ), 'reference' => 'c6c942b1ac76c82448322025e084cadc56048b4e', ), 'symfony/process' => array ( 'pretty_version' => '12345.1.2', 'version' => '12345.1.2.0', 'aliases' => array ( ), 'reference' => '28ebf252e9e21386d873e48b302b9fa044a96e5f', ), ), );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/ClassLoader.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/ClassLoader.php
<?php /* * This file is part of Composer. * * (c) Nils Adermann <naderman@naderman.de> * Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Composer\Autoload; /** * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. * * $loader = new \Composer\Autoload\ClassLoader(); * * // register classes with namespaces * $loader->add('Symfony\Component', __DIR__.'/component'); * $loader->add('Symfony', __DIR__.'/framework'); * * // activate the autoloader * $loader->register(); * * // to enable searching the include path (eg. for PEAR packages) * $loader->setUseIncludePath(true); * * In this example, if you try to use a class in the Symfony\Component * namespace or one of its children (Symfony\Component\Console for instance), * the autoloader will first look for the class under the component/ * directory, and it will then fallback to the framework/ directory if not * found before giving up. * * This class is loosely based on the Symfony UniversalClassLoader. * * @author Fabien Potencier <fabien@symfony.com> * @author Jordi Boggiano <j.boggiano@seld.be> * @see https://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-4/ */ class ClassLoader { private $vendorDir; // PSR-4 private $prefixLengthsPsr4 = array(); private $prefixDirsPsr4 = array(); private $fallbackDirsPsr4 = array(); // PSR-0 private $prefixesPsr0 = array(); private $fallbackDirsPsr0 = array(); private $useIncludePath = false; private $classMap = array(); private $classMapAuthoritative = false; private $missingClasses = array(); private $apcuPrefix; private static $registeredLoaders = array(); public function __construct($vendorDir = null) { $this->vendorDir = $vendorDir; } public function getPrefixes() { if (!empty($this->prefixesPsr0)) { return call_user_func_array('array_merge', array_values($this->prefixesPsr0)); } return array(); } public function getPrefixesPsr4() { return $this->prefixDirsPsr4; } public function getFallbackDirs() { return $this->fallbackDirsPsr0; } public function getFallbackDirsPsr4() { return $this->fallbackDirsPsr4; } public function getClassMap() { return $this->classMap; } /** * @param array $classMap Class to filename map */ public function addClassMap(array $classMap) { if ($this->classMap) { $this->classMap = array_merge($this->classMap, $classMap); } else { $this->classMap = $classMap; } } /** * Registers a set of PSR-0 directories for a given prefix, either * appending or prepending to the ones previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 root directories * @param bool $prepend Whether to prepend the directories */ public function add($prefix, $paths, $prepend = false) { if (!$prefix) { if ($prepend) { $this->fallbackDirsPsr0 = array_merge( (array) $paths, $this->fallbackDirsPsr0 ); } else { $this->fallbackDirsPsr0 = array_merge( $this->fallbackDirsPsr0, (array) $paths ); } return; } $first = $prefix[0]; if (!isset($this->prefixesPsr0[$first][$prefix])) { $this->prefixesPsr0[$first][$prefix] = (array) $paths; return; } if ($prepend) { $this->prefixesPsr0[$first][$prefix] = array_merge( (array) $paths, $this->prefixesPsr0[$first][$prefix] ); } else { $this->prefixesPsr0[$first][$prefix] = array_merge( $this->prefixesPsr0[$first][$prefix], (array) $paths ); } } /** * Registers a set of PSR-4 directories for a given namespace, either * appending or prepending to the ones previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * @param bool $prepend Whether to prepend the directories * * @throws \InvalidArgumentException */ public function addPsr4($prefix, $paths, $prepend = false) { if (!$prefix) { // Register directories for the root namespace. if ($prepend) { $this->fallbackDirsPsr4 = array_merge( (array) $paths, $this->fallbackDirsPsr4 ); } else { $this->fallbackDirsPsr4 = array_merge( $this->fallbackDirsPsr4, (array) $paths ); } } elseif (!isset($this->prefixDirsPsr4[$prefix])) { // Register directories for a new namespace. $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } elseif ($prepend) { // Prepend directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( (array) $paths, $this->prefixDirsPsr4[$prefix] ); } else { // Append directories for an already registered namespace. $this->prefixDirsPsr4[$prefix] = array_merge( $this->prefixDirsPsr4[$prefix], (array) $paths ); } } /** * Registers a set of PSR-0 directories for a given prefix, * replacing any others previously set for this prefix. * * @param string $prefix The prefix * @param array|string $paths The PSR-0 base directories */ public function set($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr0 = (array) $paths; } else { $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; } } /** * Registers a set of PSR-4 directories for a given namespace, * replacing any others previously set for this namespace. * * @param string $prefix The prefix/namespace, with trailing '\\' * @param array|string $paths The PSR-4 base directories * * @throws \InvalidArgumentException */ public function setPsr4($prefix, $paths) { if (!$prefix) { $this->fallbackDirsPsr4 = (array) $paths; } else { $length = strlen($prefix); if ('\\' !== $prefix[$length - 1]) { throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); } $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; $this->prefixDirsPsr4[$prefix] = (array) $paths; } } /** * Turns on searching the include path for class files. * * @param bool $useIncludePath */ public function setUseIncludePath($useIncludePath) { $this->useIncludePath = $useIncludePath; } /** * Can be used to check if the autoloader uses the include path to check * for classes. * * @return bool */ public function getUseIncludePath() { return $this->useIncludePath; } /** * Turns off searching the prefix and fallback directories for classes * that have not been registered with the class map. * * @param bool $classMapAuthoritative */ public function setClassMapAuthoritative($classMapAuthoritative) { $this->classMapAuthoritative = $classMapAuthoritative; } /** * Should class lookup fail if not found in the current class map? * * @return bool */ public function isClassMapAuthoritative() { return $this->classMapAuthoritative; } /** * APCu prefix to use to cache found/not-found classes, if the extension is enabled. * * @param string|null $apcuPrefix */ public function setApcuPrefix($apcuPrefix) { $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; } /** * The APCu prefix in use, or null if APCu caching is not enabled. * * @return string|null */ public function getApcuPrefix() { return $this->apcuPrefix; } /** * Registers this instance as an autoloader. * * @param bool $prepend Whether to prepend the autoloader or not */ public function register($prepend = false) { spl_autoload_register(array($this, 'loadClass'), true, $prepend); if (null === $this->vendorDir) { return; } if ($prepend) { self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders; } else { unset(self::$registeredLoaders[$this->vendorDir]); self::$registeredLoaders[$this->vendorDir] = $this; } } /** * Unregisters this instance as an autoloader. */ public function unregister() { spl_autoload_unregister(array($this, 'loadClass')); if (null !== $this->vendorDir) { unset(self::$registeredLoaders[$this->vendorDir]); } } /** * Loads the given class or interface. * * @param string $class The name of the class * @return bool|null True if loaded, null otherwise */ public function loadClass($class) { if ($file = $this->findFile($class)) { includeFile($file); return true; } } /** * Finds the path to the file where the class is defined. * * @param string $class The name of the class * * @return string|false The path if found, false otherwise */ public function findFile($class) { // class map lookup if (isset($this->classMap[$class])) { return $this->classMap[$class]; } if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { return false; } if (null !== $this->apcuPrefix) { $file = apcu_fetch($this->apcuPrefix.$class, $hit); if ($hit) { return $file; } } $file = $this->findFileWithExtension($class, '.php'); // Search for Hack files if we are running on HHVM if (false === $file && defined('HHVM_VERSION')) { $file = $this->findFileWithExtension($class, '.hh'); } if (null !== $this->apcuPrefix) { apcu_add($this->apcuPrefix.$class, $file); } if (false === $file) { // Remember that this class does not exist. $this->missingClasses[$class] = true; } return $file; } /** * Returns the currently registered loaders indexed by their corresponding vendor directories. * * @return self[] */ public static function getRegisteredLoaders() { return self::$registeredLoaders; } private function findFileWithExtension($class, $ext) { // PSR-4 lookup $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; $first = $class[0]; if (isset($this->prefixLengthsPsr4[$first])) { $subPath = $class; while (false !== $lastPos = strrpos($subPath, '\\')) { $subPath = substr($subPath, 0, $lastPos); $search = $subPath . '\\'; if (isset($this->prefixDirsPsr4[$search])) { $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); foreach ($this->prefixDirsPsr4[$search] as $dir) { if (file_exists($file = $dir . $pathEnd)) { return $file; } } } } } // PSR-4 fallback dirs foreach ($this->fallbackDirsPsr4 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { return $file; } } // PSR-0 lookup if (false !== $pos = strrpos($class, '\\')) { // namespaced class name $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); } else { // PEAR-like class name $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; } if (isset($this->prefixesPsr0[$first])) { foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { if (0 === strpos($class, $prefix)) { foreach ($dirs as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } } } } // PSR-0 fallback dirs foreach ($this->fallbackDirsPsr0 as $dir) { if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { return $file; } } // PSR-0 include paths. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { return $file; } return false; } } /** * Scope isolated include. * * Prevents access to $this/self from included files. */ function includeFile($file) { include $file; }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_classmap.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/autoload_classmap.php
<?php // autoload_classmap.php @generated by Composer $vendorDir = dirname(dirname(__FILE__)); $baseDir = dirname($vendorDir); return array( 'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php', 'Hooks' => $baseDir . '/Hooks.php', 'PluginA' => $vendorDir . '/plugin/a/PluginA.php', 'PluginB' => $vendorDir . '/plugin/b/PluginB.php', );
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/platform_check.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/composer/platform_check.php
<?php // platform_check.php @generated by Composer $issues = array(); if (!(PHP_VERSION_ID >= 70205)) { $issues[] = 'Your Composer dependencies require a PHP version ">= 7.2.5". You are running ' . PHP_VERSION . '.'; } if ($issues) { if (!headers_sent()) { header('HTTP/1.1 500 Internal Server Error'); } if (!ini_get('display_errors')) { if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') { fwrite(STDERR, 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . implode(PHP_EOL, $issues) . PHP_EOL.PHP_EOL); } elseif (!headers_sent()) { echo 'Composer detected issues in your platform:' . PHP_EOL.PHP_EOL . str_replace('You are running '.PHP_VERSION.'.', '', implode(PHP_EOL, $issues)) . PHP_EOL.PHP_EOL; } } trigger_error( 'Composer detected issues in your platform: ' . implode(' ', $issues), E_USER_ERROR ); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/bootstrap.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/bootstrap.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Ctype as p; if (\PHP_VERSION_ID >= 80000) { return require __DIR__.'/bootstrap80.php'; } if (!function_exists('ctype_alnum')) { function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } } if (!function_exists('ctype_alpha')) { function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } } if (!function_exists('ctype_cntrl')) { function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } } if (!function_exists('ctype_digit')) { function ctype_digit($text) { return p\Ctype::ctype_digit($text); } } if (!function_exists('ctype_graph')) { function ctype_graph($text) { return p\Ctype::ctype_graph($text); } } if (!function_exists('ctype_lower')) { function ctype_lower($text) { return p\Ctype::ctype_lower($text); } } if (!function_exists('ctype_print')) { function ctype_print($text) { return p\Ctype::ctype_print($text); } } if (!function_exists('ctype_punct')) { function ctype_punct($text) { return p\Ctype::ctype_punct($text); } } if (!function_exists('ctype_space')) { function ctype_space($text) { return p\Ctype::ctype_space($text); } } if (!function_exists('ctype_upper')) { function ctype_upper($text) { return p\Ctype::ctype_upper($text); } } if (!function_exists('ctype_xdigit')) { function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/bootstrap80.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/bootstrap80.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Symfony\Polyfill\Ctype as p; if (!function_exists('ctype_alnum')) { function ctype_alnum(mixed $text): bool { return p\Ctype::ctype_alnum($text); } } if (!function_exists('ctype_alpha')) { function ctype_alpha(mixed $text): bool { return p\Ctype::ctype_alpha($text); } } if (!function_exists('ctype_cntrl')) { function ctype_cntrl(mixed $text): bool { return p\Ctype::ctype_cntrl($text); } } if (!function_exists('ctype_digit')) { function ctype_digit(mixed $text): bool { return p\Ctype::ctype_digit($text); } } if (!function_exists('ctype_graph')) { function ctype_graph(mixed $text): bool { return p\Ctype::ctype_graph($text); } } if (!function_exists('ctype_lower')) { function ctype_lower(mixed $text): bool { return p\Ctype::ctype_lower($text); } } if (!function_exists('ctype_print')) { function ctype_print(mixed $text): bool { return p\Ctype::ctype_print($text); } } if (!function_exists('ctype_punct')) { function ctype_punct(mixed $text): bool { return p\Ctype::ctype_punct($text); } } if (!function_exists('ctype_space')) { function ctype_space(mixed $text): bool { return p\Ctype::ctype_space($text); } } if (!function_exists('ctype_upper')) { function ctype_upper(mixed $text): bool { return p\Ctype::ctype_upper($text); } } if (!function_exists('ctype_xdigit')) { function ctype_xdigit(mixed $text): bool { return p\Ctype::ctype_xdigit($text); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/Ctype.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/polyfill-ctype/Ctype.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Polyfill\Ctype; /** * Ctype implementation through regex. * * @internal * * @author Gert de Pagter <BackEndTea@gmail.com> */ final class Ctype { /** * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. * * @see https://php.net/ctype-alnum * * @param string|int $text * * @return bool */ public static function ctype_alnum($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); } /** * Returns TRUE if every character in text is a letter, FALSE otherwise. * * @see https://php.net/ctype-alpha * * @param string|int $text * * @return bool */ public static function ctype_alpha($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); } /** * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. * * @see https://php.net/ctype-cntrl * * @param string|int $text * * @return bool */ public static function ctype_cntrl($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); } /** * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. * * @see https://php.net/ctype-digit * * @param string|int $text * * @return bool */ public static function ctype_digit($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); } /** * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. * * @see https://php.net/ctype-graph * * @param string|int $text * * @return bool */ public static function ctype_graph($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); } /** * Returns TRUE if every character in text is a lowercase letter. * * @see https://php.net/ctype-lower * * @param string|int $text * * @return bool */ public static function ctype_lower($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); } /** * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. * * @see https://php.net/ctype-print * * @param string|int $text * * @return bool */ public static function ctype_print($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); } /** * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. * * @see https://php.net/ctype-punct * * @param string|int $text * * @return bool */ public static function ctype_punct($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); } /** * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. * * @see https://php.net/ctype-space * * @param string|int $text * * @return bool */ public static function ctype_space($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); } /** * Returns TRUE if every character in text is an uppercase letter. * * @see https://php.net/ctype-upper * * @param string|int $text * * @return bool */ public static function ctype_upper($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); } /** * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. * * @see https://php.net/ctype-xdigit * * @param string|int $text * * @return bool */ public static function ctype_xdigit($text) { $text = self::convert_int_to_char_for_ctype($text); return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); } /** * Converts integers to their char versions according to normal ctype behaviour, if needed. * * If an integer between -128 and 255 inclusive is provided, * it is interpreted as the ASCII value of a single character * (negative values have 256 added in order to allow characters in the Extended ASCII range). * Any other integer is interpreted as a string containing the decimal digits of the integer. * * @param string|int $int * * @return mixed */ private static function convert_int_to_char_for_ctype($int) { if (!\is_int($int)) { return $int; } if ($int < -128 || $int > 255) { return (string) $int; } if ($int < 0) { $int += 256; } return \chr($int); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Filesystem.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Filesystem.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem; use Symfony\Component\Filesystem\Exception\FileNotFoundException; use Symfony\Component\Filesystem\Exception\InvalidArgumentException; use Symfony\Component\Filesystem\Exception\IOException; /** * Provides basic utility to manipulate the file system. * * @author Fabien Potencier <fabien@symfony.com> */ class Filesystem { private static $lastError; /** * Copies a file. * * If the target file is older than the origin file, it's always overwritten. * If the target file is newer, it is overwritten only when the * $overwriteNewerFiles option is set to true. * * @throws FileNotFoundException When originFile doesn't exist * @throws IOException When copy fails */ public function copy(string $originFile, string $targetFile, bool $overwriteNewerFiles = false) { $originIsLocal = stream_is_local($originFile) || 0 === stripos($originFile, 'file://'); if ($originIsLocal && !is_file($originFile)) { throw new FileNotFoundException(sprintf('Failed to copy "%s" because file does not exist.', $originFile), 0, null, $originFile); } $this->mkdir(\dirname($targetFile)); $doCopy = true; if (!$overwriteNewerFiles && null === parse_url($originFile, \PHP_URL_HOST) && is_file($targetFile)) { $doCopy = filemtime($originFile) > filemtime($targetFile); } if ($doCopy) { // https://bugs.php.net/64634 if (false === $source = @fopen($originFile, 'r')) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } // Stream context created to allow files overwrite when using FTP stream wrapper - disabled by default if (false === $target = @fopen($targetFile, 'w', null, stream_context_create(['ftp' => ['overwrite' => true]]))) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because target file could not be opened for writing.', $originFile, $targetFile), 0, null, $originFile); } $bytesCopied = stream_copy_to_stream($source, $target); fclose($source); fclose($target); unset($source, $target); if (!is_file($targetFile)) { throw new IOException(sprintf('Failed to copy "%s" to "%s".', $originFile, $targetFile), 0, null, $originFile); } if ($originIsLocal) { // Like `cp`, preserve executable permission bits @chmod($targetFile, fileperms($targetFile) | (fileperms($originFile) & 0111)); if ($bytesCopied !== $bytesOrigin = filesize($originFile)) { throw new IOException(sprintf('Failed to copy the whole content of "%s" to "%s" (%g of %g bytes copied).', $originFile, $targetFile, $bytesCopied, $bytesOrigin), 0, null, $originFile); } } } } /** * Creates a directory recursively. * * @param string|iterable $dirs The directory path * * @throws IOException On any directory creation failure */ public function mkdir($dirs, int $mode = 0777) { foreach ($this->toIterable($dirs) as $dir) { if (is_dir($dir)) { continue; } if (!self::box('mkdir', $dir, $mode, true)) { if (!is_dir($dir)) { // The directory was not created by a concurrent process. Let's throw an exception with a developer friendly error message if we have one if (self::$lastError) { throw new IOException(sprintf('Failed to create "%s": ', $dir).self::$lastError, 0, null, $dir); } throw new IOException(sprintf('Failed to create "%s".', $dir), 0, null, $dir); } } } } /** * Checks the existence of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to check * * @return bool true if the file exists, false otherwise */ public function exists($files) { $maxPathLength = \PHP_MAXPATHLEN - 2; foreach ($this->toIterable($files) as $file) { if (\strlen($file) > $maxPathLength) { throw new IOException(sprintf('Could not check if file exist because path length exceeds %d characters.', $maxPathLength), 0, null, $file); } if (!file_exists($file)) { return false; } } return true; } /** * Sets access and modification time of file. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to create * @param int|null $time The touch time as a Unix timestamp, if not supplied the current system time is used * @param int|null $atime The access time as a Unix timestamp, if not supplied the current system time is used * * @throws IOException When touch fails */ public function touch($files, int $time = null, int $atime = null) { foreach ($this->toIterable($files) as $file) { $touch = $time ? @touch($file, $time, $atime) : @touch($file); if (true !== $touch) { throw new IOException(sprintf('Failed to touch "%s".', $file), 0, null, $file); } } } /** * Removes files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to remove * * @throws IOException When removal fails */ public function remove($files) { if ($files instanceof \Traversable) { $files = iterator_to_array($files, false); } elseif (!\is_array($files)) { $files = [$files]; } $files = array_reverse($files); foreach ($files as $file) { if (is_link($file)) { // See https://bugs.php.net/52176 if (!(self::box('unlink', $file) || '\\' !== \DIRECTORY_SEPARATOR || self::box('rmdir', $file)) && file_exists($file)) { throw new IOException(sprintf('Failed to remove symlink "%s": ', $file).self::$lastError); } } elseif (is_dir($file)) { $this->remove(new \FilesystemIterator($file, \FilesystemIterator::CURRENT_AS_PATHNAME | \FilesystemIterator::SKIP_DOTS)); if (!self::box('rmdir', $file) && file_exists($file)) { throw new IOException(sprintf('Failed to remove directory "%s": ', $file).self::$lastError); } } elseif (!self::box('unlink', $file) && (false !== strpos(self::$lastError, 'Permission denied') || file_exists($file))) { throw new IOException(sprintf('Failed to remove file "%s": ', $file).self::$lastError); } } } /** * Change mode for an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change mode * @param int $mode The new mode (octal) * @param int $umask The mode mask (octal) * @param bool $recursive Whether change the mod recursively or not * * @throws IOException When the change fails */ public function chmod($files, int $mode, int $umask = 0000, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ((\PHP_VERSION_ID < 80000 || \is_int($mode)) && true !== @chmod($file, $mode & ~$umask)) { throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file); } if ($recursive && is_dir($file) && !is_link($file)) { $this->chmod(new \FilesystemIterator($file), $mode, $umask, true); } } } /** * Change the owner of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change owner * @param string|int $user A user name or number * @param bool $recursive Whether change the owner recursively or not * * @throws IOException When the change fails */ public function chown($files, $user, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chown(new \FilesystemIterator($file), $user, true); } if (is_link($file) && \function_exists('lchown')) { if (true !== @lchown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } else { if (true !== @chown($file, $user)) { throw new IOException(sprintf('Failed to chown file "%s".', $file), 0, null, $file); } } } } /** * Change the group of an array of files or directories. * * @param string|iterable $files A filename, an array of files, or a \Traversable instance to change group * @param string|int $group A group name or number * @param bool $recursive Whether change the group recursively or not * * @throws IOException When the change fails */ public function chgrp($files, $group, bool $recursive = false) { foreach ($this->toIterable($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chgrp(new \FilesystemIterator($file), $group, true); } if (is_link($file) && \function_exists('lchgrp')) { if (true !== @lchgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } else { if (true !== @chgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } } } /** * Renames a file or a directory. * * @throws IOException When target file or directory already exists * @throws IOException When origin cannot be renamed */ public function rename(string $origin, string $target, bool $overwrite = false) { // we check that target does not exist if (!$overwrite && $this->isReadable($target)) { throw new IOException(sprintf('Cannot rename because the target "%s" already exists.', $target), 0, null, $target); } if (true !== @rename($origin, $target)) { if (is_dir($origin)) { // See https://bugs.php.net/54097 & https://php.net/rename#113943 $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]); $this->remove($origin); return; } throw new IOException(sprintf('Cannot rename "%s" to "%s".', $origin, $target), 0, null, $target); } } /** * Tells whether a file exists and is readable. * * @throws IOException When windows path is longer than 258 characters */ private function isReadable(string $filename): bool { $maxPathLength = \PHP_MAXPATHLEN - 2; if (\strlen($filename) > $maxPathLength) { throw new IOException(sprintf('Could not check if file is readable because path length exceeds %d characters.', $maxPathLength), 0, null, $filename); } return is_readable($filename); } /** * Creates a symbolic link or copy a directory. * * @throws IOException When symlink fails */ public function symlink(string $originDir, string $targetDir, bool $copyOnWindows = false) { if ('\\' === \DIRECTORY_SEPARATOR) { $originDir = strtr($originDir, '/', '\\'); $targetDir = strtr($targetDir, '/', '\\'); if ($copyOnWindows) { $this->mirror($originDir, $targetDir); return; } } $this->mkdir(\dirname($targetDir)); if (is_link($targetDir)) { if (readlink($targetDir) === $originDir) { return; } $this->remove($targetDir); } if (!self::box('symlink', $originDir, $targetDir)) { $this->linkException($originDir, $targetDir, 'symbolic'); } } /** * Creates a hard link, or several hard links to a file. * * @param string|string[] $targetFiles The target file(s) * * @throws FileNotFoundException When original file is missing or not a file * @throws IOException When link fails, including if link already exists */ public function hardlink(string $originFile, $targetFiles) { if (!$this->exists($originFile)) { throw new FileNotFoundException(null, 0, null, $originFile); } if (!is_file($originFile)) { throw new FileNotFoundException(sprintf('Origin file "%s" is not a file.', $originFile)); } foreach ($this->toIterable($targetFiles) as $targetFile) { if (is_file($targetFile)) { if (fileinode($originFile) === fileinode($targetFile)) { continue; } $this->remove($targetFile); } if (!self::box('link', $originFile, $targetFile)) { $this->linkException($originFile, $targetFile, 'hard'); } } } /** * @param string $linkType Name of the link type, typically 'symbolic' or 'hard' */ private function linkException(string $origin, string $target, string $linkType) { if (self::$lastError) { if ('\\' === \DIRECTORY_SEPARATOR && false !== strpos(self::$lastError, 'error code(1314)')) { throw new IOException(sprintf('Unable to create "%s" link due to error code 1314: \'A required privilege is not held by the client\'. Do you have the required Administrator-rights?', $linkType), 0, null, $target); } } throw new IOException(sprintf('Failed to create "%s" link from "%s" to "%s".', $linkType, $origin, $target), 0, null, $target); } /** * Resolves links in paths. * * With $canonicalize = false (default) * - if $path does not exist or is not a link, returns null * - if $path is a link, returns the next direct target of the link without considering the existence of the target * * With $canonicalize = true * - if $path does not exist, returns null * - if $path exists, returns its absolute fully resolved final version * * @return string|null */ public function readlink(string $path, bool $canonicalize = false) { if (!$canonicalize && !is_link($path)) { return null; } if ($canonicalize) { if (!$this->exists($path)) { return null; } if ('\\' === \DIRECTORY_SEPARATOR) { $path = readlink($path); } return realpath($path); } if ('\\' === \DIRECTORY_SEPARATOR) { return realpath($path); } return readlink($path); } /** * Given an existing path, convert it to a path relative to a given starting path. * * @return string Path of target relative to starting path */ public function makePathRelative(string $endPath, string $startPath) { if (!$this->isAbsolutePath($startPath)) { throw new InvalidArgumentException(sprintf('The start path "%s" is not absolute.', $startPath)); } if (!$this->isAbsolutePath($endPath)) { throw new InvalidArgumentException(sprintf('The end path "%s" is not absolute.', $endPath)); } // Normalize separators on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $endPath = str_replace('\\', '/', $endPath); $startPath = str_replace('\\', '/', $startPath); } $splitDriveLetter = function ($path) { return (\strlen($path) > 2 && ':' === $path[1] && '/' === $path[2] && ctype_alpha($path[0])) ? [substr($path, 2), strtoupper($path[0])] : [$path, null]; }; $splitPath = function ($path) { $result = []; foreach (explode('/', trim($path, '/')) as $segment) { if ('..' === $segment) { array_pop($result); } elseif ('.' !== $segment && '' !== $segment) { $result[] = $segment; } } return $result; }; [$endPath, $endDriveLetter] = $splitDriveLetter($endPath); [$startPath, $startDriveLetter] = $splitDriveLetter($startPath); $startPathArr = $splitPath($startPath); $endPathArr = $splitPath($endPath); if ($endDriveLetter && $startDriveLetter && $endDriveLetter != $startDriveLetter) { // End path is on another drive, so no relative path exists return $endDriveLetter.':/'.($endPathArr ? implode('/', $endPathArr).'/' : ''); } // Find for which directory the common path stops $index = 0; while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) { ++$index; } // Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels) if (1 === \count($startPathArr) && '' === $startPathArr[0]) { $depth = 0; } else { $depth = \count($startPathArr) - $index; } // Repeated "../" for each level need to reach the common path $traverser = str_repeat('../', $depth); $endPathRemainder = implode('/', \array_slice($endPathArr, $index)); // Construct $endPath from traversing to the common path, then to the remaining $endPath $relativePath = $traverser.('' !== $endPathRemainder ? $endPathRemainder.'/' : ''); return '' === $relativePath ? './' : $relativePath; } /** * Mirrors a directory to another. * * Copies files and directories from the origin directory into the target directory. By default: * * - existing files in the target directory will be overwritten, except if they are newer (see the `override` option) * - files in the target directory that do not exist in the source directory will not be deleted (see the `delete` option) * * @param \Traversable|null $iterator Iterator that filters which files and directories to copy, if null a recursive iterator is created * @param array $options An array of boolean options * Valid options are: * - $options['override'] If true, target files newer than origin files are overwritten (see copy(), defaults to false) * - $options['copy_on_windows'] Whether to copy files instead of links on Windows (see symlink(), defaults to false) * - $options['delete'] Whether to delete files that are not in the source directory (defaults to false) * * @throws IOException When file type is unknown */ public function mirror(string $originDir, string $targetDir, \Traversable $iterator = null, array $options = []) { $targetDir = rtrim($targetDir, '/\\'); $originDir = rtrim($originDir, '/\\'); $originDirLen = \strlen($originDir); if (!$this->exists($originDir)) { throw new IOException(sprintf('The origin directory specified "%s" was not found.', $originDir), 0, null, $originDir); } // Iterate in destination folder to remove obsolete entries if ($this->exists($targetDir) && isset($options['delete']) && $options['delete']) { $deleteIterator = $iterator; if (null === $deleteIterator) { $flags = \FilesystemIterator::SKIP_DOTS; $deleteIterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($targetDir, $flags), \RecursiveIteratorIterator::CHILD_FIRST); } $targetDirLen = \strlen($targetDir); foreach ($deleteIterator as $file) { $origin = $originDir.substr($file->getPathname(), $targetDirLen); if (!$this->exists($origin)) { $this->remove($file); } } } $copyOnWindows = $options['copy_on_windows'] ?? false; if (null === $iterator) { $flags = $copyOnWindows ? \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS : \FilesystemIterator::SKIP_DOTS; $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($originDir, $flags), \RecursiveIteratorIterator::SELF_FIRST); } $this->mkdir($targetDir); $filesCreatedWhileMirroring = []; foreach ($iterator as $file) { if ($file->getPathname() === $targetDir || $file->getRealPath() === $targetDir || isset($filesCreatedWhileMirroring[$file->getRealPath()])) { continue; } $target = $targetDir.substr($file->getPathname(), $originDirLen); $filesCreatedWhileMirroring[$target] = true; if (!$copyOnWindows && is_link($file)) { $this->symlink($file->getLinkTarget(), $target); } elseif (is_dir($file)) { $this->mkdir($target); } elseif (is_file($file)) { $this->copy($file, $target, $options['override'] ?? false); } else { throw new IOException(sprintf('Unable to guess "%s" file type.', $file), 0, null, $file); } } } /** * Returns whether the file path is an absolute path. * * @return bool */ public function isAbsolutePath(string $file) { return '' !== $file && (strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, \PHP_URL_SCHEME) ); } /** * Creates a temporary file with support for custom stream wrappers. * * @param string $prefix The prefix of the generated temporary filename * Note: Windows uses only the first three characters of prefix * @param string $suffix The suffix of the generated temporary filename * * @return string The new temporary filename (with path), or throw an exception on failure */ public function tempnam(string $dir, string $prefix/*, string $suffix = ''*/) { $suffix = \func_num_args() > 2 ? func_get_arg(2) : ''; [$scheme, $hierarchy] = $this->getSchemeAndHierarchy($dir); // If no scheme or scheme is "file" or "gs" (Google Cloud) create temp file in local filesystem if ((null === $scheme || 'file' === $scheme || 'gs' === $scheme) && '' === $suffix) { $tmpFile = @tempnam($hierarchy, $prefix); // If tempnam failed or no scheme return the filename otherwise prepend the scheme if (false !== $tmpFile) { if (null !== $scheme && 'gs' !== $scheme) { return $scheme.'://'.$tmpFile; } return $tmpFile; } throw new IOException('A temporary file could not be created.'); } // Loop until we create a valid temp file or have reached 10 attempts for ($i = 0; $i < 10; ++$i) { // Create a unique filename $tmpFile = $dir.'/'.$prefix.uniqid(mt_rand(), true).$suffix; // Use fopen instead of file_exists as some streams do not support stat // Use mode 'x+' to atomically check existence and create to avoid a TOCTOU vulnerability $handle = @fopen($tmpFile, 'x+'); // If unsuccessful restart the loop if (false === $handle) { continue; } // Close the file if it was successfully opened @fclose($handle); return $tmpFile; } throw new IOException('A temporary file could not be created.'); } /** * Atomically dumps content into a file. * * @param string|resource $content The data to write into the file * * @throws IOException if the file cannot be written to */ public function dumpFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } // Will create a temp file with 0600 access rights // when the filesystem supports chmod. $tmpFile = $this->tempnam($dir, basename($filename)); try { if (false === @file_put_contents($tmpFile, $content)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } @chmod($tmpFile, file_exists($filename) ? fileperms($filename) : 0666 & ~umask()); $this->rename($tmpFile, $filename, true); } finally { if (file_exists($tmpFile)) { @unlink($tmpFile); } } } /** * Appends content to an existing file. * * @param string|resource $content The content to append * * @throws IOException If the file is not writable */ public function appendToFile(string $filename, $content) { if (\is_array($content)) { throw new \TypeError(sprintf('Argument 2 passed to "%s()" must be string or resource, array given.', __METHOD__)); } $dir = \dirname($filename); if (!is_dir($dir)) { $this->mkdir($dir); } if (!is_writable($dir)) { throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); } if (false === @file_put_contents($filename, $content, \FILE_APPEND)) { throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); } } private function toIterable($files): iterable { return \is_array($files) || $files instanceof \Traversable ? $files : [$files]; } /** * Gets a 2-tuple of scheme (may be null) and hierarchical part of a filename (e.g. file:///tmp -> [file, tmp]). */ private function getSchemeAndHierarchy(string $filename): array { $components = explode('://', $filename, 2); return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; } /** * @return mixed */ private static function box(callable $func) { self::$lastError = null; set_error_handler(__CLASS__.'::handleError'); try { $result = $func(...\array_slice(\func_get_args(), 1)); restore_error_handler(); return $result; } catch (\Throwable $e) { } restore_error_handler(); throw $e; } /** * @internal */ public static function handleError($type, $msg) { self::$lastError = $msg; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/FileNotFoundException.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/FileNotFoundException.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem\Exception; /** * Exception class thrown when a file couldn't be found. * * @author Fabien Potencier <fabien@symfony.com> * @author Christian Gärtner <christiangaertner.film@googlemail.com> */ class FileNotFoundException extends IOException { public function __construct(string $message = null, int $code = 0, \Throwable $previous = null, string $path = null) { if (null === $message) { if (null === $path) { $message = 'File could not be found.'; } else { $message = sprintf('File "%s" could not be found.', $path); } } parent::__construct($message, $code, $previous, $path); } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/ExceptionInterface.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/ExceptionInterface.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem\Exception; /** * Exception interface for all exceptions thrown by the component. * * @author Romain Neutron <imprec@gmail.com> */ interface ExceptionInterface extends \Throwable { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/InvalidArgumentException.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/InvalidArgumentException.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem\Exception; /** * @author Christian Flothmann <christian.flothmann@sensiolabs.de> */ class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface { }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/IOException.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/IOException.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem\Exception; /** * Exception class thrown when a filesystem operation failure happens. * * @author Romain Neutron <imprec@gmail.com> * @author Christian Gärtner <christiangaertner.film@googlemail.com> * @author Fabien Potencier <fabien@symfony.com> */ class IOException extends \RuntimeException implements IOExceptionInterface { private $path; public function __construct(string $message, int $code = 0, \Throwable $previous = null, string $path = null) { $this->path = $path; parent::__construct($message, $code, $previous); } /** * {@inheritdoc} */ public function getPath() { return $this->path; } }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false
composer/composer
https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/IOExceptionInterface.php
tests/Composer/Test/Fixtures/functional/installed-versions2/vendor/symfony/filesystem/Exception/IOExceptionInterface.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Filesystem\Exception; /** * IOException interface for file and input/output stream related exceptions thrown by the component. * * @author Christian Gärtner <christiangaertner.film@googlemail.com> */ interface IOExceptionInterface extends ExceptionInterface { /** * Returns the associated path for the exception. * * @return string|null The path */ public function getPath(); }
php
MIT
be033a851d9ba436ac0d28e14734b012a58c1edc
2026-01-04T15:02:34.256072Z
false