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/Package/Archiver/ArchivableFilesFilter.php | src/Composer/Package/Archiver/ArchivableFilesFilter.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\Package\Archiver;
use FilterIterator;
use Iterator;
use PharData;
use SplFileInfo;
/**
* @phpstan-extends FilterIterator<string, SplFileInfo, Iterator<string, SplFileInfo>>
*/
class ArchivableFilesFilter extends FilterIterator
{
/** @var string[] */
private $dirs = [];
/**
* @return bool true if the current element is acceptable, otherwise false.
*/
public function accept(): bool
{
$file = $this->getInnerIterator()->current();
if ($file->isDir()) {
$this->dirs[] = (string) $file;
return false;
}
return true;
}
public function addEmptyDir(PharData $phar, string $sources): void
{
foreach ($this->dirs as $filepath) {
$localname = str_replace($sources . "/", '', $filepath);
$phar->addEmptyDir($localname);
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/PharArchiver.php | src/Composer/Package/Archiver/PharArchiver.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\Package\Archiver;
use PharData;
/**
* @author Till Klampaeckel <till@php.net>
* @author Nils Adermann <naderman@naderman.de>
* @author Matthieu Moquet <matthieu@moquet.net>
*/
class PharArchiver implements ArchiverInterface
{
/** @var array<string, int> */
protected static $formats = [
'zip' => \Phar::ZIP,
'tar' => \Phar::TAR,
'tar.gz' => \Phar::TAR,
'tar.bz2' => \Phar::TAR,
];
/** @var array<string, int> */
protected static $compressFormats = [
'tar.gz' => \Phar::GZ,
'tar.bz2' => \Phar::BZ2,
];
/**
* @inheritDoc
*/
public function archive(string $sources, string $target, string $format, array $excludes = [], bool $ignoreFilters = false): string
{
$sources = realpath($sources);
// Phar would otherwise load the file which we don't want
if (file_exists($target)) {
unlink($target);
}
try {
$filename = substr($target, 0, strrpos($target, $format) - 1);
// Check if compress format
if (isset(static::$compressFormats[$format])) {
// Current compress format supported base on tar
$target = $filename . '.tar';
}
$phar = new PharData(
$target,
\FilesystemIterator::KEY_AS_PATHNAME | \FilesystemIterator::CURRENT_AS_FILEINFO,
'',
static::$formats[$format]
);
$files = new ArchivableFilesFinder($sources, $excludes, $ignoreFilters);
$filesOnly = new ArchivableFilesFilter($files);
$phar->buildFromIterator($filesOnly, $sources);
$filesOnly->addEmptyDir($phar, $sources);
if (!file_exists($target)) {
$target = $filename . '.' . $format;
unset($phar);
if ($format === 'tar') {
// create an empty tar file (=10240 null bytes) if the tar file is empty and PharData thus did not write it to disk
file_put_contents($target, str_repeat("\0", 10240));
} elseif ($format === 'zip') {
// create minimal valid ZIP file (Empty Central Directory + End of Central Directory record)
$eocd = pack(
'VvvvvVVv',
0x06054b50, // End of central directory signature
0, // Number of this disk
0, // Disk where central directory starts
0, // Number of central directory records on this disk
0, // Total number of central directory records
0, // Size of central directory (bytes)
0, // Offset of start of central directory
0 // Comment length
);
file_put_contents($target, $eocd);
} elseif ($format === 'tar.gz' || $format === 'tar.bz2') {
if (!PharData::canCompress(static::$compressFormats[$format])) {
throw new \RuntimeException(sprintf('Can not compress to %s format', $format));
}
if ($format === 'tar.gz' && function_exists('gzcompress')) {
file_put_contents($target, gzcompress(str_repeat("\0", 10240)));
} elseif ($format === 'tar.bz2' && function_exists('bzcompress')) {
file_put_contents($target, bzcompress(str_repeat("\0", 10240)));
}
}
return $target;
}
if (isset(static::$compressFormats[$format])) {
// Check can be compressed?
if (!PharData::canCompress(static::$compressFormats[$format])) {
throw new \RuntimeException(sprintf('Can not compress to %s format', $format));
}
// Delete old tar
unlink($target);
// Compress the new tar
$phar->compress(static::$compressFormats[$format]);
// Make the correct filename
$target = $filename . '.' . $format;
}
return $target;
} catch (\UnexpectedValueException $e) {
$message = sprintf(
"Could not create archive '%s' from '%s': %s",
$target,
$sources,
$e->getMessage()
);
throw new \RuntimeException($message, $e->getCode(), $e);
}
}
/**
* @inheritDoc
*/
public function supports(string $format, ?string $sourceType): bool
{
return isset(static::$formats[$format]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/GitExcludeFilter.php | src/Composer/Package/Archiver/GitExcludeFilter.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\Package\Archiver;
use Composer\Pcre\Preg;
/**
* An exclude filter that processes gitattributes
*
* It respects export-ignore git attributes
*
* @author Nils Adermann <naderman@naderman.de>
*/
class GitExcludeFilter extends BaseExcludeFilter
{
/**
* Parses .gitattributes if it exists
*/
public function __construct(string $sourcePath)
{
parent::__construct($sourcePath);
if (file_exists($sourcePath.'/.gitattributes')) {
$this->excludePatterns = array_merge(
$this->excludePatterns,
$this->parseLines(
file($sourcePath.'/.gitattributes'),
[$this, 'parseGitAttributesLine']
)
);
}
}
/**
* Callback parser which finds export-ignore rules in git attribute lines
*
* @param string $line A line from .gitattributes
*
* @return array{0: string, 1: bool, 2: bool}|null An exclude pattern for filter()
*/
public function parseGitAttributesLine(string $line): ?array
{
$parts = Preg::split('#\s+#', $line);
if (count($parts) === 2 && $parts[1] === 'export-ignore') {
return $this->generatePattern($parts[0]);
}
if (count($parts) === 2 && $parts[1] === '-export-ignore') {
return $this->generatePattern('!'.$parts[0]);
}
return null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/ComposerExcludeFilter.php | src/Composer/Package/Archiver/ComposerExcludeFilter.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\Package\Archiver;
/**
* An exclude filter which processes composer's own exclude rules
*
* @author Nils Adermann <naderman@naderman.de>
*/
class ComposerExcludeFilter extends BaseExcludeFilter
{
/**
* @param string $sourcePath Directory containing sources to be filtered
* @param string[] $excludeRules An array of exclude rules from composer.json
*/
public function __construct(string $sourcePath, array $excludeRules)
{
parent::__construct($sourcePath);
$this->excludePatterns = $this->generatePatterns($excludeRules);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Archiver/ArchiverInterface.php | src/Composer/Package/Archiver/ArchiverInterface.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\Package\Archiver;
/**
* @author Till Klampaeckel <till@php.net>
* @author Matthieu Moquet <matthieu@moquet.net>
* @author Nils Adermann <naderman@naderman.de>
*/
interface ArchiverInterface
{
/**
* Create an archive from the sources.
*
* @param string $sources The sources directory
* @param string $target The target file
* @param string $format The format used for archive
* @param string[] $excludes A list of patterns for files to exclude
* @param bool $ignoreFilters Whether to ignore filters when looking for files
*
* @return string The path to the written archive file
*/
public function archive(string $sources, string $target, string $format, array $excludes = [], bool $ignoreFilters = false): string;
/**
* Format supported by the archiver.
*
* @param string $format The archive format
* @param ?string $sourceType The source type (git, svn, hg, etc.)
*
* @return bool true if the format is supported by the archiver
*/
public function supports(string $format, ?string $sourceType): bool;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Dumper/ArrayDumper.php | src/Composer/Package/Dumper/ArrayDumper.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\Package\Dumper;
use Composer\Package\BasePackage;
use Composer\Package\PackageInterface;
use Composer\Package\CompletePackageInterface;
use Composer\Package\RootPackageInterface;
/**
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ArrayDumper
{
/**
* @return array<string, mixed>
*/
public function dump(PackageInterface $package): array
{
$keys = [
'binaries' => 'bin',
'type',
'extra',
'installationSource' => 'installation-source',
'autoload',
'devAutoload' => 'autoload-dev',
'notificationUrl' => 'notification-url',
'includePaths' => 'include-path',
'phpExt' => 'php-ext',
];
$data = [];
$data['name'] = $package->getPrettyName();
$data['version'] = $package->getPrettyVersion();
$data['version_normalized'] = $package->getVersion();
if ($package->getTargetDir() !== null) {
$data['target-dir'] = $package->getTargetDir();
}
if ($package->getSourceType() !== null) {
$data['source']['type'] = $package->getSourceType();
$data['source']['url'] = $package->getSourceUrl();
if (null !== ($value = $package->getSourceReference())) {
$data['source']['reference'] = $value;
}
if ($mirrors = $package->getSourceMirrors()) {
$data['source']['mirrors'] = $mirrors;
}
}
if ($package->getDistType() !== null) {
$data['dist']['type'] = $package->getDistType();
$data['dist']['url'] = $package->getDistUrl();
if (null !== ($value = $package->getDistReference())) {
$data['dist']['reference'] = $value;
}
if (null !== ($value = $package->getDistSha1Checksum())) {
$data['dist']['shasum'] = $value;
}
if ($mirrors = $package->getDistMirrors()) {
$data['dist']['mirrors'] = $mirrors;
}
}
foreach (BasePackage::$supportedLinkTypes as $type => $opts) {
$links = $package->{'get'.ucfirst($opts['method'])}();
if (\count($links) === 0) {
continue;
}
foreach ($links as $link) {
$data[$type][$link->getTarget()] = $link->getPrettyConstraint();
}
ksort($data[$type]);
}
$packages = $package->getSuggests();
if (\count($packages) > 0) {
ksort($packages);
$data['suggest'] = $packages;
}
if ($package->getReleaseDate() instanceof \DateTimeInterface) {
$data['time'] = $package->getReleaseDate()->format(DATE_RFC3339);
}
if ($package->isDefaultBranch()) {
$data['default-branch'] = true;
}
$data = $this->dumpValues($package, $keys, $data);
if ($package instanceof CompletePackageInterface) {
if ($package->getArchiveName()) {
$data['archive']['name'] = $package->getArchiveName();
}
if ($package->getArchiveExcludes()) {
$data['archive']['exclude'] = $package->getArchiveExcludes();
}
$keys = [
'scripts',
'license',
'authors',
'description',
'homepage',
'keywords',
'repositories',
'support',
'funding',
];
$data = $this->dumpValues($package, $keys, $data);
if (isset($data['keywords']) && \is_array($data['keywords'])) {
sort($data['keywords']);
}
if ($package->isAbandoned()) {
$data['abandoned'] = $package->getReplacementPackage() ?: true;
}
}
if ($package instanceof RootPackageInterface) {
$minimumStability = $package->getMinimumStability();
if ($minimumStability !== '') {
$data['minimum-stability'] = $minimumStability;
}
}
if (\count($package->getTransportOptions()) > 0) {
$data['transport-options'] = $package->getTransportOptions();
}
return $data;
}
/**
* @param array<int|string, string> $keys
* @param array<string, mixed> $data
*
* @return array<string, mixed>
*/
private function dumpValues(PackageInterface $package, array $keys, array $data): array
{
foreach ($keys as $method => $key) {
if (is_numeric($method)) {
$method = $key;
}
$getter = 'get'.ucfirst($method);
$value = $package->{$getter}();
if (null !== $value && !(\is_array($value) && 0 === \count($value))) {
$data[$key] = $value;
}
}
return $data;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/ValidatingArrayLoader.php | src/Composer/Package/Loader/ValidatingArrayLoader.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\Package\Loader;
use Composer\Package\BasePackage;
use Composer\Pcre\Preg;
use Composer\Semver\Constraint\Constraint;
use Composer\Package\Version\VersionParser;
use Composer\Repository\PlatformRepository;
use Composer\Semver\Constraint\MatchNoneConstraint;
use Composer\Semver\Intervals;
use Composer\Spdx\SpdxLicenses;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ValidatingArrayLoader implements LoaderInterface
{
public const CHECK_ALL = 3;
public const CHECK_UNBOUND_CONSTRAINTS = 1;
public const CHECK_STRICT_CONSTRAINTS = 2;
/** @var LoaderInterface */
private $loader;
/** @var VersionParser */
private $versionParser;
/** @var list<string> */
private $errors;
/** @var list<string> */
private $warnings;
/** @var mixed[] */
private $config;
/** @var int One or more of self::CHECK_* constants */
private $flags;
/**
* @param true $strictName
*/
public function __construct(LoaderInterface $loader, bool $strictName = true, ?VersionParser $parser = null, int $flags = 0)
{
$this->loader = $loader;
$this->versionParser = $parser ?? new VersionParser();
$this->flags = $flags;
if ($strictName !== true) { // @phpstan-ignore-line
trigger_error('$strictName must be set to true in ValidatingArrayLoader\'s constructor as of 2.2, and it will be removed in 3.0', E_USER_DEPRECATED);
}
}
/**
* @inheritDoc
*/
public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage
{
$this->errors = [];
$this->warnings = [];
$this->config = $config;
$this->validateString('name', true);
if (isset($config['name']) && null !== ($err = self::hasPackageNamingError($config['name']))) {
$this->errors[] = 'name : '.$err;
}
if (isset($this->config['version'])) {
if (!is_scalar($this->config['version'])) {
$this->validateString('version');
} else {
if (!is_string($this->config['version'])) {
$this->config['version'] = (string) $this->config['version'];
}
try {
$this->versionParser->normalize($this->config['version']);
} catch (\Exception $e) {
$this->errors[] = 'version : invalid value ('.$this->config['version'].'): '.$e->getMessage();
unset($this->config['version']);
}
}
}
if (isset($this->config['config']['platform'])) {
foreach ((array) $this->config['config']['platform'] as $key => $platform) {
if (false === $platform) {
continue;
}
if (!is_string($platform)) {
$this->errors[] = 'config.platform.' . $key . ' : invalid value ('.get_debug_type($platform).' '.var_export($platform, true).'): expected string or false';
continue;
}
try {
$this->versionParser->normalize($platform);
} catch (\Exception $e) {
$this->errors[] = 'config.platform.' . $key . ' : invalid value ('.$platform.'): '.$e->getMessage();
}
}
}
$this->validateRegex('type', '[A-Za-z0-9-]+');
$this->validateString('target-dir');
$this->validateArray('extra');
if (isset($this->config['bin'])) {
if (is_string($this->config['bin'])) {
$this->validateString('bin');
} else {
$this->validateFlatArray('bin');
}
}
$this->validateArray('scripts'); // TODO validate event names & listener syntax
$this->validateString('description');
$this->validateUrl('homepage');
$this->validateFlatArray('keywords', '[\p{N}\p{L} ._-]+');
$releaseDate = null;
$this->validateString('time');
if (isset($this->config['time'])) {
try {
$releaseDate = new \DateTime($this->config['time'], new \DateTimeZone('UTC'));
} catch (\Exception $e) {
$this->errors[] = 'time : invalid value ('.$this->config['time'].'): '.$e->getMessage();
unset($this->config['time']);
}
}
if (isset($this->config['license'])) {
// validate main data types
if (is_array($this->config['license']) || is_string($this->config['license'])) {
$licenses = (array) $this->config['license'];
foreach ($licenses as $index => $license) {
if (!is_string($license)) {
$this->warnings[] = sprintf(
'License %s should be a string.',
json_encode($license)
);
unset($licenses[$index]);
}
}
// check for license validity on newly updated branches/tags
if (null === $releaseDate || $releaseDate->getTimestamp() >= strtotime('-8days')) {
$licenseValidator = new SpdxLicenses();
foreach ($licenses as $license) {
// replace proprietary by MIT for validation purposes since it's not a valid SPDX identifier, but is accepted by composer
if ('proprietary' === $license) {
continue;
}
$licenseToValidate = str_replace('proprietary', 'MIT', $license);
if (!$licenseValidator->validate($licenseToValidate)) {
if ($licenseValidator->validate(trim($licenseToValidate))) {
$this->warnings[] = sprintf(
'License %s must not contain extra spaces, make sure to trim it.',
json_encode($license)
);
} else {
$this->warnings[] = sprintf(
'License %s is not a valid SPDX license identifier, see https://spdx.org/licenses/ if you use an open license.' . PHP_EOL .
'If the software is closed-source, you may use "proprietary" as license.',
json_encode($license)
);
}
}
}
}
$this->config['license'] = array_values($licenses);
} else {
$this->warnings[] = sprintf(
'License must be a string or array of strings, got %s.',
json_encode($this->config['license'])
);
unset($this->config['license']);
}
}
if ($this->validateArray('authors')) {
foreach ($this->config['authors'] as $key => $author) {
if (!is_array($author)) {
$this->errors[] = 'authors.'.$key.' : should be an array, '.get_debug_type($author).' given';
unset($this->config['authors'][$key]);
continue;
}
foreach (['homepage', 'email', 'name', 'role'] as $authorData) {
if (isset($author[$authorData]) && !is_string($author[$authorData])) {
$this->errors[] = 'authors.'.$key.'.'.$authorData.' : invalid value, must be a string';
unset($this->config['authors'][$key][$authorData]);
}
}
if (isset($author['homepage']) && !$this->filterUrl($author['homepage'])) {
$this->warnings[] = 'authors.'.$key.'.homepage : invalid value ('.$author['homepage'].'), must be an http/https URL';
unset($this->config['authors'][$key]['homepage']);
}
if (isset($author['email']) && false === filter_var($author['email'], FILTER_VALIDATE_EMAIL)) {
$this->warnings[] = 'authors.'.$key.'.email : invalid value ('.$author['email'].'), must be a valid email address';
unset($this->config['authors'][$key]['email']);
}
if (\count($this->config['authors'][$key]) === 0) {
unset($this->config['authors'][$key]);
}
}
if (\count($this->config['authors']) === 0) {
unset($this->config['authors']);
}
}
if ($this->validateArray('support') && !empty($this->config['support'])) {
foreach (['issues', 'forum', 'wiki', 'source', 'email', 'irc', 'docs', 'rss', 'chat', 'security'] as $key) {
if (isset($this->config['support'][$key]) && !is_string($this->config['support'][$key])) {
$this->errors[] = 'support.'.$key.' : invalid value, must be a string';
unset($this->config['support'][$key]);
}
}
if (isset($this->config['support']['email']) && !filter_var($this->config['support']['email'], FILTER_VALIDATE_EMAIL)) {
$this->warnings[] = 'support.email : invalid value ('.$this->config['support']['email'].'), must be a valid email address';
unset($this->config['support']['email']);
}
if (isset($this->config['support']['irc']) && !$this->filterUrl($this->config['support']['irc'], ['irc', 'ircs'])) {
$this->warnings[] = 'support.irc : invalid value ('.$this->config['support']['irc'].'), must be a irc://<server>/<channel> or ircs:// URL';
unset($this->config['support']['irc']);
}
foreach (['issues', 'forum', 'wiki', 'source', 'docs', 'chat', 'security'] as $key) {
if (isset($this->config['support'][$key]) && !$this->filterUrl($this->config['support'][$key])) {
$this->warnings[] = 'support.'.$key.' : invalid value ('.$this->config['support'][$key].'), must be an http/https URL';
unset($this->config['support'][$key]);
}
}
if (empty($this->config['support'])) {
unset($this->config['support']);
}
}
if ($this->validateArray('funding') && !empty($this->config['funding'])) {
foreach ($this->config['funding'] as $key => $fundingOption) {
if (!is_array($fundingOption)) {
$this->errors[] = 'funding.'.$key.' : should be an array, '.get_debug_type($fundingOption).' given';
unset($this->config['funding'][$key]);
continue;
}
foreach (['type', 'url'] as $fundingData) {
if (isset($fundingOption[$fundingData]) && !is_string($fundingOption[$fundingData])) {
$this->errors[] = 'funding.'.$key.'.'.$fundingData.' : invalid value, must be a string';
unset($this->config['funding'][$key][$fundingData]);
}
}
if (isset($fundingOption['url']) && !$this->filterUrl($fundingOption['url'])) {
$this->warnings[] = 'funding.'.$key.'.url : invalid value ('.$fundingOption['url'].'), must be an http/https URL';
unset($this->config['funding'][$key]['url']);
}
if (empty($this->config['funding'][$key])) {
unset($this->config['funding'][$key]);
}
}
if (empty($this->config['funding'])) {
unset($this->config['funding']);
}
}
if (isset($this->config['php-ext']) && $this->validateArray('php-ext')) {
if (!in_array($this->config['type'] ?? '', ['php-ext', 'php-ext-zend'], true)) {
$this->errors[] = 'php-ext can only be set by packages of type "php-ext" or "php-ext-zend" which must be C extensions';
unset($this->config['php-ext']);
}
$phpExt = &$this->config['php-ext'];
if (isset($phpExt['extension-name']) && !is_string($phpExt['extension-name'])) {
$this->errors[] = 'php-ext.extension-name : should be a string, '.get_debug_type($phpExt['extension-name']).' given';
unset($phpExt['extension-name']);
}
if (isset($phpExt['priority']) && !is_int($phpExt['priority'])) {
$this->errors[] = 'php-ext.priority : should be an integer, '.get_debug_type($phpExt['priority']).' given';
unset($phpExt['priority']);
}
if (isset($phpExt['support-zts']) && !is_bool($phpExt['support-zts'])) {
$this->errors[] = 'php-ext.support-zts : should be a boolean, '.get_debug_type($phpExt['support-zts']).' given';
unset($phpExt['support-zts']);
}
if (isset($phpExt['support-nts']) && !is_bool($phpExt['support-nts'])) {
$this->errors[] = 'php-ext.support-nts : should be a boolean, '.get_debug_type($phpExt['support-nts']).' given';
unset($phpExt['support-nts']);
}
if (isset($phpExt['build-path']) && !is_string($phpExt['build-path']) && !is_null($phpExt['build-path'])) {
$this->errors[] = 'php-ext.build-path : should be a string or null, '.get_debug_type($phpExt['build-path']).' given';
unset($phpExt['build-path']);
}
if (isset($phpExt['download-url-method'])) {
if (!is_string($phpExt['download-url-method'])) {
$this->errors[] = 'php-ext.download-url-method : should be a string, '.get_debug_type($phpExt['download-url-method']).' given';
unset($phpExt['download-url-method']);
} elseif (!in_array($phpExt['download-url-method'], ['composer-default', 'pre-packaged-source'], true)) {
$this->errors[] = 'php-ext.download-url-method : invalid value ('.$phpExt['download-url-method'].'), must be one of composer-default, pre-packaged-source';
unset($phpExt['download-url-method']);
}
}
if (isset($phpExt['os-families']) && isset($phpExt['os-families-exclude'])) {
$this->errors[] = 'php-ext : os-families and os-families-exclude cannot both be specified';
unset($phpExt['os-families'], $phpExt['os-families-exclude']);
} else {
$validOsFamilies = ['windows', 'bsd', 'darwin', 'solaris', 'linux', 'unknown'];
foreach (['os-families', 'os-families-exclude'] as $fieldName) {
if (isset($phpExt[$fieldName])) {
if (!is_array($phpExt[$fieldName])) {
$this->errors[] = 'php-ext.'.$fieldName.' : should be an array, '.get_debug_type($phpExt[$fieldName]).' given';
unset($phpExt[$fieldName]);
} elseif ([] === $phpExt[$fieldName]) {
$this->errors[] = 'php-ext.'.$fieldName.' : must contain at least one element';
unset($phpExt[$fieldName]);
} else {
foreach ($phpExt[$fieldName] as $key => $osFamily) {
if (!is_string($osFamily)) {
$this->errors[] = 'php-ext.'.$fieldName.'.'.$key.' : should be a string, '.get_debug_type($osFamily).' given';
unset($phpExt[$fieldName][$key]);
} elseif (!in_array($osFamily, $validOsFamilies, true)) {
$this->errors[] = 'php-ext.'.$fieldName.'.'.$key.' : invalid value ('.$osFamily.'), must be one of '.implode(', ', $validOsFamilies);
unset($phpExt[$fieldName][$key]);
}
}
if ([] === $phpExt[$fieldName]) {
unset($phpExt[$fieldName]);
}
}
}
}
}
if (isset($phpExt['configure-options'])) {
if (!is_array($phpExt['configure-options'])) {
$this->errors[] = 'php-ext.configure-options : should be an array, '.get_debug_type($phpExt['configure-options']).' given';
unset($phpExt['configure-options']);
} else {
foreach ($phpExt['configure-options'] as $key => $option) {
if (!is_array($option)) {
$this->errors[] = 'php-ext.configure-options.'.$key.' : should be an array, '.get_debug_type($option).' given';
unset($phpExt['configure-options'][$key]);
continue;
}
if (!isset($option['name'])) {
$this->errors[] = 'php-ext.configure-options.'.$key.'.name : must be present';
unset($phpExt['configure-options'][$key]);
continue;
}
if (!is_string($option['name'])) {
$this->errors[] = 'php-ext.configure-options.'.$key.'.name : should be a string, '.get_debug_type($option['name']).' given';
unset($phpExt['configure-options'][$key]);
continue;
}
if (isset($option['needs-value']) && !is_bool($option['needs-value'])) {
$this->errors[] = 'php-ext.configure-options.'.$key.'.needs-value : should be a boolean, '.get_debug_type($option['needs-value']).' given';
unset($phpExt['configure-options'][$key]['needs-value']);
}
if (isset($option['description']) && !is_string($option['description'])) {
$this->errors[] = 'php-ext.configure-options.'.$key.'.description : should be a string, '.get_debug_type($option['description']).' given';
unset($phpExt['configure-options'][$key]['description']);
}
}
if ([] === $phpExt['configure-options']) {
unset($phpExt['configure-options']);
}
}
}
// If php-ext is now empty, unset it
if ([] === $phpExt) {
unset($this->config['php-ext']);
}
unset($phpExt);
}
$unboundConstraint = new Constraint('=', '10000000-dev');
foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) {
if ($this->validateArray($linkType) && isset($this->config[$linkType])) {
foreach ($this->config[$linkType] as $package => $constraint) {
$package = (string) $package;
if (isset($this->config['name']) && 0 === strcasecmp($package, $this->config['name'])) {
$this->errors[] = $linkType.'.'.$package.' : a package cannot set a '.$linkType.' on itself';
unset($this->config[$linkType][$package]);
continue;
}
if ($err = self::hasPackageNamingError($package, true)) {
$this->warnings[] = $linkType.'.'.$err;
} elseif (!Preg::isMatch('{^[A-Za-z0-9_./-]+$}', $package)) {
$this->errors[] = $linkType.'.'.$package.' : invalid key, package names must be strings containing only [A-Za-z0-9_./-]';
}
if (!is_string($constraint)) {
$this->errors[] = $linkType.'.'.$package.' : invalid value, must be a string containing a version constraint';
unset($this->config[$linkType][$package]);
} elseif ('self.version' !== $constraint) {
try {
$linkConstraint = $this->versionParser->parseConstraints($constraint);
} catch (\Exception $e) {
$this->errors[] = $linkType.'.'.$package.' : invalid version constraint ('.$e->getMessage().')';
unset($this->config[$linkType][$package]);
continue;
}
// check requires for unbound constraints on non-platform packages
if (
($this->flags & self::CHECK_UNBOUND_CONSTRAINTS)
&& 'require' === $linkType
&& $linkConstraint->matches($unboundConstraint)
&& !PlatformRepository::isPlatformPackage($package)
) {
$this->warnings[] = $linkType.'.'.$package.' : unbound version constraints ('.$constraint.') should be avoided';
} elseif (
// check requires for exact constraints
($this->flags & self::CHECK_STRICT_CONSTRAINTS)
&& 'require' === $linkType
&& $linkConstraint instanceof Constraint && in_array($linkConstraint->getOperator(), ['==', '='], true)
&& (new Constraint('>=', '1.0.0.0-dev'))->matches($linkConstraint)
) {
$this->warnings[] = $linkType.'.'.$package.' : exact version constraints ('.$constraint.') should be avoided if the package follows semantic versioning';
}
$compacted = Intervals::compactConstraint($linkConstraint);
if ($compacted instanceof MatchNoneConstraint) {
$this->warnings[] = $linkType.'.'.$package.' : this version constraint cannot possibly match anything ('.$constraint.')';
}
}
if ($linkType === 'conflict' && isset($this->config['replace']) && $keys = array_intersect_key($this->config['replace'], $this->config['conflict'])) {
$this->errors[] = $linkType.'.'.$package.' : you cannot conflict with a package that is also replaced, as replace already creates an implicit conflict rule';
unset($this->config[$linkType][$package]);
}
}
}
}
if ($this->validateArray('suggest') && isset($this->config['suggest'])) {
foreach ($this->config['suggest'] as $package => $description) {
if (!is_string($description)) {
$this->errors[] = 'suggest.'.$package.' : invalid value, must be a string describing why the package is suggested';
unset($this->config['suggest'][$package]);
}
}
}
if ($this->validateString('minimum-stability') && isset($this->config['minimum-stability'])) {
if (!isset(BasePackage::STABILITIES[strtolower($this->config['minimum-stability'])]) && $this->config['minimum-stability'] !== 'RC') {
$this->errors[] = 'minimum-stability : invalid value ('.$this->config['minimum-stability'].'), must be one of '.implode(', ', array_keys(BasePackage::STABILITIES));
unset($this->config['minimum-stability']);
}
}
if ($this->validateArray('autoload') && isset($this->config['autoload'])) {
$types = ['psr-0', 'psr-4', 'classmap', 'files', 'exclude-from-classmap'];
foreach ($this->config['autoload'] as $type => $typeConfig) {
if (!in_array($type, $types)) {
$this->errors[] = 'autoload : invalid value ('.$type.'), must be one of '.implode(', ', $types);
unset($this->config['autoload'][$type]);
}
if ($type === 'psr-4') {
foreach ($typeConfig as $namespace => $dirs) {
if ($namespace !== '' && '\\' !== substr((string) $namespace, -1)) {
$this->errors[] = 'autoload.psr-4 : invalid value ('.$namespace.'), namespaces must end with a namespace separator, should be '.$namespace.'\\\\';
}
}
}
}
}
if (isset($this->config['autoload']['psr-4']) && isset($this->config['target-dir'])) {
$this->errors[] = 'target-dir : this can not be used together with the autoload.psr-4 setting, remove target-dir to upgrade to psr-4';
// Unset the psr-4 setting, since unsetting target-dir might
// interfere with other settings.
unset($this->config['autoload']['psr-4']);
}
foreach (['source', 'dist'] as $srcType) {
if ($this->validateArray($srcType) && !empty($this->config[$srcType])) {
if (!isset($this->config[$srcType]['type'])) {
$this->errors[] = $srcType . '.type : must be present';
}
if (!isset($this->config[$srcType]['url'])) {
$this->errors[] = $srcType . '.url : must be present';
}
if ($srcType === 'source' && !isset($this->config[$srcType]['reference'])) {
$this->errors[] = $srcType . '.reference : must be present';
}
if (isset($this->config[$srcType]['type']) && !is_string($this->config[$srcType]['type'])) {
$this->errors[] = $srcType . '.type : should be a string, '.get_debug_type($this->config[$srcType]['type']).' given';
}
if (isset($this->config[$srcType]['url']) && !is_string($this->config[$srcType]['url'])) {
$this->errors[] = $srcType . '.url : should be a string, '.get_debug_type($this->config[$srcType]['url']).' given';
}
if (isset($this->config[$srcType]['reference']) && !is_string($this->config[$srcType]['reference']) && !is_int($this->config[$srcType]['reference'])) {
$this->errors[] = $srcType . '.reference : should be a string or int, '.get_debug_type($this->config[$srcType]['reference']).' given';
}
if (isset($this->config[$srcType]['reference']) && Preg::isMatch('{^\s*-}', (string) $this->config[$srcType]['reference'])) {
$this->errors[] = $srcType . '.reference : must not start with a "-", "'.$this->config[$srcType]['reference'].'" given';
}
if (isset($this->config[$srcType]['url']) && Preg::isMatch('{^\s*-}', (string) $this->config[$srcType]['url'])) {
$this->errors[] = $srcType . '.url : must not start with a "-", "'.$this->config[$srcType]['url'].'" given';
}
}
}
// TODO validate repositories
// TODO validate package repositories' packages using this recursively
$this->validateFlatArray('include-path');
$this->validateArray('transport-options');
// branch alias validation
if (isset($this->config['extra']['branch-alias'])) {
if (!is_array($this->config['extra']['branch-alias'])) {
$this->errors[] = 'extra.branch-alias : must be an array of versions => aliases';
} else {
foreach ($this->config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
if (!is_string($targetBranch)) {
$this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.json_encode($targetBranch).') must be a string, "'.get_debug_type($targetBranch).'" received.';
unset($this->config['extra']['branch-alias'][$sourceBranch]);
continue;
}
// ensure it is an alias to a -dev package
if ('-dev' !== substr($targetBranch, -4)) {
$this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must end in -dev';
unset($this->config['extra']['branch-alias'][$sourceBranch]);
continue;
}
// normalize without -dev and ensure it's a numeric branch that is parseable
$validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
if ('-dev' !== substr($validatedTargetBranch, -4)) {
$this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must be a parseable number like 2.0-dev';
unset($this->config['extra']['branch-alias'][$sourceBranch]);
continue;
}
// If using numeric aliases ensure the alias is a valid subversion
if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
&& ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
&& (stripos($targetPrefix, $sourcePrefix) !== 0)
) {
$this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') is not a valid numeric alias for this version';
unset($this->config['extra']['branch-alias'][$sourceBranch]);
}
}
}
}
if ($this->errors) {
throw new InvalidPackageException($this->errors, $this->warnings, $config);
}
$package = $this->loader->load($this->config, $class);
$this->config = [];
return $package;
}
/**
* @return list<string>
*/
public function getWarnings(): array
{
return $this->warnings;
}
/**
* @return list<string>
*/
public function getErrors(): array
{
return $this->errors;
}
public static function hasPackageNamingError(string $name, bool $isLink = false): ?string
{
if (PlatformRepository::isPlatformPackage($name)) {
return null;
}
if (!Preg::isMatch('{^[a-z0-9](?:[_.-]?[a-z0-9]++)*+/[a-z0-9](?:(?:[_.]|-{1,2})?[a-z0-9]++)*+$}iD', $name)) {
return $name.' is invalid, it should have a vendor name, a forward slash, and a package name. The vendor and package name can be words separated by -, . or _. The complete name should match "^[a-z0-9]([_.-]?[a-z0-9]+)*/[a-z0-9](([_.]?|-{0,2})[a-z0-9]+)*$".';
}
$reservedNames = ['nul', 'con', 'prn', 'aux', 'com1', 'com2', 'com3', 'com4', 'com5', 'com6', 'com7', 'com8', 'com9', 'lpt1', 'lpt2', 'lpt3', 'lpt4', 'lpt5', 'lpt6', 'lpt7', 'lpt8', 'lpt9'];
$bits = explode('/', strtolower($name));
if (in_array($bits[0], $reservedNames, true) || in_array($bits[1], $reservedNames, true)) {
return $name.' is reserved, package and vendor names can not match any of: '.implode(', ', $reservedNames).'.';
}
if (Preg::isMatch('{\.json$}', $name)) {
return $name.' is invalid, package names can not end in .json, consider renaming it or perhaps using a -json suffix instead.';
}
if (Preg::isMatch('{[A-Z]}', $name)) {
if ($isLink) {
return $name.' is invalid, it should not contain uppercase characters. Please use '.strtolower($name).' instead.';
}
$suggestName = Preg::replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
$suggestName = strtolower($suggestName);
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/ArrayLoader.php | src/Composer/Package/Loader/ArrayLoader.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\Package\Loader;
use Composer\Package\BasePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\CompletePackage;
use Composer\Package\RootPackage;
use Composer\Package\PackageInterface;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Link;
use Composer\Package\RootAliasPackage;
use Composer\Package\Version\VersionParser;
use Composer\Pcre\Preg;
/**
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ArrayLoader implements LoaderInterface
{
/** @var VersionParser */
protected $versionParser;
/** @var bool */
protected $loadOptions;
public function __construct(?VersionParser $parser = null, bool $loadOptions = false)
{
if (!$parser) {
$parser = new VersionParser;
}
$this->versionParser = $parser;
$this->loadOptions = $loadOptions;
}
/**
* @inheritDoc
*/
public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage
{
if ($class !== 'Composer\Package\CompletePackage' && $class !== 'Composer\Package\RootPackage') {
trigger_error('The $class arg is deprecated, please reach out to Composer maintainers ASAP if you still need this.', E_USER_DEPRECATED);
}
$package = $this->createObject($config, $class);
foreach (BasePackage::$supportedLinkTypes as $type => $opts) {
if (!isset($config[$type]) || !is_array($config[$type])) {
continue;
}
$method = 'set'.ucfirst($opts['method']);
$package->{$method}(
$this->parseLinks(
$package->getName(),
$package->getPrettyVersion(),
$opts['method'],
$config[$type]
)
);
}
$package = $this->configureObject($package, $config);
return $package;
}
/**
* @param array<array<mixed>> $versions
*
* @return list<CompletePackage|CompleteAliasPackage>
*/
public function loadPackages(array $versions): array
{
$packages = [];
$linkCache = [];
foreach ($versions as $version) {
$package = $this->createObject($version, 'Composer\Package\CompletePackage');
$this->configureCachedLinks($linkCache, $package, $version);
$package = $this->configureObject($package, $version);
$packages[] = $package;
}
return $packages;
}
/**
* @template PackageClass of CompletePackage
*
* @param mixed[] $config package data
* @param string $class FQCN to be instantiated
*
* @return CompletePackage|RootPackage
*
* @phpstan-param class-string<PackageClass> $class
*/
private function createObject(array $config, string $class): CompletePackage
{
if (!isset($config['name'])) {
throw new \UnexpectedValueException('Unknown package has no name defined ('.json_encode($config).').');
}
if (!isset($config['version']) || !is_scalar($config['version'])) {
throw new \UnexpectedValueException('Package '.$config['name'].' has no version defined.');
}
if (!is_string($config['version'])) {
$config['version'] = (string) $config['version'];
}
// handle already normalized versions
if (isset($config['version_normalized']) && is_string($config['version_normalized'])) {
$version = $config['version_normalized'];
// handling of existing repos which need to remain composer v1 compatible, in case the version_normalized contained VersionParser::DEFAULT_BRANCH_ALIAS, we renormalize it
if ($version === VersionParser::DEFAULT_BRANCH_ALIAS) {
$version = $this->versionParser->normalize($config['version']);
}
} else {
$version = $this->versionParser->normalize($config['version']);
}
return new $class($config['name'], $version, $config['version']);
}
/**
* @param CompletePackage $package
* @param mixed[] $config package data
*
* @return RootPackage|RootAliasPackage|CompletePackage|CompleteAliasPackage
*/
private function configureObject(PackageInterface $package, array $config): BasePackage
{
if (!$package instanceof CompletePackage) {
throw new \LogicException('ArrayLoader expects instances of the Composer\Package\CompletePackage class to function correctly');
}
$package->setType(isset($config['type']) ? strtolower($config['type']) : 'library');
if (isset($config['target-dir'])) {
$package->setTargetDir($config['target-dir']);
}
if (isset($config['extra']) && \is_array($config['extra'])) {
$package->setExtra($config['extra']);
}
if (isset($config['bin'])) {
if (!\is_array($config['bin'])) {
$config['bin'] = [$config['bin']];
}
foreach ($config['bin'] as $key => $bin) {
$config['bin'][$key] = ltrim($bin, '/');
}
$package->setBinaries($config['bin']);
}
if (isset($config['installation-source'])) {
$package->setInstallationSource($config['installation-source']);
}
if (isset($config['default-branch']) && $config['default-branch'] === true) {
$package->setIsDefaultBranch(true);
}
if (isset($config['source'])) {
if (!isset($config['source']['type'], $config['source']['url'], $config['source']['reference'])) {
throw new \UnexpectedValueException(sprintf(
"Package %s's source key should be specified as {\"type\": ..., \"url\": ..., \"reference\": ...},\n%s given.",
$config['name'],
json_encode($config['source'])
));
}
$package->setSourceType($config['source']['type']);
$package->setSourceUrl($config['source']['url']);
$package->setSourceReference(isset($config['source']['reference']) ? (string) $config['source']['reference'] : null);
if (isset($config['source']['mirrors'])) {
$package->setSourceMirrors($config['source']['mirrors']);
}
}
if (isset($config['dist'])) {
if (!isset($config['dist']['type'], $config['dist']['url'])) {
throw new \UnexpectedValueException(sprintf(
"Package %s's dist key should be specified as ".
"{\"type\": ..., \"url\": ..., \"reference\": ..., \"shasum\": ...},\n%s given.",
$config['name'],
json_encode($config['dist'])
));
}
$package->setDistType($config['dist']['type']);
$package->setDistUrl($config['dist']['url']);
$package->setDistReference(isset($config['dist']['reference']) ? (string) $config['dist']['reference'] : null);
$package->setDistSha1Checksum($config['dist']['shasum'] ?? null);
if (isset($config['dist']['mirrors'])) {
$package->setDistMirrors($config['dist']['mirrors']);
}
}
if (isset($config['suggest']) && \is_array($config['suggest'])) {
foreach ($config['suggest'] as $target => $reason) {
if ('self.version' === trim($reason)) {
$config['suggest'][$target] = $package->getPrettyVersion();
}
}
$package->setSuggests($config['suggest']);
}
if (isset($config['autoload'])) {
$package->setAutoload($config['autoload']);
}
if (isset($config['autoload-dev'])) {
$package->setDevAutoload($config['autoload-dev']);
}
if (isset($config['include-path'])) {
$package->setIncludePaths($config['include-path']);
}
if (isset($config['php-ext'])) {
$package->setPhpExt($config['php-ext']);
}
if (!empty($config['time'])) {
$time = Preg::isMatch('/^\d++$/D', $config['time']) ? '@'.$config['time'] : $config['time'];
try {
$date = new \DateTime($time, new \DateTimeZone('UTC'));
$package->setReleaseDate($date);
} catch (\Exception $e) {
}
}
if (!empty($config['notification-url'])) {
$package->setNotificationUrl($config['notification-url']);
}
if ($package instanceof CompletePackageInterface) {
if (!empty($config['archive']['name'])) {
$package->setArchiveName($config['archive']['name']);
}
if (!empty($config['archive']['exclude'])) {
$package->setArchiveExcludes($config['archive']['exclude']);
}
if (isset($config['scripts']) && \is_array($config['scripts'])) {
foreach ($config['scripts'] as $event => $listeners) {
$config['scripts'][$event] = (array) $listeners;
}
foreach (['composer', 'php', 'putenv'] as $reserved) {
if (isset($config['scripts'][$reserved])) {
trigger_error('The `'.$reserved.'` script name is reserved for internal use, please avoid defining it', E_USER_DEPRECATED);
}
}
$package->setScripts($config['scripts']);
}
if (!empty($config['description']) && \is_string($config['description'])) {
$package->setDescription($config['description']);
}
if (!empty($config['homepage']) && \is_string($config['homepage'])) {
$package->setHomepage($config['homepage']);
}
if (!empty($config['keywords']) && \is_array($config['keywords'])) {
$package->setKeywords(array_map('strval', $config['keywords']));
}
if (!empty($config['license'])) {
$package->setLicense(\is_array($config['license']) ? $config['license'] : [$config['license']]);
}
if (!empty($config['authors']) && \is_array($config['authors'])) {
$package->setAuthors($config['authors']);
}
if (isset($config['support']) && \is_array($config['support'])) {
$package->setSupport($config['support']);
}
if (!empty($config['funding']) && \is_array($config['funding'])) {
$package->setFunding($config['funding']);
}
if (isset($config['abandoned'])) {
$package->setAbandoned($config['abandoned']);
}
}
if ($this->loadOptions && isset($config['transport-options'])) {
$package->setTransportOptions($config['transport-options']);
}
if ($aliasNormalized = $this->getBranchAlias($config)) {
$prettyAlias = Preg::replace('{(\.9{7})+}', '.x', $aliasNormalized);
if ($package instanceof RootPackage) {
return new RootAliasPackage($package, $aliasNormalized, $prettyAlias);
}
return new CompleteAliasPackage($package, $aliasNormalized, $prettyAlias);
}
return $package;
}
/**
* @param array<string, array<string, array<int|string, array<int|string, array{string, Link}>>>> $linkCache
* @param mixed[] $config
*/
private function configureCachedLinks(array &$linkCache, PackageInterface $package, array $config): void
{
$name = $package->getName();
$prettyVersion = $package->getPrettyVersion();
foreach (BasePackage::$supportedLinkTypes as $type => $opts) {
if (isset($config[$type])) {
$method = 'set'.ucfirst($opts['method']);
$links = [];
foreach ($config[$type] as $prettyTarget => $constraint) {
$target = strtolower($prettyTarget);
// recursive links are not supported
if ($target === $name) {
continue;
}
if ($constraint === 'self.version') {
$links[$target] = $this->createLink($name, $prettyVersion, $opts['method'], $target, $constraint);
} else {
if (!isset($linkCache[$name][$type][$target][$constraint])) {
$linkCache[$name][$type][$target][$constraint] = [$target, $this->createLink($name, $prettyVersion, $opts['method'], $target, $constraint)];
}
[$target, $link] = $linkCache[$name][$type][$target][$constraint];
$links[$target] = $link;
}
}
$package->{$method}($links);
}
}
}
/**
* @param string $source source package name
* @param string $sourceVersion source package version (pretty version ideally)
* @param string $description link description (e.g. requires, replaces, ..)
* @param array<string|int, string> $links array of package name => constraint mappings
*
* @return Link[]
*
* @phpstan-param Link::TYPE_* $description
*/
public function parseLinks(string $source, string $sourceVersion, string $description, array $links): array
{
$res = [];
foreach ($links as $target => $constraint) {
if (!is_string($constraint)) {
continue;
}
$target = strtolower((string) $target);
$res[$target] = $this->createLink($source, $sourceVersion, $description, $target, $constraint);
}
return $res;
}
/**
* @param string $source source package name
* @param string $sourceVersion source package version (pretty version ideally)
* @param Link::TYPE_* $description link description (e.g. requires, replaces, ..)
* @param string $target target package name
* @param string $prettyConstraint constraint string
*/
private function createLink(string $source, string $sourceVersion, string $description, string $target, string $prettyConstraint): Link
{
if (!\is_string($prettyConstraint)) {
throw new \UnexpectedValueException('Link constraint in '.$source.' '.$description.' > '.$target.' should be a string, got '.\get_debug_type($prettyConstraint) . ' (' . var_export($prettyConstraint, true) . ')');
}
if ('self.version' === $prettyConstraint) {
$parsedConstraint = $this->versionParser->parseConstraints($sourceVersion);
} else {
$parsedConstraint = $this->versionParser->parseConstraints($prettyConstraint);
}
return new Link($source, $target, $parsedConstraint, $description, $prettyConstraint);
}
/**
* Retrieves a branch alias (dev-master => 1.0.x-dev for example) if it exists
*
* @param mixed[] $config the entire package config
*
* @return string|null normalized version of the branch alias or null if there is none
*/
public function getBranchAlias(array $config): ?string
{
if (!isset($config['version']) || !is_scalar($config['version'])) {
throw new \UnexpectedValueException('no/invalid version defined');
}
if (!is_string($config['version'])) {
$config['version'] = (string) $config['version'];
}
if (strpos($config['version'], 'dev-') !== 0 && '-dev' !== substr($config['version'], -4)) {
return null;
}
if (isset($config['extra']['branch-alias']) && \is_array($config['extra']['branch-alias'])) {
foreach ($config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
$sourceBranch = (string) $sourceBranch;
// ensure it is an alias to a -dev package
if ('-dev' !== substr($targetBranch, -4)) {
continue;
}
// normalize without -dev and ensure it's a numeric branch that is parseable
if ($targetBranch === VersionParser::DEFAULT_BRANCH_ALIAS) {
$validatedTargetBranch = VersionParser::DEFAULT_BRANCH_ALIAS;
} else {
$validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
}
if ('-dev' !== substr($validatedTargetBranch, -4)) {
continue;
}
// ensure that it is the current branch aliasing itself
if (strtolower($config['version']) !== strtolower($sourceBranch)) {
continue;
}
// If using numeric aliases ensure the alias is a valid subversion
if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
&& ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
&& (stripos($targetPrefix, $sourcePrefix) !== 0)
) {
continue;
}
return $validatedTargetBranch;
}
}
if (
isset($config['default-branch'])
&& $config['default-branch'] === true
&& false === $this->versionParser->parseNumericAliasPrefix(Preg::replace('{^v}', '', $config['version']))
) {
return VersionParser::DEFAULT_BRANCH_ALIAS;
}
return null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/LoaderInterface.php | src/Composer/Package/Loader/LoaderInterface.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\Package\Loader;
use Composer\Package\CompletePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\RootAliasPackage;
use Composer\Package\RootPackage;
use Composer\Package\BasePackage;
/**
* Defines a loader that takes an array to create package instances
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface LoaderInterface
{
/**
* Converts a package from an array to a real instance
*
* @param mixed[] $config package data
* @param string $class FQCN to be instantiated
*
* @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage
*
* @phpstan-param class-string<CompletePackage|RootPackage> $class
*/
public function load(array $config, string $class = 'Composer\Package\CompletePackage'): BasePackage;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/InvalidPackageException.php | src/Composer/Package/Loader/InvalidPackageException.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\Package\Loader;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class InvalidPackageException extends \Exception
{
/** @var list<string> */
private $errors;
/** @var list<string> */
private $warnings;
/** @var mixed[] package config */
private $data;
/**
* @param list<string> $errors
* @param list<string> $warnings
* @param mixed[] $data
*/
public function __construct(array $errors, array $warnings, array $data)
{
$this->errors = $errors;
$this->warnings = $warnings;
$this->data = $data;
parent::__construct("Invalid package information: \n".implode("\n", array_merge($errors, $warnings)));
}
/**
* @return mixed[]
*/
public function getData(): array
{
return $this->data;
}
/**
* @return list<string>
*/
public function getErrors(): array
{
return $this->errors;
}
/**
* @return list<string>
*/
public function getWarnings(): array
{
return $this->warnings;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/JsonLoader.php | src/Composer/Package/Loader/JsonLoader.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\Package\Loader;
use Composer\Json\JsonFile;
use Composer\Package\BasePackage;
use Composer\Package\CompletePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\RootPackage;
use Composer\Package\RootAliasPackage;
/**
* @author Konstantin Kudryashiv <ever.zet@gmail.com>
*/
class JsonLoader
{
/** @var LoaderInterface */
private $loader;
public function __construct(LoaderInterface $loader)
{
$this->loader = $loader;
}
/**
* @param string|JsonFile $json A filename, json string or JsonFile instance to load the package from
* @return CompletePackage|CompleteAliasPackage|RootPackage|RootAliasPackage
*/
public function load($json): BasePackage
{
if ($json instanceof JsonFile) {
$config = $json->read();
} elseif (file_exists($json)) {
$config = JsonFile::parseJson(file_get_contents($json), $json);
} elseif (is_string($json)) {
$config = JsonFile::parseJson($json);
} else {
throw new \InvalidArgumentException(sprintf(
"JsonLoader: Unknown \$json parameter %s. Please report at https://github.com/composer/composer/issues/new.",
get_debug_type($json)
));
}
return $this->loader->load($config);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Loader/RootPackageLoader.php | src/Composer/Package/Loader/RootPackageLoader.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\Package\Loader;
use Composer\Package\BasePackage;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Package\RootAliasPackage;
use Composer\Pcre\Preg;
use Composer\Repository\RepositoryFactory;
use Composer\Package\Version\VersionGuesser;
use Composer\Package\Version\VersionParser;
use Composer\Package\RootPackage;
use Composer\Repository\RepositoryManager;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
/**
* ArrayLoader built for the sole purpose of loading the root package
*
* Sets additional defaults and loads repositories
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RootPackageLoader extends ArrayLoader
{
/**
* @var RepositoryManager
*/
private $manager;
/**
* @var Config
*/
private $config;
/**
* @var VersionGuesser
*/
private $versionGuesser;
/**
* @var IOInterface|null
*/
private $io;
public function __construct(RepositoryManager $manager, Config $config, ?VersionParser $parser = null, ?VersionGuesser $versionGuesser = null, ?IOInterface $io = null)
{
parent::__construct($parser);
$this->manager = $manager;
$this->config = $config;
if (null === $versionGuesser) {
$processExecutor = new ProcessExecutor($io);
$processExecutor->enableAsync();
$versionGuesser = new VersionGuesser($config, $processExecutor, $this->versionParser);
}
$this->versionGuesser = $versionGuesser;
$this->io = $io;
}
/**
* @inheritDoc
*
* @return RootPackage|RootAliasPackage
*
* @phpstan-param class-string<RootPackage> $class
*/
public function load(array $config, string $class = 'Composer\Package\RootPackage', ?string $cwd = null): BasePackage
{
if ($class !== 'Composer\Package\RootPackage') {
trigger_error('The $class arg is deprecated, please reach out to Composer maintainers ASAP if you still need this.', E_USER_DEPRECATED);
}
if (!isset($config['name'])) {
$config['name'] = '__root__';
} elseif ($err = ValidatingArrayLoader::hasPackageNamingError($config['name'])) {
throw new \RuntimeException('Your package name '.$err);
}
$autoVersioned = false;
if (!isset($config['version'])) {
$commit = null;
// override with env var if available
if (Platform::getEnv('COMPOSER_ROOT_VERSION')) {
$config['version'] = $this->versionGuesser->getRootVersionFromEnv();
} else {
$versionData = $this->versionGuesser->guessVersion($config, $cwd ?? Platform::getCwd(true));
if ($versionData) {
$config['version'] = $versionData['pretty_version'];
$config['version_normalized'] = $versionData['version'];
$commit = $versionData['commit'];
}
}
if (!isset($config['version'])) {
if ($this->io !== null && $config['name'] !== '__root__' && 'project' !== ($config['type'] ?? '')) {
$this->io->warning(
sprintf(
"Composer could not detect the root package (%s) version, defaulting to '1.0.0'. See https://getcomposer.org/root-version",
$config['name']
)
);
}
$config['version'] = '1.0.0';
$autoVersioned = true;
}
if ($commit) {
$config['source'] = [
'type' => '',
'url' => '',
'reference' => $commit,
];
$config['dist'] = [
'type' => '',
'url' => '',
'reference' => $commit,
];
}
}
/** @var RootPackage|RootAliasPackage $package */
$package = parent::load($config, $class);
if ($package instanceof RootAliasPackage) {
$realPackage = $package->getAliasOf();
} else {
$realPackage = $package;
}
if (!$realPackage instanceof RootPackage) {
throw new \LogicException('Expecting a Composer\Package\RootPackage at this point');
}
if ($autoVersioned) {
$realPackage->replaceVersion($realPackage->getVersion(), RootPackage::DEFAULT_PRETTY_VERSION);
}
if (isset($config['minimum-stability'])) {
$realPackage->setMinimumStability(VersionParser::normalizeStability($config['minimum-stability']));
}
$aliases = [];
$stabilityFlags = [];
$references = [];
foreach (['require', 'require-dev'] as $linkType) {
if (isset($config[$linkType])) {
$linkInfo = BasePackage::$supportedLinkTypes[$linkType];
$method = 'get'.ucfirst($linkInfo['method']);
$links = [];
foreach ($realPackage->{$method}() as $link) {
$links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
}
$aliases = $this->extractAliases($links, $aliases);
$stabilityFlags = self::extractStabilityFlags($links, $realPackage->getMinimumStability(), $stabilityFlags);
$references = self::extractReferences($links, $references);
if (isset($links[$config['name']])) {
throw new \RuntimeException(sprintf('Root package \'%s\' cannot require itself in its composer.json' . PHP_EOL .
'Did you accidentally name your root package after an external package?', $config['name']));
}
}
}
foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) {
if (isset($config[$linkType])) {
foreach ($config[$linkType] as $linkName => $constraint) {
if ($err = ValidatingArrayLoader::hasPackageNamingError($linkName, true)) {
throw new \RuntimeException($linkType.'.'.$err);
}
}
}
}
$realPackage->setAliases($aliases);
$realPackage->setStabilityFlags($stabilityFlags);
$realPackage->setReferences($references);
if (isset($config['prefer-stable'])) {
$realPackage->setPreferStable((bool) $config['prefer-stable']);
}
if (isset($config['config'])) {
$realPackage->setConfig($config['config']);
}
$repos = RepositoryFactory::defaultRepos(null, $this->config, $this->manager);
foreach ($repos as $repo) {
$this->manager->addRepository($repo);
}
$realPackage->setRepositories($this->config->getRepositories());
return $package;
}
/**
* @param array<string, string> $requires
* @param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
*
* @return list<array{package: string, version: string, alias: string, alias_normalized: string}>
*/
private function extractAliases(array $requires, array $aliases): array
{
foreach ($requires as $reqName => $reqVersion) {
if (Preg::isMatchStrictGroups('{(?:^|\| *|, *)([^,\s#|]+)(?:#[^ ]+)? +as +([^,\s|]+)(?:$| *\|| *,)}', $reqVersion, $match)) {
$aliases[] = [
'package' => strtolower($reqName),
'version' => $this->versionParser->normalize($match[1], $reqVersion),
'alias' => $match[2],
'alias_normalized' => $this->versionParser->normalize($match[2], $reqVersion),
];
} elseif (strpos($reqVersion, ' as ') !== false) {
throw new \UnexpectedValueException('Invalid alias definition in "'.$reqName.'": "'.$reqVersion.'". Aliases should be in the form "exact-version as other-exact-version".');
}
}
return $aliases;
}
/**
* @internal
*
* @param array<string, string> $requires
* @param array<string, int> $stabilityFlags
* @param key-of<BasePackage::STABILITIES> $minimumStability
*
* @return array<string, int>
*
* @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags
* @phpstan-return array<string, BasePackage::STABILITY_*>
*/
public static function extractStabilityFlags(array $requires, string $minimumStability, array $stabilityFlags): array
{
$stabilities = BasePackage::STABILITIES;
$minimumStability = $stabilities[$minimumStability];
foreach ($requires as $reqName => $reqVersion) {
$constraints = [];
// extract all sub-constraints in case it is an OR/AND multi-constraint
$orSplit = Preg::split('{\s*\|\|?\s*}', trim($reqVersion));
foreach ($orSplit as $orConstraint) {
$andSplit = Preg::split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $orConstraint);
foreach ($andSplit as $andConstraint) {
$constraints[] = $andConstraint;
}
}
// parse explicit stability flags to the most unstable
$matched = false;
foreach ($constraints as $constraint) {
if (Preg::isMatchStrictGroups('{^[^@]*?@('.implode('|', array_keys($stabilities)).')$}i', $constraint, $match)) {
$name = strtolower($reqName);
$stability = $stabilities[VersionParser::normalizeStability($match[1])];
if (isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) {
continue;
}
$stabilityFlags[$name] = $stability;
$matched = true;
}
}
if ($matched) {
continue;
}
foreach ($constraints as $constraint) {
// infer flags for requirements that have an explicit -dev or -beta version specified but only
// for those that are more unstable than the minimumStability or existing flags
$reqVersion = Preg::replace('{^([^,\s@]+) as .+$}', '$1', $constraint);
if (Preg::isMatch('{^[^,\s@]+$}', $reqVersion) && 'stable' !== ($stabilityName = VersionParser::parseStability($reqVersion))) {
$name = strtolower($reqName);
$stability = $stabilities[$stabilityName];
if ((isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) || ($minimumStability > $stability)) {
continue;
}
$stabilityFlags[$name] = $stability;
}
}
}
return $stabilityFlags;
}
/**
* @internal
*
* @param array<string, string> $requires
* @param array<string, string> $references
*
* @return array<string, string>
*/
public static function extractReferences(array $requires, array $references): array
{
foreach ($requires as $reqName => $reqVersion) {
$reqVersion = Preg::replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
if (Preg::isMatchStrictGroups('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) && 'dev' === VersionParser::parseStability($reqVersion)) {
$name = strtolower($reqName);
$references[$name] = $match[1];
}
}
return $references;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Comparer/Comparer.php | src/Composer/Package/Comparer/Comparer.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\Package\Comparer;
use Composer\Util\Platform;
/**
* class Comparer
*
* @author Hector Prats <hectorpratsortega@gmail.com>
*/
class Comparer
{
/** @var string Source directory */
private $source;
/** @var string Target directory */
private $update;
/** @var array{changed?: string[], removed?: string[], added?: string[]} */
private $changed;
public function setSource(string $source): void
{
$this->source = $source;
}
public function setUpdate(string $update): void
{
$this->update = $update;
}
/**
* @return array{changed?: string[], removed?: string[], added?: string[]}|false false if no change
*/
public function getChanged(bool $explicated = false)
{
$changed = $this->changed;
if (!count($changed)) {
return false;
}
if ($explicated) {
foreach ($changed as $sectionKey => $itemSection) {
foreach ($itemSection as $itemKey => $item) {
$changed[$sectionKey][$itemKey] = $item.' ('.$sectionKey.')';
}
}
}
return $changed;
}
/**
* @return string empty string if no changes
*/
public function getChangedAsString(bool $toString = false, bool $explicated = false): string
{
$changed = $this->getChanged($explicated);
if (false === $changed) {
return '';
}
$strings = [];
foreach ($changed as $sectionKey => $itemSection) {
foreach ($itemSection as $itemKey => $item) {
$strings[] = $item."\r\n";
}
}
return trim(implode("\r\n", $strings));
}
public function doCompare(): void
{
$source = [];
$destination = [];
$this->changed = [];
$currentDirectory = Platform::getCwd();
chdir($this->source);
$source = $this->doTree('.', $source);
if (!is_array($source)) {
return;
}
chdir($currentDirectory);
chdir($this->update);
$destination = $this->doTree('.', $destination);
if (!is_array($destination)) {
exit;
}
chdir($currentDirectory);
foreach ($source as $dir => $value) {
foreach ($value as $file => $hash) {
if (isset($destination[$dir][$file])) {
if ($hash !== $destination[$dir][$file]) {
$this->changed['changed'][] = $dir.'/'.$file;
}
} else {
$this->changed['removed'][] = $dir.'/'.$file;
}
}
}
foreach ($destination as $dir => $value) {
foreach ($value as $file => $hash) {
if (!isset($source[$dir][$file])) {
$this->changed['added'][] = $dir.'/'.$file;
}
}
}
}
/**
* @param mixed[] $array
*
* @return array<string, array<string, string|false>>|false
*/
private function doTree(string $dir, array &$array)
{
if ($dh = opendir($dir)) {
while ($file = readdir($dh)) {
if ($file !== '.' && $file !== '..') {
if (is_link($dir.'/'.$file)) {
$array[$dir][$file] = readlink($dir.'/'.$file);
} elseif (is_dir($dir.'/'.$file)) {
if (!count($array)) {
$array[0] = 'Temp';
}
if (!$this->doTree($dir.'/'.$file, $array)) {
return false;
}
} elseif (is_file($dir.'/'.$file) && filesize($dir.'/'.$file)) {
$array[$dir][$file] = hash_file(\PHP_VERSION_ID > 80100 ? 'xxh3' : 'sha1', $dir.'/'.$file);
}
}
}
if (count($array) > 1 && isset($array['0'])) {
unset($array['0']);
}
return $array;
}
return false;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Version/VersionSelector.php | src/Composer/Package/Version/VersionSelector.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\Package\Version;
use Composer\Filter\PlatformRequirementFilter\IgnoreAllPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\IgnoreListPlatformRequirementFilter;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterFactory;
use Composer\Filter\PlatformRequirementFilter\PlatformRequirementFilterInterface;
use Composer\IO\IOInterface;
use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
use Composer\Package\PackageInterface;
use Composer\Composer;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Pcre\Preg;
use Composer\Repository\RepositorySet;
use Composer\Repository\PlatformRepository;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
/**
* Selects the best possible version for a package
*
* @author Ryan Weaver <ryan@knpuniversity.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class VersionSelector
{
/** @var RepositorySet */
private $repositorySet;
/** @var array<string, ConstraintInterface[]> */
private $platformConstraints = [];
/** @var VersionParser */
private $parser;
/**
* @param PlatformRepository $platformRepo If passed in, the versions found will be filtered against their requirements to eliminate any not matching the current platform packages
*/
public function __construct(RepositorySet $repositorySet, ?PlatformRepository $platformRepo = null)
{
$this->repositorySet = $repositorySet;
if ($platformRepo) {
foreach ($platformRepo->getPackages() as $package) {
$this->platformConstraints[$package->getName()][] = new Constraint('==', $package->getVersion());
}
}
}
/**
* Given a package name and optional version, returns the latest PackageInterface
* that matches.
*
* @param PlatformRequirementFilterInterface|bool|string[] $platformRequirementFilter
* @param IOInterface|null $io If passed, warnings will be output there in case versions cannot be selected due to platform requirements
* @param callable(PackageInterface):bool|bool $showWarnings
* @return PackageInterface|false
*/
public function findBestCandidate(string $packageName, ?string $targetPackageVersion = null, string $preferredStability = 'stable', $platformRequirementFilter = null, int $repoSetFlags = 0, ?IOInterface $io = null, $showWarnings = true)
{
if (!isset(BasePackage::STABILITIES[$preferredStability])) {
// If you get this, maybe you are still relying on the Composer 1.x signature where the 3rd arg was the php version
throw new \UnexpectedValueException('Expected a valid stability name as 3rd argument, got '.$preferredStability);
}
if (null === $platformRequirementFilter) {
$platformRequirementFilter = PlatformRequirementFilterFactory::ignoreNothing();
} elseif (!($platformRequirementFilter instanceof PlatformRequirementFilterInterface)) {
trigger_error('VersionSelector::findBestCandidate with ignored platform reqs as bool|array is deprecated since Composer 2.2, use an instance of PlatformRequirementFilterInterface instead.', E_USER_DEPRECATED);
$platformRequirementFilter = PlatformRequirementFilterFactory::fromBoolOrList($platformRequirementFilter);
}
$constraint = $targetPackageVersion ? $this->getParser()->parseConstraints($targetPackageVersion) : null;
$candidates = $this->repositorySet->findPackages(strtolower($packageName), $constraint, $repoSetFlags);
$minPriority = BasePackage::STABILITIES[$preferredStability];
usort($candidates, static function (PackageInterface $a, PackageInterface $b) use ($minPriority) {
$aPriority = $a->getStabilityPriority();
$bPriority = $b->getStabilityPriority();
// A is less stable than our preferred stability,
// and B is more stable than A, select B
if ($minPriority < $aPriority && $bPriority < $aPriority) {
return 1;
}
// A is less stable than our preferred stability,
// and B is less stable than A, select A
if ($minPriority < $aPriority && $aPriority < $bPriority) {
return -1;
}
// A is more stable than our preferred stability,
// and B is less stable than preferred stability, select A
if ($minPriority >= $aPriority && $minPriority < $bPriority) {
return -1;
}
// select highest version of the two
return version_compare($b->getVersion(), $a->getVersion());
});
if (count($this->platformConstraints) > 0 && !($platformRequirementFilter instanceof IgnoreAllPlatformRequirementFilter)) {
/** @var array<string, true> $alreadyWarnedNames */
$alreadyWarnedNames = [];
/** @var array<string, true> $alreadySeenNames */
$alreadySeenNames = [];
foreach ($candidates as $pkg) {
$reqs = $pkg->getRequires();
$skip = false;
foreach ($reqs as $name => $link) {
if (!PlatformRepository::isPlatformPackage($name) || $platformRequirementFilter->isIgnored($name)) {
continue;
}
if (isset($this->platformConstraints[$name])) {
foreach ($this->platformConstraints[$name] as $providedConstraint) {
if ($link->getConstraint()->matches($providedConstraint)) {
// constraint satisfied, go to next require
continue 2;
}
if ($platformRequirementFilter instanceof IgnoreListPlatformRequirementFilter && $platformRequirementFilter->isUpperBoundIgnored($name)) {
$filteredConstraint = $platformRequirementFilter->filterConstraint($name, $link->getConstraint());
if ($filteredConstraint->matches($providedConstraint)) {
// constraint satisfied with the upper bound ignored, go to next require
continue 2;
}
}
}
// constraint not satisfied
$reason = 'is not satisfied by your platform';
} else {
// Package requires a platform package that is unknown on current platform.
// It means that current platform cannot validate this constraint and so package is not installable.
$reason = 'is missing from your platform';
}
$isLatestVersion = !isset($alreadySeenNames[$pkg->getName()]);
$alreadySeenNames[$pkg->getName()] = true;
if ($io !== null && ($showWarnings === true || (is_callable($showWarnings) && $showWarnings($pkg)))) {
$isFirstWarning = !isset($alreadyWarnedNames[$pkg->getName().'/'.$link->getTarget()]);
$alreadyWarnedNames[$pkg->getName().'/'.$link->getTarget()] = true;
$latest = $isLatestVersion ? "'s latest version" : '';
$io->writeError(
'<warning>Cannot use '.$pkg->getPrettyName().$latest.' '.$pkg->getPrettyVersion().' as it '.$link->getDescription().' '.$link->getTarget().' '.$link->getPrettyConstraint().' which '.$reason.'.</>',
true,
$isFirstWarning ? IOInterface::NORMAL : IOInterface::VERBOSE
);
}
// skip candidate
$skip = true;
}
if ($skip) {
continue;
}
$package = $pkg;
break;
}
} else {
$package = count($candidates) > 0 ? $candidates[0] : null;
}
if (!isset($package)) {
return false;
}
// if we end up with 9999999-dev as selected package, make sure we use the original version instead of the alias
if ($package instanceof AliasPackage && $package->getVersion() === VersionParser::DEFAULT_BRANCH_ALIAS) {
$package = $package->getAliasOf();
}
return $package;
}
/**
* Given a concrete version, this returns a ^ constraint (when possible)
* that should be used, for example, in composer.json.
*
* For example:
* * 1.2.1 -> ^1.2
* * 1.2.1.2 -> ^1.2
* * 1.2 -> ^1.2
* * v3.2.1 -> ^3.2
* * 2.0-beta.1 -> ^2.0@beta
* * dev-master -> ^2.1@dev (dev version with alias)
* * dev-master -> dev-master (dev versions are untouched)
*/
public function findRecommendedRequireVersion(PackageInterface $package): string
{
// Extensions which are versioned in sync with PHP should rather be required as "*" to simplify
// the requires and have only one required version to change when bumping the php requirement
if (0 === strpos($package->getName(), 'ext-')) {
$phpVersion = PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;
$extVersion = implode('.', array_slice(explode('.', $package->getVersion()), 0, 3));
if ($phpVersion === $extVersion) {
return '*';
}
}
$version = $package->getVersion();
if (!$package->isDev()) {
return $this->transformVersion($version, $package->getPrettyVersion(), $package->getStability());
}
$loader = new ArrayLoader($this->getParser());
$dumper = new ArrayDumper();
$extra = $loader->getBranchAlias($dumper->dump($package));
if ($extra && $extra !== VersionParser::DEFAULT_BRANCH_ALIAS) {
$extra = Preg::replace('{^(\d+\.\d+\.\d+)(\.9999999)-dev$}', '$1.0', $extra, -1, $count);
if ($count > 0) {
$extra = str_replace('.9999999', '.0', $extra);
return $this->transformVersion($extra, $extra, 'dev');
}
}
return $package->getPrettyVersion();
}
private function transformVersion(string $version, string $prettyVersion, string $stability): string
{
// attempt to transform 2.1.1 to 2.1
// this allows you to upgrade through minor versions
$semanticVersionParts = explode('.', $version);
// check to see if we have a semver-looking version
if (count($semanticVersionParts) === 4 && Preg::isMatch('{^\d+\D?}', $semanticVersionParts[3])) {
// remove the last parts (i.e. the patch version number and any extra)
if ($semanticVersionParts[0] === '0') {
unset($semanticVersionParts[3]);
} else {
unset($semanticVersionParts[2], $semanticVersionParts[3]);
}
$version = implode('.', $semanticVersionParts);
} else {
return $prettyVersion;
}
// append stability flag if not default
if ($stability !== 'stable') {
$version .= '@'.$stability;
}
// 2.1 -> ^2.1
return '^' . $version;
}
private function getParser(): VersionParser
{
if ($this->parser === null) {
$this->parser = new VersionParser();
}
return $this->parser;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Version/VersionBumper.php | src/Composer/Package/Version/VersionBumper.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\Package\Version;
use Composer\Package\PackageInterface;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Pcre\Preg;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Intervals;
use Composer\Util\Platform;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @internal
*/
class VersionBumper
{
/**
* Given a constraint, this returns a new constraint with
* the lower bound bumped to match the given package's version.
*
* For example:
* * ^1.0 + 1.2.1 -> ^1.2.1
* * ^1.2 + 1.2.0 -> ^1.2
* * ^1.2.0 + 1.3.0 -> ^1.3.0
* * ^1.2 || ^2.3 + 1.3.0 -> ^1.3 || ^2.3
* * ^1.2 || ^2.3 + 2.4.0 -> ^1.2 || ^2.4
* * ^3@dev + 3.2.99999-dev -> ^3.2@dev
* * ~2 + 2.0-beta.1 -> ~2
* * ~2.0.0 + 2.0.3 -> ~2.0.3
* * ~2.0 + 2.0.3 -> ^2.0.3
* * dev-master + dev-master -> dev-master
* * * + 1.2.3 -> >=1.2.3
*/
public function bumpRequirement(ConstraintInterface $constraint, PackageInterface $package): string
{
$parser = new VersionParser();
$prettyConstraint = $constraint->getPrettyString();
if (str_starts_with($constraint->getPrettyString(), 'dev-')) {
return $prettyConstraint;
}
$version = $package->getVersion();
if (str_starts_with($package->getVersion(), 'dev-')) {
$loader = new ArrayLoader($parser);
$dumper = new ArrayDumper();
$extra = $loader->getBranchAlias($dumper->dump($package));
// dev packages without branch alias cannot be processed
if (null === $extra || $extra === VersionParser::DEFAULT_BRANCH_ALIAS) {
return $prettyConstraint;
}
$version = $extra;
}
$intervals = Intervals::get($constraint);
// complex constraints with branch names are not bumped
if (\count($intervals['branches']['names']) > 0) {
return $prettyConstraint;
}
$major = Preg::replace('{^([1-9][0-9]*|0\.\d+).*}', '$1', $version);
$versionWithoutSuffix = Preg::replace('{(?:\.(?:0|9999999))+(-dev)?$}', '', $version);
$newPrettyConstraint = '^'.$versionWithoutSuffix;
// not a simple stable version, abort
if (!Preg::isMatch('{^\^\d+(\.\d+)*$}', $newPrettyConstraint)) {
return $prettyConstraint;
}
$pattern = '{
(?<=,|\ |\||^) # leading separator
(?P<constraint>
\^v?'.$major.'(?:\.\d+)* # e.g. ^2.anything
| ~v?'.$major.'(?:\.\d+){1,3} # e.g. ~2.2 or ~2.2.2 or ~2.2.2.2
| v?'.$major.'(?:\.[*x])+ # e.g. 2.* or 2.*.* or 2.x.x.x etc
| >=v?\d(?:\.\d+)* # e.g. >=2 or >=1.2 etc
| \* # full wildcard
)
(?=,|$|\ |\||@) # trailing separator
}x';
if (Preg::isMatchAllWithOffsets($pattern, $prettyConstraint, $matches)) {
$modified = $prettyConstraint;
foreach (array_reverse($matches['constraint']) as $match) {
assert(is_string($match[0]));
$suffix = '';
if (substr_count($match[0], '.') === 2 && substr_count($versionWithoutSuffix, '.') === 1) {
$suffix = '.0';
}
if (str_starts_with($match[0], '~') && substr_count($match[0], '.') !== 1) {
// take as many version bits from the current version as we have in the constraint to bump it without making it more specific
$versionBits = explode('.', $versionWithoutSuffix);
$versionBits = array_pad($versionBits, substr_count($match[0], '.') + 1, '0');
$replacement = '~'.implode('.', array_slice($versionBits, 0, substr_count($match[0], '.') + 1));
} elseif ($match[0] === '*' || str_starts_with($match[0], '>=')) {
$replacement = '>='.$versionWithoutSuffix.$suffix;
} else {
$replacement = $newPrettyConstraint.$suffix;
}
$modified = substr_replace($modified, $replacement, $match[1], Platform::strlen($match[0]));
}
// if it is strictly equal to the previous one then no need to change anything
$newConstraint = $parser->parseConstraints($modified);
if (Intervals::isSubsetOf($newConstraint, $constraint) && Intervals::isSubsetOf($constraint, $newConstraint)) {
return $prettyConstraint;
}
return $modified;
}
return $prettyConstraint;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Version/VersionParser.php | src/Composer/Package/Version/VersionParser.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\Package\Version;
use Composer\Pcre\Preg;
use Composer\Repository\PlatformRepository;
use Composer\Semver\VersionParser as SemverVersionParser;
use Composer\Semver\Semver;
use Composer\Semver\Constraint\ConstraintInterface;
class VersionParser extends SemverVersionParser
{
public const DEFAULT_BRANCH_ALIAS = '9999999-dev';
/** @var array<string, ConstraintInterface> Constraint parsing cache */
private static $constraints = [];
/**
* @inheritDoc
*/
public function parseConstraints($constraints): ConstraintInterface
{
if (!isset(self::$constraints[$constraints])) {
self::$constraints[$constraints] = parent::parseConstraints($constraints);
}
return self::$constraints[$constraints];
}
/**
* Parses an array of strings representing package/version pairs.
*
* The parsing results in an array of arrays, each of which
* contain a 'name' key with value and optionally a 'version' key with value.
*
* @param string[] $pairs a set of package/version pairs separated by ":", "=" or " "
*
* @return list<array{name: string, version?: string}>
*/
public function parseNameVersionPairs(array $pairs): array
{
$pairs = array_values($pairs);
$result = [];
for ($i = 0, $count = count($pairs); $i < $count; $i++) {
$pair = Preg::replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i]));
if (false === strpos($pair, ' ') && isset($pairs[$i + 1]) && false === strpos($pairs[$i + 1], '/') && !Preg::isMatch('{(?<=[a-z0-9_/-])\*|\*(?=[a-z0-9_/-])}i', $pairs[$i + 1]) && !PlatformRepository::isPlatformPackage($pairs[$i + 1])) {
$pair .= ' '.$pairs[$i + 1];
$i++;
}
if (strpos($pair, ' ')) {
[$name, $version] = explode(' ', $pair, 2);
$result[] = ['name' => $name, 'version' => $version];
} else {
$result[] = ['name' => $pair];
}
}
return $result;
}
public static function isUpgrade(string $normalizedFrom, string $normalizedTo): bool
{
if ($normalizedFrom === $normalizedTo) {
return true;
}
if (in_array($normalizedFrom, ['dev-master', 'dev-trunk', 'dev-default'], true)) {
$normalizedFrom = VersionParser::DEFAULT_BRANCH_ALIAS;
}
if (in_array($normalizedTo, ['dev-master', 'dev-trunk', 'dev-default'], true)) {
$normalizedTo = VersionParser::DEFAULT_BRANCH_ALIAS;
}
if (strpos($normalizedFrom, 'dev-') === 0 || strpos($normalizedTo, 'dev-') === 0) {
return true;
}
$sorted = Semver::sort([$normalizedTo, $normalizedFrom]);
return $sorted[0] === $normalizedFrom;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Package/Version/StabilityFilter.php | src/Composer/Package/Version/StabilityFilter.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\Package\Version;
use Composer\Package\BasePackage;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class StabilityFilter
{
/**
* Checks if any of the provided package names in the given stability match the configured acceptable stability and flags
*
* @param int[] $acceptableStabilities array of stability => BasePackage::STABILITY_* value
* @phpstan-param array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*> $acceptableStabilities
* @param int[] $stabilityFlags an array of package name => BasePackage::STABILITY_* value
* @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags
* @param string[] $names The package name(s) to check for stability flags
* @param key-of<BasePackage::STABILITIES> $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev'
* @return bool true if any package name is acceptable
*/
public static function isPackageAcceptable(array $acceptableStabilities, array $stabilityFlags, array $names, string $stability): bool
{
foreach ($names as $name) {
// allow if package matches the package-specific stability flag
if (isset($stabilityFlags[$name])) {
if (BasePackage::STABILITIES[$stability] <= $stabilityFlags[$name]) {
return true;
}
} elseif (isset($acceptableStabilities[$stability])) {
// allow if package matches the global stability requirement and has no exception
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/Package/Version/VersionGuesser.php | src/Composer/Package/Version/VersionGuesser.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\Package\Version;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Repository\Vcs\HgDriver;
use Composer\IO\NullIO;
use Composer\Semver\VersionParser as SemverVersionParser;
use Composer\Util\Git as GitUtil;
use Composer\Util\HttpDownloader;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Util\Svn as SvnUtil;
use Symfony\Component\Process\Process;
/**
* Try to guess the current version number based on different VCS configuration.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Samuel Roze <samuel.roze@gmail.com>
*
* @phpstan-type Version array{version: string, commit: string|null, pretty_version: string|null}|array{version: string, commit: string|null, pretty_version: string|null, feature_version: string|null, feature_pretty_version: string|null}
*/
class VersionGuesser
{
/**
* @var Config
*/
private $config;
/**
* @var ProcessExecutor
*/
private $process;
/**
* @var SemverVersionParser
*/
private $versionParser;
/**
* @var IOInterface|null
*/
private $io;
public function __construct(Config $config, ProcessExecutor $process, SemverVersionParser $versionParser, ?IOInterface $io = null)
{
$this->config = $config;
$this->process = $process;
$this->versionParser = $versionParser;
$this->io = $io;
}
/**
* @param array<string, mixed> $packageConfig
* @param string $path Path to guess into
*
* @phpstan-return Version|null
*/
public function guessVersion(array $packageConfig, string $path): ?array
{
if (!function_exists('proc_open')) {
return null;
}
// bypass version guessing in bash completions as it takes time to create
// new processes and the root version is usually not that important
if (Platform::isInputCompletionProcess()) {
return null;
}
$versionData = $this->guessGitVersion($packageConfig, $path);
if (null !== $versionData['version']) {
return $this->postprocess($versionData);
}
$versionData = $this->guessHgVersion($packageConfig, $path);
if (null !== $versionData && null !== $versionData['version']) {
return $this->postprocess($versionData);
}
$versionData = $this->guessFossilVersion($path);
if (null !== $versionData['version']) {
return $this->postprocess($versionData);
}
$versionData = $this->guessSvnVersion($packageConfig, $path);
if (null !== $versionData && null !== $versionData['version']) {
return $this->postprocess($versionData);
}
return null;
}
/**
* @phpstan-param Version $versionData
*
* @phpstan-return Version
*/
private function postprocess(array $versionData): array
{
if (!empty($versionData['feature_version']) && $versionData['feature_version'] === $versionData['version'] && $versionData['feature_pretty_version'] === $versionData['pretty_version']) {
unset($versionData['feature_version'], $versionData['feature_pretty_version']);
}
if ('-dev' === substr($versionData['version'], -4) && Preg::isMatch('{\.9{7}}', $versionData['version'])) {
$versionData['pretty_version'] = Preg::replace('{(\.9{7})+}', '.x', $versionData['version']);
}
if (!empty($versionData['feature_version']) && '-dev' === substr($versionData['feature_version'], -4) && Preg::isMatch('{\.9{7}}', $versionData['feature_version'])) {
$versionData['feature_pretty_version'] = Preg::replace('{(\.9{7})+}', '.x', $versionData['feature_version']);
}
return $versionData;
}
/**
* @param array<string, mixed> $packageConfig
*
* @return array{version: string|null, commit: string|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null}
*/
private function guessGitVersion(array $packageConfig, string $path): array
{
GitUtil::cleanEnv($this->process);
$commit = null;
$version = null;
$prettyVersion = null;
$featureVersion = null;
$featurePrettyVersion = null;
$isDetached = false;
// try to fetch current version from git branch
if (0 === $this->process->execute(['git', 'branch', '-a', '--no-color', '--no-abbrev', '-v'], $output, $path)) {
$branches = [];
$isFeatureBranch = false;
// find current branch and collect all branch names
foreach ($this->process->splitLines($output) as $branch) {
if ($branch && Preg::isMatchStrictGroups('{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\(HEAD detached at \S+\)|\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
if (
$match[1] === '(no branch)'
|| strpos($match[1], '(detached ') === 0
|| strpos($match[1], '(HEAD detached at') === 0
) {
$version = 'dev-' . $match[2];
$prettyVersion = $version;
$isFeatureBranch = true;
$isDetached = true;
} else {
$version = $this->versionParser->normalizeBranch($match[1]);
$prettyVersion = 'dev-' . $match[1];
$isFeatureBranch = $this->isFeatureBranch($packageConfig, $match[1]);
}
$commit = $match[2];
}
if ($branch && !Preg::isMatchStrictGroups('{^ *.+/HEAD }', $branch)) {
if (Preg::isMatchStrictGroups('{^(?:\* )? *((?:remotes/(?:origin|upstream)/)?[^\s/]+) *([a-f0-9]+) .*$}', $branch, $match)) {
$branches[] = $match[1];
}
}
}
if ($isFeatureBranch) {
$featureVersion = $version;
$featurePrettyVersion = $prettyVersion;
// try to find the best (nearest) version branch to assume this feature's version
$result = $this->guessFeatureVersion($packageConfig, $version, $branches, ['git', 'rev-list', '%candidate%..%branch%'], $path);
$version = $result['version'];
$prettyVersion = $result['pretty_version'];
}
}
GitUtil::checkForRepoOwnershipError($this->process->getErrorOutput(), $path, $this->io);
if (!$version || $isDetached) {
$result = $this->versionFromGitTags($path);
if ($result) {
$version = $result['version'];
$prettyVersion = $result['pretty_version'];
$featureVersion = null;
$featurePrettyVersion = null;
}
}
if (null === $commit) {
$command = GitUtil::buildRevListCommand($this->process, array_merge(['--format=%H', '-n1', 'HEAD'], GitUtil::getNoShowSignatureFlags($this->process)));
if (0 === $this->process->execute($command, $output, $path)) {
$commit = trim(GitUtil::parseRevListOutput($output, $this->process)) ?: null;
}
}
if ($featureVersion) {
return ['version' => $version, 'commit' => $commit, 'pretty_version' => $prettyVersion, 'feature_version' => $featureVersion, 'feature_pretty_version' => $featurePrettyVersion];
}
return ['version' => $version, 'commit' => $commit, 'pretty_version' => $prettyVersion];
}
/**
* @return array{version: string, pretty_version: string}|null
*/
private function versionFromGitTags(string $path): ?array
{
// try to fetch current version from git tags
if (0 === $this->process->execute(['git', 'describe', '--exact-match', '--tags'], $output, $path)) {
try {
$version = $this->versionParser->normalize(trim($output));
return ['version' => $version, 'pretty_version' => trim($output)];
} catch (\Exception $e) {
}
}
return null;
}
/**
* @param array<string, mixed> $packageConfig
*
* @return array{version: string|null, commit: ''|null, pretty_version: string|null, feature_version?: string|null, feature_pretty_version?: string|null}|null
*/
private function guessHgVersion(array $packageConfig, string $path): ?array
{
// try to fetch current version from hg branch
if (0 === $this->process->execute(['hg', 'branch'], $output, $path)) {
$branch = trim($output);
$version = $this->versionParser->normalizeBranch($branch);
$isFeatureBranch = 0 === strpos($version, 'dev-');
if (VersionParser::DEFAULT_BRANCH_ALIAS === $version) {
return ['version' => $version, 'commit' => null, 'pretty_version' => 'dev-'.$branch];
}
if (!$isFeatureBranch) {
return ['version' => $version, 'commit' => null, 'pretty_version' => $version];
}
// re-use the HgDriver to fetch branches (this properly includes bookmarks)
$io = new NullIO();
$driver = new HgDriver(['url' => $path], $io, $this->config, new HttpDownloader($io, $this->config), $this->process);
$branches = array_map('strval', array_keys($driver->getBranches()));
// try to find the best (nearest) version branch to assume this feature's version
$result = $this->guessFeatureVersion($packageConfig, $version, $branches, ['hg', 'log', '-r', 'not ancestors(\'%candidate%\') and ancestors(\'%branch%\')', '--template', '"{node}\\n"'], $path);
$result['commit'] = '';
$result['feature_version'] = $version;
$result['feature_pretty_version'] = $version;
return $result;
}
return null;
}
/**
* @param array<string, mixed> $packageConfig
* @param list<string> $branches
* @param list<string> $scmCmdline
*
* @return array{version: string|null, pretty_version: string|null}
*/
private function guessFeatureVersion(array $packageConfig, ?string $version, array $branches, array $scmCmdline, string $path): array
{
$prettyVersion = $version;
// ignore feature branches if they have no branch-alias or self.version is used
// and find the branch they came from to use as a version instead
if (!isset($packageConfig['extra']['branch-alias'][$version])
|| strpos(json_encode($packageConfig), '"self.version"')
) {
$branch = Preg::replace('{^dev-}', '', $version);
$length = PHP_INT_MAX;
// return directly, if branch is configured to be non-feature branch
if (!$this->isFeatureBranch($packageConfig, $branch)) {
return ['version' => $version, 'pretty_version' => $prettyVersion];
}
// sort local branches first then remote ones
// and sort numeric branches below named ones, to make sure if the branch has the same distance from main and 1.10 and 1.9 for example, 1.9 is picked
// and sort using natural sort so that 1.10 will appear before 1.9
usort($branches, static function ($a, $b): int {
$aRemote = 0 === strpos($a, 'remotes/');
$bRemote = 0 === strpos($b, 'remotes/');
if ($aRemote !== $bRemote) {
return $aRemote ? 1 : -1;
}
return strnatcasecmp($b, $a);
});
$promises = [];
$this->process->setMaxJobs(30);
try {
$lastIndex = -1;
foreach ($branches as $index => $candidate) {
$candidateVersion = Preg::replace('{^remotes/\S+/}', '', $candidate);
// do not compare against itself or other feature branches
if ($candidate === $branch || $this->isFeatureBranch($packageConfig, $candidateVersion)) {
continue;
}
$cmdLine = array_map(static function (string $component) use ($candidate, $branch) {
return str_replace(['%candidate%', '%branch%'], [$candidate, $branch], $component);
}, $scmCmdline);
$promises[] = $this->process->executeAsync($cmdLine, $path)->then(function (Process $process) use (&$lastIndex, $index, &$length, &$version, &$prettyVersion, $candidateVersion, &$promises): void {
if (!$process->isSuccessful()) {
return;
}
$output = $process->getOutput();
// overwrite existing if we have a shorter diff, or we have an equal diff and an index that comes later in the array (i.e. older version)
// as newer versions typically have more commits, if the feature branch is based on a newer branch it should have a longer diff to the old version
// but if it doesn't and they have equal diffs, then it probably is based on the old version
if (strlen($output) < $length || (strlen($output) === $length && $lastIndex < $index)) {
$lastIndex = $index;
$length = strlen($output);
$version = $this->versionParser->normalizeBranch($candidateVersion);
$prettyVersion = 'dev-' . $candidateVersion;
if ($length === 0) {
foreach ($promises as $promise) {
// to support react/promise 2.x we wrap the promise in a resolve() call for safety
\React\Promise\resolve($promise)->cancel();
}
}
}
});
}
$this->process->wait();
} finally {
$this->process->resetMaxJobs();
}
}
return ['version' => $version, 'pretty_version' => $prettyVersion];
}
/**
* @param array<string, mixed> $packageConfig
*/
private function isFeatureBranch(array $packageConfig, ?string $branchName): bool
{
$nonFeatureBranches = '';
if (!empty($packageConfig['non-feature-branches'])) {
$nonFeatureBranches = implode('|', $packageConfig['non-feature-branches']);
}
return !Preg::isMatch('{^(' . $nonFeatureBranches . '|master|main|latest|next|current|support|tip|trunk|default|develop|\d+\..+)$}', $branchName, $match);
}
/**
* @return array{version: string|null, commit: '', pretty_version: string|null}
*/
private function guessFossilVersion(string $path): array
{
$version = null;
$prettyVersion = null;
// try to fetch current version from fossil
if (0 === $this->process->execute(['fossil', 'branch', 'list'], $output, $path)) {
$branch = trim($output);
$version = $this->versionParser->normalizeBranch($branch);
$prettyVersion = 'dev-' . $branch;
}
// try to fetch current version from fossil tags
if (0 === $this->process->execute(['fossil', 'tag', 'list'], $output, $path)) {
try {
$version = $this->versionParser->normalize(trim($output));
$prettyVersion = trim($output);
} catch (\Exception $e) {
}
}
return ['version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion];
}
/**
* @param array<string, mixed> $packageConfig
*
* @return array{version: string, commit: '', pretty_version: string}|null
*/
private function guessSvnVersion(array $packageConfig, string $path): ?array
{
SvnUtil::cleanEnv();
// try to fetch current version from svn
if (0 === $this->process->execute(['svn', 'info', '--xml'], $output, $path)) {
$trunkPath = isset($packageConfig['trunk-path']) ? preg_quote($packageConfig['trunk-path'], '#') : 'trunk';
$branchesPath = isset($packageConfig['branches-path']) ? preg_quote($packageConfig['branches-path'], '#') : 'branches';
$tagsPath = isset($packageConfig['tags-path']) ? preg_quote($packageConfig['tags-path'], '#') : 'tags';
$urlPattern = '#<url>.*/(' . $trunkPath . '|(' . $branchesPath . '|' . $tagsPath . ')/(.*))</url>#';
if (Preg::isMatch($urlPattern, $output, $matches)) {
if (isset($matches[2], $matches[3]) && ($branchesPath === $matches[2] || $tagsPath === $matches[2])) {
// we are in a branches path
$version = $this->versionParser->normalizeBranch($matches[3]);
$prettyVersion = 'dev-' . $matches[3];
return ['version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion];
}
assert(is_string($matches[1]));
$prettyVersion = trim($matches[1]);
if ($prettyVersion === 'trunk') {
$version = 'dev-trunk';
} else {
$version = $this->versionParser->normalize($prettyVersion);
}
return ['version' => $version, 'commit' => '', 'pretty_version' => $prettyVersion];
}
}
return null;
}
public function getRootVersionFromEnv(): string
{
$version = Platform::getEnv('COMPOSER_ROOT_VERSION');
if (!is_string($version) || $version === '') {
throw new \RuntimeException('COMPOSER_ROOT_VERSION not set or empty');
}
if (Preg::isMatch('{^(\d+(?:\.\d+)*)-dev$}i', $version, $match)) {
$version = $match[1].'.x-dev';
}
return $version;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/SelfUpdate/Keys.php | src/Composer/SelfUpdate/Keys.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\SelfUpdate;
use Composer\Pcre\Preg;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Keys
{
public static function fingerprint(string $path): string
{
$hash = strtoupper(hash('sha256', Preg::replace('{\s}', '', file_get_contents($path))));
return implode(' ', [
substr($hash, 0, 8),
substr($hash, 8, 8),
substr($hash, 16, 8),
substr($hash, 24, 8),
'', // Extra space
substr($hash, 32, 8),
substr($hash, 40, 8),
substr($hash, 48, 8),
substr($hash, 56, 8),
]);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/SelfUpdate/Versions.php | src/Composer/SelfUpdate/Versions.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\SelfUpdate;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Util\HttpDownloader;
use Composer\Config;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class Versions
{
/**
* @var string[]
* @deprecated use Versions::CHANNELS
*/
public static $channels = self::CHANNELS;
public const CHANNELS = ['stable', 'preview', 'snapshot', '1', '2', '2.2'];
/** @var HttpDownloader */
private $httpDownloader;
/** @var Config */
private $config;
/** @var string */
private $channel;
/** @var array<string, array<int, array{path: string, version: string, min-php: int, eol?: true}>>|null */
private $versionsData = null;
public function __construct(Config $config, HttpDownloader $httpDownloader)
{
$this->httpDownloader = $httpDownloader;
$this->config = $config;
}
public function getChannel(): string
{
if ($this->channel) {
return $this->channel;
}
$channelFile = $this->config->get('home').'/update-channel';
if (file_exists($channelFile)) {
$channel = trim(file_get_contents($channelFile));
if (in_array($channel, ['stable', 'preview', 'snapshot', '2.2'], true)) {
return $this->channel = $channel;
}
}
return $this->channel = 'stable';
}
public function setChannel(string $channel, ?IOInterface $io = null): void
{
if (!in_array($channel, self::CHANNELS, true)) {
throw new \InvalidArgumentException('Invalid channel '.$channel.', must be one of: ' . implode(', ', self::CHANNELS));
}
$channelFile = $this->config->get('home').'/update-channel';
$this->channel = $channel;
// rewrite '2' and '1' channels to stable for future self-updates, but LTS ones like '2.2' remain pinned
$storedChannel = Preg::isMatch('{^\d+$}D', $channel) ? 'stable' : $channel;
$previouslyStored = file_exists($channelFile) ? trim((string) file_get_contents($channelFile)) : null;
file_put_contents($channelFile, $storedChannel.PHP_EOL);
if ($io !== null && $previouslyStored !== $storedChannel) {
$io->writeError('Storing "<info>'.$storedChannel.'</info>" as default update channel for the next self-update run.');
}
}
/**
* @return array{path: string, version: string, min-php: int, eol?: true}
*/
public function getLatest(?string $channel = null): array
{
$versions = $this->getVersionsData();
foreach ($versions[$channel ?: $this->getChannel()] as $version) {
if ($version['min-php'] <= \PHP_VERSION_ID) {
return $version;
}
}
throw new \UnexpectedValueException('There is no version of Composer available for your PHP version ('.PHP_VERSION.')');
}
/**
* @return array<string, array<int, array{path: string, version: string, min-php: int, eol?: true}>>
*/
private function getVersionsData(): array
{
if (null === $this->versionsData) {
if ($this->config->get('disable-tls') === true) {
$protocol = 'http';
} else {
$protocol = 'https';
}
$this->versionsData = $this->httpDownloader->get($protocol . '://getcomposer.org/versions')->decodeJson();
}
return $this->versionsData;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/PHPStan/ConfigReturnTypeExtension.php | src/Composer/PHPStan/ConfigReturnTypeExtension.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\PHPStan;
use Composer\Config;
use Composer\Json\JsonFile;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\IntegerRangeType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
use PHPStan\Type\UnionType;
final class ConfigReturnTypeExtension implements DynamicMethodReturnTypeExtension
{
/** @var array<string, Type> */
private $properties = [];
public function __construct()
{
$schema = JsonFile::parseJson((string) file_get_contents(JsonFile::COMPOSER_SCHEMA_PATH));
/**
* @var string $prop
*/
foreach ($schema['properties']['config']['properties'] as $prop => $conf) {
$type = $this->parseType($conf, $prop);
$this->properties[$prop] = $type;
}
}
public function getClass(): string
{
return Config::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return strtolower($methodReflection->getName()) === 'get';
}
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type
{
$args = $methodCall->getArgs();
if (count($args) < 1) {
return null;
}
$keyType = $scope->getType($args[0]->value);
if (method_exists($keyType, 'getConstantStrings')) { // @phpstan-ignore function.alreadyNarrowedType (- depending on PHPStan version, this method will always exist, or not.)
$strings = $keyType->getConstantStrings();
} else {
// for compat with old phpstan versions, we use a deprecated phpstan method.
$strings = TypeUtils::getConstantStrings($keyType); // @phpstan-ignore staticMethod.deprecated (ignore deprecation)
}
if ($strings !== []) {
$types = [];
foreach ($strings as $string) {
if (!isset($this->properties[$string->getValue()])) {
return null;
}
$types[] = $this->properties[$string->getValue()];
}
return TypeCombinator::union(...$types);
}
return null;
}
/**
* @param array<mixed> $def
*/
private function parseType(array $def, string $path): Type
{
if (isset($def['type'])) {
$types = [];
foreach ((array) $def['type'] as $type) {
switch ($type) {
case 'integer':
if (in_array($path, ['process-timeout', 'cache-ttl', 'cache-files-ttl', 'cache-files-maxsize'], true)) {
$types[] = IntegerRangeType::createAllGreaterThanOrEqualTo(0);
} else {
$types[] = new IntegerType();
}
break;
case 'string':
if ($path === 'cache-files-maxsize') {
// passthru, skip as it is always converted to int
} elseif ($path === 'discard-changes') {
$types[] = new ConstantStringType('stash');
} elseif ($path === 'use-parent-dir') {
$types[] = new ConstantStringType('prompt');
} elseif ($path === 'store-auths') {
$types[] = new ConstantStringType('prompt');
} elseif ($path === 'platform-check') {
$types[] = new ConstantStringType('php-only');
} elseif ($path === 'github-protocols') {
$types[] = new UnionType([new ConstantStringType('git'), new ConstantStringType('https'), new ConstantStringType('ssh'), new ConstantStringType('http')]);
} elseif (str_starts_with($path, 'preferred-install')) {
$types[] = new UnionType([new ConstantStringType('source'), new ConstantStringType('dist'), new ConstantStringType('auto')]);
} else {
$types[] = new StringType();
}
break;
case 'boolean':
if ($path === 'platform.additionalProperties') {
$types[] = new ConstantBooleanType(false);
} else {
$types[] = new BooleanType();
}
break;
case 'object':
$addlPropType = null;
if (isset($def['additionalProperties'])) {
$addlPropType = $this->parseType($def['additionalProperties'], $path.'.additionalProperties');
}
if (isset($def['properties'])) {
$keyNames = [];
$valTypes = [];
$optionalKeys = [];
$propIndex = 0;
foreach ($def['properties'] as $propName => $propdef) {
$keyNames[] = new ConstantStringType($propName);
$valType = $this->parseType($propdef, $path.'.'.$propName);
if (!isset($def['required']) || !in_array($propName, $def['required'], true)) {
$valType = TypeCombinator::addNull($valType);
$optionalKeys[] = $propIndex;
}
$valTypes[] = $valType;
$propIndex++;
}
if ($addlPropType !== null) {
$types[] = new ArrayType(TypeCombinator::union(new StringType(), ...$keyNames), TypeCombinator::union($addlPropType, ...$valTypes));
} else {
$types[] = new ConstantArrayType($keyNames, $valTypes, [0], $optionalKeys);
}
} else {
$types[] = new ArrayType(new StringType(), $addlPropType ?? new MixedType());
}
break;
case 'array':
if (isset($def['items'])) {
$valType = $this->parseType($def['items'], $path.'.items');
} else {
$valType = new MixedType();
}
$types[] = new ArrayType(new IntegerType(), $valType);
break;
default:
$types[] = new MixedType();
}
}
$type = TypeCombinator::union(...$types);
} elseif (isset($def['enum'])) {
$type = TypeCombinator::union(...array_map(static function (string $value): ConstantStringType {
return new ConstantStringType($value);
}, $def['enum']));
} else {
$type = new MixedType();
}
// allow-plugins defaults to null until July 1st 2022 for some BC hackery, but after that it is not nullable anymore
if ($path === 'allow-plugins' && time() < strtotime('2022-07-01')) {
$type = TypeCombinator::addNull($type);
}
// default null props
if (in_array($path, ['autoloader-suffix', 'gitlab-protocol'], true)) {
$type = TypeCombinator::addNull($type);
}
return $type;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/PHPStan/RuleReasonDataReturnTypeExtension.php | src/Composer/PHPStan/RuleReasonDataReturnTypeExtension.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\PHPStan;
use Composer\DependencyResolver\Rule;
use Composer\Package\BasePackage;
use Composer\Package\Link;
use Composer\Semver\Constraint\ConstraintInterface;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\Accessory\AccessoryNonEmptyStringType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\IntegerType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeCombinator;
use PhpParser\Node\Identifier;
final class RuleReasonDataReturnTypeExtension implements DynamicMethodReturnTypeExtension
{
public function getClass(): string
{
return Rule::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return strtolower($methodReflection->getName()) === 'getreasondata';
}
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$reasonType = $scope->getType(new MethodCall($methodCall->var, new Identifier('getReason')));
$types = [
Rule::RULE_ROOT_REQUIRE => new ConstantArrayType([new ConstantStringType('packageName'), new ConstantStringType('constraint')], [new StringType, new ObjectType(ConstraintInterface::class)]),
Rule::RULE_FIXED => new ConstantArrayType([new ConstantStringType('package')], [new ObjectType(BasePackage::class)]),
Rule::RULE_PACKAGE_CONFLICT => new ObjectType(Link::class),
Rule::RULE_PACKAGE_REQUIRES => new ObjectType(Link::class),
Rule::RULE_PACKAGE_SAME_NAME => TypeCombinator::intersect(new StringType, new AccessoryNonEmptyStringType()),
Rule::RULE_LEARNED => new IntegerType(),
Rule::RULE_PACKAGE_ALIAS => new ObjectType(BasePackage::class),
Rule::RULE_PACKAGE_INVERSE_ALIAS => new ObjectType(BasePackage::class),
];
foreach ($types as $const => $type) {
if ((new ConstantIntegerType($const))->isSuperTypeOf($reasonType)->yes()) {
return $type;
}
}
return TypeCombinator::union(...$types);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/GzipDownloader.php | src/Composer/Downloader/GzipDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Util\Platform;
/**
* GZip archive downloader.
*
* @author Pavel Puchkin <i@neoascetic.me>
*/
class GzipDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
$filename = pathinfo(parse_url(strtr((string) $package->getDistUrl(), '\\', '/'), PHP_URL_PATH), PATHINFO_FILENAME);
$targetFilepath = $path . DIRECTORY_SEPARATOR . $filename;
// Try to use gunzip on *nix
if (!Platform::isWindows()) {
$command = ['sh', '-c', 'gzip -cd -- "$0" > "$1"', $file, $targetFilepath];
if (0 === $this->process->execute($command, $ignoredOutput)) {
return \React\Promise\resolve(null);
}
if (extension_loaded('zlib')) {
// Fallback to using the PHP extension.
$this->extractUsingExt($file, $targetFilepath);
return \React\Promise\resolve(null);
}
$processError = 'Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput();
throw new \RuntimeException($processError);
}
// Windows version of PHP has built-in support of gzip functions
$this->extractUsingExt($file, $targetFilepath);
return \React\Promise\resolve(null);
}
private function extractUsingExt(string $file, string $targetFilepath): void
{
$archiveFile = gzopen($file, 'rb');
$targetFile = fopen($targetFilepath, 'wb');
while ($string = gzread($archiveFile, 4096)) {
fwrite($targetFile, $string, Platform::strlen($string));
}
gzclose($archiveFile);
fclose($targetFile);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/DownloaderInterface.php | src/Composer/Downloader/DownloaderInterface.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\Downloader;
use Composer\Package\PackageInterface;
use React\Promise\PromiseInterface;
/**
* Downloader interface.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface DownloaderInterface
{
/**
* Returns installation source (either source or dist).
*
* @return string "source" or "dist"
*/
public function getInstallationSource(): string;
/**
* This should do any network-related tasks to prepare for an upcoming install/update
*
* @param string $path download path
* @phpstan-return PromiseInterface<void|null|string>
*/
public function download(PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface;
/**
* Do anything that needs to be done between all downloads have been completed and the actual operation is executed
*
* All packages get first downloaded, then all together prepared, then all together installed/updated/uninstalled. Therefore
* for error recovery it is important to avoid failing during install/update/uninstall as much as possible, and risky things or
* user prompts should happen in the prepare step rather. In case of failure, cleanup() will be called so that changes can
* be undone as much as possible.
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param string $path download path
* @param PackageInterface $prevPackage previous package instance in case of an update
* @phpstan-return PromiseInterface<void|null>
*/
public function prepare(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface;
/**
* Installs specific package into specific folder.
*
* @param PackageInterface $package package instance
* @param string $path download path
* @phpstan-return PromiseInterface<void|null>
*/
public function install(PackageInterface $package, string $path): PromiseInterface;
/**
* Updates specific package in specific folder from initial to target version.
*
* @param PackageInterface $initial initial package
* @param PackageInterface $target updated package
* @param string $path download path
* @phpstan-return PromiseInterface<void|null>
*/
public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface;
/**
* Removes specific package from specific folder.
*
* @param PackageInterface $package package instance
* @param string $path download path
* @phpstan-return PromiseInterface<void|null>
*/
public function remove(PackageInterface $package, string $path): PromiseInterface;
/**
* Do anything to cleanup changes applied in the prepare or install/update/uninstall steps
*
* Note that cleanup will be called for all packages, either after install/update/uninstall is complete,
* or if any package failed any operation. This is to give all installers a change to cleanup things
* they did previously, so you need to keep track of changes applied in the installer/downloader themselves.
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param string $path download path
* @param PackageInterface $prevPackage previous package instance in case of an update
* @phpstan-return PromiseInterface<void|null>
*/
public function cleanup(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/HgDownloader.php | src/Composer/Downloader/HgDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Util\Hg as HgUtils;
/**
* @author Per Bernhardt <plb@webfactory.de>
*/
class HgDownloader extends VcsDownloader
{
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface
{
if (null === HgUtils::getVersion($this->process)) {
throw new \RuntimeException('hg was not found in your PATH, skipping source download');
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface
{
$hgUtils = new HgUtils($this->io, $this->config, $this->process);
$cloneCommand = static function (string $url) use ($path): array {
return ['hg', 'clone', '--', $url, $path];
};
$hgUtils->runCommand($cloneCommand, $url, $path);
$command = ['hg', 'up', '--', (string) $package->getSourceReference()];
if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface
{
$hgUtils = new HgUtils($this->io, $this->config, $this->process);
$ref = $target->getSourceReference();
$this->io->writeError(" Updating to ".$target->getSourceReference());
if (!$this->hasMetadataRepository($path)) {
throw new \RuntimeException('The .hg directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
}
$command = static function ($url): array {
return ['hg', 'pull', '--', $url];
};
$hgUtils->runCommand($command, $url, $path);
$command = static function () use ($ref): array {
return ['hg', 'up', '--', $ref];
};
$hgUtils->runCommand($command, $url, $path);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
if (!is_dir($path.'/.hg')) {
return null;
}
$this->process->execute(['hg', 'st'], $output, realpath($path));
$output = trim($output);
return strlen($output) > 0 ? $output : null;
}
/**
* @inheritDoc
*/
protected function getCommitLogs(string $fromReference, string $toReference, string $path): string
{
$command = ['hg', 'log', '-r', $fromReference.':'.$toReference, '--style', 'compact'];
if (0 !== $this->process->execute($command, $output, realpath($path))) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
return $output;
}
/**
* @inheritDoc
*/
protected function hasMetadataRepository(string $path): bool
{
return is_dir($path . '/.hg');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/GitDownloader.php | src/Composer/Downloader/GitDownloader.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\Downloader;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Util\Filesystem;
use Composer\Util\Git as GitUtil;
use Composer\Util\Url;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Cache;
use React\Promise\PromiseInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GitDownloader extends VcsDownloader implements DvcsDownloaderInterface
{
/**
* @var bool[]
* @phpstan-var array<string, bool>
*/
private $hasStashedChanges = [];
/**
* @var bool[]
* @phpstan-var array<string, bool>
*/
private $hasDiscardedChanges = [];
/**
* @var GitUtil
*/
private $gitUtil;
/**
* @var array
* @phpstan-var array<int, array<string, bool>>
*/
private $cachedPackages = [];
public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?Filesystem $fs = null)
{
parent::__construct($io, $config, $process, $fs);
$this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem);
}
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface
{
// Do not create an extra local cache when repository is already local
if (Filesystem::isLocalPath($url)) {
return \React\Promise\resolve(null);
}
GitUtil::cleanEnv($this->process);
$cachePath = $this->config->get('cache-vcs-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($url)).'/';
$gitVersion = GitUtil::getVersion($this->process);
// --dissociate option is only available since git 2.3.0-rc0
if ($gitVersion && version_compare($gitVersion, '2.3.0-rc0', '>=') && Cache::isUsable($cachePath)) {
$this->io->writeError(" - Syncing <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>) into cache");
$this->io->writeError(sprintf(' Cloning to cache at %s', $cachePath), true, IOInterface::DEBUG);
$ref = $package->getSourceReference();
if ($this->gitUtil->fetchRefOrSyncMirror($url, $cachePath, $ref, $package->getPrettyVersion()) && is_dir($cachePath)) {
$this->cachedPackages[$package->getId()][$ref] = true;
}
} elseif (null === $gitVersion) {
throw new \RuntimeException('git was not found in your PATH, skipping source download');
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface
{
GitUtil::cleanEnv($this->process);
$path = $this->normalizePath($path);
$cachePath = $this->config->get('cache-vcs-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($url)).'/';
$ref = $package->getSourceReference();
if (!empty($this->cachedPackages[$package->getId()][$ref])) {
$msg = "Cloning ".$this->getShortHash($ref).' from cache';
$cloneFlags = ['--dissociate', '--reference', $cachePath];
$transportOptions = $package->getTransportOptions();
if (isset($transportOptions['git']['single_use_clone']) && $transportOptions['git']['single_use_clone']) {
$cloneFlags = [];
}
$commands = [
array_merge(['git', 'clone', '--no-checkout', $cachePath, $path], $cloneFlags),
['git', 'remote', 'set-url', 'origin', '--', '%sanitizedUrl%'],
['git', 'remote', 'add', 'composer', '--', '%sanitizedUrl%'],
];
} else {
$msg = "Cloning ".$this->getShortHash($ref);
$commands = [
array_merge(['git', 'clone', '--no-checkout', '--', '%url%', $path]),
['git', 'remote', 'add', 'composer', '--', '%url%'],
['git', 'fetch', 'composer'],
['git', 'remote', 'set-url', 'origin', '--', '%sanitizedUrl%'],
['git', 'remote', 'set-url', 'composer', '--', '%sanitizedUrl%'],
];
if (Platform::getEnv('COMPOSER_DISABLE_NETWORK')) {
throw new \RuntimeException('The required git reference for '.$package->getName().' is not in cache and network is disabled, aborting');
}
}
$this->io->writeError($msg);
$this->gitUtil->runCommands($commands, $url, $path, true);
$sourceUrl = $package->getSourceUrl();
if ($url !== $sourceUrl && $sourceUrl !== null) {
$this->updateOriginUrl($path, $sourceUrl);
} else {
$this->setPushUrl($path, $url);
}
if ($newRef = $this->updateToCommit($package, $path, (string) $ref, $package->getPrettyVersion())) {
if ($package->getDistReference() === $package->getSourceReference()) {
$package->setDistReference($newRef);
}
$package->setSourceReference($newRef);
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface
{
GitUtil::cleanEnv($this->process);
$path = $this->normalizePath($path);
if (!$this->hasMetadataRepository($path)) {
throw new \RuntimeException('The .git directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
}
$cachePath = $this->config->get('cache-vcs-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($url)).'/';
$ref = $target->getSourceReference();
if (!empty($this->cachedPackages[$target->getId()][$ref])) {
$msg = "Checking out ".$this->getShortHash($ref).' from cache';
$remoteUrl = $cachePath;
} else {
$msg = "Checking out ".$this->getShortHash($ref);
$remoteUrl = '%url%';
if (Platform::getEnv('COMPOSER_DISABLE_NETWORK')) {
throw new \RuntimeException('The required git reference for '.$target->getName().' is not in cache and network is disabled, aborting');
}
}
$this->io->writeError($msg);
if (0 !== $this->process->execute(['git', 'rev-parse', '--quiet', '--verify', $ref.'^{commit}'], $output, $path)) {
$commands = [
['git', 'remote', 'set-url', 'composer', '--', $remoteUrl],
['git', 'fetch', 'composer'],
['git', 'fetch', '--tags', 'composer'],
];
$this->gitUtil->runCommands($commands, $url, $path);
}
$command = ['git', 'remote', 'set-url', 'composer', '--', '%sanitizedUrl%'];
$this->gitUtil->runCommands([$command], $url, $path);
if ($newRef = $this->updateToCommit($target, $path, (string) $ref, $target->getPrettyVersion())) {
if ($target->getDistReference() === $target->getSourceReference()) {
$target->setDistReference($newRef);
}
$target->setSourceReference($newRef);
}
$updateOriginUrl = false;
if (
0 === $this->process->execute(['git', 'remote', '-v'], $output, $path)
&& Preg::isMatch('{^origin\s+(?P<url>\S+)}m', $output, $originMatch)
&& Preg::isMatch('{^composer\s+(?P<url>\S+)}m', $output, $composerMatch)
) {
if ($originMatch['url'] === $composerMatch['url'] && $composerMatch['url'] !== $target->getSourceUrl()) {
$updateOriginUrl = true;
}
}
if ($updateOriginUrl && $target->getSourceUrl() !== null) {
$this->updateOriginUrl($path, $target->getSourceUrl());
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
GitUtil::cleanEnv($this->process);
if (!$this->hasMetadataRepository($path)) {
return null;
}
$command = ['git', 'status', '--porcelain', '--untracked-files=no'];
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
$output = trim($output);
return strlen($output) > 0 ? $output : null;
}
public function getUnpushedChanges(PackageInterface $package, string $path): ?string
{
GitUtil::cleanEnv($this->process);
$path = $this->normalizePath($path);
if (!$this->hasMetadataRepository($path)) {
return null;
}
$command = ['git', 'show-ref', '--head', '-d'];
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
$refs = trim($output);
if (!Preg::isMatchStrictGroups('{^([a-f0-9]+) HEAD$}mi', $refs, $match)) {
// could not match the HEAD for some reason
return null;
}
$headRef = $match[1];
if (!Preg::isMatchAllStrictGroups('{^'.preg_quote($headRef).' refs/heads/(.+)$}mi', $refs, $matches)) {
// not on a branch, we are either on a not-modified tag or some sort of detached head, so skip this
return null;
}
$candidateBranches = $matches[1];
// use the first match as branch name for now
$branch = $candidateBranches[0];
$unpushedChanges = null;
$branchNotFoundError = false;
// do two passes, as if we find anything we want to fetch and then re-try
for ($i = 0; $i <= 1; $i++) {
$remoteBranches = [];
// try to find matching branch names in remote repos
foreach ($candidateBranches as $candidate) {
if (Preg::isMatchAllStrictGroups('{^[a-f0-9]+ refs/remotes/((?:[^/]+)/'.preg_quote($candidate).')$}mi', $refs, $matches)) {
foreach ($matches[1] as $match) {
$branch = $candidate;
$remoteBranches[] = $match;
}
break;
}
}
// if it doesn't exist, then we assume it is an unpushed branch
// this is bad as we have no reference point to do a diff so we just bail listing
// the branch as being unpushed
if (count($remoteBranches) === 0) {
$unpushedChanges = 'Branch ' . $branch . ' could not be found on any remote and appears to be unpushed';
$branchNotFoundError = true;
} else {
// if first iteration found no remote branch but it has now found some, reset $unpushedChanges
// so we get the real diff output no matter its length
if ($branchNotFoundError) {
$unpushedChanges = null;
}
foreach ($remoteBranches as $remoteBranch) {
$command = ['git', 'diff', '--name-status', $remoteBranch.'...'.$branch, '--'];
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
$output = trim($output);
// keep the shortest diff from all remote branches we compare against
if ($unpushedChanges === null || strlen($output) < strlen($unpushedChanges)) {
$unpushedChanges = $output;
}
}
}
// first pass and we found unpushed changes, fetch from all remotes to make sure we have up to date
// remotes and then try again as outdated remotes can sometimes cause false-positives
if ($unpushedChanges && $i === 0) {
$this->process->execute(['git', 'fetch', '--all'], $output, $path);
// update list of refs after fetching
$command = ['git', 'show-ref', '--head', '-d'];
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
$refs = trim($output);
}
// abort after first pass if we didn't find anything
if (!$unpushedChanges) {
break;
}
}
return $unpushedChanges;
}
/**
* @inheritDoc
*/
protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface
{
GitUtil::cleanEnv($this->process);
$path = $this->normalizePath($path);
$unpushed = $this->getUnpushedChanges($package, $path);
if ($unpushed && ($this->io->isInteractive() || $this->config->get('discard-changes') !== true)) {
throw new \RuntimeException('Source directory ' . $path . ' has unpushed changes on the current branch: '."\n".$unpushed);
}
if (null === ($changes = $this->getLocalChanges($package, $path))) {
return \React\Promise\resolve(null);
}
if (!$this->io->isInteractive()) {
$discardChanges = $this->config->get('discard-changes');
if (true === $discardChanges) {
return $this->discardChanges($path);
}
if ('stash' === $discardChanges) {
if (!$update) {
return parent::cleanChanges($package, $path, $update);
}
return $this->stashChanges($path);
}
return parent::cleanChanges($package, $path, $update);
}
$changes = array_map(static function ($elem): string {
return ' '.$elem;
}, Preg::split('{\s*\r?\n\s*}', $changes));
$this->io->writeError(' <error>'.$package->getPrettyName().' has modified files:</error>');
$this->io->writeError(array_slice($changes, 0, 10));
if (count($changes) > 10) {
$this->io->writeError(' <info>' . (count($changes) - 10) . ' more files modified, choose "v" to view the full list</info>');
}
while (true) {
switch ($this->io->ask(' <info>Discard changes [y,n,v,d,'.($update ? 's,' : '').'?]?</info> ', '?')) {
case 'y':
$this->discardChanges($path);
break 2;
case 's':
if (!$update) {
goto help;
}
$this->stashChanges($path);
break 2;
case 'n':
throw new \RuntimeException('Update aborted');
case 'v':
$this->io->writeError($changes);
break;
case 'd':
$this->viewDiff($path);
break;
case '?':
default:
help :
$this->io->writeError([
' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
' v - view modified files',
' d - view local modifications (diff)',
]);
if ($update) {
$this->io->writeError(' s - stash changes and try to reapply them after the update');
}
$this->io->writeError(' ? - print help');
break;
}
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function reapplyChanges(string $path): void
{
$path = $this->normalizePath($path);
if (!empty($this->hasStashedChanges[$path])) {
unset($this->hasStashedChanges[$path]);
$this->io->writeError(' <info>Re-applying stashed changes</info>');
if (0 !== $this->process->execute(['git', 'stash', 'pop'], $output, $path)) {
throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
}
}
unset($this->hasDiscardedChanges[$path]);
}
/**
* Updates the given path to the given commit ref
*
* @throws \RuntimeException
* @return null|string if a string is returned, it is the commit reference that was checked out if the original could not be found
*/
protected function updateToCommit(PackageInterface $package, string $path, string $reference, string $prettyVersion): ?string
{
$force = !empty($this->hasDiscardedChanges[$path]) || !empty($this->hasStashedChanges[$path]) ? ['-f'] : [];
// This uses the "--" sequence to separate branch from file parameters.
//
// Otherwise git tries the branch name as well as file name.
// If the non-existent branch is actually the name of a file, the file
// is checked out.
$branch = Preg::replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $prettyVersion);
/**
* @var \Closure(non-empty-list<string>): bool $execute
* @phpstan-ignore varTag.nativeType
*/
$execute = function (array $command) use (&$output, $path) {
/** @var non-empty-list<string> $command */
$output = '';
return 0 === $this->process->execute($command, $output, $path);
};
$branches = null;
if ($execute(['git', 'branch', '-r'])) {
$branches = $output;
}
// check whether non-commitish are branches or tags, and fetch branches with the remote name
$gitRef = $reference;
if (!Preg::isMatch('{^[a-f0-9]{40}$}', $reference)
&& null !== $branches
&& Preg::isMatch('{^\s+composer/'.preg_quote($reference).'$}m', $branches)
) {
$command1 = array_merge(['git', 'checkout'], $force, ['-B', $branch, 'composer/'.$reference, '--']);
$command2 = ['git', 'reset', '--hard', 'composer/'.$reference, '--'];
if ($execute($command1) && $execute($command2)) {
return null;
}
}
// try to checkout branch by name and then reset it so it's on the proper branch name
if (Preg::isMatch('{^[a-f0-9]{40}$}', $reference)) {
// add 'v' in front of the branch if it was stripped when generating the pretty name
if (null !== $branches && !Preg::isMatch('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && Preg::isMatch('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) {
$branch = 'v' . $branch;
}
$command = ['git', 'checkout', $branch, '--'];
$fallbackCommand = array_merge(['git', 'checkout'], $force, ['-B', $branch, 'composer/'.$branch, '--']);
$resetCommand = ['git', 'reset', '--hard', $reference, '--'];
if (($execute($command) || $execute($fallbackCommand)) && $execute($resetCommand)) {
return null;
}
}
$command1 = array_merge(['git', 'checkout'], $force, [$gitRef, '--']);
$command2 = ['git', 'reset', '--hard', $gitRef, '--'];
if ($execute($command1) && $execute($command2)) {
return null;
}
$exceptionExtra = '';
// reference was not found (prints "fatal: reference is not a tree: $ref")
if (false !== strpos($this->process->getErrorOutput(), $reference)) {
$this->io->writeError(' <warning>'.$reference.' is gone (history was rewritten?)</warning>');
$exceptionExtra = "\nIt looks like the commit hash is not available in the repository, maybe ".($package->isDev() ? 'the commit was removed from the branch' : 'the tag was recreated').'? Run "composer update '.$package->getPrettyName().'" to resolve this.';
}
$command = implode(' ', $command1). ' && '.implode(' ', $command2);
throw new \RuntimeException(Url::sanitize('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput() . $exceptionExtra));
}
protected function updateOriginUrl(string $path, string $url): void
{
$this->process->execute(['git', 'remote', 'set-url', 'origin', '--', $url], $output, $path);
$this->setPushUrl($path, $url);
}
protected function setPushUrl(string $path, string $url): void
{
// set push url for github projects
if (Preg::isMatch('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) {
$protocols = $this->config->get('github-protocols');
$pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
if (!in_array('ssh', $protocols, true)) {
$pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git';
}
$cmd = ['git', 'remote', 'set-url', '--push', 'origin', '--', $pushUrl];
$this->process->execute($cmd, $ignoredOutput, $path);
}
}
/**
* @inheritDoc
*/
protected function getCommitLogs(string $fromReference, string $toReference, string $path): string
{
$path = $this->normalizePath($path);
$command = GitUtil::buildRevListCommand($this->process, array_merge(['--format=%h - %an: %s', $fromReference.'..'.$toReference], GitUtil::getNoShowSignatureFlags($this->process)));
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
return GitUtil::parseRevListOutput($output, $this->process);
}
/**
* @phpstan-return PromiseInterface<void|null>
* @throws \RuntimeException
*/
protected function discardChanges(string $path): PromiseInterface
{
$path = $this->normalizePath($path);
if (0 !== $this->process->execute(['git', 'clean', '-df'], $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$output);
}
if (0 !== $this->process->execute(['git', 'reset', '--hard'], $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$output);
}
$this->hasDiscardedChanges[$path] = true;
return \React\Promise\resolve(null);
}
/**
* @phpstan-return PromiseInterface<void|null>
* @throws \RuntimeException
*/
protected function stashChanges(string $path): PromiseInterface
{
$path = $this->normalizePath($path);
if (0 !== $this->process->execute(['git', 'stash', '--include-untracked'], $output, $path)) {
throw new \RuntimeException("Could not stash changes\n\n:".$output);
}
$this->hasStashedChanges[$path] = true;
return \React\Promise\resolve(null);
}
/**
* @throws \RuntimeException
*/
protected function viewDiff(string $path): void
{
$path = $this->normalizePath($path);
if (0 !== $this->process->execute(['git', 'diff', 'HEAD'], $output, $path)) {
throw new \RuntimeException("Could not view diff\n\n:".$output);
}
$this->io->writeError($output);
}
protected function normalizePath(string $path): string
{
if (Platform::isWindows() && strlen($path) > 0) {
$basePath = $path;
$removed = [];
while (!is_dir($basePath) && $basePath !== '\\') {
array_unshift($removed, basename($basePath));
$basePath = dirname($basePath);
}
if ($basePath === '\\') {
return $path;
}
$path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
}
return $path;
}
/**
* @inheritDoc
*/
protected function hasMetadataRepository(string $path): bool
{
$path = $this->normalizePath($path);
return is_dir($path.'/.git');
}
protected function getShortHash(string $reference): string
{
if (!$this->io->isVerbose() && Preg::isMatch('{^[0-9a-f]{40}$}', $reference)) {
return substr($reference, 0, 10);
}
return $reference;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/FileDownloader.php | src/Composer/Downloader/FileDownloader.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\Downloader;
use Composer\Config;
use Composer\Cache;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Composer\Exception\IrrecoverableDownloadException;
use Composer\Package\Comparer\Comparer;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\Package\PackageInterface;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PostFileDownloadEvent;
use Composer\Plugin\PreFileDownloadEvent;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\Filesystem;
use Composer\Util\Http\Response;
use Composer\Util\Platform;
use Composer\Util\Silencer;
use Composer\Util\HttpDownloader;
use Composer\Util\Url as UrlUtil;
use Composer\Util\ProcessExecutor;
use React\Promise\PromiseInterface;
/**
* Base downloader for files
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author François Pluchino <francois.pluchino@opendisplay.com>
* @author Nils Adermann <naderman@naderman.de>
*/
class FileDownloader implements DownloaderInterface, ChangeReportInterface
{
/** @var IOInterface */
protected $io;
/** @var Config */
protected $config;
/** @var HttpDownloader */
protected $httpDownloader;
/** @var Filesystem */
protected $filesystem;
/** @var ?Cache */
protected $cache;
/** @var ?EventDispatcher */
protected $eventDispatcher;
/** @var ProcessExecutor */
protected $process;
/**
* @var array<string, int|string>
* @private
* @internal
*/
public static $downloadMetadata = [];
/**
* Collects response headers when running on GH Actions
*
* @see https://github.com/composer/composer/issues/11148
* @var array<string, array<string>>
* @private
* @internal
*/
public static $responseHeaders = [];
/**
* @var array<string, string> Map of package name to cache key
*/
private $lastCacheWrites = [];
/** @var array<string, string[]> Map of package name to list of paths */
private $additionalCleanupPaths = [];
/**
* Constructor.
*
* @param IOInterface $io The IO instance
* @param Config $config The config
* @param HttpDownloader $httpDownloader The remote filesystem
* @param EventDispatcher $eventDispatcher The event dispatcher
* @param Cache $cache Cache instance
* @param Filesystem $filesystem The filesystem
*/
public function __construct(IOInterface $io, Config $config, HttpDownloader $httpDownloader, ?EventDispatcher $eventDispatcher = null, ?Cache $cache = null, ?Filesystem $filesystem = null, ?ProcessExecutor $process = null)
{
$this->io = $io;
$this->config = $config;
$this->eventDispatcher = $eventDispatcher;
$this->httpDownloader = $httpDownloader;
$this->cache = $cache;
$this->process = $process ?? new ProcessExecutor($io);
$this->filesystem = $filesystem ?? new Filesystem($this->process);
if ($this->cache !== null && $this->cache->gcIsNecessary()) {
$this->io->writeError('Running cache garbage collection', true, IOInterface::VERY_VERBOSE);
$this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize'));
}
}
/**
* @inheritDoc
*/
public function getInstallationSource(): string
{
return 'dist';
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, string $path, ?PackageInterface $prevPackage = null, bool $output = true): PromiseInterface
{
if (null === $package->getDistUrl()) {
throw new \InvalidArgumentException('The given package is missing url information');
}
$cacheKeyGenerator = static function (PackageInterface $package, $key): string {
$cacheKey = hash('sha1', $key);
return $package->getName().'/'.$cacheKey.'.'.$package->getDistType();
};
$retries = 3;
$distUrls = $package->getDistUrls();
/** @var array<array{base: non-empty-string, processed: non-empty-string, cacheKey: string}> $urls */
$urls = [];
foreach ($distUrls as $index => $url) {
$processedUrl = $this->processUrl($package, $url);
$urls[$index] = [
'base' => $url,
'processed' => $processedUrl,
// we use the complete download url here to avoid conflicting entries
// from different packages, which would potentially allow a given package
// in a third party repo to pre-populate the cache for the same package in
// packagist for example.
'cacheKey' => $cacheKeyGenerator($package, $processedUrl),
];
}
assert(count($urls) > 0);
$fileName = $this->getFileName($package, $path);
$this->filesystem->ensureDirectoryExists($path);
$this->filesystem->ensureDirectoryExists(dirname($fileName));
$accept = null;
$reject = null;
$download = function () use ($output, $cacheKeyGenerator, $package, $fileName, &$urls, &$accept, &$reject) {
$url = reset($urls);
$index = key($urls);
if ($this->eventDispatcher !== null) {
$preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->httpDownloader, $url['processed'], 'package', $package);
$this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
if ($preFileDownloadEvent->getCustomCacheKey() !== null) {
$url['cacheKey'] = $cacheKeyGenerator($package, $preFileDownloadEvent->getCustomCacheKey());
} elseif ($preFileDownloadEvent->getProcessedUrl() !== $url['processed']) {
$url['cacheKey'] = $cacheKeyGenerator($package, $preFileDownloadEvent->getProcessedUrl());
}
$url['processed'] = $preFileDownloadEvent->getProcessedUrl();
}
$urls[$index] = $url;
$checksum = $package->getDistSha1Checksum();
$cacheKey = $url['cacheKey'];
// use from cache if it is present and has a valid checksum or we have no checksum to check against
if ($this->cache !== null && ($checksum === null || $checksum === '' || $checksum === $this->cache->sha1($cacheKey)) && $this->cache->copyTo($cacheKey, $fileName)) {
if ($output) {
$this->io->writeError(" - Loading <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>) from cache", true, IOInterface::VERY_VERBOSE);
}
// mark the file as having been written in cache even though it is only read from cache, so that if
// the cache is corrupt the archive will be deleted and the next attempt will re-download it
// see https://github.com/composer/composer/issues/10028
if (!$this->cache->isReadOnly()) {
$this->lastCacheWrites[$package->getName()] = $cacheKey;
}
$result = \React\Promise\resolve($fileName);
} else {
if ($output) {
$this->io->writeError(" - Downloading <info>" . $package->getName() . "</info> (<comment>" . $package->getFullPrettyVersion() . "</comment>)");
}
$result = $this->httpDownloader->addCopy($url['processed'], $fileName, $package->getTransportOptions())
->then($accept, $reject);
}
return $result->then(function ($result) use ($fileName, $checksum, $url, $package): string {
// in case of retry, the first call's Promise chain finally calls this twice at the end,
// once with $result being the returned $fileName from $accept, and then once for every
// failed request with a null result, which can be skipped.
if (null === $result) {
return $fileName;
}
if (!file_exists($fileName)) {
throw new \UnexpectedValueException($url['base'].' could not be saved to '.$fileName.', make sure the'
.' directory is writable and you have internet connectivity');
}
if ($checksum !== null && $checksum !== '' && hash_file('sha1', $fileName) !== $checksum) {
throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url['base'].')');
}
if ($this->eventDispatcher !== null) {
$postFileDownloadEvent = new PostFileDownloadEvent(PluginEvents::POST_FILE_DOWNLOAD, $fileName, $checksum, $url['processed'], 'package', $package);
$this->eventDispatcher->dispatch($postFileDownloadEvent->getName(), $postFileDownloadEvent);
}
return $fileName;
});
};
$accept = function (Response $response) use ($package, $fileName, &$urls): string {
$url = reset($urls);
$cacheKey = $url['cacheKey'];
$fileSize = @filesize($fileName);
if (false === $fileSize) {
$fileSize = $response->getHeader('Content-Length') ?? '?';
}
FileDownloader::$downloadMetadata[$package->getName()] = $fileSize;
if (Platform::getEnv('GITHUB_ACTIONS') !== false && Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING') === false) {
FileDownloader::$responseHeaders[$package->getName()] = $response->getHeaders();
}
if ($this->cache !== null && !$this->cache->isReadOnly()) {
$this->lastCacheWrites[$package->getName()] = $cacheKey;
$this->cache->copyFrom($cacheKey, $fileName);
}
$response->collect();
return $fileName;
};
$reject = function ($e) use (&$urls, $download, $fileName, $package, &$retries) {
// clean up
if (file_exists($fileName)) {
$this->filesystem->unlink($fileName);
}
$this->clearLastCacheWrite($package);
if ($e instanceof IrrecoverableDownloadException) {
throw $e;
}
if ($e instanceof MaxFileSizeExceededException) {
throw $e;
}
if ($e instanceof TransportException) {
// if we got an http response with a proper code, then requesting again will probably not help, abort
if (0 !== $e->getCode() && !in_array($e->getCode(), [500, 502, 503, 504], true)) {
$retries = 0;
}
}
// special error code returned when network is being artificially disabled
if ($e instanceof TransportException && $e->getStatusCode() === 499) {
$retries = 0;
$urls = [];
}
if ($retries > 0) {
usleep(500000);
$retries--;
return $download();
}
array_shift($urls);
if (\count($urls) > 0) {
if ($this->io->isDebug()) {
$this->io->writeError(' Failed downloading '.$package->getName().': ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage());
$this->io->writeError(' Trying the next URL for '.$package->getName());
} else {
$this->io->writeError(' Failed downloading '.$package->getName().', trying the next URL ('.$e->getCode().': '.$e->getMessage().')');
}
$retries = 3;
usleep(100000);
return $download();
}
throw $e;
};
return $download();
}
/**
* @inheritDoc
*/
public function prepare(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function cleanup(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
$fileName = $this->getFileName($package, $path);
if (file_exists($fileName)) {
$this->filesystem->unlink($fileName);
}
$dirsToCleanUp = [
$path,
$this->config->get('vendor-dir').'/'.explode('/', $package->getPrettyName())[0],
$this->config->get('vendor-dir').'/composer/',
$this->config->get('vendor-dir'),
];
if (isset($this->additionalCleanupPaths[$package->getName()])) {
foreach ($this->additionalCleanupPaths[$package->getName()] as $pathToClean) {
$this->filesystem->remove($pathToClean);
}
}
foreach ($dirsToCleanUp as $dir) {
if (is_dir($dir) && $this->filesystem->isDirEmpty($dir) && realpath($dir) !== Platform::getCwd()) {
$this->filesystem->removeDirectoryPhp($dir);
}
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface
{
if ($output) {
$this->io->writeError(" - " . InstallOperation::format($package));
}
$vendorDir = $this->config->get('vendor-dir');
// clean up the target directory, unless it contains the vendor dir, as the vendor dir contains
// the file to be installed. This is the case when installing with create-project in the current directory
// but in that case we ensure the directory is empty already in ProjectInstaller so no need to empty it here.
if (false === strpos($this->filesystem->normalizePath($vendorDir), $this->filesystem->normalizePath($path.DIRECTORY_SEPARATOR))) {
$this->filesystem->emptyDirectory($path);
}
$this->filesystem->ensureDirectoryExists($path);
$this->filesystem->rename($this->getFileName($package, $path), $path . '/' . $this->getDistPath($package, PATHINFO_BASENAME));
// Single files can not have a mode set like files in archives
// so we make sure if the file is a binary that it is executable
foreach ($package->getBinaries() as $bin) {
if (file_exists($path . '/' . $bin) && !is_executable($path . '/' . $bin)) {
Silencer::call('chmod', $path . '/' . $bin, 0777 & ~umask());
}
}
return \React\Promise\resolve(null);
}
/**
* @param PATHINFO_EXTENSION|PATHINFO_BASENAME $component
*/
protected function getDistPath(PackageInterface $package, int $component): string
{
return pathinfo((string) parse_url(strtr((string) $package->getDistUrl(), '\\', '/'), PHP_URL_PATH), $component);
}
protected function clearLastCacheWrite(PackageInterface $package): void
{
if ($this->cache !== null && isset($this->lastCacheWrites[$package->getName()])) {
$this->cache->remove($this->lastCacheWrites[$package->getName()]);
unset($this->lastCacheWrites[$package->getName()]);
}
}
protected function addCleanupPath(PackageInterface $package, string $path): void
{
$this->additionalCleanupPaths[$package->getName()][] = $path;
}
protected function removeCleanupPath(PackageInterface $package, string $path): void
{
if (isset($this->additionalCleanupPaths[$package->getName()])) {
$idx = array_search($path, $this->additionalCleanupPaths[$package->getName()], true);
if (false !== $idx) {
unset($this->additionalCleanupPaths[$package->getName()][$idx]);
}
}
}
/**
* @inheritDoc
*/
public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface
{
$this->io->writeError(" - " . UpdateOperation::format($initial, $target) . $this->getInstallOperationAppendix($target, $path));
$promise = $this->remove($initial, $path, false);
return $promise->then(function () use ($target, $path): PromiseInterface {
return $this->install($target, $path, false);
});
}
/**
* @inheritDoc
*/
public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface
{
if ($output) {
$this->io->writeError(" - " . UninstallOperation::format($package));
}
$promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(static function ($result) use ($path): void {
if (!$result) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
}
});
}
/**
* Gets file name for specific package
*
* @param PackageInterface $package package instance
* @param string $path download path
* @return string file name
*/
protected function getFileName(PackageInterface $package, string $path): string
{
$extension = $this->getDistPath($package, PATHINFO_EXTENSION);
if ($extension === '') {
$extension = $package->getDistType();
}
return rtrim($this->config->get('vendor-dir') . '/composer/tmp-' . hash('md5', $package . spl_object_hash($package)) . '.' . $extension, '.');
}
/**
* Gets appendix message to add to the "- Upgrading x" string being output on update
*
* @param PackageInterface $package package instance
* @param string $path download path
*/
protected function getInstallOperationAppendix(PackageInterface $package, string $path): string
{
return '';
}
/**
* Process the download url
*
* @param PackageInterface $package package instance
* @param non-empty-string $url download url
* @throws \RuntimeException If any problem with the url
* @return non-empty-string url
*/
protected function processUrl(PackageInterface $package, string $url): string
{
if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) {
throw new \RuntimeException('You must enable the openssl extension to download files via https');
}
if ($package->getDistReference() !== null) {
$url = UrlUtil::updateDistReference($this->config, $url, $package->getDistReference());
}
return $url;
}
/**
* @inheritDoc
* @throws \RuntimeException
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
$prevIO = $this->io;
$this->io = new NullIO;
$this->io->loadConfiguration($this->config);
$e = null;
$output = '';
$targetDir = Filesystem::trimTrailingSlash($path);
try {
if (is_dir($targetDir.'_compare')) {
$this->filesystem->removeDirectory($targetDir.'_compare');
}
$promise = $this->download($package, $targetDir.'_compare', null, false);
$promise->then(null, static function ($ex) use (&$e) {
$e = $ex;
});
$this->httpDownloader->wait();
if ($e !== null) {
throw $e;
}
$promise = $this->install($package, $targetDir.'_compare', false);
$promise->then(null, static function ($ex) use (&$e) {
$e = $ex;
});
$this->process->wait();
if ($e !== null) {
throw $e;
}
$comparer = new Comparer();
$comparer->setSource($targetDir.'_compare');
$comparer->setUpdate($targetDir);
$comparer->doCompare();
$output = $comparer->getChangedAsString(true);
$this->filesystem->removeDirectory($targetDir.'_compare');
} catch (\Exception $e) {
}
$this->io = $prevIO;
if ($e !== null) {
if ($this->io->isDebug()) {
throw $e;
}
return 'Failed to detect changes: ['.get_class($e).'] '.$e->getMessage();
}
$output = trim($output);
return strlen($output) > 0 ? $output : null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/VcsDownloader.php | src/Composer/Downloader/VcsDownloader.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\Downloader;
use Composer\Config;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionGuesser;
use Composer\Package\Version\VersionParser;
use Composer\Util\ProcessExecutor;
use Composer\IO\IOInterface;
use Composer\Util\Filesystem;
use React\Promise\PromiseInterface;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterface, VcsCapableDownloaderInterface
{
/** @var IOInterface */
protected $io;
/** @var Config */
protected $config;
/** @var ProcessExecutor */
protected $process;
/** @var Filesystem */
protected $filesystem;
/** @var array<string, true> */
protected $hasCleanedChanges = [];
public function __construct(IOInterface $io, Config $config, ?ProcessExecutor $process = null, ?Filesystem $fs = null)
{
$this->io = $io;
$this->config = $config;
$this->process = $process ?? new ProcessExecutor($io);
$this->filesystem = $fs ?? new Filesystem($this->process);
}
/**
* @inheritDoc
*/
public function getInstallationSource(): string
{
return 'source';
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
if (!$package->getSourceReference()) {
throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information');
}
$urls = $this->prepareUrls($package->getSourceUrls());
while ($url = array_shift($urls)) {
try {
return $this->doDownload($package, $path, $url, $prevPackage);
} catch (\Exception $e) {
// rethrow phpunit exceptions to avoid hard to debug bug failures
if ($e instanceof \PHPUnit\Framework\Exception) {
throw $e;
}
if ($this->io->isDebug()) {
$this->io->writeError('Failed: ['.get_class($e).'] '.$e->getMessage());
} elseif (count($urls)) {
$this->io->writeError(' Failed, trying the next URL');
}
if (!count($urls)) {
throw $e;
}
}
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function prepare(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
if ($type === 'update') {
$this->cleanChanges($prevPackage, $path, true);
$this->hasCleanedChanges[$prevPackage->getUniqueName()] = true;
} elseif ($type === 'install') {
$this->filesystem->emptyDirectory($path);
} elseif ($type === 'uninstall') {
$this->cleanChanges($package, $path, false);
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function cleanup(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
if ($type === 'update' && isset($this->hasCleanedChanges[$prevPackage->getUniqueName()])) {
$this->reapplyChanges($path);
unset($this->hasCleanedChanges[$prevPackage->getUniqueName()]);
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function install(PackageInterface $package, string $path): PromiseInterface
{
if (!$package->getSourceReference()) {
throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information');
}
$this->io->writeError(" - " . InstallOperation::format($package).': ', false);
$urls = $this->prepareUrls($package->getSourceUrls());
while ($url = array_shift($urls)) {
try {
$this->doInstall($package, $path, $url);
break;
} catch (\Exception $e) {
// rethrow phpunit exceptions to avoid hard to debug bug failures
if ($e instanceof \PHPUnit\Framework\Exception) {
throw $e;
}
if ($this->io->isDebug()) {
$this->io->writeError('Failed: ['.get_class($e).'] '.$e->getMessage());
} elseif (count($urls)) {
$this->io->writeError(' Failed, trying the next URL');
}
if (!count($urls)) {
throw $e;
}
}
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function update(PackageInterface $initial, PackageInterface $target, string $path): PromiseInterface
{
if (!$target->getSourceReference()) {
throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information');
}
$this->io->writeError(" - " . UpdateOperation::format($initial, $target).': ', false);
$urls = $this->prepareUrls($target->getSourceUrls());
$exception = null;
while ($url = array_shift($urls)) {
try {
$this->doUpdate($initial, $target, $path, $url);
$exception = null;
break;
} catch (\Exception $exception) {
// rethrow phpunit exceptions to avoid hard to debug bug failures
if ($exception instanceof \PHPUnit\Framework\Exception) {
throw $exception;
}
if ($this->io->isDebug()) {
$this->io->writeError('Failed: ['.get_class($exception).'] '.$exception->getMessage());
} elseif (count($urls)) {
$this->io->writeError(' Failed, trying the next URL');
}
}
}
// print the commit logs if in verbose mode and VCS metadata is present
// because in case of missing metadata code would trigger another exception
if (!$exception && $this->io->isVerbose() && $this->hasMetadataRepository($path)) {
$message = 'Pulling in changes:';
$logs = $this->getCommitLogs($initial->getSourceReference(), $target->getSourceReference(), $path);
if ('' === trim($logs)) {
$message = 'Rolling back changes:';
$logs = $this->getCommitLogs($target->getSourceReference(), $initial->getSourceReference(), $path);
}
if ('' !== trim($logs)) {
$logs = implode("\n", array_map(static function ($line): string {
return ' ' . $line;
}, explode("\n", $logs)));
// escape angle brackets for proper output in the console
$logs = str_replace('<', '\<', $logs);
$this->io->writeError(' '.$message);
$this->io->writeError($logs);
}
}
if (!$urls && $exception) {
throw $exception;
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function remove(PackageInterface $package, string $path): PromiseInterface
{
$this->io->writeError(" - " . UninstallOperation::format($package));
$promise = $this->filesystem->removeDirectoryAsync($path);
return $promise->then(static function (bool $result) use ($path) {
if (!$result) {
throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
}
});
}
/**
* @inheritDoc
*/
public function getVcsReference(PackageInterface $package, string $path): ?string
{
$parser = new VersionParser;
$guesser = new VersionGuesser($this->config, $this->process, $parser, $this->io);
$dumper = new ArrayDumper;
$packageConfig = $dumper->dump($package);
if ($packageVersion = $guesser->guessVersion($packageConfig, $path)) {
return $packageVersion['commit'];
}
return null;
}
/**
* Prompt the user to check if changes should be stashed/removed or the operation aborted
*
* @param bool $update if true (update) the changes can be stashed and reapplied after an update,
* if false (remove) the changes should be assumed to be lost if the operation is not aborted
*
* @throws \RuntimeException in case the operation must be aborted
* @phpstan-return PromiseInterface<void|null>
*/
protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface
{
// the default implementation just fails if there are any changes, override in child classes to provide stash-ability
if (null !== $this->getLocalChanges($package, $path)) {
throw new \RuntimeException('Source directory ' . $path . ' has uncommitted changes.');
}
return \React\Promise\resolve(null);
}
/**
* Reapply previously stashes changes if applicable, only called after an update (regardless if successful or not)
*
* @throws \RuntimeException in case the operation must be aborted or the patch does not apply cleanly
*/
protected function reapplyChanges(string $path): void
{
}
/**
* Downloads data needed to run an install/update later
*
* @param PackageInterface $package package instance
* @param string $path download path
* @param string $url package url
* @param PackageInterface|null $prevPackage previous package (in case of an update)
* @phpstan-return PromiseInterface<void|null>
*/
abstract protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface;
/**
* Downloads specific package into specific folder.
*
* @param PackageInterface $package package instance
* @param string $path download path
* @param string $url package url
* @phpstan-return PromiseInterface<void|null>
*/
abstract protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface;
/**
* Updates specific package in specific folder from initial to target version.
*
* @param PackageInterface $initial initial package
* @param PackageInterface $target updated package
* @param string $path download path
* @param string $url package url
* @phpstan-return PromiseInterface<void|null>
*/
abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface;
/**
* Fetches the commit logs between two commits
*
* @param string $fromReference the source reference
* @param string $toReference the target reference
* @param string $path the package path
*/
abstract protected function getCommitLogs(string $fromReference, string $toReference, string $path): string;
/**
* Checks if VCS metadata repository has been initialized
* repository example: .git|.svn|.hg
*/
abstract protected function hasMetadataRepository(string $path): bool;
/**
* @param string[] $urls
*
* @return string[]
*/
private function prepareUrls(array $urls): array
{
foreach ($urls as $index => $url) {
if (Filesystem::isLocalPath($url)) {
// realpath() below will not understand
// url that starts with "file://"
$fileProtocol = 'file://';
$isFileProtocol = false;
if (0 === strpos($url, $fileProtocol)) {
$url = substr($url, strlen($fileProtocol));
$isFileProtocol = true;
}
// realpath() below will not understand %20 spaces etc.
if (false !== strpos($url, '%')) {
$url = rawurldecode($url);
}
$urls[$index] = realpath($url);
if ($isFileProtocol) {
$urls[$index] = $fileProtocol . $urls[$index];
}
}
}
return $urls;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/PharDownloader.php | src/Composer/Downloader/PharDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
/**
* Downloader for phar files
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class PharDownloader extends ArchiveDownloader
{
/**
* @inheritDoc
*/
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
// Can throw an UnexpectedValueException
$archive = new \Phar($file);
$archive->extractTo($path, null, true);
/* TODO: handle openssl signed phars
* https://github.com/composer/composer/pull/33#issuecomment-2250768
* https://github.com/koto/phar-util
* http://blog.kotowicz.net/2010/08/hardening-php-how-to-securely-include.html
*/
return \React\Promise\resolve(null);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/XzDownloader.php | src/Composer/Downloader/XzDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
/**
* Xz archive downloader.
*
* @author Pavel Puchkin <i@neoascetic.me>
* @author Pierre Rudloff <contact@rudloff.pro>
*/
class XzDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
$command = ['tar', '-xJf', $file, '-C', $path];
if (0 === $this->process->execute($command, $ignoredOutput)) {
return \React\Promise\resolve(null);
}
$processError = 'Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput();
throw new \RuntimeException($processError);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/RarDownloader.php | src/Composer/Downloader/RarDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Util\IniHelper;
use Composer\Util\Platform;
use Composer\Package\PackageInterface;
use RarArchive;
/**
* RAR archive downloader.
*
* Based on previous work by Jordi Boggiano ({@see ZipDownloader}).
*
* @author Derrick Nelson <drrcknlsn@gmail.com>
*/
class RarDownloader extends ArchiveDownloader
{
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
$processError = null;
// Try to use unrar on *nix
if (!Platform::isWindows()) {
$command = ['sh', '-c', 'unrar x -- "$0" "$1" >/dev/null && chmod -R u+w "$1"', $file, $path];
if (0 === $this->process->execute($command, $ignoredOutput)) {
return \React\Promise\resolve(null);
}
$processError = 'Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput();
}
if (!class_exists('RarArchive')) {
// php.ini path is added to the error message to help users find the correct file
$iniMessage = IniHelper::getMessage();
$error = "Could not decompress the archive, enable the PHP rar extension or install unrar.\n"
. $iniMessage . "\n" . $processError;
if (!Platform::isWindows()) {
$error = "Could not decompress the archive, enable the PHP rar extension.\n" . $iniMessage;
}
throw new \RuntimeException($error);
}
$rarArchive = RarArchive::open($file);
if (false === $rarArchive) {
throw new \UnexpectedValueException('Could not open RAR archive: ' . $file);
}
$entries = $rarArchive->getEntries();
if (false === $entries) {
throw new \RuntimeException('Could not retrieve RAR archive entries');
}
foreach ($entries as $entry) {
if (false === $entry->extract($path)) {
throw new \RuntimeException('Could not extract entry');
}
}
$rarArchive->close();
return \React\Promise\resolve(null);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/ChangeReportInterface.php | src/Composer/Downloader/ChangeReportInterface.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\Downloader;
use Composer\Package\PackageInterface;
/**
* ChangeReport interface.
*
* @author Sascha Egerer <sascha.egerer@dkd.de>
*/
interface ChangeReportInterface
{
/**
* Checks for changes to the local copy
*
* @param PackageInterface $package package instance
* @param string $path package directory
* @return string|null changes or null
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/DownloadManager.php | src/Composer/Downloader/DownloadManager.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\Downloader;
use Composer\Package\PackageInterface;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Util\Filesystem;
use Composer\Exception\IrrecoverableDownloadException;
use React\Promise\PromiseInterface;
/**
* Downloaders manager.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class DownloadManager
{
/** @var IOInterface */
private $io;
/** @var bool */
private $preferDist = false;
/** @var bool */
private $preferSource;
/** @var array<string, string> */
private $packagePreferences = [];
/** @var Filesystem */
private $filesystem;
/** @var array<string, DownloaderInterface> */
private $downloaders = [];
/**
* Initializes download manager.
*
* @param IOInterface $io The Input Output Interface
* @param bool $preferSource prefer downloading from source
* @param Filesystem|null $filesystem custom Filesystem object
*/
public function __construct(IOInterface $io, bool $preferSource = false, ?Filesystem $filesystem = null)
{
$this->io = $io;
$this->preferSource = $preferSource;
$this->filesystem = $filesystem ?: new Filesystem();
}
/**
* Makes downloader prefer source installation over the dist.
*
* @param bool $preferSource prefer downloading from source
*/
public function setPreferSource(bool $preferSource): self
{
$this->preferSource = $preferSource;
return $this;
}
/**
* Makes downloader prefer dist installation over the source.
*
* @param bool $preferDist prefer downloading from dist
*/
public function setPreferDist(bool $preferDist): self
{
$this->preferDist = $preferDist;
return $this;
}
/**
* Sets fine tuned preference settings for package level source/dist selection.
*
* @param array<string, string> $preferences array of preferences by package patterns
*/
public function setPreferences(array $preferences): self
{
$this->packagePreferences = $preferences;
return $this;
}
/**
* Sets installer downloader for a specific installation type.
*
* @param string $type installation type
* @param DownloaderInterface $downloader downloader instance
*/
public function setDownloader(string $type, DownloaderInterface $downloader): self
{
$type = strtolower($type);
$this->downloaders[$type] = $downloader;
return $this;
}
/**
* Returns downloader for a specific installation type.
*
* @param string $type installation type
* @throws \InvalidArgumentException if downloader for provided type is not registered
*/
public function getDownloader(string $type): DownloaderInterface
{
$type = strtolower($type);
if (!isset($this->downloaders[$type])) {
throw new \InvalidArgumentException(sprintf('Unknown downloader type: %s. Available types: %s.', $type, implode(', ', array_keys($this->downloaders))));
}
return $this->downloaders[$type];
}
/**
* Returns downloader for already installed package.
*
* @param PackageInterface $package package instance
* @throws \InvalidArgumentException if package has no installation source specified
* @throws \LogicException if specific downloader used to load package with
* wrong type
*/
public function getDownloaderForPackage(PackageInterface $package): ?DownloaderInterface
{
$installationSource = $package->getInstallationSource();
if ('metapackage' === $package->getType()) {
return null;
}
if ('dist' === $installationSource) {
$downloader = $this->getDownloader($package->getDistType());
} elseif ('source' === $installationSource) {
$downloader = $this->getDownloader($package->getSourceType());
} else {
throw new \InvalidArgumentException(
'Package '.$package.' does not have an installation source set'
);
}
if ($installationSource !== $downloader->getInstallationSource()) {
throw new \LogicException(sprintf(
'Downloader "%s" is a %s type downloader and can not be used to download %s for package %s',
get_class($downloader),
$downloader->getInstallationSource(),
$installationSource,
$package
));
}
return $downloader;
}
public function getDownloaderType(DownloaderInterface $downloader): string
{
return array_search($downloader, $this->downloaders);
}
/**
* Downloads package into target dir.
*
* @param PackageInterface $package package instance
* @param string $targetDir target dir
* @param PackageInterface|null $prevPackage previous package instance in case of updates
* @phpstan-return PromiseInterface<void|null>
*
* @throws \InvalidArgumentException if package have no urls to download from
* @throws \RuntimeException
*/
public function download(PackageInterface $package, string $targetDir, ?PackageInterface $prevPackage = null): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$this->filesystem->ensureDirectoryExists(dirname($targetDir));
$sources = $this->getAvailableSources($package, $prevPackage);
$io = $this->io;
$download = function ($retry = false) use (&$sources, $io, $package, $targetDir, &$download, $prevPackage) {
$source = array_shift($sources);
if ($retry) {
$io->writeError(' <warning>Now trying to download from ' . $source . '</warning>');
}
$package->setInstallationSource($source);
$downloader = $this->getDownloaderForPackage($package);
if (!$downloader) {
return \React\Promise\resolve(null);
}
$handleError = static function ($e) use ($sources, $source, $package, $io, $download) {
if ($e instanceof \RuntimeException && !$e instanceof IrrecoverableDownloadException) {
if (!$sources) {
throw $e;
}
$io->writeError(
' <warning>Failed to download '.
$package->getPrettyName().
' from ' . $source . ': '.
$e->getMessage().'</warning>'
);
return $download(true);
}
throw $e;
};
try {
$result = $downloader->download($package, $targetDir, $prevPackage);
} catch (\Exception $e) {
return $handleError($e);
}
$res = $result->then(static function ($res) {
return $res;
}, $handleError);
return $res;
};
return $download();
}
/**
* Prepares an operation execution
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param string $targetDir target dir
* @param PackageInterface|null $prevPackage previous package instance in case of updates
* @phpstan-return PromiseInterface<void|null>
*/
public function prepare(string $type, PackageInterface $package, string $targetDir, ?PackageInterface $prevPackage = null): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
if ($downloader) {
return $downloader->prepare($type, $package, $targetDir, $prevPackage);
}
return \React\Promise\resolve(null);
}
/**
* Installs package into target dir.
*
* @param PackageInterface $package package instance
* @param string $targetDir target dir
* @phpstan-return PromiseInterface<void|null>
*
* @throws \InvalidArgumentException if package have no urls to download from
* @throws \RuntimeException
*/
public function install(PackageInterface $package, string $targetDir): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
if ($downloader) {
return $downloader->install($package, $targetDir);
}
return \React\Promise\resolve(null);
}
/**
* Updates package from initial to target version.
*
* @param PackageInterface $initial initial package version
* @param PackageInterface $target target package version
* @param string $targetDir target dir
* @phpstan-return PromiseInterface<void|null>
*
* @throws \InvalidArgumentException if initial package is not installed
*/
public function update(PackageInterface $initial, PackageInterface $target, string $targetDir): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($target);
$initialDownloader = $this->getDownloaderForPackage($initial);
// no downloaders present means update from metapackage to metapackage, nothing to do
if (!$initialDownloader && !$downloader) {
return \React\Promise\resolve(null);
}
// if we have a downloader present before, but not after, the package became a metapackage and its files should be removed
if (!$downloader) {
return $initialDownloader->remove($initial, $targetDir);
}
$initialType = $this->getDownloaderType($initialDownloader);
$targetType = $this->getDownloaderType($downloader);
if ($initialType === $targetType) {
try {
return $downloader->update($initial, $target, $targetDir);
} catch (\RuntimeException $e) {
if (!$this->io->isInteractive()) {
throw $e;
}
$this->io->writeError('<error> Update failed ('.$e->getMessage().')</error>');
if (!$this->io->askConfirmation(' Would you like to try reinstalling the package instead [<comment>yes</comment>]? ')) {
throw $e;
}
}
}
// if downloader type changed, or update failed and user asks for reinstall,
// we wipe the dir and do a new install instead of updating it
$promise = $initialDownloader->remove($initial, $targetDir);
return $promise->then(function ($res) use ($target, $targetDir): PromiseInterface {
return $this->install($target, $targetDir);
});
}
/**
* Removes package from target dir.
*
* @param PackageInterface $package package instance
* @param string $targetDir target dir
* @phpstan-return PromiseInterface<void|null>
*/
public function remove(PackageInterface $package, string $targetDir): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
if ($downloader) {
return $downloader->remove($package, $targetDir);
}
return \React\Promise\resolve(null);
}
/**
* Cleans up a failed operation
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param string $targetDir target dir
* @param PackageInterface|null $prevPackage previous package instance in case of updates
* @phpstan-return PromiseInterface<void|null>
*/
public function cleanup(string $type, PackageInterface $package, string $targetDir, ?PackageInterface $prevPackage = null): PromiseInterface
{
$targetDir = $this->normalizeTargetDir($targetDir);
$downloader = $this->getDownloaderForPackage($package);
if ($downloader) {
return $downloader->cleanup($type, $package, $targetDir, $prevPackage);
}
return \React\Promise\resolve(null);
}
/**
* Determines the install preference of a package
*
* @param PackageInterface $package package instance
*/
protected function resolvePackageInstallPreference(PackageInterface $package): string
{
foreach ($this->packagePreferences as $pattern => $preference) {
$pattern = '{^'.str_replace('\\*', '.*', preg_quote($pattern)).'$}i';
if (Preg::isMatch($pattern, $package->getName())) {
if ('dist' === $preference || (!$package->isDev() && 'auto' === $preference)) {
return 'dist';
}
return 'source';
}
}
return $package->isDev() ? 'source' : 'dist';
}
/**
* @return string[]
* @phpstan-return array<'dist'|'source'>&non-empty-array
*/
private function getAvailableSources(PackageInterface $package, ?PackageInterface $prevPackage = null): array
{
$sourceType = $package->getSourceType();
$distType = $package->getDistType();
// add source before dist by default
$sources = [];
if ($sourceType) {
$sources[] = 'source';
}
if ($distType) {
$sources[] = 'dist';
}
if (empty($sources)) {
throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified');
}
if (
$prevPackage
// if we are updating, we want to keep the same source as the previously installed package (if available in the new one)
&& in_array($prevPackage->getInstallationSource(), $sources, true)
// unless the previous package was stable dist (by default) and the new package is dev, then we allow the new default to take over
&& !(!$prevPackage->isDev() && $prevPackage->getInstallationSource() === 'dist' && $package->isDev())
) {
$prevSource = $prevPackage->getInstallationSource();
usort($sources, static function ($a, $b) use ($prevSource): int {
return $a === $prevSource ? -1 : 1;
});
return $sources;
}
// reverse sources in case dist is the preferred source for this package
if (!$this->preferSource && ($this->preferDist || 'dist' === $this->resolvePackageInstallPreference($package))) {
$sources = array_reverse($sources);
}
return $sources;
}
/**
* Downloaders expect a /path/to/dir without trailing slash
*
* If any Installer provides a path with a trailing slash, this can cause bugs so make sure we remove them
*/
private function normalizeTargetDir(string $dir): string
{
if ($dir === '\\' || $dir === '/') {
return $dir;
}
return rtrim($dir, '\\/');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/PerforceDownloader.php | src/Composer/Downloader/PerforceDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Repository\VcsRepository;
use Composer\Util\Perforce;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceDownloader extends VcsDownloader
{
/** @var Perforce|null */
protected $perforce;
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface
{
$ref = $package->getSourceReference();
$label = $this->getLabelFromSourceReference((string) $ref);
$this->io->writeError('Cloning ' . $ref);
$this->initPerforce($package, $path, $url);
$this->perforce->setStream($ref);
$this->perforce->p4Login();
$this->perforce->writeP4ClientSpec();
$this->perforce->connectClient();
$this->perforce->syncCodeBase($label);
$this->perforce->cleanupClientSpec();
return \React\Promise\resolve(null);
}
private function getLabelFromSourceReference(string $ref): ?string
{
$pos = strpos($ref, '@');
if (false !== $pos) {
return substr($ref, $pos + 1);
}
return null;
}
public function initPerforce(PackageInterface $package, string $path, string $url): void
{
if (!empty($this->perforce)) {
$this->perforce->initializePath($path);
return;
}
$repository = $package->getRepository();
$repoConfig = null;
if ($repository instanceof VcsRepository) {
$repoConfig = $this->getRepoConfig($repository);
}
$this->perforce = Perforce::create($repoConfig, $url, $path, $this->process, $this->io);
}
/**
* @return array<string, mixed>
*/
private function getRepoConfig(VcsRepository $repository): array
{
return $repository->getRepoConfig();
}
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface
{
return $this->doInstall($target, $path, $url);
}
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
$this->io->writeError('Perforce driver does not check for local changes before overriding');
return null;
}
/**
* @inheritDoc
*/
protected function getCommitLogs(string $fromReference, string $toReference, string $path): string
{
return $this->perforce->getCommitLogs($fromReference, $toReference);
}
public function setPerforce(Perforce $perforce): void
{
$this->perforce = $perforce;
}
/**
* @inheritDoc
*/
protected function hasMetadataRepository(string $path): bool
{
return true;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/VcsCapableDownloaderInterface.php | src/Composer/Downloader/VcsCapableDownloaderInterface.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\Downloader;
use Composer\Package\PackageInterface;
/**
* VCS Capable Downloader interface.
*
* @author Steve Buzonas <steve@fancyguy.com>
*/
interface VcsCapableDownloaderInterface
{
/**
* Gets the VCS Reference for the package at path
*
* @param PackageInterface $package package instance
* @param string $path package directory
* @return string|null reference or null
*/
public function getVcsReference(PackageInterface $package, string $path): ?string;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/SvnDownloader.php | src/Composer/Downloader/SvnDownloader.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\Downloader;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Util\Svn as SvnUtil;
use Composer\Repository\VcsRepository;
use React\Promise\PromiseInterface;
/**
* @author Ben Bieker <mail@ben-bieker.de>
* @author Till Klampaeckel <till@php.net>
*/
class SvnDownloader extends VcsDownloader
{
/** @var bool */
protected $cacheCredentials = true;
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface
{
SvnUtil::cleanEnv();
$util = new SvnUtil($url, $this->io, $this->config, $this->process);
if (null === $util->binaryVersion()) {
throw new \RuntimeException('svn was not found in your PATH, skipping source download');
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface
{
SvnUtil::cleanEnv();
$ref = $package->getSourceReference();
$repo = $package->getRepository();
if ($repo instanceof VcsRepository) {
$repoConfig = $repo->getRepoConfig();
if (array_key_exists('svn-cache-credentials', $repoConfig)) {
$this->cacheCredentials = (bool) $repoConfig['svn-cache-credentials'];
}
}
$this->io->writeError(" Checking out ".$package->getSourceReference());
$this->execute($package, $url, ['svn', 'co'], sprintf("%s/%s", $url, $ref), null, $path);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface
{
SvnUtil::cleanEnv();
$ref = $target->getSourceReference();
if (!$this->hasMetadataRepository($path)) {
throw new \RuntimeException('The .svn directory is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
}
$util = new SvnUtil($url, $this->io, $this->config, $this->process);
$flags = [];
if (version_compare($util->binaryVersion(), '1.7.0', '>=')) {
$flags[] = '--ignore-ancestry';
}
$this->io->writeError(" Checking out " . $ref);
$this->execute($target, $url, array_merge(['svn', 'switch'], $flags), sprintf("%s/%s", $url, $ref), $path);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
if (!$this->hasMetadataRepository($path)) {
return null;
}
$this->process->execute(['svn', 'status', '--ignore-externals'], $output, $path);
return Preg::isMatch('{^ *[^X ] +}m', $output) ? $output : null;
}
/**
* Execute an SVN command and try to fix up the process with credentials
* if necessary.
*
* @param string $baseUrl Base URL of the repository
* @param non-empty-list<string> $command SVN command to run
* @param string $url SVN url
* @param string $cwd Working directory
* @param string $path Target for a checkout
* @throws \RuntimeException
*/
protected function execute(PackageInterface $package, string $baseUrl, array $command, string $url, ?string $cwd = null, ?string $path = null): string
{
$util = new SvnUtil($baseUrl, $this->io, $this->config, $this->process);
$util->setCacheCredentials($this->cacheCredentials);
try {
return $util->execute($command, $url, $cwd, $path, $this->io->isVerbose());
} catch (\RuntimeException $e) {
throw new \RuntimeException(
$package->getPrettyName().' could not be downloaded, '.$e->getMessage()
);
}
}
/**
* @inheritDoc
*/
protected function cleanChanges(PackageInterface $package, string $path, bool $update): PromiseInterface
{
if (null === ($changes = $this->getLocalChanges($package, $path))) {
return \React\Promise\resolve(null);
}
if (!$this->io->isInteractive()) {
if (true === $this->config->get('discard-changes')) {
return $this->discardChanges($path);
}
return parent::cleanChanges($package, $path, $update);
}
$changes = array_map(static function ($elem): string {
return ' '.$elem;
}, Preg::split('{\s*\r?\n\s*}', $changes));
$countChanges = count($changes);
$this->io->writeError(sprintf(' <error>'.$package->getPrettyName().' has modified file%s:</error>', $countChanges === 1 ? '' : 's'));
$this->io->writeError(array_slice($changes, 0, 10));
if ($countChanges > 10) {
$remainingChanges = $countChanges - 10;
$this->io->writeError(
sprintf(
' <info>'.$remainingChanges.' more file%s modified, choose "v" to view the full list</info>',
$remainingChanges === 1 ? '' : 's'
)
);
}
while (true) {
switch ($this->io->ask(' <info>Discard changes [y,n,v,?]?</info> ', '?')) {
case 'y':
$this->discardChanges($path);
break 2;
case 'n':
throw new \RuntimeException('Update aborted');
case 'v':
$this->io->writeError($changes);
break;
case '?':
default:
$this->io->writeError([
' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
' v - view modified files',
' ? - print help',
]);
break;
}
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function getCommitLogs(string $fromReference, string $toReference, string $path): string
{
if (Preg::isMatch('{@(\d+)$}', $fromReference) && Preg::isMatch('{@(\d+)$}', $toReference)) {
// retrieve the svn base url from the checkout folder
$command = ['svn', 'info', '--non-interactive', '--xml', '--', $path];
if (0 !== $this->process->execute($command, $output, $path)) {
throw new \RuntimeException(
'Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput()
);
}
$urlPattern = '#<url>(.*)</url>#';
if (Preg::isMatchStrictGroups($urlPattern, $output, $matches)) {
$baseUrl = $matches[1];
} else {
throw new \RuntimeException(
'Unable to determine svn url for path '. $path
);
}
// strip paths from references and only keep the actual revision
$fromRevision = Preg::replace('{.*@(\d+)$}', '$1', $fromReference);
$toRevision = Preg::replace('{.*@(\d+)$}', '$1', $toReference);
$command = ['svn', 'log', '-r', $fromRevision.':'.$toRevision, '--incremental'];
$util = new SvnUtil($baseUrl, $this->io, $this->config, $this->process);
$util->setCacheCredentials($this->cacheCredentials);
try {
return $util->executeLocal($command, $path, null, $this->io->isVerbose());
} catch (\RuntimeException $e) {
throw new \RuntimeException(
'Failed to execute ' . implode(' ', $command) . "\n\n".$e->getMessage()
);
}
}
return "Could not retrieve changes between $fromReference and $toReference due to missing revision information";
}
/**
* @phpstan-return PromiseInterface<void|null>
*/
protected function discardChanges(string $path): PromiseInterface
{
if (0 !== $this->process->execute(['svn', 'revert', '-R', '.'], $output, $path)) {
throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function hasMetadataRepository(string $path): bool
{
return is_dir($path.'/.svn');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/FossilDownloader.php | src/Composer/Downloader/FossilDownloader.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\Downloader;
use Composer\Util\Platform;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use RuntimeException;
/**
* @author BohwaZ <http://bohwaz.net/>
*/
class FossilDownloader extends VcsDownloader
{
/**
* @inheritDoc
*/
protected function doDownload(PackageInterface $package, string $path, string $url, ?PackageInterface $prevPackage = null): PromiseInterface
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doInstall(PackageInterface $package, string $path, string $url): PromiseInterface
{
// Ensure we are allowed to use this URL by config
$this->config->prohibitUrlByConfig($url, $this->io);
$repoFile = $path . '.fossil';
$realPath = Platform::realpath($path);
$this->io->writeError("Cloning ".$package->getSourceReference());
$this->execute(['fossil', 'clone', '--', $url, $repoFile]);
$this->execute(['fossil', 'open', '--nested', '--', $repoFile], $realPath);
$this->execute(['fossil', 'update', '--', (string) $package->getSourceReference()], $realPath);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
protected function doUpdate(PackageInterface $initial, PackageInterface $target, string $path, string $url): PromiseInterface
{
// Ensure we are allowed to use this URL by config
$this->config->prohibitUrlByConfig($url, $this->io);
$this->io->writeError(" Updating to ".$target->getSourceReference());
if (!$this->hasMetadataRepository($path)) {
throw new RuntimeException('The .fslckout file is missing from '.$path.', see https://getcomposer.org/commit-deps for more information');
}
$realPath = Platform::realpath($path);
$this->execute(['fossil', 'pull'], $realPath);
$this->execute(['fossil', 'up', (string) $target->getSourceReference()], $realPath);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function getLocalChanges(PackageInterface $package, string $path): ?string
{
if (!$this->hasMetadataRepository($path)) {
return null;
}
$this->process->execute(['fossil', 'changes'], $output, Platform::realpath($path));
$output = trim($output);
return strlen($output) > 0 ? $output : null;
}
/**
* @inheritDoc
*/
protected function getCommitLogs(string $fromReference, string $toReference, string $path): string
{
$this->execute(['fossil', 'timeline', '-t', 'ci', '-W', '0', '-n', '0', 'before', $toReference], Platform::realpath($path), $output);
$log = '';
$match = '/\d\d:\d\d:\d\d\s+\[' . $toReference . '\]/';
foreach ($this->process->splitLines($output) as $line) {
if (Preg::isMatch($match, $line)) {
break;
}
$log .= $line;
}
return $log;
}
/**
* @param non-empty-list<string> $command
* @throws RuntimeException
*/
private function execute(array $command, ?string $cwd = null, ?string &$output = null): void
{
if (0 !== $this->process->execute($command, $output, $cwd)) {
throw new RuntimeException('Failed to execute ' . implode(' ', $command) . "\n\n" . $this->process->getErrorOutput());
}
}
/**
* @inheritDoc
*/
protected function hasMetadataRepository(string $path): bool
{
return is_file($path . '/.fslckout') || is_file($path . '/_FOSSIL_');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/MaxFileSizeExceededException.php | src/Composer/Downloader/MaxFileSizeExceededException.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\Downloader;
class MaxFileSizeExceededException extends TransportException
{
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/PathDownloader.php | src/Composer/Downloader/PathDownloader.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\Downloader;
use React\Promise\PromiseInterface;
use Composer\Package\Archiver\ArchivableFilesFinder;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionGuesser;
use Composer\Package\Version\VersionParser;
use Composer\Util\Platform;
use Composer\Util\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
use Symfony\Component\Filesystem\Filesystem as SymfonyFilesystem;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
/**
* Download a package from a local path.
*
* @author Samuel Roze <samuel.roze@gmail.com>
* @author Johann Reinke <johann.reinke@gmail.com>
*/
class PathDownloader extends FileDownloader implements VcsCapableDownloaderInterface
{
private const STRATEGY_SYMLINK = 10;
private const STRATEGY_MIRROR = 20;
/**
* @inheritDoc
*/
public function download(PackageInterface $package, string $path, ?PackageInterface $prevPackage = null, bool $output = true): PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
$url = $package->getDistUrl();
if (null === $url) {
throw new \RuntimeException('The package '.$package->getPrettyName().' has no dist url configured, cannot download.');
}
$realUrl = realpath($url);
if (false === $realUrl || !file_exists($realUrl) || !is_dir($realUrl)) {
throw new \RuntimeException(sprintf(
'Source path "%s" is not found for package %s',
$url,
$package->getName()
));
}
if (realpath($path) === $realUrl) {
return \React\Promise\resolve(null);
}
if (strpos(realpath($path) . DIRECTORY_SEPARATOR, $realUrl . DIRECTORY_SEPARATOR) === 0) {
// IMPORTANT NOTICE: If you wish to change this, don't. You are wasting your time and ours.
//
// Please see https://github.com/composer/composer/pull/5974 and https://github.com/composer/composer/pull/6174
// for previous attempts that were shut down because they did not work well enough or introduced too many risks.
throw new \RuntimeException(sprintf(
'Package %s cannot install to "%s" inside its source at "%s"',
$package->getName(),
realpath($path),
$realUrl
));
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
$url = $package->getDistUrl();
if (null === $url) {
throw new \RuntimeException('The package '.$package->getPrettyName().' has no dist url configured, cannot install.');
}
$realUrl = realpath($url);
if (false === $realUrl) {
throw new \RuntimeException('Failed to realpath '.$url);
}
if (realpath($path) === $realUrl) {
if ($output) {
$this->io->writeError(" - " . InstallOperation::format($package) . $this->getInstallOperationAppendix($package, $path));
}
return \React\Promise\resolve(null);
}
// Get the transport options with default values
$transportOptions = $package->getTransportOptions() + ['relative' => true];
[$currentStrategy, $allowedStrategies] = $this->computeAllowedStrategies($transportOptions);
$symfonyFilesystem = new SymfonyFilesystem();
$this->filesystem->removeDirectory($path);
if ($output) {
$this->io->writeError(" - " . InstallOperation::format($package).': ', false);
}
$isFallback = false;
if (self::STRATEGY_SYMLINK === $currentStrategy) {
try {
if (Platform::isWindows()) {
// Implement symlinks as NTFS junctions on Windows
if ($output) {
$this->io->writeError(sprintf('Junctioning from %s', $url), false);
}
$this->filesystem->junction($realUrl, $path);
} else {
$path = rtrim($path, "/");
if ($output) {
$this->io->writeError(sprintf('Symlinking from %s', $url), false);
}
if ($transportOptions['relative'] === true) {
$absolutePath = $path;
if (!$this->filesystem->isAbsolutePath($absolutePath)) {
$absolutePath = Platform::getCwd() . DIRECTORY_SEPARATOR . $path;
}
$shortestPath = $this->filesystem->findShortestPath($absolutePath, $realUrl, false, true);
$symfonyFilesystem->symlink($shortestPath.'/', $path);
} else {
$symfonyFilesystem->symlink($realUrl.'/', $path);
}
}
} catch (IOException $e) {
if (in_array(self::STRATEGY_MIRROR, $allowedStrategies, true)) {
if ($output) {
$this->io->writeError('');
$this->io->writeError(' <error>Symlink failed, fallback to use mirroring!</error>');
}
$currentStrategy = self::STRATEGY_MIRROR;
$isFallback = true;
} else {
throw new \RuntimeException(sprintf('Symlink from "%s" to "%s" failed!', $realUrl, $path));
}
}
}
// Fallback if symlink failed or if symlink is not allowed for the package
if (self::STRATEGY_MIRROR === $currentStrategy) {
$realUrl = $this->filesystem->normalizePath($realUrl);
if ($output) {
$this->io->writeError(sprintf('%sMirroring from %s', $isFallback ? ' ' : '', $url), false);
}
$iterator = new ArchivableFilesFinder($realUrl, []);
$symfonyFilesystem->mirror($realUrl, $path, $iterator);
}
if ($output) {
$this->io->writeError('');
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function remove(PackageInterface $package, string $path, bool $output = true): PromiseInterface
{
$path = Filesystem::trimTrailingSlash($path);
/**
* realpath() may resolve Windows junctions to the source path, so we'll check for a junction first
* to prevent a false positive when checking if the dist and install paths are the same.
* See https://bugs.php.net/bug.php?id=77639
*
* For junctions don't blindly rely on Filesystem::removeDirectory as it may be overzealous. If a process
* inadvertently locks the file the removal will fail, but it would fall back to recursive delete which
* is disastrous within a junction. So in that case we have no other real choice but to fail hard.
*/
if (Platform::isWindows() && $this->filesystem->isJunction($path)) {
if ($output) {
$this->io->writeError(" - " . UninstallOperation::format($package).", source is still present in $path");
}
if (!$this->filesystem->removeJunction($path)) {
$this->io->writeError(" <warning>Could not remove junction at " . $path . " - is another process locking it?</warning>");
throw new \RuntimeException('Could not reliably remove junction for package ' . $package->getName());
}
return \React\Promise\resolve(null);
}
$url = $package->getDistUrl();
if (null === $url) {
throw new \RuntimeException('The package '.$package->getPrettyName().' has no dist url configured, cannot remove.');
}
// ensure that the source path (dist url) is not the same as the install path, which
// can happen when using custom installers, see https://github.com/composer/composer/pull/9116
// not using realpath here as we do not want to resolve the symlink to the original dist url
// it points to
$fs = new Filesystem;
$absPath = $fs->isAbsolutePath($path) ? $path : Platform::getCwd() . '/' . $path;
$absDistUrl = $fs->isAbsolutePath($url) ? $url : Platform::getCwd() . '/' . $url;
if ($fs->normalizePath($absPath) === $fs->normalizePath($absDistUrl)) {
if ($output) {
$this->io->writeError(" - " . UninstallOperation::format($package).", source is still present in $path");
}
return \React\Promise\resolve(null);
}
return parent::remove($package, $path, $output);
}
/**
* @inheritDoc
*/
public function getVcsReference(PackageInterface $package, string $path): ?string
{
$path = Filesystem::trimTrailingSlash($path);
$parser = new VersionParser;
$guesser = new VersionGuesser($this->config, $this->process, $parser, $this->io);
$dumper = new ArrayDumper;
$packageConfig = $dumper->dump($package);
$packageVersion = $guesser->guessVersion($packageConfig, $path);
if ($packageVersion !== null) {
return $packageVersion['commit'];
}
return null;
}
/**
* @inheritDoc
*/
protected function getInstallOperationAppendix(PackageInterface $package, string $path): string
{
$url = $package->getDistUrl();
if (null === $url) {
throw new \RuntimeException('The package '.$package->getPrettyName().' has no dist url configured, cannot install.');
}
$realUrl = realpath($url);
if (false === $realUrl) {
throw new \RuntimeException('Failed to realpath '.$url);
}
if (realpath($path) === $realUrl) {
return ': Source already present';
}
[$currentStrategy] = $this->computeAllowedStrategies($package->getTransportOptions());
if ($currentStrategy === self::STRATEGY_SYMLINK) {
if (Platform::isWindows()) {
return ': Junctioning from '.$package->getDistUrl();
}
return ': Symlinking from '.$package->getDistUrl();
}
return ': Mirroring from '.$package->getDistUrl();
}
/**
* @param mixed[] $transportOptions
*
* @phpstan-return array{self::STRATEGY_*, non-empty-list<self::STRATEGY_*>}
*/
private function computeAllowedStrategies(array $transportOptions): array
{
// When symlink transport option is null, both symlink and mirror are allowed
$currentStrategy = self::STRATEGY_SYMLINK;
$allowedStrategies = [self::STRATEGY_SYMLINK, self::STRATEGY_MIRROR];
$mirrorPathRepos = Platform::getEnv('COMPOSER_MIRROR_PATH_REPOS');
if ((bool) $mirrorPathRepos) {
$currentStrategy = self::STRATEGY_MIRROR;
}
$symlinkOption = $transportOptions['symlink'] ?? null;
if (true === $symlinkOption) {
$currentStrategy = self::STRATEGY_SYMLINK;
$allowedStrategies = [self::STRATEGY_SYMLINK];
} elseif (false === $symlinkOption) {
$currentStrategy = self::STRATEGY_MIRROR;
$allowedStrategies = [self::STRATEGY_MIRROR];
}
// Check we can use junctions safely if we are on Windows
if (Platform::isWindows() && self::STRATEGY_SYMLINK === $currentStrategy && !$this->safeJunctions()) {
if (!in_array(self::STRATEGY_MIRROR, $allowedStrategies, true)) {
throw new \RuntimeException('You are on an old Windows / old PHP combo which does not allow Composer to use junctions/symlinks and this path repository has symlink:true in its options so copying is not allowed');
}
$currentStrategy = self::STRATEGY_MIRROR;
$allowedStrategies = [self::STRATEGY_MIRROR];
}
// Check we can use symlink() otherwise
if (!Platform::isWindows() && self::STRATEGY_SYMLINK === $currentStrategy && !function_exists('symlink')) {
if (!in_array(self::STRATEGY_MIRROR, $allowedStrategies, true)) {
throw new \RuntimeException('Your PHP has the symlink() function disabled which does not allow Composer to use symlinks and this path repository has symlink:true in its options so copying is not allowed');
}
$currentStrategy = self::STRATEGY_MIRROR;
$allowedStrategies = [self::STRATEGY_MIRROR];
}
return [$currentStrategy, $allowedStrategies];
}
/**
* Returns true if junctions can be created and safely used on Windows
*
* A PHP bug makes junction detection fragile, leading to possible data loss
* when removing a package. See https://bugs.php.net/bug.php?id=77552
*
* For safety we require a minimum version of Windows 7, so we can call the
* system rmdir which will preserve target content if given a junction.
*
* The PHP bug was fixed in 7.2.16 and 7.3.3 (requires at least Windows 7).
*/
private function safeJunctions(): bool
{
// We need to call mklink, and rmdir on Windows 7 (version 6.1)
return function_exists('proc_open') &&
(PHP_WINDOWS_VERSION_MAJOR > 6 ||
(PHP_WINDOWS_VERSION_MAJOR === 6 && PHP_WINDOWS_VERSION_MINOR >= 1));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/TarDownloader.php | src/Composer/Downloader/TarDownloader.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\Downloader;
use Composer\Package\PackageInterface;
use React\Promise\PromiseInterface;
/**
* Downloader for tar files: tar, tar.gz or tar.bz2
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
*/
class TarDownloader extends ArchiveDownloader
{
/**
* @inheritDoc
*/
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
// Can throw an UnexpectedValueException
$archive = new \PharData($file);
$archive->extractTo($path, null, true);
return \React\Promise\resolve(null);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/ArchiveDownloader.php | src/Composer/Downloader/ArchiveDownloader.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\Downloader;
use Composer\Package\PackageInterface;
use Composer\Util\Platform;
use Symfony\Component\Finder\Finder;
use React\Promise\PromiseInterface;
use Composer\DependencyResolver\Operation\InstallOperation;
/**
* Base downloader for archives
*
* @author Kirill chEbba Chebunin <iam@chebba.org>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author François Pluchino <francois.pluchino@opendisplay.com>
*/
abstract class ArchiveDownloader extends FileDownloader
{
/**
* @var array<string, true>
*/
protected $cleanupExecuted = [];
public function prepare(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
unset($this->cleanupExecuted[$package->getName()]);
return parent::prepare($type, $package, $path, $prevPackage);
}
public function cleanup(string $type, PackageInterface $package, string $path, ?PackageInterface $prevPackage = null): PromiseInterface
{
$this->cleanupExecuted[$package->getName()] = true;
return parent::cleanup($type, $package, $path, $prevPackage);
}
/**
* @inheritDoc
*
* @throws \RuntimeException
* @throws \UnexpectedValueException
*/
public function install(PackageInterface $package, string $path, bool $output = true): PromiseInterface
{
if ($output) {
$this->io->writeError(" - " . InstallOperation::format($package) . $this->getInstallOperationAppendix($package, $path));
}
$vendorDir = $this->config->get('vendor-dir');
// clean up the target directory, unless it contains the vendor dir, as the vendor dir contains
// the archive to be extracted. This is the case when installing with create-project in the current directory
// but in that case we ensure the directory is empty already in ProjectInstaller so no need to empty it here.
if (false === strpos($this->filesystem->normalizePath($vendorDir), $this->filesystem->normalizePath($path.DIRECTORY_SEPARATOR))) {
$this->filesystem->emptyDirectory($path);
}
do {
$temporaryDir = $vendorDir.'/composer/'.bin2hex(random_bytes(4));
} while (is_dir($temporaryDir));
$this->addCleanupPath($package, $temporaryDir);
// avoid cleaning up $path if installing in "." for eg create-project as we can not
// delete the directory we are currently in on windows
if (!is_dir($path) || realpath($path) !== Platform::getCwd()) {
$this->addCleanupPath($package, $path);
}
$this->filesystem->ensureDirectoryExists($temporaryDir);
$fileName = $this->getFileName($package, $path);
$filesystem = $this->filesystem;
$cleanup = function () use ($path, $filesystem, $temporaryDir, $package) {
// remove cache if the file was corrupted
$this->clearLastCacheWrite($package);
// clean up
$filesystem->removeDirectory($temporaryDir);
if (is_dir($path) && realpath($path) !== Platform::getCwd()) {
$filesystem->removeDirectory($path);
}
$this->removeCleanupPath($package, $temporaryDir);
$realpath = realpath($path);
if ($realpath !== false) {
$this->removeCleanupPath($package, $realpath);
}
};
try {
$promise = $this->extract($package, $fileName, $temporaryDir);
} catch (\Exception $e) {
$cleanup();
throw $e;
}
return $promise->then(function () use ($package, $filesystem, $fileName, $temporaryDir, $path): PromiseInterface {
if (file_exists($fileName)) {
$filesystem->unlink($fileName);
}
/**
* Returns the folder content, excluding .DS_Store
*
* @param string $dir Directory
* @return \SplFileInfo[]
*/
$getFolderContent = static function ($dir): array {
$finder = Finder::create()
->ignoreVCS(false)
->ignoreDotFiles(false)
->notName('.DS_Store')
->depth(0)
->in($dir);
return iterator_to_array($finder);
};
$renameRecursively = null;
/**
* Renames (and recursively merges if needed) a folder into another one
*
* For custom installers, where packages may share paths, and given Composer 2's parallelism, we need to make sure
* that the source directory gets merged into the target one if the target exists. Otherwise rename() by default would
* put the source into the target e.g. src/ => target/src/ (assuming target exists) instead of src/ => target/
*
* @param string $from Directory
* @param string $to Directory
* @return void
*/
$renameRecursively = static function ($from, $to) use ($filesystem, $getFolderContent, $package, &$renameRecursively) {
$contentDir = $getFolderContent($from);
// move files back out of the temp dir
foreach ($contentDir as $file) {
$file = (string) $file;
if (is_dir($to . '/' . basename($file))) {
if (!is_dir($file)) {
throw new \RuntimeException('Installing '.$package.' would lead to overwriting the '.$to.'/'.basename($file).' directory with a file from the package, invalid operation.');
}
$renameRecursively($file, $to . '/' . basename($file));
} else {
$filesystem->rename($file, $to . '/' . basename($file));
}
}
};
$renameAsOne = false;
if (!file_exists($path)) {
$renameAsOne = true;
} elseif ($filesystem->isDirEmpty($path)) {
try {
if ($filesystem->removeDirectoryPhp($path)) {
$renameAsOne = true;
}
} catch (\RuntimeException $e) {
// ignore error, and simply do not renameAsOne
}
}
$contentDir = $getFolderContent($temporaryDir);
$singleDirAtTopLevel = 1 === count($contentDir) && is_dir((string) reset($contentDir));
if ($renameAsOne) {
// if the target $path is clear, we can rename the whole package in one go instead of looping over the contents
if ($singleDirAtTopLevel) {
$extractedDir = (string) reset($contentDir);
} else {
$extractedDir = $temporaryDir;
}
$filesystem->rename($extractedDir, $path);
} else {
// only one dir in the archive, extract its contents out of it
$from = $temporaryDir;
if ($singleDirAtTopLevel) {
$from = (string) reset($contentDir);
}
$renameRecursively($from, $path);
}
$promise = $filesystem->removeDirectoryAsync($temporaryDir);
return $promise->then(function () use ($package, $path, $temporaryDir) {
$this->removeCleanupPath($package, $temporaryDir);
$this->removeCleanupPath($package, $path);
});
}, static function ($e) use ($cleanup) {
$cleanup();
throw $e;
});
}
/**
* @inheritDoc
*/
protected function getInstallOperationAppendix(PackageInterface $package, string $path): string
{
return ': Extracting archive';
}
/**
* Extract file to directory
*
* @param string $file Extracted file
* @param string $path Directory
* @phpstan-return PromiseInterface<void|null>
*
* @throws \UnexpectedValueException If can not extract downloaded file to path
*/
abstract protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/TransportException.php | src/Composer/Downloader/TransportException.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\Downloader;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class TransportException extends \RuntimeException
{
/** @var ?array<string> */
protected $headers;
/** @var ?string */
protected $response;
/** @var ?int */
protected $statusCode;
/** @var array<mixed> */
protected $responseInfo = [];
public function __construct(string $message = "", int $code = 400, ?\Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
/**
* @param array<string> $headers
*/
public function setHeaders(array $headers): void
{
$this->headers = $headers;
}
/**
* @return ?array<string>
*/
public function getHeaders(): ?array
{
return $this->headers;
}
public function setResponse(?string $response): void
{
$this->response = $response;
}
public function getResponse(): ?string
{
return $this->response;
}
/**
* @param ?int $statusCode
*/
public function setStatusCode($statusCode): void
{
$this->statusCode = $statusCode;
}
public function getStatusCode(): ?int
{
return $this->statusCode;
}
/**
* @return array<mixed>
*/
public function getResponseInfo(): array
{
return $this->responseInfo;
}
/**
* @param array<mixed> $responseInfo
*/
public function setResponseInfo(array $responseInfo): void
{
$this->responseInfo = $responseInfo;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/DvcsDownloaderInterface.php | src/Composer/Downloader/DvcsDownloaderInterface.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\Downloader;
use Composer\Package\PackageInterface;
/**
* DVCS Downloader interface.
*
* @author James Titcumb <james@asgrim.com>
*/
interface DvcsDownloaderInterface
{
/**
* Checks for unpushed changes to a current branch
*
* @param PackageInterface $package package instance
* @param string $path package directory
* @return string|null changes or null
*/
public function getUnpushedChanges(PackageInterface $package, string $path): ?string;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/ZipDownloader.php | src/Composer/Downloader/ZipDownloader.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\Downloader;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Util\IniHelper;
use Composer\Util\Platform;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use React\Promise\PromiseInterface;
use ZipArchive;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ZipDownloader extends ArchiveDownloader
{
/** @var array<int, non-empty-list<string>> */
private static $unzipCommands;
/** @var bool */
private static $hasZipArchive;
/** @var bool */
private static $isWindows;
/** @var ZipArchive|null */
private $zipArchiveObject; // @phpstan-ignore property.onlyRead (helper property that is set via reflection for testing purposes)
/**
* @inheritDoc
*/
public function download(PackageInterface $package, string $path, ?PackageInterface $prevPackage = null, bool $output = true): PromiseInterface
{
if (null === self::$unzipCommands) {
self::$unzipCommands = [];
$finder = new ExecutableFinder;
if (Platform::isWindows() && ($cmd = $finder->find('7z', null, ['C:\Program Files\7-Zip']))) {
self::$unzipCommands[] = ['7z', $cmd, 'x', '-bb0', '-y', '%file%', '-o%path%'];
}
if ($cmd = $finder->find('unzip')) {
self::$unzipCommands[] = ['unzip', $cmd, '-qq', '%file%', '-d', '%path%'];
}
if (!Platform::isWindows() && ($cmd = $finder->find('7z'))) { // 7z linux/macOS support is only used if unzip is not present
self::$unzipCommands[] = ['7z', $cmd, 'x', '-bb0', '-y', '%file%', '-o%path%'];
}
if (!Platform::isWindows() && ($cmd = $finder->find('7zz'))) { // 7zz linux/macOS support is only used if unzip is not present
self::$unzipCommands[] = ['7zz', $cmd, 'x', '-bb0', '-y', '%file%', '-o%path%'];
}
}
$procOpenMissing = false;
if (!function_exists('proc_open')) {
self::$unzipCommands = [];
$procOpenMissing = true;
}
if (null === self::$hasZipArchive) {
self::$hasZipArchive = class_exists('ZipArchive');
}
if (!self::$hasZipArchive && !self::$unzipCommands) {
// php.ini path is added to the error message to help users find the correct file
$iniMessage = IniHelper::getMessage();
if ($procOpenMissing) {
$error = "The zip extension is missing and unzip/7z commands cannot be called as proc_open is disabled, skipping.\n" . $iniMessage;
} else {
$error = "The zip extension and unzip/7z commands are both missing, skipping.\n" . $iniMessage;
}
throw new \RuntimeException($error);
}
if (null === self::$isWindows) {
self::$isWindows = Platform::isWindows();
if (!self::$isWindows && !self::$unzipCommands) {
if ($procOpenMissing) {
$this->io->writeError("<warning>proc_open is disabled so 'unzip' and '7z' commands cannot be used, zip files are being unpacked using the PHP zip extension.</warning>");
$this->io->writeError("<warning>This may cause invalid reports of corrupted archives. Besides, any UNIX permissions (e.g. executable) defined in the archives will be lost.</warning>");
$this->io->writeError("<warning>Enabling proc_open and installing 'unzip' or '7z' (21.01+) may remediate them.</warning>");
} else {
$this->io->writeError("<warning>As there is no 'unzip' nor '7z' command installed zip files are being unpacked using the PHP zip extension.</warning>");
$this->io->writeError("<warning>This may cause invalid reports of corrupted archives. Besides, any UNIX permissions (e.g. executable) defined in the archives will be lost.</warning>");
$this->io->writeError("<warning>Installing 'unzip' or '7z' (21.01+) may remediate them.</warning>");
}
}
}
return parent::download($package, $path, $prevPackage, $output);
}
/**
* extract $file to $path with "unzip" command
*
* @param string $file File to extract
* @param string $path Path where to extract file
* @phpstan-return PromiseInterface<void|null>
*/
private function extractWithSystemUnzip(PackageInterface $package, string $file, string $path): PromiseInterface
{
static $warned7ZipLinux = false;
// Force Exception throwing if the other alternative extraction method is not available
$isLastChance = !self::$hasZipArchive;
if (0 === \count(self::$unzipCommands)) {
// This was call as the favorite extract way, but is not available
// We switch to the alternative
return $this->extractWithZipArchive($package, $file, $path);
}
$commandSpec = reset(self::$unzipCommands);
$executable = $commandSpec[0];
$command = array_slice($commandSpec, 1);
$map = [
// normalize separators to backslashes to avoid problems with 7-zip on windows
// see https://github.com/composer/composer/issues/10058
'%file%' => strtr($file, '/', DIRECTORY_SEPARATOR),
'%path%' => strtr($path, '/', DIRECTORY_SEPARATOR),
];
$command = array_map(static function ($value) use ($map) {
return strtr($value, $map);
}, $command);
if (!$warned7ZipLinux && !Platform::isWindows() && in_array($executable, ['7z', '7zz'], true)) {
$warned7ZipLinux = true;
if (0 === $this->process->execute([$commandSpec[1]], $output)) {
if (Preg::isMatchStrictGroups('{^\s*7-Zip(?: \[64\])? ([0-9.]+)}', $output, $match) && version_compare($match[1], '21.01', '<')) {
$this->io->writeError(' <warning>Unzipping using '.$executable.' '.$match[1].' may result in incorrect file permissions. Install '.$executable.' 21.01+ or unzip to ensure you get correct permissions.</warning>');
}
}
}
$io = $this->io;
$tryFallback = function (\Throwable $processError) use ($isLastChance, $io, $file, $path, $package, $executable): PromiseInterface {
if ($isLastChance) {
throw $processError;
}
if (str_contains($processError->getMessage(), 'zip bomb')) {
throw $processError;
}
if (!is_file($file)) {
$io->writeError(' <warning>'.$processError->getMessage().'</warning>');
$io->writeError(' <warning>This most likely is due to a custom installer plugin not handling the returned Promise from the downloader</warning>');
$io->writeError(' <warning>See https://github.com/composer/installers/commit/5006d0c28730ade233a8f42ec31ac68fb1c5c9bb for an example fix</warning>');
} else {
$io->writeError(' <warning>'.$processError->getMessage().'</warning>');
$io->writeError(' The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems)');
$io->writeError(' Unzip with '.$executable.' command failed, falling back to ZipArchive class');
// additional debug data to try to figure out GH actions issues https://github.com/composer/composer/issues/11148
if (Platform::getEnv('GITHUB_ACTIONS') !== false && Platform::getEnv('COMPOSER_TESTS_ARE_RUNNING') === false) {
$io->writeError(' <warning>Additional debug info, please report to https://github.com/composer/composer/issues/11148 if you see this:</warning>');
$io->writeError('File size: '.@filesize($file));
$io->writeError('File SHA1: '.hash_file('sha1', $file));
$io->writeError('First 100 bytes (hex): '.bin2hex(substr((string) file_get_contents($file), 0, 100)));
$io->writeError('Last 100 bytes (hex): '.bin2hex(substr((string) file_get_contents($file), -100)));
if (strlen((string) $package->getDistUrl()) > 0) {
$io->writeError('Origin URL: '.$this->processUrl($package, (string) $package->getDistUrl()));
$io->writeError('Response Headers: '.json_encode(FileDownloader::$responseHeaders[$package->getName()] ?? []));
}
}
}
return $this->extractWithZipArchive($package, $file, $path);
};
try {
$promise = $this->process->executeAsync($command);
return $promise->then(function (Process $process) use ($tryFallback, $command, $package, $file) {
if (!$process->isSuccessful()) {
if (isset($this->cleanupExecuted[$package->getName()])) {
throw new \RuntimeException('Failed to extract '.$package->getName().' as the installation was aborted by another package operation.');
}
$output = $process->getErrorOutput();
$output = str_replace(', '.$file.'.zip or '.$file.'.ZIP', '', $output);
return $tryFallback(new \RuntimeException('Failed to extract '.$package->getName().': ('.$process->getExitCode().') '.implode(' ', $command)."\n\n".$output));
}
});
} catch (\Throwable $e) {
return $tryFallback($e);
}
}
/**
* extract $file to $path with ZipArchive
*
* @param string $file File to extract
* @param string $path Path where to extract file
* @phpstan-return PromiseInterface<void|null>
*/
private function extractWithZipArchive(PackageInterface $package, string $file, string $path): PromiseInterface
{
$processError = null;
$zipArchive = $this->zipArchiveObject ?: new ZipArchive();
try {
if (!file_exists($file) || ($filesize = filesize($file)) === false || $filesize === 0) {
$retval = -1;
} else {
$retval = $zipArchive->open($file);
}
if (true === $retval) {
$totalSize = 0;
$archiveSize = filesize($file);
$totalFiles = $zipArchive->count();
if ($totalFiles > 0) {
$inspectAll = false;
$filesToInspect = min($totalFiles, 5);
for ($i = 0; $i < $filesToInspect; $i++) {
$stat = $zipArchive->statIndex($inspectAll ? $i : random_int(0, $totalFiles - 1));
if ($stat === false) {
continue;
}
$totalSize += $stat['size'];
if (!$inspectAll && $stat['size'] > $stat['comp_size'] * 200) {
$totalSize = 0;
$inspectAll = true;
$i = -1;
$filesToInspect = $totalFiles;
}
}
if ($archiveSize !== false && $totalSize > $archiveSize * 100 && $totalSize > 50 * 1024 * 1024) {
throw new \RuntimeException('Invalid zip file for "'.$package->getName().'" with compression ratio >99% (possible zip bomb)');
}
}
$extractResult = $zipArchive->extractTo($path);
if (true === $extractResult) {
$zipArchive->close();
return \React\Promise\resolve(null);
}
$processError = new \RuntimeException(rtrim("There was an error extracting the ZIP file for \"{$package->getName()}\", it is either corrupted or using an invalid format.\n"));
} else {
$processError = new \UnexpectedValueException(rtrim($this->getErrorMessage($retval, $file)."\n"), $retval);
}
} catch (\ErrorException $e) {
$processError = new \RuntimeException('The archive for "'.$package->getName().'" may contain identical file names with different capitalization (which fails on case insensitive filesystems): '.$e->getMessage(), 0, $e);
} catch (\Throwable $e) {
$processError = $e;
}
throw $processError;
}
/**
* extract $file to $path
*
* @param string $file File to extract
* @param string $path Path where to extract file
*/
protected function extract(PackageInterface $package, string $file, string $path): PromiseInterface
{
return $this->extractWithSystemUnzip($package, $file, $path);
}
/**
* Give a meaningful error message to the user.
*/
protected function getErrorMessage(int $retval, string $file): string
{
switch ($retval) {
case ZipArchive::ER_EXISTS:
return sprintf("File '%s' already exists.", $file);
case ZipArchive::ER_INCONS:
return sprintf("Zip archive '%s' is inconsistent.", $file);
case ZipArchive::ER_INVAL:
return sprintf("Invalid argument (%s)", $file);
case ZipArchive::ER_MEMORY:
return sprintf("Malloc failure (%s)", $file);
case ZipArchive::ER_NOENT:
return sprintf("No such zip file: '%s'", $file);
case ZipArchive::ER_NOZIP:
return sprintf("'%s' is not a zip archive.", $file);
case ZipArchive::ER_OPEN:
return sprintf("Can't open zip file: %s", $file);
case ZipArchive::ER_READ:
return sprintf("Zip read error (%s)", $file);
case ZipArchive::ER_SEEK:
return sprintf("Zip seek error (%s)", $file);
case -1:
return sprintf("'%s' is a corrupted zip archive (0 bytes), try again.", $file);
default:
return sprintf("'%s' is not a valid zip archive, got error code: %s", $file, $retval);
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Downloader/FilesystemException.php | src/Composer/Downloader/FilesystemException.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\Downloader;
/**
* Exception thrown when issues exist on local filesystem
*
* @author Javier Spagnoletti <jspagnoletti@javierspagnoletti.com.ar>
*/
class FilesystemException extends \Exception
{
public function __construct(string $message = '', int $code = 0, ?\Exception $previous = null)
{
parent::__construct("Filesystem exception: \n".$message, $code, $previous);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/LibraryInstaller.php | src/Composer/Installer/LibraryInstaller.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\Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\PartialComposer;
use Composer\Pcre\Preg;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\Util\Filesystem;
use Composer\Util\Silencer;
use Composer\Util\Platform;
use React\Promise\PromiseInterface;
use Composer\Downloader\DownloadManager;
/**
* Package installation manager.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class LibraryInstaller implements InstallerInterface, BinaryPresenceInterface
{
/** @var PartialComposer */
protected $composer;
/** @var string */
protected $vendorDir;
/** @var DownloadManager|null */
protected $downloadManager;
/** @var IOInterface */
protected $io;
/** @var string */
protected $type;
/** @var Filesystem */
protected $filesystem;
/** @var BinaryInstaller */
protected $binaryInstaller;
/**
* Initializes library installer.
*/
public function __construct(IOInterface $io, PartialComposer $composer, ?string $type = 'library', ?Filesystem $filesystem = null, ?BinaryInstaller $binaryInstaller = null)
{
$this->composer = $composer;
$this->downloadManager = $composer instanceof Composer ? $composer->getDownloadManager() : null;
$this->io = $io;
$this->type = $type;
$this->filesystem = $filesystem ?: new Filesystem();
$this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/');
$this->binaryInstaller = $binaryInstaller ?: new BinaryInstaller($this->io, rtrim($composer->getConfig()->get('bin-dir'), '/'), $composer->getConfig()->get('bin-compat'), $this->filesystem, $this->vendorDir);
}
/**
* @inheritDoc
*/
public function supports(string $packageType)
{
return $packageType === $this->type || null === $this->type;
}
/**
* @inheritDoc
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if (!$repo->hasPackage($package)) {
return false;
}
$installPath = $this->getInstallPath($package);
if (Filesystem::isReadable($installPath)) {
return true;
}
if (Platform::isWindows() && $this->filesystem->isJunction($installPath)) {
return true;
}
if (is_link($installPath)) {
if (realpath($installPath) === false) {
return false;
}
return true;
}
return false;
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->getDownloadManager()->download($package, $downloadPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->getDownloadManager()->prepare($type, $package, $downloadPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function cleanup($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
return $this->getDownloadManager()->cleanup($type, $package, $downloadPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->initializeVendorDir();
$downloadPath = $this->getInstallPath($package);
// remove the binaries if it appears the package files are missing
if (!Filesystem::isReadable($downloadPath) && $repo->hasPackage($package)) {
$this->binaryInstaller->removeBinaries($package);
}
$promise = $this->installCode($package);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
$binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($package);
return $promise->then(static function () use ($binaryInstaller, $installPath, $package, $repo): void {
$binaryInstaller->installBinaries($package, $installPath);
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
}
});
}
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
if (!$repo->hasPackage($initial)) {
throw new \InvalidArgumentException('Package is not installed: '.$initial);
}
$this->initializeVendorDir();
$this->binaryInstaller->removeBinaries($initial);
$promise = $this->updateCode($initial, $target);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
$binaryInstaller = $this->binaryInstaller;
$installPath = $this->getInstallPath($target);
return $promise->then(static function () use ($binaryInstaller, $installPath, $target, $initial, $repo): void {
$binaryInstaller->installBinaries($target, $installPath);
$repo->removePackage($initial);
if (!$repo->hasPackage($target)) {
$repo->addPackage(clone $target);
}
});
}
/**
* @inheritDoc
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if (!$repo->hasPackage($package)) {
throw new \InvalidArgumentException('Package is not installed: '.$package);
}
$promise = $this->removeCode($package);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
$binaryInstaller = $this->binaryInstaller;
$downloadPath = $this->getPackageBasePath($package);
$filesystem = $this->filesystem;
return $promise->then(static function () use ($binaryInstaller, $filesystem, $downloadPath, $package, $repo): void {
$binaryInstaller->removeBinaries($package);
$repo->removePackage($package);
if (strpos($package->getName(), '/')) {
$packageVendorDir = dirname($downloadPath);
if (is_dir($packageVendorDir) && $filesystem->isDirEmpty($packageVendorDir)) {
Silencer::call('rmdir', $packageVendorDir);
}
}
});
}
/**
* @inheritDoc
*
* @return string
*/
public function getInstallPath(PackageInterface $package)
{
$this->initializeVendorDir();
$basePath = ($this->vendorDir ? $this->vendorDir.'/' : '') . $package->getPrettyName();
$targetDir = $package->getTargetDir();
return $basePath . ($targetDir ? '/'.$targetDir : '');
}
/**
* Make sure binaries are installed for a given package.
*
* @param PackageInterface $package Package instance
*/
public function ensureBinariesPresence(PackageInterface $package)
{
$this->binaryInstaller->installBinaries($package, $this->getInstallPath($package), false);
}
/**
* Returns the base path of the package without target-dir path
*
* It is used for BC as getInstallPath tends to be overridden by
* installer plugins but not getPackageBasePath
*
* @return string
*/
protected function getPackageBasePath(PackageInterface $package)
{
$installPath = $this->getInstallPath($package);
$targetDir = $package->getTargetDir();
if ($targetDir) {
return Preg::replace('{/*'.str_replace('/', '/+', preg_quote($targetDir)).'/?$}', '', $installPath);
}
return $installPath;
}
/**
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
protected function installCode(PackageInterface $package)
{
$downloadPath = $this->getInstallPath($package);
return $this->getDownloadManager()->install($package, $downloadPath);
}
/**
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
protected function updateCode(PackageInterface $initial, PackageInterface $target)
{
$initialDownloadPath = $this->getInstallPath($initial);
$targetDownloadPath = $this->getInstallPath($target);
if ($targetDownloadPath !== $initialDownloadPath) {
// if the target and initial dirs intersect, we force a remove + install
// to avoid the rename wiping the target dir as part of the initial dir cleanup
if (strpos($initialDownloadPath, $targetDownloadPath) === 0
|| strpos($targetDownloadPath, $initialDownloadPath) === 0
) {
$promise = $this->removeCode($initial);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
return $promise->then(function () use ($target): PromiseInterface {
$promise = $this->installCode($target);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve(null);
});
}
$this->filesystem->rename($initialDownloadPath, $targetDownloadPath);
}
return $this->getDownloadManager()->update($initial, $target, $targetDownloadPath);
}
/**
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
protected function removeCode(PackageInterface $package)
{
$downloadPath = $this->getPackageBasePath($package);
return $this->getDownloadManager()->remove($package, $downloadPath);
}
/**
* @return void
*/
protected function initializeVendorDir()
{
$this->filesystem->ensureDirectoryExists($this->vendorDir);
$this->vendorDir = realpath($this->vendorDir);
}
protected function getDownloadManager(): DownloadManager
{
assert($this->downloadManager instanceof DownloadManager, new \LogicException(self::class.' should be initialized with a fully loaded Composer instance to be able to install/... packages'));
return $this->downloadManager;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/BinaryInstaller.php | src/Composer/Installer/BinaryInstaller.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\Installer;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Util\Silencer;
/**
* Utility to handle installation of package "bin"/binaries
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Helmut Hummel <info@helhum.io>
*/
class BinaryInstaller
{
/** @var string */
protected $binDir;
/** @var string */
protected $binCompat;
/** @var IOInterface */
protected $io;
/** @var Filesystem */
protected $filesystem;
/** @var string|null */
private $vendorDir;
public function __construct(IOInterface $io, string $binDir, string $binCompat, ?Filesystem $filesystem = null, ?string $vendorDir = null)
{
$this->binDir = $binDir;
$this->binCompat = $binCompat;
$this->io = $io;
$this->filesystem = $filesystem ?: new Filesystem();
$this->vendorDir = $vendorDir;
}
public function installBinaries(PackageInterface $package, string $installPath, bool $warnOnOverwrite = true): void
{
$binaries = $this->getBinaries($package);
if (!$binaries) {
return;
}
Platform::workaroundFilesystemIssues();
foreach ($binaries as $bin) {
$binPath = $installPath.'/'.$bin;
if (!file_exists($binPath)) {
$this->io->writeError(' <warning>Skipped installation of bin '.$bin.' for package '.$package->getName().': file not found in package</warning>');
continue;
}
if (is_dir($binPath)) {
$this->io->writeError(' <warning>Skipped installation of bin '.$bin.' for package '.$package->getName().': found a directory at that path</warning>');
continue;
}
if (!$this->filesystem->isAbsolutePath($binPath)) {
// in case a custom installer returned a relative path for the
// $package, we can now safely turn it into a absolute path (as we
// already checked the binary's existence). The following helpers
// will require absolute paths to work properly.
$binPath = realpath($binPath);
}
$this->initializeBinDir();
$link = $this->binDir.'/'.basename($bin);
if (file_exists($link)) {
if (!is_link($link)) {
if ($warnOnOverwrite) {
$this->io->writeError(' Skipped installation of bin '.$bin.' for package '.$package->getName().': name conflicts with an existing file');
}
continue;
}
if (realpath($link) === realpath($binPath)) {
// It is a linked binary from a previous installation, which can be replaced with a proxy file
$this->filesystem->unlink($link);
}
}
$binCompat = $this->binCompat;
if ($binCompat === "auto" && (Platform::isWindows() || Platform::isWindowsSubsystemForLinux())) {
$binCompat = 'full';
}
if ($binCompat === "full") {
$this->installFullBinaries($binPath, $link, $bin, $package);
} else {
$this->installUnixyProxyBinaries($binPath, $link);
}
Silencer::call('chmod', $binPath, 0777 & ~umask());
}
}
public function removeBinaries(PackageInterface $package): void
{
$this->initializeBinDir();
$binaries = $this->getBinaries($package);
if (!$binaries) {
return;
}
foreach ($binaries as $bin) {
$link = $this->binDir.'/'.basename($bin);
if (is_link($link) || file_exists($link)) { // still checking for symlinks here for legacy support
$this->filesystem->unlink($link);
}
if (is_file($link.'.bat')) {
$this->filesystem->unlink($link.'.bat');
}
}
// attempt removing the bin dir in case it is left empty
if (is_dir($this->binDir) && $this->filesystem->isDirEmpty($this->binDir)) {
Silencer::call('rmdir', $this->binDir);
}
}
public static function determineBinaryCaller(string $bin): string
{
if ('.bat' === substr($bin, -4) || '.exe' === substr($bin, -4)) {
return 'call';
}
$handle = fopen($bin, 'r');
$line = fgets($handle);
fclose($handle);
if (Preg::isMatchStrictGroups('{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m', (string) $line, $match)) {
return trim($match[1]);
}
return 'php';
}
/**
* @return string[]
*/
protected function getBinaries(PackageInterface $package): array
{
return $package->getBinaries();
}
protected function installFullBinaries(string $binPath, string $link, string $bin, PackageInterface $package): void
{
// add unixy support for cygwin and similar environments
if ('.bat' !== substr($binPath, -4)) {
$this->installUnixyProxyBinaries($binPath, $link);
$link .= '.bat';
if (file_exists($link)) {
$this->io->writeError(' Skipped installation of bin '.$bin.'.bat proxy for package '.$package->getName().': a .bat proxy was already installed');
}
}
if (!file_exists($link)) {
file_put_contents($link, $this->generateWindowsProxyCode($binPath, $link));
Silencer::call('chmod', $link, 0777 & ~umask());
}
}
protected function installUnixyProxyBinaries(string $binPath, string $link): void
{
file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link));
Silencer::call('chmod', $link, 0777 & ~umask());
}
protected function initializeBinDir(): void
{
$this->filesystem->ensureDirectoryExists($this->binDir);
$this->binDir = realpath($this->binDir);
}
protected function generateWindowsProxyCode(string $bin, string $link): string
{
$binPath = $this->filesystem->findShortestPath($link, $bin);
$caller = self::determineBinaryCaller($bin);
// if the target is a php file, we run the unixy proxy file
// to ensure that _composer_autoload_path gets defined, instead
// of running the binary directly
if ($caller === 'php') {
return "@ECHO OFF\r\n".
"setlocal DISABLEDELAYEDEXPANSION\r\n".
"SET BIN_TARGET=%~dp0/".trim(ProcessExecutor::escape(basename($link, '.bat')), '"\'')."\r\n".
"SET COMPOSER_RUNTIME_BIN_DIR=%~dp0\r\n".
"{$caller} \"%BIN_TARGET%\" %*\r\n";
}
return "@ECHO OFF\r\n".
"setlocal DISABLEDELAYEDEXPANSION\r\n".
"SET BIN_TARGET=%~dp0/".trim(ProcessExecutor::escape($binPath), '"\'')."\r\n".
"SET COMPOSER_RUNTIME_BIN_DIR=%~dp0\r\n".
"{$caller} \"%BIN_TARGET%\" %*\r\n";
}
protected function generateUnixyProxyCode(string $bin, string $link): string
{
$binPath = $this->filesystem->findShortestPath($link, $bin);
$binDir = ProcessExecutor::escape(dirname($binPath));
$binFile = basename($binPath);
$binContents = (string) file_get_contents($bin, false, null, 0, 500);
// For php files, we generate a PHP proxy instead of a shell one,
// which allows calling the proxy with a custom php process
if (Preg::isMatch('{^(#!.*\r?\n)?[\r\n\t ]*<\?php}', $binContents, $match)) {
// carry over the existing shebang if present, otherwise add our own
$proxyCode = $match[1] === null ? '#!/usr/bin/env php' : trim($match[1]);
$binPathExported = $this->filesystem->findShortestPathCode($link, $bin, false, true);
$streamProxyCode = $streamHint = '';
$globalsCode = '$GLOBALS[\'_composer_bin_dir\'] = __DIR__;'."\n";
$phpunitHack1 = $phpunitHack2 = '';
// Don't expose autoload path when vendor dir was not set in custom installers
if ($this->vendorDir !== null) {
// ensure comparisons work accurately if the CWD is a symlink, as $link is realpath'd already
$vendorDirReal = realpath($this->vendorDir);
if ($vendorDirReal === false) {
$vendorDirReal = $this->vendorDir;
}
$globalsCode .= '$GLOBALS[\'_composer_autoload_path\'] = ' . $this->filesystem->findShortestPathCode($link, $vendorDirReal . '/autoload.php', false, true).";\n";
}
// Add workaround for PHPUnit process isolation
if ($this->filesystem->normalizePath($bin) === $this->filesystem->normalizePath($this->vendorDir.'/phpunit/phpunit/phpunit')) {
// workaround issue on PHPUnit 6.5+ running on PHP 8+
$globalsCode .= '$GLOBALS[\'__PHPUNIT_ISOLATION_EXCLUDE_LIST\'] = $GLOBALS[\'__PHPUNIT_ISOLATION_BLACKLIST\'] = array(realpath('.$binPathExported.'));'."\n";
// workaround issue on all PHPUnit versions running on PHP <8
$phpunitHack1 = "'phpvfscomposer://'.";
$phpunitHack2 = '
$data = str_replace(\'__DIR__\', var_export(dirname($this->realpath), true), $data);
$data = str_replace(\'__FILE__\', var_export($this->realpath, true), $data);';
}
if (trim($match[0]) !== '<?php') {
$streamHint = ' using a stream wrapper to prevent the shebang from being output on PHP<8'."\n *";
$streamProxyCode = <<<STREAMPROXY
if (PHP_VERSION_ID < 80000) {
if (!class_exists('Composer\BinProxyWrapper')) {
/**
* @internal
*/
final class BinProxyWrapper
{
private \$handle;
private \$position;
private \$realpath;
public function stream_open(\$path, \$mode, \$options, &\$opened_path)
{
// get rid of phpvfscomposer:// prefix for __FILE__ & __DIR__ resolution
\$opened_path = substr(\$path, 17);
\$this->realpath = realpath(\$opened_path) ?: \$opened_path;
\$opened_path = $phpunitHack1\$this->realpath;
\$this->handle = fopen(\$this->realpath, \$mode);
\$this->position = 0;
return (bool) \$this->handle;
}
public function stream_read(\$count)
{
\$data = fread(\$this->handle, \$count);
if (\$this->position === 0) {
\$data = preg_replace('{^#!.*\\r?\\n}', '', \$data);
}$phpunitHack2
\$this->position += strlen(\$data);
return \$data;
}
public function stream_cast(\$castAs)
{
return \$this->handle;
}
public function stream_close()
{
fclose(\$this->handle);
}
public function stream_lock(\$operation)
{
return \$operation ? flock(\$this->handle, \$operation) : true;
}
public function stream_seek(\$offset, \$whence)
{
if (0 === fseek(\$this->handle, \$offset, \$whence)) {
\$this->position = ftell(\$this->handle);
return true;
}
return false;
}
public function stream_tell()
{
return \$this->position;
}
public function stream_eof()
{
return feof(\$this->handle);
}
public function stream_stat()
{
return array();
}
public function stream_set_option(\$option, \$arg1, \$arg2)
{
return true;
}
public function url_stat(\$path, \$flags)
{
\$path = substr(\$path, 17);
if (file_exists(\$path)) {
return stat(\$path);
}
return false;
}
}
}
if (
(function_exists('stream_get_wrappers') && in_array('phpvfscomposer', stream_get_wrappers(), true))
|| (function_exists('stream_wrapper_register') && stream_wrapper_register('phpvfscomposer', 'Composer\BinProxyWrapper'))
) {
return include("phpvfscomposer://" . $binPathExported);
}
}
STREAMPROXY;
}
return $proxyCode . "\n" . <<<PROXY
<?php
/**
* Proxy PHP file generated by Composer
*
* This file includes the referenced bin path ($binPath)
*$streamHint
* @generated
*/
namespace Composer;
$globalsCode
$streamProxyCode
return include $binPathExported;
PROXY;
}
return <<<PROXY
#!/usr/bin/env sh
# Support bash to support `source` with fallback on $0 if this does not run with bash
# https://stackoverflow.com/a/35006505/6512
selfArg="\$BASH_SOURCE"
if [ -z "\$selfArg" ]; then
selfArg="\$0"
fi
self=\$(realpath "\$selfArg" 2> /dev/null)
if [ -z "\$self" ]; then
self="\$selfArg"
fi
dir=\$(cd "\${self%[/\\\\]*}" > /dev/null; cd $binDir && pwd)
if [ -d /proc/cygdrive ]; then
case \$(which php) in
\$(readlink -n /proc/cygdrive)/*)
# We are in Cygwin using Windows php, so the path must be translated
dir=\$(cygpath -m "\$dir");
;;
esac
fi
export COMPOSER_RUNTIME_BIN_DIR="\$(cd "\${self%[/\\\\]*}" > /dev/null; pwd)"
# If bash is sourcing this file, we have to source the target as well
bashSource="\$BASH_SOURCE"
if [ -n "\$bashSource" ]; then
if [ "\$bashSource" != "\$0" ]; then
source "\${dir}/$binFile" "\$@"
return
fi
fi
exec "\${dir}/$binFile" "\$@"
PROXY;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/NoopInstaller.php | src/Composer/Installer/NoopInstaller.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\Installer;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
/**
* Does not install anything but marks packages installed in the repo
*
* Useful for dry runs
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class NoopInstaller implements InstallerInterface
{
/**
* @inheritDoc
*/
public function supports(string $packageType)
{
return true;
}
/**
* @inheritDoc
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
{
return $repo->hasPackage($package);
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null)
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function cleanup($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
if (!$repo->hasPackage($initial)) {
throw new \InvalidArgumentException('Package is not installed: '.$initial);
}
$repo->removePackage($initial);
if (!$repo->hasPackage($target)) {
$repo->addPackage(clone $target);
}
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if (!$repo->hasPackage($package)) {
throw new \InvalidArgumentException('Package is not installed: '.$package);
}
$repo->removePackage($package);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function getInstallPath(PackageInterface $package)
{
$targetDir = $package->getTargetDir();
return $package->getPrettyName() . ($targetDir ? '/'.$targetDir : '');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/BinaryPresenceInterface.php | src/Composer/Installer/BinaryPresenceInterface.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\Installer;
use Composer\Package\PackageInterface;
/**
* Interface for the package installation manager that handle binary installation.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface BinaryPresenceInterface
{
/**
* Make sure binaries are installed for a given package.
*
* @param PackageInterface $package package instance
*
* @return void
*/
public function ensureBinariesPresence(PackageInterface $package);
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/InstallerEvent.php | src/Composer/Installer/InstallerEvent.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\Installer;
use Composer\Composer;
use Composer\DependencyResolver\Transaction;
use Composer\EventDispatcher\Event;
use Composer\IO\IOInterface;
class InstallerEvent extends Event
{
/**
* @var Composer
*/
private $composer;
/**
* @var IOInterface
*/
private $io;
/**
* @var bool
*/
private $devMode;
/**
* @var bool
*/
private $executeOperations;
/**
* @var Transaction
*/
private $transaction;
/**
* Constructor.
*/
public function __construct(string $eventName, Composer $composer, IOInterface $io, bool $devMode, bool $executeOperations, Transaction $transaction)
{
parent::__construct($eventName);
$this->composer = $composer;
$this->io = $io;
$this->devMode = $devMode;
$this->executeOperations = $executeOperations;
$this->transaction = $transaction;
}
public function getComposer(): Composer
{
return $this->composer;
}
public function getIO(): IOInterface
{
return $this->io;
}
public function isDevMode(): bool
{
return $this->devMode;
}
public function isExecutingOperations(): bool
{
return $this->executeOperations;
}
public function getTransaction(): ?Transaction
{
return $this->transaction;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/PluginInstaller.php | src/Composer/Installer/PluginInstaller.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\Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\PartialComposer;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\Plugin\PluginManager;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
use React\Promise\PromiseInterface;
/**
* Installer for plugin packages
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Nils Adermann <naderman@naderman.de>
*/
class PluginInstaller extends LibraryInstaller
{
public function __construct(IOInterface $io, PartialComposer $composer, ?Filesystem $fs = null, ?BinaryInstaller $binaryInstaller = null)
{
parent::__construct($io, $composer, 'composer-plugin', $fs, $binaryInstaller);
}
/**
* @inheritDoc
*/
public function supports(string $packageType)
{
return $packageType === 'composer-plugin' || $packageType === 'composer-installer';
}
public function disablePlugins(): void
{
$this->getPluginManager()->disablePlugins();
}
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
// fail install process early if it is going to fail due to a plugin not being allowed
if (($type === 'install' || $type === 'update') && !$this->getPluginManager()->arePluginsDisabled('local')) {
$this->getPluginManager()->isPluginAllowed($package->getName(), false, true === ($package->getExtra()['plugin-optional'] ?? false));
}
return parent::prepare($type, $package, $prevPackage);
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null)
{
$extra = $package->getExtra();
if (empty($extra['class'])) {
throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
}
return parent::download($package, $prevPackage);
}
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$promise = parent::install($repo, $package);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
return $promise->then(function () use ($package, $repo): void {
try {
Platform::workaroundFilesystemIssues();
$this->getPluginManager()->registerPackage($package, true);
} catch (\Exception $e) {
$this->rollbackInstall($e, $repo, $package);
}
});
}
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
$promise = parent::update($repo, $initial, $target);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
return $promise->then(function () use ($initial, $target, $repo): void {
try {
Platform::workaroundFilesystemIssues();
$this->getPluginManager()->deactivatePackage($initial);
$this->getPluginManager()->registerPackage($target, true);
} catch (\Exception $e) {
$this->rollbackInstall($e, $repo, $target);
}
});
}
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->getPluginManager()->uninstallPackage($package);
return parent::uninstall($repo, $package);
}
private function rollbackInstall(\Exception $e, InstalledRepositoryInterface $repo, PackageInterface $package): void
{
$this->io->writeError('Plugin initialization failed ('.$e->getMessage().'), uninstalling plugin');
parent::uninstall($repo, $package);
throw $e;
}
protected function getPluginManager(): PluginManager
{
assert($this->composer instanceof Composer, new \LogicException(self::class.' should be initialized with a fully loaded Composer instance.'));
$pluginManager = $this->composer->getPluginManager();
return $pluginManager;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/PackageEvent.php | src/Composer/Installer/PackageEvent.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\Installer;
use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\DependencyResolver\Operation\OperationInterface;
use Composer\Repository\RepositoryInterface;
use Composer\EventDispatcher\Event;
/**
* The Package Event.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PackageEvent extends Event
{
/**
* @var Composer
*/
private $composer;
/**
* @var IOInterface
*/
private $io;
/**
* @var bool
*/
private $devMode;
/**
* @var RepositoryInterface
*/
private $localRepo;
/**
* @var OperationInterface[]
*/
private $operations;
/**
* @var OperationInterface The operation instance which is being executed
*/
private $operation;
/**
* Constructor.
*
* @param OperationInterface[] $operations
*/
public function __construct(string $eventName, Composer $composer, IOInterface $io, bool $devMode, RepositoryInterface $localRepo, array $operations, OperationInterface $operation)
{
parent::__construct($eventName);
$this->composer = $composer;
$this->io = $io;
$this->devMode = $devMode;
$this->localRepo = $localRepo;
$this->operations = $operations;
$this->operation = $operation;
}
public function getComposer(): Composer
{
return $this->composer;
}
public function getIO(): IOInterface
{
return $this->io;
}
public function isDevMode(): bool
{
return $this->devMode;
}
public function getLocalRepo(): RepositoryInterface
{
return $this->localRepo;
}
/**
* @return OperationInterface[]
*/
public function getOperations(): array
{
return $this->operations;
}
/**
* Returns the package instance.
*/
public function getOperation(): OperationInterface
{
return $this->operation;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/ProjectInstaller.php | src/Composer/Installer/ProjectInstaller.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\Installer;
use React\Promise\PromiseInterface;
use Composer\Package\PackageInterface;
use Composer\Downloader\DownloadManager;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Util\Filesystem;
/**
* Project Installer is used to install a single package into a directory as
* root project.
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
*/
class ProjectInstaller implements InstallerInterface
{
/** @var string */
private $installPath;
/** @var DownloadManager */
private $downloadManager;
/** @var Filesystem */
private $filesystem;
public function __construct(string $installPath, DownloadManager $dm, Filesystem $fs)
{
$this->installPath = rtrim(strtr($installPath, '\\', '/'), '/').'/';
$this->downloadManager = $dm;
$this->filesystem = $fs;
}
/**
* Decides if the installer supports the given type
*/
public function supports(string $packageType): bool
{
return true;
}
/**
* @inheritDoc
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool
{
return false;
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null): ?PromiseInterface
{
$installPath = $this->installPath;
if (file_exists($installPath) && !$this->filesystem->isDirEmpty($installPath)) {
throw new \InvalidArgumentException("Project directory $installPath is not empty.");
}
if (!is_dir($installPath)) {
mkdir($installPath, 0777, true);
}
return $this->downloadManager->download($package, $installPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, ?PackageInterface $prevPackage = null): ?PromiseInterface
{
return $this->downloadManager->prepare($type, $package, $this->installPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function cleanup($type, PackageInterface $package, ?PackageInterface $prevPackage = null): ?PromiseInterface
{
return $this->downloadManager->cleanup($type, $package, $this->installPath, $prevPackage);
}
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package): ?PromiseInterface
{
return $this->downloadManager->install($package, $this->installPath);
}
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target): ?PromiseInterface
{
throw new \InvalidArgumentException("not supported");
}
/**
* @inheritDoc
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package): ?PromiseInterface
{
throw new \InvalidArgumentException("not supported");
}
/**
* Returns the installation path of a package
*
* @return string configured install path
*/
public function getInstallPath(PackageInterface $package): string
{
return $this->installPath;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/InstallerInterface.php | src/Composer/Installer/InstallerInterface.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\Installer;
use Composer\Package\PackageInterface;
use Composer\Repository\InstalledRepositoryInterface;
use InvalidArgumentException;
use React\Promise\PromiseInterface;
/**
* Interface for the package installation manager.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface InstallerInterface
{
/**
* Decides if the installer supports the given type
*
* @return bool
*/
public function supports(string $packageType);
/**
* Checks that provided package is installed.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param PackageInterface $package package instance
*
* @return bool
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package);
/**
* Downloads the files needed to later install the given package.
*
* @param PackageInterface $package package instance
* @param PackageInterface $prevPackage previous package instance in case of an update
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null);
/**
* Do anything that needs to be done between all downloads have been completed and the actual operation is executed
*
* All packages get first downloaded, then all together prepared, then all together installed/updated/uninstalled. Therefore
* for error recovery it is important to avoid failing during install/update/uninstall as much as possible, and risky things or
* user prompts should happen in the prepare step rather. In case of failure, cleanup() will be called so that changes can
* be undone as much as possible.
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param PackageInterface $prevPackage previous package instance in case of an update
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function prepare(string $type, PackageInterface $package, ?PackageInterface $prevPackage = null);
/**
* Installs specific package.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param PackageInterface $package package instance
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package);
/**
* Updates specific package.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param PackageInterface $initial already installed package version
* @param PackageInterface $target updated version
* @throws InvalidArgumentException if $initial package is not installed
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target);
/**
* Uninstalls specific package.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param PackageInterface $package package instance
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package);
/**
* Do anything to cleanup changes applied in the prepare or install/update/uninstall steps
*
* Note that cleanup will be called for all packages regardless if they failed an operation or not, to give
* all installers a change to cleanup things they did previously, so you need to keep track of changes
* applied in the installer/downloader themselves.
*
* @param string $type one of install/update/uninstall
* @param PackageInterface $package package instance
* @param PackageInterface $prevPackage previous package instance in case of an update
* @return PromiseInterface|null
* @phpstan-return PromiseInterface<void|null>|null
*/
public function cleanup(string $type, PackageInterface $package, ?PackageInterface $prevPackage = null);
/**
* Returns the absolute installation path of a package.
*
* @return string|null absolute path to install to, which MUST not end with a slash, or null if the package does not have anything installed on disk
*/
public function getInstallPath(PackageInterface $package);
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/PackageEvents.php | src/Composer/Installer/PackageEvents.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\Installer;
/**
* Package Events.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PackageEvents
{
/**
* The PRE_PACKAGE_INSTALL event occurs before a package is installed.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const PRE_PACKAGE_INSTALL = 'pre-package-install';
/**
* The POST_PACKAGE_INSTALL event occurs after a package is installed.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const POST_PACKAGE_INSTALL = 'post-package-install';
/**
* The PRE_PACKAGE_UPDATE event occurs before a package is updated.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const PRE_PACKAGE_UPDATE = 'pre-package-update';
/**
* The POST_PACKAGE_UPDATE event occurs after a package is updated.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const POST_PACKAGE_UPDATE = 'post-package-update';
/**
* The PRE_PACKAGE_UNINSTALL event occurs before a package has been uninstalled.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const PRE_PACKAGE_UNINSTALL = 'pre-package-uninstall';
/**
* The POST_PACKAGE_UNINSTALL event occurs after a package has been uninstalled.
*
* The event listener method receives a Composer\Installer\PackageEvent instance.
*
* @var string
*/
public const POST_PACKAGE_UNINSTALL = 'post-package-uninstall';
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/InstallerEvents.php | src/Composer/Installer/InstallerEvents.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\Installer;
class InstallerEvents
{
/**
* The PRE_OPERATIONS_EXEC event occurs before the lock file gets
* installed and operations are executed.
*
* The event listener method receives an Composer\Installer\InstallerEvent instance.
*
* @var string
*/
public const PRE_OPERATIONS_EXEC = 'pre-operations-exec';
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/SuggestedPackagesReporter.php | src/Composer/Installer/SuggestedPackagesReporter.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\Installer;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Pcre\Preg;
use Composer\Repository\InstalledRepository;
use Symfony\Component\Console\Formatter\OutputFormatter;
/**
* Add suggested packages from different places to output them in the end.
*
* @author Haralan Dobrev <hkdobrev@gmail.com>
*/
class SuggestedPackagesReporter
{
public const MODE_LIST = 1;
public const MODE_BY_PACKAGE = 2;
public const MODE_BY_SUGGESTION = 4;
/**
* @var array<array{source: string, target: string, reason: string}>
*/
protected $suggestedPackages = [];
/**
* @var IOInterface
*/
private $io;
public function __construct(IOInterface $io)
{
$this->io = $io;
}
/**
* @return array<array{source: string, target: string, reason: string}> Suggested packages with source, target and reason keys.
*/
public function getPackages(): array
{
return $this->suggestedPackages;
}
/**
* Add suggested packages to be listed after install
*
* Could be used to add suggested packages both from the installer
* or from CreateProjectCommand.
*
* @param string $source Source package which made the suggestion
* @param string $target Target package to be suggested
* @param string $reason Reason the target package to be suggested
*/
public function addPackage(string $source, string $target, string $reason): SuggestedPackagesReporter
{
$this->suggestedPackages[] = [
'source' => $source,
'target' => $target,
'reason' => $reason,
];
return $this;
}
/**
* Add all suggestions from a package.
*/
public function addSuggestionsFromPackage(PackageInterface $package): SuggestedPackagesReporter
{
$source = $package->getPrettyName();
foreach ($package->getSuggests() as $target => $reason) {
$this->addPackage(
$source,
$target,
$reason
);
}
return $this;
}
/**
* Output suggested packages.
*
* Do not list the ones already installed if installed repository provided.
*
* @param int $mode One of the MODE_* constants from this class
* @param InstalledRepository|null $installedRepo If passed in, suggested packages which are installed already will be skipped
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
*/
public function output(int $mode, ?InstalledRepository $installedRepo = null, ?PackageInterface $onlyDependentsOf = null): void
{
$suggestedPackages = $this->getFilteredSuggestions($installedRepo, $onlyDependentsOf);
$suggesters = [];
$suggested = [];
foreach ($suggestedPackages as $suggestion) {
$suggesters[$suggestion['source']][$suggestion['target']] = $suggestion['reason'];
$suggested[$suggestion['target']][$suggestion['source']] = $suggestion['reason'];
}
ksort($suggesters);
ksort($suggested);
// Simple mode
if ($mode & self::MODE_LIST) {
foreach (array_keys($suggested) as $name) {
$this->io->write(sprintf('<info>%s</info>', $name));
}
return;
}
// Grouped by package
if ($mode & self::MODE_BY_PACKAGE) {
foreach ($suggesters as $suggester => $suggestions) {
$this->io->write(sprintf('<comment>%s</comment> suggests:', $suggester));
foreach ($suggestions as $suggestion => $reason) {
$this->io->write(sprintf(' - <info>%s</info>' . ($reason ? ': %s' : ''), $suggestion, $this->escapeOutput($reason)));
}
$this->io->write('');
}
}
// Grouped by suggestion
if ($mode & self::MODE_BY_SUGGESTION) {
// Improve readability in full mode
if ($mode & self::MODE_BY_PACKAGE) {
$this->io->write(str_repeat('-', 78));
}
foreach ($suggested as $suggestion => $suggesters) {
$this->io->write(sprintf('<comment>%s</comment> is suggested by:', $suggestion));
foreach ($suggesters as $suggester => $reason) {
$this->io->write(sprintf(' - <info>%s</info>' . ($reason ? ': %s' : ''), $suggester, $this->escapeOutput($reason)));
}
$this->io->write('');
}
}
if ($onlyDependentsOf) {
$allSuggestedPackages = $this->getFilteredSuggestions($installedRepo);
$diff = count($allSuggestedPackages) - count($suggestedPackages);
if ($diff) {
$this->io->write('<info>'.$diff.' additional suggestions</info> by transitive dependencies can be shown with <info>--all</info>');
}
}
}
/**
* Output number of new suggested packages and a hint to use suggest command.
*
* @param InstalledRepository|null $installedRepo If passed in, suggested packages which are installed already will be skipped
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
*/
public function outputMinimalistic(?InstalledRepository $installedRepo = null, ?PackageInterface $onlyDependentsOf = null): void
{
$suggestedPackages = $this->getFilteredSuggestions($installedRepo, $onlyDependentsOf);
if ($suggestedPackages) {
$this->io->writeError('<info>'.count($suggestedPackages).' package suggestions were added by new dependencies, use `composer suggest` to see details.</info>');
}
}
/**
* @param InstalledRepository|null $installedRepo If passed in, suggested packages which are installed already will be skipped
* @param PackageInterface|null $onlyDependentsOf If passed in, only the suggestions from direct dependents of that package, or from the package itself, will be shown
* @return mixed[]
*/
private function getFilteredSuggestions(?InstalledRepository $installedRepo = null, ?PackageInterface $onlyDependentsOf = null): array
{
$suggestedPackages = $this->getPackages();
$installedNames = [];
if (null !== $installedRepo && !empty($suggestedPackages)) {
foreach ($installedRepo->getPackages() as $package) {
$installedNames = array_merge(
$installedNames,
$package->getNames()
);
}
}
$sourceFilter = [];
if ($onlyDependentsOf) {
$sourceFilter = array_map(static function ($link): string {
return $link->getTarget();
}, array_merge($onlyDependentsOf->getRequires(), $onlyDependentsOf->getDevRequires()));
$sourceFilter[] = $onlyDependentsOf->getName();
}
$suggestions = [];
foreach ($suggestedPackages as $suggestion) {
if (in_array($suggestion['target'], $installedNames) || (\count($sourceFilter) > 0 && !in_array($suggestion['source'], $sourceFilter))) {
continue;
}
$suggestions[] = $suggestion;
}
return $suggestions;
}
private function escapeOutput(string $string): string
{
return OutputFormatter::escape(
$this->removeControlCharacters($string)
);
}
private function removeControlCharacters(string $string): string
{
return Preg::replace(
'/[[:cntrl:]]/',
'',
str_replace("\n", ' ', $string)
);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/MetapackageInstaller.php | src/Composer/Installer/MetapackageInstaller.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\Installer;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\Package\PackageInterface;
use Composer\IO\IOInterface;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
/**
* Metapackage installation manager.
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class MetapackageInstaller implements InstallerInterface
{
/** @var IOInterface */
private $io;
public function __construct(IOInterface $io)
{
$this->io = $io;
}
/**
* @inheritDoc
*/
public function supports(string $packageType)
{
return $packageType === 'metapackage';
}
/**
* @inheritDoc
*/
public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
{
return $repo->hasPackage($package);
}
/**
* @inheritDoc
*/
public function download(PackageInterface $package, ?PackageInterface $prevPackage = null)
{
// noop
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function prepare($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
// noop
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function cleanup($type, PackageInterface $package, ?PackageInterface $prevPackage = null)
{
// noop
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
{
$this->io->writeError(" - " . InstallOperation::format($package));
$repo->addPackage(clone $package);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
{
if (!$repo->hasPackage($initial)) {
throw new \InvalidArgumentException('Package is not installed: '.$initial);
}
$this->io->writeError(" - " . UpdateOperation::format($initial, $target));
$repo->removePackage($initial);
$repo->addPackage(clone $target);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*/
public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
{
if (!$repo->hasPackage($package)) {
throw new \InvalidArgumentException('Package is not installed: '.$package);
}
$this->io->writeError(" - " . UninstallOperation::format($package));
$repo->removePackage($package);
return \React\Promise\resolve(null);
}
/**
* @inheritDoc
*
* @return null
*/
public function getInstallPath(PackageInterface $package)
{
return null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Installer/InstallationManager.php | src/Composer/Installer/InstallationManager.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\Installer;
use Composer\IO\IOInterface;
use Composer\IO\ConsoleIO;
use Composer\Package\PackageInterface;
use Composer\Package\AliasPackage;
use Composer\Repository\InstalledRepositoryInterface;
use Composer\DependencyResolver\Operation\OperationInterface;
use Composer\DependencyResolver\Operation\InstallOperation;
use Composer\DependencyResolver\Operation\UpdateOperation;
use Composer\DependencyResolver\Operation\UninstallOperation;
use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation;
use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation;
use Composer\Downloader\FileDownloader;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\Loop;
use Composer\Util\Platform;
use React\Promise\PromiseInterface;
use Seld\Signal\SignalHandler;
/**
* Package operation manager.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Nils Adermann <naderman@naderman.de>
*/
class InstallationManager
{
/** @var list<InstallerInterface> */
private $installers = [];
/** @var array<string, InstallerInterface> */
private $cache = [];
/** @var array<string, array<PackageInterface>> */
private $notifiablePackages = [];
/** @var Loop */
private $loop;
/** @var IOInterface */
private $io;
/** @var ?EventDispatcher */
private $eventDispatcher;
/** @var bool */
private $outputProgress;
public function __construct(Loop $loop, IOInterface $io, ?EventDispatcher $eventDispatcher = null)
{
$this->loop = $loop;
$this->io = $io;
$this->eventDispatcher = $eventDispatcher;
}
public function reset(): void
{
$this->notifiablePackages = [];
FileDownloader::$downloadMetadata = [];
}
/**
* Adds installer
*
* @param InstallerInterface $installer installer instance
*/
public function addInstaller(InstallerInterface $installer): void
{
array_unshift($this->installers, $installer);
$this->cache = [];
}
/**
* Removes installer
*
* @param InstallerInterface $installer installer instance
*/
public function removeInstaller(InstallerInterface $installer): void
{
if (false !== ($key = array_search($installer, $this->installers, true))) {
array_splice($this->installers, $key, 1);
$this->cache = [];
}
}
/**
* Disables plugins.
*
* We prevent any plugins from being instantiated by
* disabling the PluginManager. This ensures that no third-party
* code is ever executed.
*/
public function disablePlugins(): void
{
foreach ($this->installers as $i => $installer) {
if (!$installer instanceof PluginInstaller) {
continue;
}
$installer->disablePlugins();
}
}
/**
* Returns installer for a specific package type.
*
* @param string $type package type
*
* @throws \InvalidArgumentException if installer for provided type is not registered
*/
public function getInstaller(string $type): InstallerInterface
{
$type = strtolower($type);
if (isset($this->cache[$type])) {
return $this->cache[$type];
}
foreach ($this->installers as $installer) {
if ($installer->supports($type)) {
return $this->cache[$type] = $installer;
}
}
throw new \InvalidArgumentException('Unknown installer type: '.$type);
}
/**
* Checks whether provided package is installed in one of the registered installers.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param PackageInterface $package package instance
*/
public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package): bool
{
if ($package instanceof AliasPackage) {
return $repo->hasPackage($package) && $this->isPackageInstalled($repo, $package->getAliasOf());
}
return $this->getInstaller($package->getType())->isInstalled($repo, $package);
}
/**
* Install binary for the given package.
* If the installer associated to this package doesn't handle that function, it'll do nothing.
*
* @param PackageInterface $package Package instance
*/
public function ensureBinariesPresence(PackageInterface $package): void
{
try {
$installer = $this->getInstaller($package->getType());
} catch (\InvalidArgumentException $e) {
// no installer found for the current package type (@see `getInstaller()`)
return;
}
// if the given installer support installing binaries
if ($installer instanceof BinaryPresenceInterface) {
$installer->ensureBinariesPresence($package);
}
}
/**
* Executes solver operation.
*
* @param InstalledRepositoryInterface $repo repository in which to add/remove/update packages
* @param OperationInterface[] $operations operations to execute
* @param bool $devMode whether the install is being run in dev mode
* @param bool $runScripts whether to dispatch script events
* @param bool $downloadOnly whether to only download packages
*/
public function execute(InstalledRepositoryInterface $repo, array $operations, bool $devMode = true, bool $runScripts = true, bool $downloadOnly = false): void
{
/** @var array<callable(): ?PromiseInterface<void|null>> $cleanupPromises */
$cleanupPromises = [];
$signalHandler = SignalHandler::create([SignalHandler::SIGINT, SignalHandler::SIGTERM, SignalHandler::SIGHUP], function (string $signal, SignalHandler $handler) use (&$cleanupPromises) {
$this->io->writeError('Received '.$signal.', aborting', true, IOInterface::DEBUG);
$this->runCleanup($cleanupPromises);
$handler->exitWithLastSignal();
});
try {
// execute operations in batches to make sure download-modifying-plugins are installed
// before the other packages get downloaded
$batches = [];
$batch = [];
foreach ($operations as $index => $operation) {
if ($operation instanceof UpdateOperation || $operation instanceof InstallOperation) {
$package = $operation instanceof UpdateOperation ? $operation->getTargetPackage() : $operation->getPackage();
if ($package->getType() === 'composer-plugin') {
$extra = $package->getExtra();
if (isset($extra['plugin-modifies-downloads']) && $extra['plugin-modifies-downloads'] === true) {
if (count($batch) > 0) {
$batches[] = $batch;
}
$batches[] = [$index => $operation];
$batch = [];
continue;
}
}
}
$batch[$index] = $operation;
}
if (count($batch) > 0) {
$batches[] = $batch;
}
foreach ($batches as $batchToExecute) {
$this->downloadAndExecuteBatch($repo, $batchToExecute, $cleanupPromises, $devMode, $runScripts, $downloadOnly, $operations);
}
} catch (\Exception $e) {
$this->runCleanup($cleanupPromises);
throw $e;
} finally {
$signalHandler->unregister();
}
if ($downloadOnly) {
return;
}
// do a last write so that we write the repository even if nothing changed
// as that can trigger an update of some files like InstalledVersions.php if
// running a new composer version
$repo->write($devMode, $this);
}
/**
* @param OperationInterface[] $operations List of operations to execute in this batch
* @param OperationInterface[] $allOperations Complete list of operations to be executed in the install job, used for event listeners
* @phpstan-param array<callable(): ?PromiseInterface<void|null>> $cleanupPromises
*/
private function downloadAndExecuteBatch(InstalledRepositoryInterface $repo, array $operations, array &$cleanupPromises, bool $devMode, bool $runScripts, bool $downloadOnly, array $allOperations): void
{
$promises = [];
foreach ($operations as $index => $operation) {
$opType = $operation->getOperationType();
// ignoring alias ops as they don't need to execute anything at this stage
if (!in_array($opType, ['update', 'install', 'uninstall'], true)) {
continue;
}
if ($opType === 'update') {
/** @var UpdateOperation $operation */
$package = $operation->getTargetPackage();
$initialPackage = $operation->getInitialPackage();
} else {
/** @var InstallOperation|MarkAliasInstalledOperation|MarkAliasUninstalledOperation|UninstallOperation $operation */
$package = $operation->getPackage();
$initialPackage = null;
}
$installer = $this->getInstaller($package->getType());
$cleanupPromises[$index] = static function () use ($opType, $installer, $package, $initialPackage): ?PromiseInterface {
// avoid calling cleanup if the download was not even initialized for a package
// as without installation source configured nothing will work
if (null === $package->getInstallationSource()) {
return \React\Promise\resolve(null);
}
return $installer->cleanup($opType, $package, $initialPackage);
};
if ($opType !== 'uninstall') {
$promise = $installer->download($package, $initialPackage);
if (null !== $promise) {
$promises[] = $promise;
}
}
}
// execute all downloads first
if (count($promises) > 0) {
$this->waitOnPromises($promises);
}
if ($downloadOnly) {
$this->runCleanup($cleanupPromises);
return;
}
// execute operations in batches to make sure every plugin is installed in the
// right order and activated before the packages depending on it are installed
$batches = [];
$batch = [];
foreach ($operations as $index => $operation) {
if ($operation instanceof InstallOperation || $operation instanceof UpdateOperation) {
$package = $operation instanceof UpdateOperation ? $operation->getTargetPackage() : $operation->getPackage();
if ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer') {
if (count($batch) > 0) {
$batches[] = $batch;
}
$batches[] = [$index => $operation];
$batch = [];
continue;
}
}
$batch[$index] = $operation;
}
if (count($batch) > 0) {
$batches[] = $batch;
}
foreach ($batches as $batchToExecute) {
$this->executeBatch($repo, $batchToExecute, $cleanupPromises, $devMode, $runScripts, $allOperations);
}
}
/**
* @param OperationInterface[] $operations List of operations to execute in this batch
* @param OperationInterface[] $allOperations Complete list of operations to be executed in the install job, used for event listeners
* @phpstan-param array<callable(): ?PromiseInterface<void|null>> $cleanupPromises
*/
private function executeBatch(InstalledRepositoryInterface $repo, array $operations, array $cleanupPromises, bool $devMode, bool $runScripts, array $allOperations): void
{
$promises = [];
$postExecCallbacks = [];
foreach ($operations as $index => $operation) {
$opType = $operation->getOperationType();
// ignoring alias ops as they don't need to execute anything
if (!in_array($opType, ['update', 'install', 'uninstall'], true)) {
// output alias ops in debug verbosity as they have no output otherwise
if ($this->io->isDebug()) {
$this->io->writeError(' - ' . $operation->show(false));
}
$this->{$opType}($repo, $operation);
continue;
}
if ($opType === 'update') {
/** @var UpdateOperation $operation */
$package = $operation->getTargetPackage();
$initialPackage = $operation->getInitialPackage();
} else {
/** @var InstallOperation|MarkAliasInstalledOperation|MarkAliasUninstalledOperation|UninstallOperation $operation */
$package = $operation->getPackage();
$initialPackage = null;
}
$installer = $this->getInstaller($package->getType());
$eventName = [
'install' => PackageEvents::PRE_PACKAGE_INSTALL,
'update' => PackageEvents::PRE_PACKAGE_UPDATE,
'uninstall' => PackageEvents::PRE_PACKAGE_UNINSTALL,
][$opType];
if ($runScripts && $this->eventDispatcher !== null) {
$this->eventDispatcher->dispatchPackageEvent($eventName, $devMode, $repo, $allOperations, $operation);
}
$dispatcher = $this->eventDispatcher;
$io = $this->io;
$promise = $installer->prepare($opType, $package, $initialPackage);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
$promise = $promise->then(function () use ($opType, $repo, $operation) {
return $this->{$opType}($repo, $operation);
})->then($cleanupPromises[$index])
->then(function () use ($devMode, $repo): void {
$repo->write($devMode, $this);
}, static function ($e) use ($opType, $package, $io): void {
$io->writeError(' <error>' . ucfirst($opType) .' of '.$package->getPrettyName().' failed</error>');
throw $e;
});
$eventName = [
'install' => PackageEvents::POST_PACKAGE_INSTALL,
'update' => PackageEvents::POST_PACKAGE_UPDATE,
'uninstall' => PackageEvents::POST_PACKAGE_UNINSTALL,
][$opType];
if ($runScripts && $dispatcher !== null) {
$postExecCallbacks[] = static function () use ($dispatcher, $eventName, $devMode, $repo, $allOperations, $operation): void {
$dispatcher->dispatchPackageEvent($eventName, $devMode, $repo, $allOperations, $operation);
};
}
$promises[] = $promise;
}
// execute all prepare => installs/updates/removes => cleanup steps
if (count($promises) > 0) {
$this->waitOnPromises($promises);
}
Platform::workaroundFilesystemIssues();
foreach ($postExecCallbacks as $cb) {
$cb();
}
}
/**
* @param array<PromiseInterface<void|null>> $promises
*/
private function waitOnPromises(array $promises): void
{
$progress = null;
if (
$this->outputProgress
&& $this->io instanceof ConsoleIO
&& !((bool) Platform::getEnv('CI'))
&& !$this->io->isDebug()
&& count($promises) > 1
) {
$progress = $this->io->getProgressBar();
}
$this->loop->wait($promises, $progress);
if ($progress !== null) {
$progress->clear();
// ProgressBar in non-decorated output does not output a final line-break and clear() does nothing
if (!$this->io->isDecorated()) {
$this->io->writeError('');
}
}
}
/**
* Executes download operation.
*
* @phpstan-return PromiseInterface<void|null>|null
*/
public function download(PackageInterface $package): ?PromiseInterface
{
$installer = $this->getInstaller($package->getType());
$promise = $installer->cleanup("install", $package);
return $promise;
}
/**
* Executes install operation.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param InstallOperation $operation operation instance
* @phpstan-return PromiseInterface<void|null>|null
*/
public function install(InstalledRepositoryInterface $repo, InstallOperation $operation): ?PromiseInterface
{
$package = $operation->getPackage();
$installer = $this->getInstaller($package->getType());
$promise = $installer->install($repo, $package);
$this->markForNotification($package);
return $promise;
}
/**
* Executes update operation.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param UpdateOperation $operation operation instance
* @phpstan-return PromiseInterface<void|null>|null
*/
public function update(InstalledRepositoryInterface $repo, UpdateOperation $operation): ?PromiseInterface
{
$initial = $operation->getInitialPackage();
$target = $operation->getTargetPackage();
$initialType = $initial->getType();
$targetType = $target->getType();
if ($initialType === $targetType) {
$installer = $this->getInstaller($initialType);
$promise = $installer->update($repo, $initial, $target);
$this->markForNotification($target);
} else {
$promise = $this->getInstaller($initialType)->uninstall($repo, $initial);
if (!$promise instanceof PromiseInterface) {
$promise = \React\Promise\resolve(null);
}
$installer = $this->getInstaller($targetType);
$promise = $promise->then(static function () use ($installer, $repo, $target): PromiseInterface {
$promise = $installer->install($repo, $target);
if ($promise instanceof PromiseInterface) {
return $promise;
}
return \React\Promise\resolve(null);
});
}
return $promise;
}
/**
* Uninstalls package.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param UninstallOperation $operation operation instance
* @phpstan-return PromiseInterface<void|null>|null
*/
public function uninstall(InstalledRepositoryInterface $repo, UninstallOperation $operation): ?PromiseInterface
{
$package = $operation->getPackage();
$installer = $this->getInstaller($package->getType());
return $installer->uninstall($repo, $package);
}
/**
* Executes markAliasInstalled operation.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param MarkAliasInstalledOperation $operation operation instance
*/
public function markAliasInstalled(InstalledRepositoryInterface $repo, MarkAliasInstalledOperation $operation): void
{
$package = $operation->getPackage();
if (!$repo->hasPackage($package)) {
$repo->addPackage(clone $package);
}
}
/**
* Executes markAlias operation.
*
* @param InstalledRepositoryInterface $repo repository in which to check
* @param MarkAliasUninstalledOperation $operation operation instance
*/
public function markAliasUninstalled(InstalledRepositoryInterface $repo, MarkAliasUninstalledOperation $operation): void
{
$package = $operation->getPackage();
$repo->removePackage($package);
}
/**
* Returns the installation path of a package
*
* @return string|null absolute path to install to, which does not end with a slash, or null if the package does not have anything installed on disk
*/
public function getInstallPath(PackageInterface $package): ?string
{
$installer = $this->getInstaller($package->getType());
return $installer->getInstallPath($package);
}
public function setOutputProgress(bool $outputProgress): void
{
$this->outputProgress = $outputProgress;
}
public function notifyInstalls(IOInterface $io): void
{
$promises = [];
try {
foreach ($this->notifiablePackages as $repoUrl => $packages) {
// non-batch API, deprecated
if (str_contains($repoUrl, '%package%')) {
foreach ($packages as $package) {
$url = str_replace('%package%', $package->getPrettyName(), $repoUrl);
$params = [
'version' => $package->getPrettyVersion(),
'version_normalized' => $package->getVersion(),
];
$opts = [
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'header' => ['Content-type: application/x-www-form-urlencoded'],
'content' => http_build_query($params, '', '&'),
'timeout' => 3,
],
];
$promises[] = $this->loop->getHttpDownloader()->add($url, $opts);
}
continue;
}
$postData = ['downloads' => []];
foreach ($packages as $package) {
$packageNotification = [
'name' => $package->getPrettyName(),
'version' => $package->getVersion(),
];
if (strpos($repoUrl, 'packagist.org/') !== false) {
if (isset(FileDownloader::$downloadMetadata[$package->getName()])) {
$packageNotification['downloaded'] = FileDownloader::$downloadMetadata[$package->getName()];
} else {
$packageNotification['downloaded'] = false;
}
}
$postData['downloads'][] = $packageNotification;
}
$opts = [
'retry-auth-failure' => false,
'http' => [
'method' => 'POST',
'header' => ['Content-Type: application/json'],
'content' => json_encode($postData),
'timeout' => 6,
],
];
$promises[] = $this->loop->getHttpDownloader()->add($repoUrl, $opts);
}
$this->loop->wait($promises);
} catch (\Exception $e) {
}
$this->reset();
}
private function markForNotification(PackageInterface $package): void
{
if ($package->getNotificationUrl() !== null) {
$this->notifiablePackages[$package->getNotificationUrl()][$package->getName()] = $package;
}
}
/**
* @phpstan-param array<callable(): ?PromiseInterface<void|null>> $cleanupPromises
*/
private function runCleanup(array $cleanupPromises): void
{
$promises = [];
$this->loop->abortJobs();
foreach ($cleanupPromises as $cleanup) {
$promises[] = new \React\Promise\Promise(static function ($resolve) use ($cleanup): void {
$promise = $cleanup();
if (!$promise instanceof PromiseInterface) {
$resolve(null);
} else {
$promise->then(static function () use ($resolve): void {
$resolve(null);
});
}
});
}
if (count($promises) > 0) {
$this->loop->wait($promises);
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/IO/NullIO.php | src/Composer/IO/NullIO.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\IO;
/**
* IOInterface that is not interactive and never writes the output
*
* @author Christophe Coevoet <stof@notk.org>
*/
class NullIO extends BaseIO
{
/**
* @inheritDoc
*/
public function isInteractive(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function isVerbose(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function isVeryVerbose(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function isDebug(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function isDecorated(): bool
{
return false;
}
/**
* @inheritDoc
*/
public function write($messages, bool $newline = true, int $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL): void
{
}
/**
* @inheritDoc
*/
public function ask($question, $default = null)
{
return $default;
}
/**
* @inheritDoc
*/
public function askConfirmation($question, $default = true): bool
{
return $default;
}
/**
* @inheritDoc
*/
public function askAndValidate($question, $validator, $attempts = null, $default = null)
{
return $default;
}
/**
* @inheritDoc
*/
public function askAndHideAnswer($question): ?string
{
return null;
}
/**
* @inheritDoc
*/
public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
{
return $default;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/IO/BufferIO.php | src/Composer/IO/BufferIO.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\IO;
use Composer\Pcre\Preg;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Output\StreamOutput;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Helper\HelperSet;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class BufferIO extends ConsoleIO
{
public function __construct(string $input = '', int $verbosity = StreamOutput::VERBOSITY_NORMAL, ?OutputFormatterInterface $formatter = null)
{
$input = new StringInput($input);
$input->setInteractive(false);
$stream = fopen('php://memory', 'rw');
if ($stream === false) {
throw new \RuntimeException('Unable to open memory output stream');
}
$output = new StreamOutput($stream, $verbosity, $formatter !== null ? $formatter->isDecorated() : false, $formatter);
parent::__construct($input, $output, new HelperSet([
new QuestionHelper(),
]));
}
/**
* @return string output
*/
public function getOutput(): string
{
assert($this->output instanceof StreamOutput);
fseek($this->output->getStream(), 0);
$output = (string) stream_get_contents($this->output->getStream());
$output = Preg::replaceCallback("{(?<=^|\n|\x08)(.+?)(\x08+)}", static function ($matches): string {
$pre = strip_tags($matches[1]);
if (strlen($pre) === strlen($matches[2])) {
return '';
}
// TODO reverse parse the string, skipping span tags and \033\[([0-9;]+)m(.*?)\033\[0m style blobs
return rtrim($matches[1])."\n";
}, $output);
return $output;
}
/**
* @param string[] $inputs
*
* @see createStream
*/
public function setUserInputs(array $inputs): void
{
if (!$this->input instanceof StreamableInputInterface) {
throw new \RuntimeException('Setting the user inputs requires at least the version 3.2 of the symfony/console component.');
}
$this->input->setStream($this->createStream($inputs));
$this->input->setInteractive(true);
}
/**
* @param string[] $inputs
*
* @return resource stream
*/
private function createStream(array $inputs)
{
$stream = fopen('php://memory', 'r+');
if ($stream === false) {
throw new \RuntimeException('Unable to open memory output stream');
}
foreach ($inputs as $input) {
fwrite($stream, $input.PHP_EOL);
}
rewind($stream);
return $stream;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/IO/IOInterface.php | src/Composer/IO/IOInterface.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\IO;
use Composer\Config;
use Psr\Log\LoggerInterface;
/**
* The Input/Output helper interface.
*
* @author François Pluchino <francois.pluchino@opendisplay.com>
*/
interface IOInterface extends LoggerInterface
{
public const QUIET = 1;
public const NORMAL = 2;
public const VERBOSE = 4;
public const VERY_VERBOSE = 8;
public const DEBUG = 16;
/**
* Is this input means interactive?
*
* @return bool
*/
public function isInteractive();
/**
* Is this output verbose?
*
* @return bool
*/
public function isVerbose();
/**
* Is the output very verbose?
*
* @return bool
*/
public function isVeryVerbose();
/**
* Is the output in debug verbosity?
*
* @return bool
*/
public function isDebug();
/**
* Is this output decorated?
*
* @return bool
*/
public function isDecorated();
/**
* Writes a message to the output.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function write($messages, bool $newline = true, int $verbosity = self::NORMAL);
/**
* Writes a message to the error output.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL);
/**
* Writes a message to the output, without formatting it.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL);
/**
* Writes a message to the error output, without formatting it.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL);
/**
* Overwrites a previous message to the output.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $size The size of line
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL);
/**
* Overwrites a previous message to the error output.
*
* @param string|string[] $messages The message as an array of lines or a single string
* @param bool $newline Whether to add a newline or not
* @param int $size The size of line
* @param int $verbosity Verbosity level from the VERBOSITY_* constants
*
* @return void
*/
public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL);
/**
* Asks a question to the user.
*
* @param string $question The question to ask
* @param string|bool|int|float|null $default The default answer if none is given by the user
*
* @throws \RuntimeException If there is no data to read in the input stream
* @return mixed The user answer
*/
public function ask(string $question, $default = null);
/**
* Asks a confirmation to the user.
*
* The question will be asked until the user answers by nothing, yes, or no.
*
* @param string $question The question to ask
* @param bool $default The default answer if the user enters nothing
*
* @return bool true if the user has confirmed, false otherwise
*/
public function askConfirmation(string $question, bool $default = true);
/**
* Asks for a value and validates the response.
*
* The validator receives the data to validate. It must return the
* validated data when the data is valid and throw an exception
* otherwise.
*
* @param string $question The question to ask
* @param callable $validator A PHP callback
* @param null|int $attempts Max number of times to ask before giving up (default of null means infinite)
* @param mixed $default The default answer if none is given by the user
*
* @throws \Exception When any of the validators return an error
* @return mixed
*/
public function askAndValidate(string $question, callable $validator, ?int $attempts = null, $default = null);
/**
* Asks a question to the user and hide the answer.
*
* @param string $question The question to ask
*
* @return string|null The answer
*/
public function askAndHideAnswer(string $question);
/**
* Asks the user to select a value.
*
* @param string $question The question to ask
* @param string[] $choices List of choices to pick from
* @param bool|string $default The default answer if the user enters nothing
* @param bool|int $attempts Max number of times to ask before giving up (false by default, which means infinite)
* @param string $errorMessage Message which will be shown if invalid value from choice list would be picked
* @param bool $multiselect Select more than one value separated by comma
*
* @throws \InvalidArgumentException
*
* @return int|string|list<string>|bool The selected value or values (the key of the choices array)
* @phpstan-return ($multiselect is true ? list<string> : string|int|bool)
*/
public function select(string $question, array $choices, $default, $attempts = false, string $errorMessage = 'Value "%s" is invalid', bool $multiselect = false);
/**
* Get all authentication information entered.
*
* @return array<string, array{username: string|null, password: string|null}> The map of authentication data
*/
public function getAuthentications();
/**
* Verify if the repository has a authentication information.
*
* @param string $repositoryName The unique name of repository
*
* @return bool
*/
public function hasAuthentication(string $repositoryName);
/**
* Get the username and password of repository.
*
* @param string $repositoryName The unique name of repository
*
* @return array{username: string|null, password: string|null}
*/
public function getAuthentication(string $repositoryName);
/**
* Set the authentication information for the repository.
*
* @param string $repositoryName The unique name of repository
* @param string $username The username
* @param null|string $password The password
*
* @return void
*/
public function setAuthentication(string $repositoryName, string $username, ?string $password = null);
/**
* Loads authentications from a config instance
*
* @return void
*/
public function loadConfiguration(Config $config);
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/IO/ConsoleIO.php | src/Composer/IO/ConsoleIO.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\IO;
use Composer\Pcre\Preg;
use Composer\Question\StrictConfirmationQuestion;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ChoiceQuestion;
use Symfony\Component\Console\Question\Question;
/**
* The Input/Output helper.
*
* @author François Pluchino <francois.pluchino@opendisplay.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ConsoleIO extends BaseIO
{
/** @var InputInterface */
protected $input;
/** @var OutputInterface */
protected $output;
/** @var HelperSet */
protected $helperSet;
/** @var string */
protected $lastMessage = '';
/** @var string */
protected $lastMessageErr = '';
/** @var float */
private $startTime;
/** @var array<IOInterface::*, OutputInterface::VERBOSITY_*> */
private $verbosityMap;
/**
* Constructor.
*
* @param InputInterface $input The input instance
* @param OutputInterface $output The output instance
* @param HelperSet $helperSet The helperSet instance
*/
public function __construct(InputInterface $input, OutputInterface $output, HelperSet $helperSet)
{
$this->input = $input;
$this->output = $output;
$this->helperSet = $helperSet;
$this->verbosityMap = [
self::QUIET => OutputInterface::VERBOSITY_QUIET,
self::NORMAL => OutputInterface::VERBOSITY_NORMAL,
self::VERBOSE => OutputInterface::VERBOSITY_VERBOSE,
self::VERY_VERBOSE => OutputInterface::VERBOSITY_VERY_VERBOSE,
self::DEBUG => OutputInterface::VERBOSITY_DEBUG,
];
}
/**
* @return void
*/
public function enableDebugging(float $startTime)
{
$this->startTime = $startTime;
}
/**
* @inheritDoc
*/
public function isInteractive()
{
return $this->input->isInteractive();
}
/**
* @inheritDoc
*/
public function isDecorated()
{
return $this->output->isDecorated();
}
/**
* @inheritDoc
*/
public function isVerbose()
{
return $this->output->isVerbose();
}
/**
* @inheritDoc
*/
public function isVeryVerbose()
{
return $this->output->isVeryVerbose();
}
/**
* @inheritDoc
*/
public function isDebug()
{
return $this->output->isDebug();
}
/**
* @inheritDoc
*/
public function write($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$messages = self::sanitize($messages);
$this->doWrite($messages, $newline, false, $verbosity);
}
/**
* @inheritDoc
*/
public function writeError($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$messages = self::sanitize($messages);
$this->doWrite($messages, $newline, true, $verbosity);
}
/**
* @inheritDoc
*/
public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$this->doWrite($messages, $newline, false, $verbosity, true);
}
/**
* @inheritDoc
*/
public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$this->doWrite($messages, $newline, true, $verbosity, true);
}
/**
* @param string[]|string $messages
*/
private function doWrite($messages, bool $newline, bool $stderr, int $verbosity, bool $raw = false): void
{
$sfVerbosity = $this->verbosityMap[$verbosity];
if ($sfVerbosity > $this->output->getVerbosity()) {
return;
}
if ($raw) {
$sfVerbosity |= OutputInterface::OUTPUT_RAW;
}
if (null !== $this->startTime) {
$memoryUsage = memory_get_usage() / 1024 / 1024;
$timeSpent = microtime(true) - $this->startTime;
$messages = array_map(static function ($message) use ($memoryUsage, $timeSpent): string {
return sprintf('[%.1fMiB/%.2fs] %s', $memoryUsage, $timeSpent, $message);
}, (array) $messages);
}
if (true === $stderr && $this->output instanceof ConsoleOutputInterface) {
$this->output->getErrorOutput()->write($messages, $newline, $sfVerbosity);
$this->lastMessageErr = implode($newline ? "\n" : '', (array) $messages);
return;
}
$this->output->write($messages, $newline, $sfVerbosity);
$this->lastMessage = implode($newline ? "\n" : '', (array) $messages);
}
/**
* @inheritDoc
*/
public function overwrite($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL)
{
$this->doOverwrite($messages, $newline, $size, false, $verbosity);
}
/**
* @inheritDoc
*/
public function overwriteError($messages, bool $newline = true, ?int $size = null, int $verbosity = self::NORMAL)
{
$this->doOverwrite($messages, $newline, $size, true, $verbosity);
}
/**
* @param string[]|string $messages
*/
private function doOverwrite($messages, bool $newline, ?int $size, bool $stderr, int $verbosity): void
{
// messages can be an array, let's convert it to string anyway
$messages = implode($newline ? "\n" : '', (array) $messages);
// since overwrite is supposed to overwrite last message...
if (!isset($size)) {
// removing possible formatting of lastMessage with strip_tags
$size = strlen(strip_tags($stderr ? $this->lastMessageErr : $this->lastMessage));
}
// ...let's fill its length with backspaces
$this->doWrite(str_repeat("\x08", $size), false, $stderr, $verbosity);
// write the new message
$this->doWrite($messages, false, $stderr, $verbosity);
// In cmd.exe on Win8.1 (possibly 10?), the line can not be cleared, so we need to
// track the length of previous output and fill it with spaces to make sure the line is cleared.
// See https://github.com/composer/composer/pull/5836 for more details
$fill = $size - strlen(strip_tags($messages));
if ($fill > 0) {
// whitespace whatever has left
$this->doWrite(str_repeat(' ', $fill), false, $stderr, $verbosity);
// move the cursor back
$this->doWrite(str_repeat("\x08", $fill), false, $stderr, $verbosity);
}
if ($newline) {
$this->doWrite('', true, $stderr, $verbosity);
}
if ($stderr) {
$this->lastMessageErr = $messages;
} else {
$this->lastMessage = $messages;
}
}
/**
* @return ProgressBar
*/
public function getProgressBar(int $max = 0)
{
return new ProgressBar($this->getErrorOutput(), $max);
}
/**
* @inheritDoc
*/
public function ask($question, $default = null)
{
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
$helper = $this->helperSet->get('question');
$question = new Question(self::sanitize($question), is_string($default) ? self::sanitize($default) : $default);
return $helper->ask($this->input, $this->getErrorOutput(), $question);
}
/**
* @inheritDoc
*/
public function askConfirmation($question, $default = true)
{
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
$helper = $this->helperSet->get('question');
$question = new StrictConfirmationQuestion(self::sanitize($question), is_string($default) ? self::sanitize($default) : $default);
return $helper->ask($this->input, $this->getErrorOutput(), $question);
}
/**
* @inheritDoc
*/
public function askAndValidate($question, $validator, $attempts = null, $default = null)
{
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
$helper = $this->helperSet->get('question');
$question = new Question(self::sanitize($question), is_string($default) ? self::sanitize($default) : $default);
$question->setValidator($validator);
$question->setMaxAttempts($attempts);
return $helper->ask($this->input, $this->getErrorOutput(), $question);
}
/**
* @inheritDoc
*/
public function askAndHideAnswer($question)
{
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
$helper = $this->helperSet->get('question');
$question = new Question(self::sanitize($question));
$question->setHidden(true);
return $helper->ask($this->input, $this->getErrorOutput(), $question);
}
/**
* @inheritDoc
*/
public function select($question, $choices, $default, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
{
/** @var \Symfony\Component\Console\Helper\QuestionHelper $helper */
$helper = $this->helperSet->get('question');
$question = new ChoiceQuestion(self::sanitize($question), self::sanitize($choices), is_string($default) ? self::sanitize($default) : $default);
$question->setMaxAttempts($attempts ?: null); // IOInterface requires false, and Question requires null or int
$question->setErrorMessage($errorMessage);
$question->setMultiselect($multiselect);
$result = $helper->ask($this->input, $this->getErrorOutput(), $question);
$isAssoc = (bool) \count(array_filter(array_keys($choices), 'is_string'));
if ($isAssoc) {
return $result;
}
if (!is_array($result)) {
return (string) array_search($result, $choices, true);
}
$results = [];
foreach ($choices as $index => $choice) {
if (in_array($choice, $result, true)) {
$results[] = (string) $index;
}
}
return $results;
}
public function getTable(): Table
{
return new Table($this->output);
}
private function getErrorOutput(): OutputInterface
{
if ($this->output instanceof ConsoleOutputInterface) {
return $this->output->getErrorOutput();
}
return $this->output;
}
/**
* Sanitize string to remove control characters
*
* If $allowNewlines is true, \x0A (\n) and \x0D\x0A (\r\n) are let through. Single \r are still sanitized away to prevent overwriting whole lines.
*
* All other control chars (except NULL bytes) as well as ANSI escape sequences are removed.
*
* Invalid unicode sequences are turned into question marks.
*
* @param string|iterable<string> $messages
* @return string|array<string>
* @phpstan-return ($messages is string ? string : array<string>)
*/
public static function sanitize($messages, bool $allowNewlines = true)
{
// Match ANSI escape sequences:
// - CSI (Control Sequence Introducer): ESC [ params intermediate final
// - OSC (Operating System Command): ESC ] ... ESC \ or BEL
// - Other ESC sequences: ESC followed by any character
$escapePattern = '\x1B\[[\x30-\x3F]*[\x20-\x2F]*[\x40-\x7E]|\x1B\].*?(?:\x1B\\\\|\x07)|\x1B.';
$pattern = $allowNewlines ? "{{$escapePattern}|[\x01-\x09\x0B\x0C\x0E-\x1A]|\r(?!\n)}u" : "{{$escapePattern}|[\x01-\x1A]}u";
if (is_string($messages)) {
$messages = self::ensureValidUtf8($messages);
return Preg::replace($pattern, '', $messages);
}
$sanitized = [];
foreach ($messages as $key => $message) {
$message = self::ensureValidUtf8($message);
$sanitized[$key] = Preg::replace($pattern, '', $message);
}
return $sanitized;
}
/**
* Ensures a string is valid UTF-8, replacing invalid byte sequences with '?'
*/
private static function ensureValidUtf8(string $string): string
{
// Quick check: if string is already valid UTF-8, return as-is
if (function_exists('mb_check_encoding') && mb_check_encoding($string, 'UTF-8')) {
return $string;
}
// Use mb_convert_encoding to replace invalid sequences with '?'
// This makes it visible when data quality issues occur
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, 'UTF-8', 'UTF-8');
}
// Fallback to iconv if mbstring unavailable
if (function_exists('iconv')) {
$cleaned = @iconv('UTF-8', 'UTF-8//TRANSLIT', $string);
if ($cleaned !== false) {
return $cleaned;
}
}
// Last resort: return as-is (should never happen - Composer requires mbstring OR iconv)
return $string;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/IO/BaseIO.php | src/Composer/IO/BaseIO.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\IO;
use Composer\Config;
use Composer\Pcre\Preg;
use Composer\Util\ProcessExecutor;
use Composer\Util\Silencer;
use Psr\Log\LogLevel;
abstract class BaseIO implements IOInterface
{
/** @var array<string, array{username: string|null, password: string|null}> */
protected $authentications = [];
/**
* @inheritDoc
*/
public function getAuthentications()
{
return $this->authentications;
}
/**
* @return void
*/
public function resetAuthentications()
{
$this->authentications = [];
}
/**
* @inheritDoc
*/
public function hasAuthentication($repositoryName)
{
return isset($this->authentications[$repositoryName]);
}
/**
* @inheritDoc
*/
public function getAuthentication($repositoryName)
{
if (isset($this->authentications[$repositoryName])) {
return $this->authentications[$repositoryName];
}
return ['username' => null, 'password' => null];
}
/**
* @inheritDoc
*/
public function setAuthentication($repositoryName, $username, $password = null)
{
$this->authentications[$repositoryName] = ['username' => $username, 'password' => $password];
}
/**
* @inheritDoc
*/
public function writeRaw($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$this->write($messages, $newline, $verbosity);
}
/**
* @inheritDoc
*/
public function writeErrorRaw($messages, bool $newline = true, int $verbosity = self::NORMAL)
{
$this->writeError($messages, $newline, $verbosity);
}
/**
* Check for overwrite and set the authentication information for the repository.
*
* @param string $repositoryName The unique name of repository
* @param string $username The username
* @param string $password The password
*
* @return void
*/
protected function checkAndSetAuthentication(string $repositoryName, string $username, ?string $password = null)
{
if ($this->hasAuthentication($repositoryName)) {
$auth = $this->getAuthentication($repositoryName);
if ($auth['username'] === $username && $auth['password'] === $password) {
return;
}
$this->writeError(
sprintf(
"<warning>Warning: You should avoid overwriting already defined auth settings for %s.</warning>",
$repositoryName
)
);
}
$this->setAuthentication($repositoryName, $username, $password);
}
/**
* @inheritDoc
*/
public function loadConfiguration(Config $config)
{
$bitbucketOauth = $config->get('bitbucket-oauth');
$githubOauth = $config->get('github-oauth');
$gitlabOauth = $config->get('gitlab-oauth');
$gitlabToken = $config->get('gitlab-token');
$forgejoToken = $config->get('forgejo-token');
$httpBasic = $config->get('http-basic');
$bearerToken = $config->get('bearer');
$customHeaders = $config->get('custom-headers');
$clientCertificate = $config->get('client-certificate');
// reload oauth tokens from config if available
foreach ($bitbucketOauth as $domain => $cred) {
$this->checkAndSetAuthentication($domain, $cred['consumer-key'], $cred['consumer-secret']);
}
foreach ($githubOauth as $domain => $token) {
if ($domain !== 'github.com' && !in_array($domain, $config->get('github-domains'), true)) {
$this->debug($domain.' is not in the configured github-domains, adding it implicitly as authentication is configured for this domain');
$config->merge(['config' => ['github-domains' => array_merge($config->get('github-domains'), [$domain])]], 'implicit-due-to-auth');
}
// allowed chars for GH tokens are from https://github.blog/changelog/2021-03-04-authentication-token-format-updates/
// plus dots which were at some point used for GH app integration tokens
if (!Preg::isMatch('{^[.A-Za-z0-9_]+$}', $token)) {
throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"');
}
$this->checkAndSetAuthentication($domain, $token, 'x-oauth-basic');
}
foreach ($gitlabOauth as $domain => $token) {
if ($domain !== 'gitlab.com' && !in_array($domain, $config->get('gitlab-domains'), true)) {
$this->debug($domain.' is not in the configured gitlab-domains, adding it implicitly as authentication is configured for this domain');
$config->merge(['config' => ['gitlab-domains' => array_merge($config->get('gitlab-domains'), [$domain])]], 'implicit-due-to-auth');
}
$token = is_array($token) ? $token["token"] : $token;
$this->checkAndSetAuthentication($domain, $token, 'oauth2');
}
foreach ($gitlabToken as $domain => $token) {
if ($domain !== 'gitlab.com' && !in_array($domain, $config->get('gitlab-domains'), true)) {
$this->debug($domain.' is not in the configured gitlab-domains, adding it implicitly as authentication is configured for this domain');
$config->merge(['config' => ['gitlab-domains' => array_merge($config->get('gitlab-domains'), [$domain])]], 'implicit-due-to-auth');
}
$username = is_array($token) ? $token["username"] : $token;
$password = is_array($token) ? $token["token"] : 'private-token';
$this->checkAndSetAuthentication($domain, $username, $password);
}
foreach ($forgejoToken as $domain => $cred) {
if (!in_array($domain, $config->get('forgejo-domains'), true)) {
$this->debug($domain.' is not in the configured forgejo-domains, adding it implicitly as authentication is configured for this domain');
$config->merge(['config' => ['forgejo-domains' => array_merge($config->get('forgejo-domains'), [$domain])]], 'implicit-due-to-auth');
}
$this->checkAndSetAuthentication($domain, $cred['username'], $cred['token']);
}
// reload http basic credentials from config if available
foreach ($httpBasic as $domain => $cred) {
$this->checkAndSetAuthentication($domain, $cred['username'], $cred['password']);
}
foreach ($bearerToken as $domain => $token) {
$this->checkAndSetAuthentication($domain, $token, 'bearer');
}
// load custom HTTP headers from config
foreach ($customHeaders as $domain => $headers) {
if ($headers !== null) {
$this->checkAndSetAuthentication($domain, (string) json_encode($headers), 'custom-headers');
}
}
// reload ssl client certificate credentials from config if available
foreach ($clientCertificate as $domain => $cred) {
$sslOptions = array_filter(
[
'local_cert' => $cred['local_cert'] ?? null,
'local_pk' => $cred['local_pk'] ?? null,
'passphrase' => $cred['passphrase'] ?? null,
],
static function (?string $value): bool { return $value !== null; }
);
if (!isset($sslOptions['local_cert'])) {
$this->writeError(
sprintf(
'<warning>Warning: Client certificate configuration is missing key `local_cert` for %s.</warning>',
$domain
)
);
continue;
}
$this->checkAndSetAuthentication($domain, 'client-certificate', (string) json_encode($sslOptions));
}
// setup process timeout
ProcessExecutor::setTimeout($config->get('process-timeout'));
}
/**
* @param string|\Stringable $message
*/
public function emergency($message, array $context = []): void
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function alert($message, array $context = []): void
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function critical($message, array $context = []): void
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function error($message, array $context = []): void
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function warning($message, array $context = []): void
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function notice($message, array $context = []): void
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function info($message, array $context = []): void
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* @param string|\Stringable $message
*/
public function debug($message, array $context = []): void
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* @param mixed|LogLevel::* $level
* @param string|\Stringable $message
*/
public function log($level, $message, array $context = []): void
{
$message = (string) $message;
if ($context !== []) {
$json = Silencer::call('json_encode', $context, JSON_INVALID_UTF8_IGNORE | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($json !== false) {
$message .= ' ' . $json;
}
}
if (in_array($level, [LogLevel::EMERGENCY, LogLevel::ALERT, LogLevel::CRITICAL, LogLevel::ERROR])) {
$this->writeError('<error>'.$message.'</error>');
} elseif ($level === LogLevel::WARNING) {
$this->writeError('<warning>'.$message.'</warning>');
} elseif ($level === LogLevel::NOTICE) {
$this->writeError('<info>'.$message.'</info>', true, self::VERBOSE);
} elseif ($level === LogLevel::INFO) {
$this->writeError('<info>'.$message.'</info>', true, self::VERY_VERBOSE);
} else {
$this->writeError($message, true, self::DEBUG);
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/VersionCacheInterface.php | src/Composer/Repository/VersionCacheInterface.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;
interface VersionCacheInterface
{
/**
* @return mixed[]|null|false Package version data if found, false to indicate the identifier is known but has no package, null for an unknown identifier
*/
public function getVersionPackage(string $version, string $identifier);
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/ArrayRepository.php | src/Composer/Repository/ArrayRepository.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;
use Composer\Package\AliasPackage;
use Composer\Package\BasePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\CompletePackage;
use Composer\Package\PackageInterface;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Version\VersionParser;
use Composer\Package\Version\StabilityFilter;
use Composer\Pcre\Preg;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\Constraint;
/**
* A repository implementation that simply stores packages in an array
*
* @author Nils Adermann <naderman@naderman.de>
*/
class ArrayRepository implements RepositoryInterface
{
/** @var ?array<BasePackage> */
protected $packages = null;
/**
* @var ?array<BasePackage> indexed by package unique name and used to cache hasPackage calls
*/
protected $packageMap = null;
/**
* @param array<PackageInterface> $packages
*/
public function __construct(array $packages = [])
{
foreach ($packages as $package) {
$this->addPackage($package);
}
}
public function getRepoName()
{
return 'array repo (defining '.$this->count().' package'.($this->count() > 1 ? 's' : '').')';
}
/**
* @inheritDoc
*/
public function loadPackages(array $packageNameMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = [])
{
$packages = $this->getPackages();
$result = [];
$namesFound = [];
foreach ($packages as $package) {
if (array_key_exists($package->getName(), $packageNameMap)) {
if (
(!$packageNameMap[$package->getName()] || $packageNameMap[$package->getName()]->matches(new Constraint('==', $package->getVersion())))
&& StabilityFilter::isPackageAcceptable($acceptableStabilities, $stabilityFlags, $package->getNames(), $package->getStability())
&& !isset($alreadyLoaded[$package->getName()][$package->getVersion()])
) {
// add selected packages which match stability requirements
$result[spl_object_hash($package)] = $package;
// add the aliased package for packages where the alias matches
if ($package instanceof AliasPackage && !isset($result[spl_object_hash($package->getAliasOf())])) {
$result[spl_object_hash($package->getAliasOf())] = $package->getAliasOf();
}
}
$namesFound[$package->getName()] = true;
}
}
// add aliases of packages that were selected, even if the aliases did not match
foreach ($packages as $package) {
if ($package instanceof AliasPackage) {
if (isset($result[spl_object_hash($package->getAliasOf())])) {
$result[spl_object_hash($package)] = $package;
}
}
}
return ['namesFound' => array_keys($namesFound), 'packages' => $result];
}
/**
* @inheritDoc
*/
public function findPackage(string $name, $constraint)
{
$name = strtolower($name);
if (!$constraint instanceof ConstraintInterface) {
$versionParser = new VersionParser();
$constraint = $versionParser->parseConstraints($constraint);
}
foreach ($this->getPackages() as $package) {
if ($name === $package->getName()) {
$pkgConstraint = new Constraint('==', $package->getVersion());
if ($constraint->matches($pkgConstraint)) {
return $package;
}
}
}
return null;
}
/**
* @inheritDoc
*/
public function findPackages(string $name, $constraint = null)
{
// normalize name
$name = strtolower($name);
$packages = [];
if (null !== $constraint && !$constraint instanceof ConstraintInterface) {
$versionParser = new VersionParser();
$constraint = $versionParser->parseConstraints($constraint);
}
foreach ($this->getPackages() as $package) {
if ($name === $package->getName()) {
if (null === $constraint || $constraint->matches(new Constraint('==', $package->getVersion()))) {
$packages[] = $package;
}
}
}
return $packages;
}
/**
* @inheritDoc
*/
public function search(string $query, int $mode = 0, ?string $type = null)
{
if ($mode === self::SEARCH_FULLTEXT) {
$regex = '{(?:'.implode('|', Preg::split('{\s+}', preg_quote($query))).')}i';
} else {
// vendor/name searches expect the caller to have preg_quoted the query
$regex = '{(?:'.implode('|', Preg::split('{\s+}', $query)).')}i';
}
$matches = [];
foreach ($this->getPackages() as $package) {
$name = $package->getName();
if ($mode === self::SEARCH_VENDOR) {
[$name] = explode('/', $name);
}
if (isset($matches[$name])) {
continue;
}
if (null !== $type && $package->getType() !== $type) {
continue;
}
if (Preg::isMatch($regex, $name)
|| ($mode === self::SEARCH_FULLTEXT && $package instanceof CompletePackageInterface && Preg::isMatch($regex, implode(' ', (array) $package->getKeywords()) . ' ' . $package->getDescription()))
) {
if ($mode === self::SEARCH_VENDOR) {
$matches[$name] = [
'name' => $name,
'description' => null,
];
} else {
$matches[$name] = [
'name' => $package->getPrettyName(),
'description' => $package instanceof CompletePackageInterface ? $package->getDescription() : null,
];
if ($package instanceof CompletePackageInterface && $package->isAbandoned()) {
$matches[$name]['abandoned'] = $package->getReplacementPackage() ?: true;
}
}
}
}
return array_values($matches);
}
/**
* @inheritDoc
*/
public function hasPackage(PackageInterface $package)
{
if ($this->packageMap === null) {
$this->packageMap = [];
foreach ($this->getPackages() as $repoPackage) {
$this->packageMap[$repoPackage->getUniqueName()] = $repoPackage;
}
}
return isset($this->packageMap[$package->getUniqueName()]);
}
/**
* Adds a new package to the repository
*
* @return void
*/
public function addPackage(PackageInterface $package)
{
if (!$package instanceof BasePackage) {
throw new \InvalidArgumentException('Only subclasses of BasePackage are supported');
}
if (null === $this->packages) {
$this->initialize();
}
$package->setRepository($this);
$this->packages[] = $package;
if ($package instanceof AliasPackage) {
$aliasedPackage = $package->getAliasOf();
if (null === $aliasedPackage->getRepository()) {
$this->addPackage($aliasedPackage);
}
}
// invalidate package map cache
$this->packageMap = null;
}
/**
* @inheritDoc
*/
public function getProviders(string $packageName)
{
$result = [];
foreach ($this->getPackages() as $candidate) {
if (isset($result[$candidate->getName()])) {
continue;
}
foreach ($candidate->getProvides() as $link) {
if ($packageName === $link->getTarget()) {
$result[$candidate->getName()] = [
'name' => $candidate->getName(),
'description' => $candidate instanceof CompletePackageInterface ? $candidate->getDescription() : null,
'type' => $candidate->getType(),
];
continue 2;
}
}
}
return $result;
}
/**
* @return AliasPackage|CompleteAliasPackage
*/
protected function createAliasPackage(BasePackage $package, string $alias, string $prettyAlias)
{
while ($package instanceof AliasPackage) {
$package = $package->getAliasOf();
}
if ($package instanceof CompletePackage) {
return new CompleteAliasPackage($package, $alias, $prettyAlias);
}
return new AliasPackage($package, $alias, $prettyAlias);
}
/**
* Removes package from repository.
*
* @param PackageInterface $package package instance
*
* @return void
*/
public function removePackage(PackageInterface $package)
{
$packageId = $package->getUniqueName();
foreach ($this->getPackages() as $key => $repoPackage) {
if ($packageId === $repoPackage->getUniqueName()) {
array_splice($this->packages, $key, 1);
// invalidate package map cache
$this->packageMap = null;
return;
}
}
}
/**
* @inheritDoc
*/
public function getPackages()
{
if (null === $this->packages) {
$this->initialize();
}
if (null === $this->packages) {
throw new \LogicException('initialize failed to initialize the packages array');
}
return $this->packages;
}
/**
* Returns the number of packages in this repository
*
* @return 0|positive-int Number of packages
*/
public function count(): int
{
if (null === $this->packages) {
$this->initialize();
}
return count($this->packages);
}
/**
* Initializes the packages array. Mostly meant as an extension point.
*
* @return void
*/
protected function initialize()
{
$this->packages = [];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/CompositeRepository.php | src/Composer/Repository/CompositeRepository.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;
use Composer\Package\BasePackage;
use Composer\Package\PackageInterface;
/**
* Composite repository.
*
* @author Beau Simensen <beau@dflydev.com>
*/
class CompositeRepository implements RepositoryInterface
{
/**
* List of repositories
* @var RepositoryInterface[]
*/
private $repositories;
/**
* Constructor
* @param RepositoryInterface[] $repositories
*/
public function __construct(array $repositories)
{
$this->repositories = [];
foreach ($repositories as $repo) {
$this->addRepository($repo);
}
}
public function getRepoName(): string
{
return 'composite repo ('.implode(', ', array_map(static function ($repo): string {
return $repo->getRepoName();
}, $this->repositories)).')';
}
/**
* Returns all the wrapped repositories
*
* @return RepositoryInterface[]
*/
public function getRepositories(): array
{
return $this->repositories;
}
/**
* @inheritDoc
*/
public function hasPackage(PackageInterface $package): bool
{
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
if ($repository->hasPackage($package)) {
return true;
}
}
return false;
}
/**
* @inheritDoc
*/
public function findPackage($name, $constraint): ?BasePackage
{
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$package = $repository->findPackage($name, $constraint);
if (null !== $package) {
return $package;
}
}
return null;
}
/**
* @inheritDoc
*/
public function findPackages($name, $constraint = null): array
{
$packages = [];
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$packages[] = $repository->findPackages($name, $constraint);
}
return $packages ? array_merge(...$packages) : [];
}
/**
* @inheritDoc
*/
public function loadPackages(array $packageNameMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = []): array
{
$packages = [];
$namesFound = [];
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$result = $repository->loadPackages($packageNameMap, $acceptableStabilities, $stabilityFlags, $alreadyLoaded);
$packages[] = $result['packages'];
$namesFound[] = $result['namesFound'];
}
return [
'packages' => $packages ? array_merge(...$packages) : [],
'namesFound' => $namesFound ? array_unique(array_merge(...$namesFound)) : [],
];
}
/**
* @inheritDoc
*/
public function search(string $query, int $mode = 0, ?string $type = null): array
{
$matches = [];
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$matches[] = $repository->search($query, $mode, $type);
}
return \count($matches) > 0 ? array_merge(...$matches) : [];
}
/**
* @inheritDoc
*/
public function getPackages(): array
{
$packages = [];
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$packages[] = $repository->getPackages();
}
return $packages ? array_merge(...$packages) : [];
}
/**
* @inheritDoc
*/
public function getProviders($packageName): array
{
$results = [];
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$results[] = $repository->getProviders($packageName);
}
return $results ? array_merge(...$results) : [];
}
public function removePackage(PackageInterface $package): void
{
foreach ($this->repositories as $repository) {
if ($repository instanceof WritableRepositoryInterface) {
$repository->removePackage($package);
}
}
}
/**
* @inheritDoc
*/
public function count(): int
{
$total = 0;
foreach ($this->repositories as $repository) {
/* @var $repository RepositoryInterface */
$total += $repository->count();
}
return $total;
}
/**
* Add a repository.
*/
public function addRepository(RepositoryInterface $repository): void
{
if ($repository instanceof self) {
foreach ($repository->getRepositories() as $repo) {
$this->addRepository($repo);
}
} else {
$this->repositories[] = $repository;
}
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositoryUtils.php | src/Composer/Repository/RepositoryUtils.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;
use Composer\Package\PackageInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @see RepositorySet for ways to work with sets of repos
*/
class RepositoryUtils
{
/**
* Find all of $packages which are required by $requirer, either directly or transitively
*
* Require-dev is ignored by default, you can enable the require-dev of the initial $requirer
* packages by passing $includeRequireDev=true, but require-dev of transitive dependencies
* are always ignored.
*
* @template T of PackageInterface
* @param array<T> $packages
* @param list<T> $bucket Do not pass this in, only used to avoid recursion with circular deps
* @return list<T>
*/
public static function filterRequiredPackages(array $packages, PackageInterface $requirer, bool $includeRequireDev = false, array $bucket = []): array
{
$requires = $requirer->getRequires();
if ($includeRequireDev) {
$requires = array_merge($requires, $requirer->getDevRequires());
}
foreach ($packages as $candidate) {
foreach ($candidate->getNames() as $name) {
if (isset($requires[$name])) {
if (!in_array($candidate, $bucket, true)) {
$bucket[] = $candidate;
$bucket = self::filterRequiredPackages($packages, $candidate, false, $bucket);
}
break;
}
}
}
return $bucket;
}
/**
* Unwraps CompositeRepository, InstalledRepository and optionally FilterRepository to get a flat array of pure repository instances
*
* @return RepositoryInterface[]
*/
public static function flattenRepositories(RepositoryInterface $repo, bool $unwrapFilterRepos = true): array
{
// unwrap filter repos
if ($unwrapFilterRepos && $repo instanceof FilterRepository) {
$repo = $repo->getRepository();
}
if (!$repo instanceof CompositeRepository) {
return [$repo];
}
$repos = [];
foreach ($repo->getRepositories() as $r) {
foreach (self::flattenRepositories($r, $unwrapFilterRepos) as $r2) {
$repos[] = $r2;
}
}
return $repos;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/FilesystemRepository.php | src/Composer/Repository/FilesystemRepository.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;
use Composer\Json\JsonFile;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\PackageInterface;
use Composer\Package\RootAliasPackage;
use Composer\Package\RootPackageInterface;
use Composer\Package\AliasPackage;
use Composer\Package\Dumper\ArrayDumper;
use Composer\Installer\InstallationManager;
use Composer\Pcre\Preg;
use Composer\Util\Filesystem;
use Composer\Util\Platform;
/**
* Filesystem repository.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class FilesystemRepository extends WritableArrayRepository
{
/** @var JsonFile */
protected $file;
/** @var bool */
private $dumpVersions;
/** @var ?RootPackageInterface */
private $rootPackage;
/** @var Filesystem */
private $filesystem;
/** @var bool|null */
private $devMode = null;
/**
* Initializes filesystem repository.
*
* @param JsonFile $repositoryFile repository json file
* @param ?RootPackageInterface $rootPackage Must be provided if $dumpVersions is true
*/
public function __construct(JsonFile $repositoryFile, bool $dumpVersions = false, ?RootPackageInterface $rootPackage = null, ?Filesystem $filesystem = null)
{
parent::__construct();
$this->file = $repositoryFile;
$this->dumpVersions = $dumpVersions;
$this->rootPackage = $rootPackage;
$this->filesystem = $filesystem ?: new Filesystem;
if ($dumpVersions && !$rootPackage) {
throw new \InvalidArgumentException('Expected a root package instance if $dumpVersions is true');
}
}
/**
* @return bool|null true if dev requirements were installed, false if --no-dev was used, null if yet unknown
*/
public function getDevMode()
{
return $this->devMode;
}
/**
* Initializes repository (reads file, or remote address).
*/
protected function initialize()
{
parent::initialize();
if (!$this->file->exists()) {
return;
}
try {
$data = $this->file->read();
if (isset($data['packages'])) {
$packages = $data['packages'];
} else {
$packages = $data;
}
if (isset($data['dev-package-names'])) {
$this->setDevPackageNames($data['dev-package-names']);
}
if (isset($data['dev'])) {
$this->devMode = $data['dev'];
}
if (!is_array($packages)) {
throw new \UnexpectedValueException('Could not parse package list from the repository');
}
} catch (\Exception $e) {
throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage());
}
$loader = new ArrayLoader(null, true);
foreach ($packages as $packageData) {
$package = $loader->load($packageData);
$this->addPackage($package);
}
}
public function reload()
{
$this->packages = null;
$this->initialize();
}
/**
* Writes writable repository.
*/
public function write(bool $devMode, InstallationManager $installationManager)
{
$data = ['packages' => [], 'dev' => $devMode, 'dev-package-names' => []];
$dumper = new ArrayDumper();
// make sure the directory is created so we can realpath it
// as realpath() does some additional normalizations with network paths that normalizePath does not
// and we need to find shortest path correctly
$repoDir = dirname($this->file->getPath());
$this->filesystem->ensureDirectoryExists($repoDir);
$repoDir = $this->filesystem->normalizePath(realpath($repoDir));
$installPaths = [];
foreach ($this->getCanonicalPackages() as $package) {
$pkgArray = $dumper->dump($package);
$path = $installationManager->getInstallPath($package);
$installPath = null;
if ('' !== $path && null !== $path) {
$normalizedPath = $this->filesystem->normalizePath($this->filesystem->isAbsolutePath($path) ? $path : Platform::getCwd() . '/' . $path);
$installPath = $this->filesystem->findShortestPath($repoDir, $normalizedPath, true);
}
$installPaths[$package->getName()] = $installPath;
$pkgArray['install-path'] = $installPath;
$data['packages'][] = $pkgArray;
// only write to the files the names which are really installed, as we receive the full list
// of dev package names before they get installed during composer install
if (in_array($package->getName(), $this->devPackageNames, true)) {
$data['dev-package-names'][] = $package->getName();
}
}
sort($data['dev-package-names']);
usort($data['packages'], static function ($a, $b): int {
return strcmp($a['name'], $b['name']);
});
$this->file->write($data);
if ($this->dumpVersions) {
$versions = $this->generateInstalledVersions($installationManager, $installPaths, $devMode, $repoDir);
$this->filesystem->filePutContentsIfModified($repoDir.'/installed.php', '<?php return ' . $this->dumpToPhpCode($versions) . ';'."\n");
$installedVersionsClass = file_get_contents(__DIR__.'/../InstalledVersions.php');
// this normally should not happen but during upgrades of Composer when it is installed in the project it is a possibility
if ($installedVersionsClass !== false) {
$this->filesystem->filePutContentsIfModified($repoDir.'/InstalledVersions.php', $installedVersionsClass);
// make sure the in memory state is up to date with on disk
\Composer\InstalledVersions::reload($versions);
// make sure the selfDir matches the expected data at runtime if the class was loaded from the vendor dir, as it may have been
// loaded from the Composer sources, causing packages to appear twice in that case if the installed.php is loaded in addition to the
// in memory loaded data from above
try {
$reflProp = new \ReflectionProperty(\Composer\InstalledVersions::class, 'selfDir');
(\PHP_VERSION_ID < 80100) and $reflProp->setAccessible(true);
$reflProp->setValue(null, strtr($repoDir, '\\', '/'));
$reflProp = new \ReflectionProperty(\Composer\InstalledVersions::class, 'installedIsLocalDir');
(\PHP_VERSION_ID < 80100) and $reflProp->setAccessible(true);
$reflProp->setValue(null, true);
} catch (\ReflectionException $e) {
if (!Preg::isMatch('{Property .*? does not exist}i', $e->getMessage())) {
throw $e;
}
// noop, if outdated class is loaded we do not want to cause trouble
}
}
}
}
/**
* As we load the file from vendor dir during bootstrap, we need to make sure it contains only expected code before executing it
*
* @internal
*/
public static function safelyLoadInstalledVersions(string $path): bool
{
$installedVersionsData = @file_get_contents($path);
$pattern = <<<'REGEX'
{(?(DEFINE)
(?<number> -? \s*+ \d++ (?:\.\d++)? )
(?<boolean> true | false | null )
(?<strings> (?&string) (?: \s*+ \. \s*+ (?&string))*+ )
(?<string> (?: " (?:[^"\\$]*+ | \\ ["\\0] )* " | ' (?:[^'\\]*+ | \\ ['\\] )* ' ) )
(?<array> array\( \s*+ (?: (?:(?&number)|(?&strings)) \s*+ => \s*+ (?: (?:__DIR__ \s*+ \. \s*+)? (?&strings) | (?&value) ) \s*+, \s*+ )*+ \s*+ \) )
(?<value> (?: (?&number) | (?&boolean) | (?&strings) | (?&array) ) )
)
^<\?php\s++return\s++(?&array)\s*+;$}ix
REGEX;
if (is_string($installedVersionsData) && Preg::isMatch($pattern, trim($installedVersionsData))) {
\Composer\InstalledVersions::reload(eval('?>'.Preg::replace('{=>\s*+__DIR__\s*+\.\s*+([\'"])}', '=> '.var_export(dirname($path), true).' . $1', $installedVersionsData)));
return true;
}
return false;
}
/**
* @param array<mixed> $array
*/
private function dumpToPhpCode(array $array = [], int $level = 0): string
{
$lines = "array(\n";
$level++;
foreach ($array as $key => $value) {
$lines .= str_repeat(' ', $level);
$lines .= is_int($key) ? $key . ' => ' : var_export($key, true) . ' => ';
if (is_array($value)) {
if (!empty($value)) {
$lines .= $this->dumpToPhpCode($value, $level);
} else {
$lines .= "array(),\n";
}
} elseif ($key === 'install_path' && is_string($value)) {
if ($this->filesystem->isAbsolutePath($value)) {
$lines .= var_export($value, true) . ",\n";
} else {
$lines .= "__DIR__ . " . var_export('/' . $value, true) . ",\n";
}
} elseif (is_string($value)) {
$lines .= var_export($value, true) . ",\n";
} elseif (is_bool($value)) {
$lines .= ($value ? 'true' : 'false') . ",\n";
} elseif (is_null($value)) {
$lines .= "null,\n";
} else {
throw new \UnexpectedValueException('Unexpected type '.get_debug_type($value));
}
}
$lines .= str_repeat(' ', $level - 1) . ')' . ($level - 1 === 0 ? '' : ",\n");
return $lines;
}
/**
* @param array<string, string> $installPaths
*
* @return array{root: array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}, versions: array<string, array{pretty_version?: string, version?: string, reference?: string|null, type?: string, install_path?: string, aliases?: string[], dev_requirement: bool, replaced?: string[], provided?: string[]}>}
*/
private function generateInstalledVersions(InstallationManager $installationManager, array $installPaths, bool $devMode, string $repoDir): array
{
$devPackages = array_flip($this->devPackageNames);
$packages = $this->getPackages();
if (null === $this->rootPackage) {
throw new \LogicException('It should not be possible to dump packages if no root package is given');
}
$packages[] = $rootPackage = $this->rootPackage;
while ($rootPackage instanceof RootAliasPackage) {
$rootPackage = $rootPackage->getAliasOf();
$packages[] = $rootPackage;
}
$versions = [
'root' => $this->dumpRootPackage($rootPackage, $installPaths, $devMode, $repoDir, $devPackages),
'versions' => [],
];
// add real installed packages
foreach ($packages as $package) {
if ($package instanceof AliasPackage) {
continue;
}
$versions['versions'][$package->getName()] = $this->dumpInstalledPackage($package, $installPaths, $repoDir, $devPackages);
}
// add provided/replaced packages
foreach ($packages as $package) {
$isDevPackage = isset($devPackages[$package->getName()]);
foreach ($package->getReplaces() as $replace) {
// exclude platform replaces as when they are really there we can not check for their presence
if (PlatformRepository::isPlatformPackage($replace->getTarget())) {
continue;
}
if (!isset($versions['versions'][$replace->getTarget()]['dev_requirement'])) {
$versions['versions'][$replace->getTarget()]['dev_requirement'] = $isDevPackage;
} elseif (!$isDevPackage) {
$versions['versions'][$replace->getTarget()]['dev_requirement'] = false;
}
$replaced = $replace->getPrettyConstraint();
if ($replaced === 'self.version') {
$replaced = $package->getPrettyVersion();
}
if (!isset($versions['versions'][$replace->getTarget()]['replaced']) || !in_array($replaced, $versions['versions'][$replace->getTarget()]['replaced'], true)) {
$versions['versions'][$replace->getTarget()]['replaced'][] = $replaced;
}
}
foreach ($package->getProvides() as $provide) {
// exclude platform provides as when they are really there we can not check for their presence
if (PlatformRepository::isPlatformPackage($provide->getTarget())) {
continue;
}
if (!isset($versions['versions'][$provide->getTarget()]['dev_requirement'])) {
$versions['versions'][$provide->getTarget()]['dev_requirement'] = $isDevPackage;
} elseif (!$isDevPackage) {
$versions['versions'][$provide->getTarget()]['dev_requirement'] = false;
}
$provided = $provide->getPrettyConstraint();
if ($provided === 'self.version') {
$provided = $package->getPrettyVersion();
}
if (!isset($versions['versions'][$provide->getTarget()]['provided']) || !in_array($provided, $versions['versions'][$provide->getTarget()]['provided'], true)) {
$versions['versions'][$provide->getTarget()]['provided'][] = $provided;
}
}
}
// add aliases
foreach ($packages as $package) {
if (!$package instanceof AliasPackage) {
continue;
}
$versions['versions'][$package->getName()]['aliases'][] = $package->getPrettyVersion();
if ($package instanceof RootPackageInterface) {
$versions['root']['aliases'][] = $package->getPrettyVersion();
}
}
ksort($versions['versions']);
ksort($versions);
foreach ($versions['versions'] as $name => $version) {
foreach (['aliases', 'replaced', 'provided'] as $key) {
if (isset($versions['versions'][$name][$key])) {
sort($versions['versions'][$name][$key], SORT_NATURAL);
}
}
}
return $versions;
}
/**
* @param array<string, string> $installPaths
* @param array<string, int> $devPackages
* @return array{pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev_requirement: bool}
*/
private function dumpInstalledPackage(PackageInterface $package, array $installPaths, string $repoDir, array $devPackages): array
{
$reference = null;
if ($package->getInstallationSource()) {
$reference = $package->getInstallationSource() === 'source' ? $package->getSourceReference() : $package->getDistReference();
}
if (null === $reference) {
$reference = ($package->getSourceReference() ?: $package->getDistReference()) ?: null;
}
if ($package instanceof RootPackageInterface) {
$to = $this->filesystem->normalizePath(realpath(Platform::getCwd()));
$installPath = $this->filesystem->findShortestPath($repoDir, $to, true);
} else {
$installPath = $installPaths[$package->getName()];
}
$data = [
'pretty_version' => $package->getPrettyVersion(),
'version' => $package->getVersion(),
'reference' => $reference,
'type' => $package->getType(),
'install_path' => $installPath,
'aliases' => [],
'dev_requirement' => isset($devPackages[$package->getName()]),
];
return $data;
}
/**
* @param array<string, string> $installPaths
* @param array<string, int> $devPackages
* @return array{name: string, pretty_version: string, version: string, reference: string|null, type: string, install_path: string, aliases: string[], dev: bool}
*/
private function dumpRootPackage(RootPackageInterface $package, array $installPaths, bool $devMode, string $repoDir, array $devPackages)
{
$data = $this->dumpInstalledPackage($package, $installPaths, $repoDir, $devPackages);
return [
'name' => $package->getName(),
'pretty_version' => $data['pretty_version'],
'version' => $data['version'],
'reference' => $data['reference'],
'type' => $data['type'],
'install_path' => $data['install_path'],
'aliases' => $data['aliases'],
'dev' => $devMode,
];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/InstalledArrayRepository.php | src/Composer/Repository/InstalledArrayRepository.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;
/**
* Installed array repository.
*
* This is used as an in-memory InstalledRepository mostly for testing purposes
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class InstalledArrayRepository extends WritableArrayRepository implements InstalledRepositoryInterface
{
public function getRepoName(): string
{
return 'installed '.parent::getRepoName();
}
/**
* @inheritDoc
*/
public function isFresh(): bool
{
// this is not a completely correct implementation but there is no way to
// distinguish an empty repo and a newly created one given this is all in-memory
return $this->count() === 0;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/PlatformRepository.php | src/Composer/Repository/PlatformRepository.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;
use Composer\Composer;
use Composer\Package\CompletePackage;
use Composer\Package\CompletePackageInterface;
use Composer\Package\Link;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionParser;
use Composer\Pcre\Preg;
use Composer\Platform\HhvmDetector;
use Composer\Platform\Runtime;
use Composer\Platform\Version;
use Composer\Plugin\PluginInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Util\Silencer;
use Composer\XdebugHandler\XdebugHandler;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PlatformRepository extends ArrayRepository
{
/**
* @deprecated use PlatformRepository::isPlatformPackage(string $name) instead
* @private
*/
public const PLATFORM_PACKAGE_REGEX = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[a-z0-9](?:[_.-]?[a-z0-9]+)*|composer(?:-(?:plugin|runtime)-api)?)$}iD';
/**
* @var ?string
*/
private static $lastSeenPlatformPhp = null;
/**
* @var VersionParser
*/
private $versionParser;
/**
* Defines overrides so that the platform can be mocked
*
* Keyed by package name (lowercased)
*
* @var array<string, array{name: string, version: string|false}>
*/
private $overrides = [];
/**
* Stores which packages have been disabled and their actual version
*
* @var array<string, CompletePackageInterface>
*/
private $disabledPackages = [];
/** @var Runtime */
private $runtime;
/** @var HhvmDetector */
private $hhvmDetector;
/**
* @param array<string, string|false> $overrides
*/
public function __construct(array $packages = [], array $overrides = [], ?Runtime $runtime = null, ?HhvmDetector $hhvmDetector = null)
{
$this->runtime = $runtime ?: new Runtime();
$this->hhvmDetector = $hhvmDetector ?: new HhvmDetector();
foreach ($overrides as $name => $version) {
if (!is_string($version) && false !== $version) { // @phpstan-ignore-line
throw new \UnexpectedValueException('config.platform.'.$name.' should be a string or false, but got '.get_debug_type($version).' '.var_export($version, true));
}
if ($name === 'php' && $version === false) {
throw new \UnexpectedValueException('config.platform.'.$name.' cannot be set to false as you cannot disable php entirely.');
}
$this->overrides[strtolower($name)] = ['name' => $name, 'version' => $version];
}
parent::__construct($packages);
}
public function getRepoName(): string
{
return 'platform repo';
}
public function isPlatformPackageDisabled(string $name): bool
{
return isset($this->disabledPackages[$name]);
}
/**
* @return array<string, CompletePackageInterface>
*/
public function getDisabledPackages(): array
{
return $this->disabledPackages;
}
protected function initialize(): void
{
parent::initialize();
$libraries = [];
$this->versionParser = new VersionParser();
// Add each of the override versions as options.
// Later we might even replace the extensions instead.
foreach ($this->overrides as $override) {
// Check that it's a platform package.
if (!self::isPlatformPackage($override['name'])) {
throw new \InvalidArgumentException('Invalid platform package name in config.platform: '.$override['name']);
}
if ($override['version'] !== false) {
$this->addOverriddenPackage($override);
}
}
$prettyVersion = Composer::getVersion();
$version = $this->versionParser->normalize($prettyVersion);
$composer = new CompletePackage('composer', $version, $prettyVersion);
$composer->setDescription('Composer package');
$this->addPackage($composer);
$prettyVersion = PluginInterface::PLUGIN_API_VERSION;
$version = $this->versionParser->normalize($prettyVersion);
$composerPluginApi = new CompletePackage('composer-plugin-api', $version, $prettyVersion);
$composerPluginApi->setDescription('The Composer Plugin API');
$this->addPackage($composerPluginApi);
$prettyVersion = Composer::RUNTIME_API_VERSION;
$version = $this->versionParser->normalize($prettyVersion);
$composerRuntimeApi = new CompletePackage('composer-runtime-api', $version, $prettyVersion);
$composerRuntimeApi->setDescription('The Composer Runtime API');
$this->addPackage($composerRuntimeApi);
try {
$prettyVersion = $this->runtime->getConstant('PHP_VERSION');
$version = $this->versionParser->normalize($prettyVersion);
} catch (\UnexpectedValueException $e) {
$prettyVersion = Preg::replace('#^([^~+-]+).*$#', '$1', $this->runtime->getConstant('PHP_VERSION'));
$version = $this->versionParser->normalize($prettyVersion);
}
$php = new CompletePackage('php', $version, $prettyVersion);
$php->setDescription('The PHP interpreter');
$this->addPackage($php);
if ($this->runtime->getConstant('PHP_DEBUG')) {
$phpdebug = new CompletePackage('php-debug', $version, $prettyVersion);
$phpdebug->setDescription('The PHP interpreter, with debugging symbols');
$this->addPackage($phpdebug);
}
if ($this->runtime->hasConstant('PHP_ZTS') && $this->runtime->getConstant('PHP_ZTS')) {
$phpzts = new CompletePackage('php-zts', $version, $prettyVersion);
$phpzts->setDescription('The PHP interpreter, with Zend Thread Safety');
$this->addPackage($phpzts);
}
if ($this->runtime->getConstant('PHP_INT_SIZE') === 8) {
$php64 = new CompletePackage('php-64bit', $version, $prettyVersion);
$php64->setDescription('The PHP interpreter, 64bit');
$this->addPackage($php64);
}
// The AF_INET6 constant is only defined if ext-sockets is available but
// IPv6 support might still be available.
if ($this->runtime->hasConstant('AF_INET6') || Silencer::call([$this->runtime, 'invoke'], 'inet_pton', ['::']) !== false) {
$phpIpv6 = new CompletePackage('php-ipv6', $version, $prettyVersion);
$phpIpv6->setDescription('The PHP interpreter, with IPv6 support');
$this->addPackage($phpIpv6);
}
$loadedExtensions = $this->runtime->getExtensions();
// Extensions scanning
foreach ($loadedExtensions as $name) {
if (in_array($name, ['standard', 'Core'])) {
continue;
}
$this->addExtension($name, $this->runtime->getExtensionVersion($name));
}
// Check for Xdebug in a restarted process
if (!in_array('xdebug', $loadedExtensions, true) && ($prettyVersion = XdebugHandler::getSkippedVersion())) {
$this->addExtension('xdebug', $prettyVersion);
}
// Another quick loop, just for possible libraries
// Doing it this way to know that functions or constants exist before
// relying on them.
foreach ($loadedExtensions as $name) {
switch ($name) {
case 'amqp':
$info = $this->runtime->getExtensionInfo($name);
// librabbitmq version => 0.9.0
if (Preg::isMatch('/^librabbitmq version => (?<version>.+)$/im', $info, $librabbitmqMatches)) {
$this->addLibrary($libraries, $name.'-librabbitmq', $librabbitmqMatches['version'], 'AMQP librabbitmq version');
}
// AMQP protocol version => 0-9-1
if (Preg::isMatchStrictGroups('/^AMQP protocol version => (?<version>.+)$/im', $info, $protocolMatches)) {
$this->addLibrary($libraries, $name.'-protocol', str_replace('-', '.', $protocolMatches['version']), 'AMQP protocol version');
}
break;
case 'bz2':
$info = $this->runtime->getExtensionInfo($name);
// BZip2 Version => 1.0.6, 6-Sept-2010
if (Preg::isMatch('/^BZip2 Version => (?<version>.*),/im', $info, $matches)) {
$this->addLibrary($libraries, $name, $matches['version']);
}
break;
case 'curl':
$curlVersion = $this->runtime->invoke('curl_version');
$this->addLibrary($libraries, $name, $curlVersion['version']);
$info = $this->runtime->getExtensionInfo($name);
// SSL Version => OpenSSL/1.0.1t
if (Preg::isMatchStrictGroups('{^SSL Version => (?<library>[^/]+)/(?<version>.+)$}im', $info, $sslMatches)) {
$library = strtolower($sslMatches['library']);
if ($library === 'openssl') {
$parsedVersion = Version::parseOpenssl($sslMatches['version'], $isFips);
$this->addLibrary($libraries, $name.'-openssl'.($isFips ? '-fips' : ''), $parsedVersion, 'curl OpenSSL version ('.$parsedVersion.')', [], $isFips ? ['curl-openssl'] : []);
} else {
if (str_starts_with($library, '(securetransport)') && Preg::isMatch('{^\(securetransport\) ([a-z0-9]+)}', $library, $securetransportMatches)) {
$shortlib = 'securetransport';
$sslLib = 'curl-'.$securetransportMatches[1];
} else {
$shortlib = $library;
$sslLib = 'curl-openssl';
}
$this->addLibrary($libraries, $name.'-'.$shortlib, $sslMatches['version'], 'curl '.$library.' version ('.$sslMatches['version'].')', [$sslLib]);
}
}
// libSSH Version => libssh2/1.4.3
if (Preg::isMatchStrictGroups('{^libSSH Version => (?<library>[^/]+)/(?<version>.+?)(?:/.*)?$}im', $info, $sshMatches)) {
$this->addLibrary($libraries, $name.'-'.strtolower($sshMatches['library']), $sshMatches['version'], 'curl '.$sshMatches['library'].' version');
}
// ZLib Version => 1.2.8
if (Preg::isMatchStrictGroups('{^ZLib Version => (?<version>.+)$}im', $info, $zlibMatches)) {
$this->addLibrary($libraries, $name.'-zlib', $zlibMatches['version'], 'curl zlib version');
}
break;
case 'date':
$info = $this->runtime->getExtensionInfo($name);
// timelib version => 2018.03
if (Preg::isMatchStrictGroups('/^timelib version => (?<version>.+)$/im', $info, $timelibMatches)) {
$this->addLibrary($libraries, $name.'-timelib', $timelibMatches['version'], 'date timelib version');
}
// Timezone Database => internal
if (Preg::isMatchStrictGroups('/^Timezone Database => (?<source>internal|external)$/im', $info, $zoneinfoSourceMatches)) {
$external = $zoneinfoSourceMatches['source'] === 'external';
if (Preg::isMatchStrictGroups('/^"Olson" Timezone Database Version => (?<version>.+?)(?:\.system)?$/im', $info, $zoneinfoMatches)) {
// If the timezonedb is provided by ext/timezonedb, register that version as a replacement
if ($external && in_array('timezonedb', $loadedExtensions, true)) {
$this->addLibrary($libraries, 'timezonedb-zoneinfo', $zoneinfoMatches['version'], 'zoneinfo ("Olson") database for date (replaced by timezonedb)', [$name.'-zoneinfo']);
} else {
$this->addLibrary($libraries, $name.'-zoneinfo', $zoneinfoMatches['version'], 'zoneinfo ("Olson") database for date');
}
}
}
break;
case 'fileinfo':
$info = $this->runtime->getExtensionInfo($name);
// libmagic => 537
if (Preg::isMatch('/^libmagic => (?<version>.+)$/im', $info, $magicMatches)) {
$this->addLibrary($libraries, $name.'-libmagic', $magicMatches['version'], 'fileinfo libmagic version');
}
break;
case 'gd':
$this->addLibrary($libraries, $name, $this->runtime->getConstant('GD_VERSION'));
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatchStrictGroups('/^libJPEG Version => (?<version>.+?)(?: compatible)?$/im', $info, $libjpegMatches)) {
$this->addLibrary($libraries, $name.'-libjpeg', Version::parseLibjpeg($libjpegMatches['version']), 'libjpeg version for gd');
}
if (Preg::isMatchStrictGroups('/^libPNG Version => (?<version>.+)$/im', $info, $libpngMatches)) {
$this->addLibrary($libraries, $name.'-libpng', $libpngMatches['version'], 'libpng version for gd');
}
if (Preg::isMatchStrictGroups('/^FreeType Version => (?<version>.+)$/im', $info, $freetypeMatches)) {
$this->addLibrary($libraries, $name.'-freetype', $freetypeMatches['version'], 'freetype version for gd');
}
if (Preg::isMatchStrictGroups('/^libXpm Version => (?<versionId>\d+)$/im', $info, $libxpmMatches)) {
$this->addLibrary($libraries, $name.'-libxpm', Version::convertLibxpmVersionId((int) $libxpmMatches['versionId']), 'libxpm version for gd');
}
break;
case 'gmp':
$this->addLibrary($libraries, $name, $this->runtime->getConstant('GMP_VERSION'));
break;
case 'iconv':
$this->addLibrary($libraries, $name, $this->runtime->getConstant('ICONV_VERSION'));
break;
case 'intl':
$info = $this->runtime->getExtensionInfo($name);
$description = 'The ICU unicode and globalization support library';
// Truthy check is for testing only so we can make the condition fail
if ($this->runtime->hasConstant('INTL_ICU_VERSION')) {
$this->addLibrary($libraries, 'icu', $this->runtime->getConstant('INTL_ICU_VERSION'), $description);
} elseif (Preg::isMatch('/^ICU version => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, 'icu', $matches['version'], $description);
}
// ICU TZData version => 2019c
if (Preg::isMatchStrictGroups('/^ICU TZData version => (?<version>.*)$/im', $info, $zoneinfoMatches) && null !== ($version = Version::parseZoneinfoVersion($zoneinfoMatches['version']))) {
$this->addLibrary($libraries, 'icu-zoneinfo', $version, 'zoneinfo ("Olson") database for icu');
}
// Add a separate version for the CLDR library version
if ($this->runtime->hasClass('ResourceBundle')) {
$resourceBundle = $this->runtime->invoke(['ResourceBundle', 'create'], ['root', 'ICUDATA', false]);
if ($resourceBundle !== null) {
$this->addLibrary($libraries, 'icu-cldr', $resourceBundle->get('Version'), 'ICU CLDR project version');
}
}
if ($this->runtime->hasClass('IntlChar')) {
$this->addLibrary($libraries, 'icu-unicode', implode('.', array_slice($this->runtime->invoke(['IntlChar', 'getUnicodeVersion']), 0, 3)), 'ICU unicode version');
}
break;
case 'imagick':
// @phpstan-ignore staticMethod.dynamicCall (called like this for mockability)
$imageMagickVersion = $this->runtime->construct('Imagick')->getVersion();
// 6.x: ImageMagick 6.2.9 08/24/06 Q16 http://www.imagemagick.org
// 7.x: ImageMagick 7.0.8-34 Q16 x86_64 2019-03-23 https://imagemagick.org
if (Preg::isMatch('/^ImageMagick (?<version>[\d.]+)(?:-(?<patch>\d+))?/', $imageMagickVersion['versionString'], $matches)) {
$version = $matches['version'];
if (isset($matches['patch'])) {
$version .= '.'.$matches['patch'];
}
$this->addLibrary($libraries, $name.'-imagemagick', $version, null, ['imagick']);
}
break;
case 'ldap':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatchStrictGroups('/^Vendor Version => (?<versionId>\d+)$/im', $info, $matches) && Preg::isMatchStrictGroups('/^Vendor Name => (?<vendor>.+)$/im', $info, $vendorMatches)) {
$this->addLibrary($libraries, $name.'-'.strtolower($vendorMatches['vendor']), Version::convertOpenldapVersionId((int) $matches['versionId']), $vendorMatches['vendor'].' version of ldap');
}
break;
case 'libxml':
// ext/dom, ext/simplexml, ext/xmlreader and ext/xmlwriter use the same libxml as the ext/libxml
$libxmlProvides = array_map(static function ($extension): string {
return $extension . '-libxml';
}, array_intersect($loadedExtensions, ['dom', 'simplexml', 'xml', 'xmlreader', 'xmlwriter']));
$this->addLibrary($libraries, $name, $this->runtime->getConstant('LIBXML_DOTTED_VERSION'), 'libxml library version', [], $libxmlProvides);
break;
case 'mbstring':
$info = $this->runtime->getExtensionInfo($name);
// libmbfl version => 1.3.2
if (Preg::isMatch('/^libmbfl version => (?<version>.+)$/im', $info, $libmbflMatches)) {
$this->addLibrary($libraries, $name.'-libmbfl', $libmbflMatches['version'], 'mbstring libmbfl version');
}
if ($this->runtime->hasConstant('MB_ONIGURUMA_VERSION')) {
$this->addLibrary($libraries, $name.'-oniguruma', $this->runtime->getConstant('MB_ONIGURUMA_VERSION'), 'mbstring oniguruma version');
// Multibyte regex (oniguruma) version => 5.9.5
// oniguruma version => 6.9.0
} elseif (Preg::isMatch('/^(?:oniguruma|Multibyte regex \(oniguruma\)) version => (?<version>.+)$/im', $info, $onigurumaMatches)) {
$this->addLibrary($libraries, $name.'-oniguruma', $onigurumaMatches['version'], 'mbstring oniguruma version');
}
break;
case 'memcached':
$info = $this->runtime->getExtensionInfo($name);
// libmemcached version => 1.0.18
if (Preg::isMatch('/^libmemcached version => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-libmemcached', $matches['version'], 'libmemcached version');
}
break;
case 'openssl':
// OpenSSL 1.1.1g 21 Apr 2020
if (Preg::isMatchStrictGroups('{^(?:OpenSSL|LibreSSL)?\s*(?<version>\S+)}i', $this->runtime->getConstant('OPENSSL_VERSION_TEXT'), $matches)) {
$parsedVersion = Version::parseOpenssl($matches['version'], $isFips);
$this->addLibrary($libraries, $name.($isFips ? '-fips' : ''), $parsedVersion, $this->runtime->getConstant('OPENSSL_VERSION_TEXT'), [], $isFips ? [$name] : []);
}
break;
case 'pcre':
$this->addLibrary($libraries, $name, Preg::replace('{^(\S+).*}', '$1', $this->runtime->getConstant('PCRE_VERSION')));
$info = $this->runtime->getExtensionInfo($name);
// PCRE Unicode Version => 12.1.0
if (Preg::isMatchStrictGroups('/^PCRE Unicode Version => (?<version>.+)$/im', $info, $pcreUnicodeMatches)) {
$this->addLibrary($libraries, $name.'-unicode', $pcreUnicodeMatches['version'], 'PCRE Unicode version support');
}
break;
case 'mysqlnd':
case 'pdo_mysql':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatchStrictGroups('/^(?:Client API version|Version) => mysqlnd (?<version>.+?) /mi', $info, $matches)) {
$this->addLibrary($libraries, $name.'-mysqlnd', $matches['version'], 'mysqlnd library version for '.$name);
}
break;
case 'mongodb':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatchStrictGroups('/^libmongoc bundled version => (?<version>.+)$/im', $info, $libmongocMatches)) {
$this->addLibrary($libraries, $name.'-libmongoc', $libmongocMatches['version'], 'libmongoc version of mongodb');
}
if (Preg::isMatchStrictGroups('/^libbson bundled version => (?<version>.+)$/im', $info, $libbsonMatches)) {
$this->addLibrary($libraries, $name.'-libbson', $libbsonMatches['version'], 'libbson version of mongodb');
}
break;
case 'pgsql':
if ($this->runtime->hasConstant('PGSQL_LIBPQ_VERSION')) {
$this->addLibrary($libraries, 'pgsql-libpq', $this->runtime->getConstant('PGSQL_LIBPQ_VERSION'), 'libpq for pgsql');
break;
}
// intentional fall-through to next case...
case 'pdo_pgsql':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatch('/^PostgreSQL\(libpq\) Version => (?<version>.*)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-libpq', $matches['version'], 'libpq for '.$name);
}
break;
case 'pq':
$info = $this->runtime->getExtensionInfo($name);
// Used Library => Compiled => Linked
// libpq => 14.3 (Ubuntu 14.3-1.pgdg22.04+1) => 15.0.2
if (Preg::isMatch('/^libpq => (?<compiled>.+) => (?<linked>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-libpq', $matches['linked'], 'libpq for '.$name);
}
break;
case 'rdkafka':
if ($this->runtime->hasConstant('RD_KAFKA_VERSION')) {
/**
* Interpreted as hex \c MM.mm.rr.xx:
* - MM = Major
* - mm = minor
* - rr = revision
* - xx = pre-release id (0xff is the final release)
*
* pre-release ID in practice is always 0xff even for RCs etc, so we ignore it
*/
$libRdKafkaVersionInt = $this->runtime->getConstant('RD_KAFKA_VERSION');
$this->addLibrary($libraries, $name.'-librdkafka', sprintf('%d.%d.%d', ($libRdKafkaVersionInt & 0x7F000000) >> 24, ($libRdKafkaVersionInt & 0x00FF0000) >> 16, ($libRdKafkaVersionInt & 0x0000FF00) >> 8), 'librdkafka for '.$name);
}
break;
case 'libsodium':
case 'sodium':
if ($this->runtime->hasConstant('SODIUM_LIBRARY_VERSION')) {
$this->addLibrary($libraries, 'libsodium', $this->runtime->getConstant('SODIUM_LIBRARY_VERSION'));
$this->addLibrary($libraries, 'libsodium', $this->runtime->getConstant('SODIUM_LIBRARY_VERSION'));
}
break;
case 'sqlite3':
case 'pdo_sqlite':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatch('/^SQLite Library => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-sqlite', $matches['version']);
}
break;
case 'ssh2':
$info = $this->runtime->getExtensionInfo($name);
if (Preg::isMatch('/^libssh2 version => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-libssh2', $matches['version']);
}
break;
case 'xsl':
$this->addLibrary($libraries, 'libxslt', $this->runtime->getConstant('LIBXSLT_DOTTED_VERSION'), null, ['xsl']);
$info = $this->runtime->getExtensionInfo('xsl');
if (Preg::isMatch('/^libxslt compiled against libxml Version => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, 'libxslt-libxml', $matches['version'], 'libxml version libxslt is compiled against');
}
break;
case 'yaml':
$info = $this->runtime->getExtensionInfo('yaml');
if (Preg::isMatch('/^LibYAML Version => (?<version>.+)$/im', $info, $matches)) {
$this->addLibrary($libraries, $name.'-libyaml', $matches['version'], 'libyaml version of yaml');
}
break;
case 'zip':
if ($this->runtime->hasConstant('LIBZIP_VERSION', 'ZipArchive')) {
$this->addLibrary($libraries, $name.'-libzip', $this->runtime->getConstant('LIBZIP_VERSION', 'ZipArchive'), null, ['zip']);
}
break;
case 'zlib':
if ($this->runtime->hasConstant('ZLIB_VERSION')) {
$this->addLibrary($libraries, $name, $this->runtime->getConstant('ZLIB_VERSION'));
// Linked Version => 1.2.8
} elseif (Preg::isMatch('/^Linked Version => (?<version>.+)$/im', $this->runtime->getExtensionInfo($name), $matches)) {
$this->addLibrary($libraries, $name, $matches['version']);
}
break;
default:
break;
}
}
$hhvmVersion = $this->hhvmDetector->getVersion();
if ($hhvmVersion) {
try {
$prettyVersion = $hhvmVersion;
$version = $this->versionParser->normalize($prettyVersion);
} catch (\UnexpectedValueException $e) {
$prettyVersion = Preg::replace('#^([^~+-]+).*$#', '$1', $hhvmVersion);
$version = $this->versionParser->normalize($prettyVersion);
}
$hhvm = new CompletePackage('hhvm', $version, $prettyVersion);
$hhvm->setDescription('The HHVM Runtime (64bit)');
$this->addPackage($hhvm);
}
}
/**
* @inheritDoc
*/
public function addPackage(PackageInterface $package): void
{
if (!$package instanceof CompletePackage) {
throw new \UnexpectedValueException('Expected CompletePackage but got '.get_class($package));
}
// Skip if overridden
if (isset($this->overrides[$package->getName()])) {
if ($this->overrides[$package->getName()]['version'] === false) {
$this->addDisabledPackage($package);
return;
}
$overrider = $this->findPackage($package->getName(), '*');
if ($package->getVersion() === $overrider->getVersion()) {
$actualText = 'same as actual';
} else {
$actualText = 'actual: '.$package->getPrettyVersion();
}
if ($overrider instanceof CompletePackageInterface) {
$overrider->setDescription($overrider->getDescription().', '.$actualText);
}
return;
}
// Skip if PHP is overridden and we are adding a php-* package
if (isset($this->overrides['php']) && 0 === strpos($package->getName(), 'php-')) {
$overrider = $this->addOverriddenPackage($this->overrides['php'], $package->getPrettyName());
if ($package->getVersion() === $overrider->getVersion()) {
$actualText = 'same as actual';
} else {
$actualText = 'actual: '.$package->getPrettyVersion();
}
$overrider->setDescription($overrider->getDescription().', '.$actualText);
return;
}
parent::addPackage($package);
}
/**
* @param array{version: string, name: string} $override
*/
private function addOverriddenPackage(array $override, ?string $name = null): CompletePackage
{
$version = $this->versionParser->normalize($override['version']);
$package = new CompletePackage($name ?: $override['name'], $version, $override['version']);
$package->setDescription('Package overridden via config.platform');
$package->setExtra(['config.platform' => true]);
parent::addPackage($package);
if ($package->getName() === 'php') {
self::$lastSeenPlatformPhp = implode('.', array_slice(explode('.', $package->getVersion()), 0, 3));
}
return $package;
}
private function addDisabledPackage(CompletePackage $package): void
{
$package->setDescription($package->getDescription().'. <warning>Package disabled via config.platform</warning>');
$package->setExtra(['config.platform' => true]);
$this->disabledPackages[$package->getName()] = $package;
}
/**
* Parses the version and adds a new package to the repository
*/
private function addExtension(string $name, string $prettyVersion): void
{
$extraDescription = null;
try {
$version = $this->versionParser->normalize($prettyVersion);
} catch (\UnexpectedValueException $e) {
$extraDescription = ' (actual version: '.$prettyVersion.')';
if (Preg::isMatchStrictGroups('{^(\d+\.\d+\.\d+(?:\.\d+)?)}', $prettyVersion, $match)) {
$prettyVersion = $match[1];
} else {
$prettyVersion = '0';
}
$version = $this->versionParser->normalize($prettyVersion);
}
$packageName = $this->buildPackageName($name);
$ext = new CompletePackage($packageName, $version, $prettyVersion);
$ext->setDescription('The '.$name.' PHP extension'.$extraDescription);
$ext->setType('php-ext');
if ($name === 'uuid') {
$ext->setReplaces([
'lib-uuid' => new Link('ext-uuid', 'lib-uuid', new Constraint('=', $version), Link::TYPE_REPLACE, $ext->getPrettyVersion()),
]);
}
$this->addPackage($ext);
}
private function buildPackageName(string $name): string
{
return 'ext-' . str_replace(' ', '-', strtolower($name));
}
/**
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositorySet.php | src/Composer/Repository/RepositorySet.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;
use Composer\DependencyResolver\PoolOptimizer;
use Composer\DependencyResolver\Pool;
use Composer\DependencyResolver\PoolBuilder;
use Composer\DependencyResolver\Request;
use Composer\DependencyResolver\SecurityAdvisoryPoolFilter;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Advisory\SecurityAdvisory;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\IO\IOInterface;
use Composer\IO\NullIO;
use Composer\Package\BasePackage;
use Composer\Package\AliasPackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\CompletePackage;
use Composer\Package\PackageInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Package\Version\StabilityFilter;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Semver\Constraint\MultiConstraint;
/**
* @author Nils Adermann <naderman@naderman.de>
*
* @see RepositoryUtils for ways to work with single repos
*/
class RepositorySet
{
/**
* Packages are returned even though their stability does not match the required stability
*/
public const ALLOW_UNACCEPTABLE_STABILITIES = 1;
/**
* Packages will be looked up in all repositories, even after they have been found in a higher prio one
*/
public const ALLOW_SHADOWED_REPOSITORIES = 2;
/**
* @var array[]
* @phpstan-var array<string, array<string, array{alias: string, alias_normalized: string}>>
*/
private $rootAliases;
/**
* @var string[]
* @phpstan-var array<string, string>
*/
private $rootReferences;
/** @var RepositoryInterface[] */
private $repositories = [];
/**
* @var int[] array of stability => BasePackage::STABILITY_* value
* @phpstan-var array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*>
*/
private $acceptableStabilities;
/**
* @var int[] array of package name => BasePackage::STABILITY_* value
* @phpstan-var array<string, BasePackage::STABILITY_*>
*/
private $stabilityFlags;
/**
* @var ConstraintInterface[]
* @phpstan-var array<string, ConstraintInterface>
*/
private $rootRequires;
/**
* @var array<string, ConstraintInterface>
*/
private $temporaryConstraints;
/** @var bool */
private $locked = false;
/** @var bool */
private $allowInstalledRepositories = false;
/**
* In most cases if you are looking to use this class as a way to find packages from repositories
* passing minimumStability is all you need to worry about. The rest is for advanced pool creation including
* aliases, pinned references and other special cases.
*
* @param key-of<BasePackage::STABILITIES> $minimumStability
* @param int[] $stabilityFlags an array of package name => BasePackage::STABILITY_* value
* @phpstan-param array<string, BasePackage::STABILITY_*> $stabilityFlags
* @param array[] $rootAliases
* @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $rootAliases
* @param string[] $rootReferences an array of package name => source reference
* @phpstan-param array<string, string> $rootReferences
* @param ConstraintInterface[] $rootRequires an array of package name => constraint from the root package
* @phpstan-param array<string, ConstraintInterface> $rootRequires
* @param array<string, ConstraintInterface> $temporaryConstraints Runtime temporary constraints that will be used to filter packages
*/
public function __construct(string $minimumStability = 'stable', array $stabilityFlags = [], array $rootAliases = [], array $rootReferences = [], array $rootRequires = [], array $temporaryConstraints = [])
{
$this->rootAliases = self::getRootAliasesPerPackage($rootAliases);
$this->rootReferences = $rootReferences;
$this->acceptableStabilities = [];
foreach (BasePackage::STABILITIES as $stability => $value) {
if ($value <= BasePackage::STABILITIES[$minimumStability]) {
$this->acceptableStabilities[$stability] = $value;
}
}
$this->stabilityFlags = $stabilityFlags;
$this->rootRequires = $rootRequires;
foreach ($rootRequires as $name => $constraint) {
if (PlatformRepository::isPlatformPackage($name)) {
unset($this->rootRequires[$name]);
}
}
$this->temporaryConstraints = $temporaryConstraints;
}
public function allowInstalledRepositories(bool $allow = true): void
{
$this->allowInstalledRepositories = $allow;
}
/**
* @return ConstraintInterface[] an array of package name => constraint from the root package, platform requirements excluded
* @phpstan-return array<string, ConstraintInterface>
*/
public function getRootRequires(): array
{
return $this->rootRequires;
}
/**
* @return array<string, ConstraintInterface> Runtime temporary constraints that will be used to filter packages
*/
public function getTemporaryConstraints(): array
{
return $this->temporaryConstraints;
}
/**
* Adds a repository to this repository set
*
* The first repos added have a higher priority. As soon as a package is found in any
* repository the search for that package ends, and following repos will not be consulted.
*
* @param RepositoryInterface $repo A package repository
*/
public function addRepository(RepositoryInterface $repo): void
{
if ($this->locked) {
throw new \RuntimeException("Pool has already been created from this repository set, it cannot be modified anymore.");
}
if ($repo instanceof CompositeRepository) {
$repos = $repo->getRepositories();
} else {
$repos = [$repo];
}
foreach ($repos as $repo) {
$this->repositories[] = $repo;
}
}
/**
* Find packages providing or matching a name and optionally meeting a constraint in all repositories
*
* Returned in the order of repositories, matching priority
*
* @param int $flags any of the ALLOW_* constants from this class to tweak what is returned
* @return BasePackage[]
*/
public function findPackages(string $name, ?ConstraintInterface $constraint = null, int $flags = 0): array
{
$ignoreStability = ($flags & self::ALLOW_UNACCEPTABLE_STABILITIES) !== 0;
$loadFromAllRepos = ($flags & self::ALLOW_SHADOWED_REPOSITORIES) !== 0;
$packages = [];
if ($loadFromAllRepos) {
foreach ($this->repositories as $repository) {
$packages[] = $repository->findPackages($name, $constraint) ?: [];
}
} else {
foreach ($this->repositories as $repository) {
$result = $repository->loadPackages([$name => $constraint], $ignoreStability ? BasePackage::STABILITIES : $this->acceptableStabilities, $ignoreStability ? [] : $this->stabilityFlags);
$packages[] = $result['packages'];
foreach ($result['namesFound'] as $nameFound) {
// avoid loading the same package again from other repositories once it has been found
if ($name === $nameFound) {
break 2;
}
}
}
}
$candidates = $packages ? array_merge(...$packages) : [];
// when using loadPackages above (!$loadFromAllRepos) the repos already filter for stability so no need to do it again
if ($ignoreStability || !$loadFromAllRepos) {
return $candidates;
}
$result = [];
foreach ($candidates as $candidate) {
if ($this->isPackageAcceptable($candidate->getNames(), $candidate->getStability())) {
$result[] = $candidate;
}
}
return $result;
}
/**
* @param string[] $packageNames
* @return ($allowPartialAdvisories is true ? array{advisories: array<string, array<PartialSecurityAdvisory|SecurityAdvisory>>, unreachableRepos: array<string>} : array{advisories: array<string, array<SecurityAdvisory>>, unreachableRepos: array<string>})
*/
public function getSecurityAdvisories(array $packageNames, bool $allowPartialAdvisories, bool $ignoreUnreachable = false): array
{
$map = [];
foreach ($packageNames as $name) {
$map[$name] = new MatchAllConstraint();
}
$unreachableRepos = [];
$advisories = $this->getSecurityAdvisoriesForConstraints($map, $allowPartialAdvisories, $ignoreUnreachable, $unreachableRepos);
return ['advisories' => $advisories, 'unreachableRepos' => $unreachableRepos];
}
/**
* @param PackageInterface[] $packages
* @return ($allowPartialAdvisories is true ? array{advisories: array<string, array<PartialSecurityAdvisory|SecurityAdvisory>>, unreachableRepos: array<string>} : array{advisories: array<string, array<SecurityAdvisory>>, unreachableRepos: array<string>})
*/
public function getMatchingSecurityAdvisories(array $packages, bool $allowPartialAdvisories = false, bool $ignoreUnreachable = false): array
{
$map = [];
foreach ($packages as $package) {
// ignore root alias versions as they are not actual package versions and should not matter when it comes to vulnerabilities
if ($package instanceof AliasPackage && $package->isRootPackageAlias()) {
continue;
}
if (isset($map[$package->getName()])) {
$map[$package->getName()] = new MultiConstraint([new Constraint('=', $package->getVersion()), $map[$package->getName()]], false);
} else {
$map[$package->getName()] = new Constraint('=', $package->getVersion());
}
}
$unreachableRepos = [];
$advisories = $this->getSecurityAdvisoriesForConstraints($map, $allowPartialAdvisories, $ignoreUnreachable, $unreachableRepos);
return ['advisories' => $advisories, 'unreachableRepos' => $unreachableRepos];
}
/**
* @param array<string, ConstraintInterface> $packageConstraintMap
* @param array<string> &$unreachableRepos Array to store messages about unreachable repositories
* @return ($allowPartialAdvisories is true ? array<string, array<PartialSecurityAdvisory|SecurityAdvisory>> : array<string, array<SecurityAdvisory>>)
*/
private function getSecurityAdvisoriesForConstraints(array $packageConstraintMap, bool $allowPartialAdvisories, bool $ignoreUnreachable = false, array &$unreachableRepos = []): array
{
$repoAdvisories = [];
foreach ($this->repositories as $repository) {
try {
if (!$repository instanceof AdvisoryProviderInterface || !$repository->hasSecurityAdvisories()) {
continue;
}
$repoAdvisories[] = $repository->getSecurityAdvisories($packageConstraintMap, $allowPartialAdvisories)['advisories'];
} catch (\Composer\Downloader\TransportException $e) {
if (!$ignoreUnreachable) {
throw $e;
}
$unreachableRepos[] = $e->getMessage();
}
}
$advisories = count($repoAdvisories) > 0 ? array_merge_recursive([], ...$repoAdvisories) : [];
ksort($advisories);
return $advisories;
}
/**
* @return array[] an array with the provider name as key and value of array('name' => '...', 'description' => '...', 'type' => '...')
* @phpstan-return array<string, array{name: string, description: string|null, type: string}>
*/
public function getProviders(string $packageName): array
{
$providers = [];
foreach ($this->repositories as $repository) {
if ($repoProviders = $repository->getProviders($packageName)) {
$providers = array_merge($providers, $repoProviders);
}
}
return $providers;
}
/**
* Check for each given package name whether it would be accepted by this RepositorySet in the given $stability
*
* @param string[] $names
* @param key-of<BasePackage::STABILITIES> $stability one of 'stable', 'RC', 'beta', 'alpha' or 'dev'
*/
public function isPackageAcceptable(array $names, string $stability): bool
{
return StabilityFilter::isPackageAcceptable($this->acceptableStabilities, $this->stabilityFlags, $names, $stability);
}
/**
* Create a pool for dependency resolution from the packages in this repository set.
*
* @param list<string> $ignoredTypes Packages of those types are ignored
* @param list<string>|null $allowedTypes Only packages of those types are allowed if set to non-null
*/
public function createPool(Request $request, IOInterface $io, ?EventDispatcher $eventDispatcher = null, ?PoolOptimizer $poolOptimizer = null, array $ignoredTypes = [], ?array $allowedTypes = null, ?SecurityAdvisoryPoolFilter $securityAdvisoryPoolFilter = null): Pool
{
$poolBuilder = new PoolBuilder($this->acceptableStabilities, $this->stabilityFlags, $this->rootAliases, $this->rootReferences, $io, $eventDispatcher, $poolOptimizer, $this->temporaryConstraints, $securityAdvisoryPoolFilter);
$poolBuilder->setIgnoredTypes($ignoredTypes);
$poolBuilder->setAllowedTypes($allowedTypes);
foreach ($this->repositories as $repo) {
if (($repo instanceof InstalledRepositoryInterface || $repo instanceof InstalledRepository) && !$this->allowInstalledRepositories) {
throw new \LogicException('The pool can not accept packages from an installed repository');
}
}
$this->locked = true;
return $poolBuilder->buildPool($this->repositories, $request);
}
/**
* Create a pool for dependency resolution from the packages in this repository set.
*/
public function createPoolWithAllPackages(): Pool
{
foreach ($this->repositories as $repo) {
if (($repo instanceof InstalledRepositoryInterface || $repo instanceof InstalledRepository) && !$this->allowInstalledRepositories) {
throw new \LogicException('The pool can not accept packages from an installed repository');
}
}
$this->locked = true;
$packages = [];
foreach ($this->repositories as $repository) {
foreach ($repository->getPackages() as $package) {
$packages[] = $package;
if (isset($this->rootAliases[$package->getName()][$package->getVersion()])) {
$alias = $this->rootAliases[$package->getName()][$package->getVersion()];
while ($package instanceof AliasPackage) {
$package = $package->getAliasOf();
}
if ($package instanceof CompletePackage) {
$aliasPackage = new CompleteAliasPackage($package, $alias['alias_normalized'], $alias['alias']);
} else {
$aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
}
$aliasPackage->setRootPackageAlias(true);
$packages[] = $aliasPackage;
}
}
}
return new Pool($packages);
}
public function createPoolForPackage(string $packageName, ?LockArrayRepository $lockedRepo = null): Pool
{
// TODO unify this with above in some simpler version without "request"?
return $this->createPoolForPackages([$packageName], $lockedRepo);
}
/**
* @param string[] $packageNames
*/
public function createPoolForPackages(array $packageNames, ?LockArrayRepository $lockedRepo = null): Pool
{
$request = new Request($lockedRepo);
$allowedPackages = [];
foreach ($packageNames as $packageName) {
if (PlatformRepository::isPlatformPackage($packageName)) {
throw new \LogicException('createPoolForPackage(s) can not be used for platform packages, as they are never loaded by the PoolBuilder which expects them to be fixed. Use createPoolWithAllPackages or pass in a proper request with the platform packages you need fixed in it.');
}
$request->requireName($packageName);
$allowedPackages[] = strtolower($packageName);
}
if (count($allowedPackages) > 0) {
$request->restrictPackages($allowedPackages);
}
return $this->createPool($request, new NullIO());
}
/**
* @param array[] $aliases
* @phpstan-param list<array{package: string, version: string, alias: string, alias_normalized: string}> $aliases
*
* @return array<string, array<string, array{alias: string, alias_normalized: string}>>
*/
private static function getRootAliasesPerPackage(array $aliases): array
{
$normalizedAliases = [];
foreach ($aliases as $alias) {
$normalizedAliases[$alias['package']][$alias['version']] = [
'alias' => $alias['alias'],
'alias_normalized' => $alias['alias_normalized'],
];
}
return $normalizedAliases;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/CanonicalPackagesTrait.php | src/Composer/Repository/CanonicalPackagesTrait.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;
use Composer\Package\AliasPackage;
use Composer\Package\PackageInterface;
/**
* Provides getCanonicalPackages() to various repository implementations
*
* @internal
*/
trait CanonicalPackagesTrait
{
/**
* Get unique packages (at most one package of each name), with aliases resolved and removed.
*
* @return PackageInterface[]
*/
public function getCanonicalPackages()
{
$packages = $this->getPackages();
// get at most one package of each name, preferring non-aliased ones
$packagesByName = [];
foreach ($packages as $package) {
if (!isset($packagesByName[$package->getName()]) || $packagesByName[$package->getName()] instanceof AliasPackage) {
$packagesByName[$package->getName()] = $package;
}
}
$canonicalPackages = [];
// unfold aliased packages
foreach ($packagesByName as $package) {
while ($package instanceof AliasPackage) {
$package = $package->getAliasOf();
}
$canonicalPackages[] = $package;
}
return $canonicalPackages;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositoryFactory.php | src/Composer/Repository/RepositoryFactory.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;
use Composer\Factory;
use Composer\IO\IOInterface;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Pcre\Preg;
use Composer\Util\HttpDownloader;
use Composer\Util\ProcessExecutor;
use Composer\Json\JsonFile;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RepositoryFactory
{
/**
* @return array|mixed
*/
public static function configFromString(IOInterface $io, Config $config, string $repository, bool $allowFilesystem = false)
{
if (0 === strpos($repository, 'http')) {
$repoConfig = ['type' => 'composer', 'url' => $repository];
} elseif ("json" === pathinfo($repository, PATHINFO_EXTENSION)) {
$json = new JsonFile($repository, Factory::createHttpDownloader($io, $config));
$data = $json->read();
if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) {
$repoConfig = ['type' => 'composer', 'url' => 'file://' . strtr(realpath($repository), '\\', '/')];
} elseif ($allowFilesystem) {
$repoConfig = ['type' => 'filesystem', 'json' => $json];
} else {
throw new \InvalidArgumentException("Invalid repository URL ($repository) given. This file does not contain a valid composer repository.");
}
} elseif (strpos($repository, '{') === 0) {
// assume it is a json object that makes a repo config
$repoConfig = JsonFile::parseJson($repository);
} else {
throw new \InvalidArgumentException("Invalid repository url ($repository) given. Has to be a .json file, an http url or a JSON object.");
}
return $repoConfig;
}
public static function fromString(IOInterface $io, Config $config, string $repository, bool $allowFilesystem = false, ?RepositoryManager $rm = null): RepositoryInterface
{
$repoConfig = static::configFromString($io, $config, $repository, $allowFilesystem);
return static::createRepo($io, $config, $repoConfig, $rm);
}
/**
* @param array<string, mixed> $repoConfig
*/
public static function createRepo(IOInterface $io, Config $config, array $repoConfig, ?RepositoryManager $rm = null): RepositoryInterface
{
if (!$rm) {
@trigger_error('Not passing a repository manager when calling createRepo is deprecated since Composer 2.3.6', E_USER_DEPRECATED);
$rm = static::manager($io, $config);
}
$repos = self::createRepos($rm, [$repoConfig]);
return reset($repos);
}
/**
* @return RepositoryInterface[]
*/
public static function defaultRepos(?IOInterface $io = null, ?Config $config = null, ?RepositoryManager $rm = null): array
{
if (null === $rm) {
@trigger_error('Not passing a repository manager when calling defaultRepos is deprecated since Composer 2.3.6, use defaultReposWithDefaultManager() instead if you cannot get a manager.', E_USER_DEPRECATED);
}
if (null === $config) {
$config = Factory::createConfig($io);
}
if (null !== $io) {
$io->loadConfiguration($config);
}
if (null === $rm) {
if (null === $io) {
throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
}
$rm = static::manager($io, $config, Factory::createHttpDownloader($io, $config));
}
return self::createRepos($rm, $config->getRepositories());
}
public static function manager(IOInterface $io, Config $config, ?HttpDownloader $httpDownloader = null, ?EventDispatcher $eventDispatcher = null, ?ProcessExecutor $process = null): RepositoryManager
{
if ($httpDownloader === null) {
$httpDownloader = Factory::createHttpDownloader($io, $config);
}
if ($process === null) {
$process = new ProcessExecutor($io);
$process->enableAsync();
}
$rm = new RepositoryManager($io, $config, $httpDownloader, $eventDispatcher, $process);
$rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
$rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
$rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
$rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('bitbucket', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('git-bitbucket', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('github', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('fossil', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
$rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
$rm->setRepositoryClass('path', 'Composer\Repository\PathRepository');
return $rm;
}
/**
* @return RepositoryInterface[]
*/
public static function defaultReposWithDefaultManager(IOInterface $io): array
{
$manager = RepositoryFactory::manager($io, $config = Factory::createConfig($io));
$io->loadConfiguration($config);
return RepositoryFactory::defaultRepos($io, $config, $manager);
}
/**
* @param array<int|string, mixed> $repoConfigs
*
* @return RepositoryInterface[]
*/
private static function createRepos(RepositoryManager $rm, array $repoConfigs): array
{
$repos = [];
foreach ($repoConfigs as $index => $repo) {
if (is_string($repo)) {
throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given');
}
if (!is_array($repo)) {
throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.get_debug_type($repo).' given');
}
if (!isset($repo['type'])) {
throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined');
}
$name = self::generateRepositoryName($index, $repo, $repos);
if ($repo['type'] === 'filesystem') {
$repos[$name] = new FilesystemRepository($repo['json']);
} else {
$repos[$name] = $rm->createRepository($repo['type'], $repo, (string) $index);
}
}
return $repos;
}
/**
* @param int|string $index
* @param array{url?: string} $repo
* @param array<int|string, mixed> $existingRepos
*/
public static function generateRepositoryName($index, array $repo, array $existingRepos): string
{
$name = is_int($index) && isset($repo['url']) ? Preg::replace('{^https?://}i', '', $repo['url']) : (string) $index;
while (isset($existingRepos[$name])) {
$name .= '2';
}
return $name;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/LockArrayRepository.php | src/Composer/Repository/LockArrayRepository.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;
/**
* Lock array repository.
*
* Regular array repository, only uses a different type to identify the lock file as the source of info
*
* @author Nils Adermann <naderman@naderman.de>
*/
class LockArrayRepository extends ArrayRepository
{
use CanonicalPackagesTrait;
public function getRepoName(): string
{
return 'lock repo';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/WritableRepositoryInterface.php | src/Composer/Repository/WritableRepositoryInterface.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;
use Composer\Package\PackageInterface;
use Composer\Installer\InstallationManager;
/**
* Writable repository interface.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
interface WritableRepositoryInterface extends RepositoryInterface
{
/**
* Writes repository (f.e. to the disc).
*
* @param bool $devMode Whether dev requirements were included or not in this installation
* @return void
*/
public function write(bool $devMode, InstallationManager $installationManager);
/**
* Adds package to the repository.
*
* @param PackageInterface $package package instance
* @return void
*/
public function addPackage(PackageInterface $package);
/**
* Removes package from the repository.
*
* @param PackageInterface $package package instance
* @return void
*/
public function removePackage(PackageInterface $package);
/**
* Get unique packages (at most one package of each name), with aliases resolved and removed.
*
* @return PackageInterface[]
*/
public function getCanonicalPackages();
/**
* Forces a reload of all packages.
*
* @return void
*/
public function reload();
/**
* @param string[] $devPackageNames
* @return void
*/
public function setDevPackageNames(array $devPackageNames);
/**
* @return string[] Names of dependencies installed through require-dev
*/
public function getDevPackageNames();
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/PearRepository.php | src/Composer/Repository/PearRepository.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;
/**
* Builds list of package from PEAR channel.
*
* Packages read from channel are named as 'pear-{channelName}/{packageName}'
* and has aliased as 'pear-{channelAlias}/{packageName}'
*
* @author Benjamin Eberlei <kontakt@beberlei.de>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @deprecated
* @private
*/
class PearRepository extends ArrayRepository
{
public function __construct()
{
throw new \InvalidArgumentException('The PEAR repository has been removed from Composer 2.x');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositorySecurityException.php | src/Composer/Repository/RepositorySecurityException.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;
/**
* Thrown when a security problem, like a broken or missing signature
*
* @author Eric Daspet <edaspet@survol.fr>
*/
class RepositorySecurityException extends \Exception
{
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/VcsRepository.php | src/Composer/Repository/VcsRepository.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;
use Composer\Downloader\TransportException;
use Composer\Pcre\Preg;
use Composer\Repository\Vcs\VcsDriverInterface;
use Composer\Package\Version\VersionParser;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Loader\ValidatingArrayLoader;
use Composer\Package\Loader\InvalidPackageException;
use Composer\Package\Loader\LoaderInterface;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Util\HttpDownloader;
use Composer\Util\Url;
use Composer\Semver\Constraint\Constraint;
use Composer\IO\IOInterface;
use Composer\Config;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class VcsRepository extends ArrayRepository implements ConfigurableRepositoryInterface
{
/** @var string */
protected $url;
/** @var ?string */
protected $packageName;
/** @var bool */
protected $isVerbose;
/** @var bool */
protected $isVeryVerbose;
/** @var IOInterface */
protected $io;
/** @var Config */
protected $config;
/** @var VersionParser */
protected $versionParser;
/** @var string */
protected $type;
/** @var ?LoaderInterface */
protected $loader;
/** @var array<string, mixed> */
protected $repoConfig;
/** @var HttpDownloader */
protected $httpDownloader;
/** @var ProcessExecutor */
protected $processExecutor;
/** @var bool */
protected $branchErrorOccurred = false;
/** @var array<string, class-string<VcsDriverInterface>> */
private $drivers;
/** @var ?VcsDriverInterface */
private $driver;
/** @var ?VersionCacheInterface */
private $versionCache;
/** @var list<string> */
private $emptyReferences = [];
/** @var array<'tags'|'branches', array<string, TransportException>> */
private $versionTransportExceptions = [];
/**
* @param array{url: string, type?: string}&array<string, mixed> $repoConfig
* @param array<string, class-string<VcsDriverInterface>>|null $drivers
*/
public function __construct(array $repoConfig, IOInterface $io, Config $config, HttpDownloader $httpDownloader, ?EventDispatcher $dispatcher = null, ?ProcessExecutor $process = null, ?array $drivers = null, ?VersionCacheInterface $versionCache = null)
{
parent::__construct();
$this->drivers = $drivers ?: [
'github' => 'Composer\Repository\Vcs\GitHubDriver',
'gitlab' => 'Composer\Repository\Vcs\GitLabDriver',
'bitbucket' => 'Composer\Repository\Vcs\GitBitbucketDriver',
'git-bitbucket' => 'Composer\Repository\Vcs\GitBitbucketDriver',
'forgejo' => 'Composer\Repository\Vcs\ForgejoDriver',
'git' => 'Composer\Repository\Vcs\GitDriver',
'hg' => 'Composer\Repository\Vcs\HgDriver',
'perforce' => 'Composer\Repository\Vcs\PerforceDriver',
'fossil' => 'Composer\Repository\Vcs\FossilDriver',
// svn must be last because identifying a subversion server for sure is practically impossible
'svn' => 'Composer\Repository\Vcs\SvnDriver',
];
$this->url = $repoConfig['url'] = Platform::expandPath($repoConfig['url']);
$this->io = $io;
$this->type = $repoConfig['type'] ?? 'vcs';
$this->isVerbose = $io->isVerbose();
$this->isVeryVerbose = $io->isVeryVerbose();
$this->config = $config;
$this->repoConfig = $repoConfig;
$this->versionCache = $versionCache;
$this->httpDownloader = $httpDownloader;
$this->processExecutor = $process ?? new ProcessExecutor($io);
}
public function getRepoName()
{
$driverClass = get_class($this->getDriver());
$driverType = array_search($driverClass, $this->drivers);
if (!$driverType) {
$driverType = $driverClass;
}
return 'vcs repo ('.$driverType.' '.Url::sanitize($this->url).')';
}
public function getRepoConfig()
{
return $this->repoConfig;
}
public function setLoader(LoaderInterface $loader): void
{
$this->loader = $loader;
}
public function getDriver(): ?VcsDriverInterface
{
if ($this->driver) {
return $this->driver;
}
if (isset($this->drivers[$this->type])) {
$class = $this->drivers[$this->type];
$this->driver = new $class($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->processExecutor);
$this->driver->initialize();
return $this->driver;
}
foreach ($this->drivers as $driver) {
if ($driver::supports($this->io, $this->config, $this->url)) {
$this->driver = new $driver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->processExecutor);
$this->driver->initialize();
return $this->driver;
}
}
foreach ($this->drivers as $driver) {
if ($driver::supports($this->io, $this->config, $this->url, true)) {
$this->driver = new $driver($this->repoConfig, $this->io, $this->config, $this->httpDownloader, $this->processExecutor);
$this->driver->initialize();
return $this->driver;
}
}
return null;
}
public function hadInvalidBranches(): bool
{
return $this->branchErrorOccurred;
}
/**
* @return list<string>
*/
public function getEmptyReferences(): array
{
return $this->emptyReferences;
}
/**
* @return array<'tags'|'branches', array<string, TransportException>>
*/
public function getVersionTransportExceptions(): array
{
return $this->versionTransportExceptions;
}
protected function initialize()
{
parent::initialize();
$isVerbose = $this->isVerbose;
$isVeryVerbose = $this->isVeryVerbose;
$driver = $this->getDriver();
if (!$driver) {
throw new \InvalidArgumentException('No driver found to handle VCS repository '.$this->url);
}
$this->versionParser = new VersionParser;
if (!$this->loader) {
$this->loader = new ArrayLoader($this->versionParser);
}
$hasRootIdentifierComposerJson = false;
try {
$hasRootIdentifierComposerJson = $driver->hasComposerFile($driver->getRootIdentifier());
if ($hasRootIdentifierComposerJson) {
$data = $driver->getComposerInformation($driver->getRootIdentifier());
$this->packageName = !empty($data['name']) ? $data['name'] : null;
}
} catch (\Exception $e) {
if ($e instanceof TransportException && $this->shouldRethrowTransportException($e)) {
throw $e;
}
if ($isVeryVerbose) {
$this->io->writeError('<error>Skipped parsing '.$driver->getRootIdentifier().', '.$e->getMessage().'</error>');
}
}
foreach ($driver->getTags() as $tag => $identifier) {
$tag = (string) $tag;
$msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $tag . '</comment>)';
// strip the release- prefix from tags if present
$tag = str_replace('release-', '', $tag);
$cachedPackage = $this->getCachedPackageVersion($tag, $identifier, $isVerbose, $isVeryVerbose);
if ($cachedPackage) {
$this->addPackage($cachedPackage);
continue;
}
if ($cachedPackage === false) {
$this->emptyReferences[] = $identifier;
continue;
}
if (!$parsedTag = $this->validateTag($tag)) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped tag '.$tag.', invalid tag name</warning>');
}
continue;
}
if ($isVeryVerbose) {
$this->io->writeError($msg);
} elseif ($isVerbose) {
$this->io->overwriteError($msg, false);
}
try {
$data = $driver->getComposerInformation($identifier);
if (null === $data) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped tag '.$tag.', no composer file</warning>');
}
$this->emptyReferences[] = $identifier;
continue;
}
// manually versioned package
if (isset($data['version'])) {
$data['version_normalized'] = $this->versionParser->normalize($data['version']);
} else {
// auto-versioned package, read value from tag
$data['version'] = $tag;
$data['version_normalized'] = $parsedTag;
}
// make sure tag packages have no -dev flag
$data['version'] = Preg::replace('{[.-]?dev$}i', '', $data['version']);
$data['version_normalized'] = Preg::replace('{(^dev-|[.-]?dev$)}i', '', $data['version_normalized']);
// make sure tag do not contain the default-branch marker
unset($data['default-branch']);
// broken package, version doesn't match tag
if ($data['version_normalized'] !== $parsedTag) {
if ($isVeryVerbose) {
if (Preg::isMatch('{(^dev-|[.-]?dev$)}i', $parsedTag)) {
$this->io->writeError('<warning>Skipped tag '.$tag.', invalid tag name, tags can not use dev prefixes or suffixes</warning>');
} else {
$this->io->writeError('<warning>Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json</warning>');
}
}
continue;
}
$tagPackageName = $this->packageName ?: ($data['name'] ?? '');
if ($existingPackage = $this->findPackage($tagPackageName, $data['version_normalized'])) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped tag '.$tag.', it conflicts with an another tag ('.$existingPackage->getPrettyVersion().') as both resolve to '.$data['version_normalized'].' internally</warning>');
}
continue;
}
if ($isVeryVerbose) {
$this->io->writeError('Importing tag '.$tag.' ('.$data['version_normalized'].')');
}
$this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier)));
} catch (\Exception $e) {
if ($e instanceof TransportException) {
$this->versionTransportExceptions['tags'][$tag] = $e;
if ($e->getCode() === 404) {
$this->emptyReferences[] = $identifier;
}
if ($this->shouldRethrowTransportException($e)) {
throw $e;
}
}
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found (' . $e->getCode() . ' HTTP status code)' : $e->getMessage()).'</warning>');
}
continue;
}
}
if (!$isVeryVerbose) {
$this->io->overwriteError('', false);
}
$branches = $driver->getBranches();
// make sure the root identifier branch gets loaded first
if ($hasRootIdentifierComposerJson && isset($branches[$driver->getRootIdentifier()])) {
$branches = [$driver->getRootIdentifier() => $branches[$driver->getRootIdentifier()]] + $branches;
}
foreach ($branches as $branch => $identifier) {
$branch = (string) $branch;
$msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $branch . '</comment>)';
if ($isVeryVerbose) {
$this->io->writeError($msg);
} elseif ($isVerbose) {
$this->io->overwriteError($msg, false);
}
if (!$parsedBranch = $this->validateBranch($branch)) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped branch '.$branch.', invalid name</warning>');
}
continue;
}
// make sure branch packages have a dev flag
if (strpos($parsedBranch, 'dev-') === 0 || VersionParser::DEFAULT_BRANCH_ALIAS === $parsedBranch) {
$version = 'dev-' . str_replace('#', '+', $branch);
$parsedBranch = str_replace('#', '+', $parsedBranch);
} else {
$prefix = strpos($branch, 'v') === 0 ? 'v' : '';
$version = $prefix . Preg::replace('{(\.9{7})+}', '.x', $parsedBranch);
}
$cachedPackage = $this->getCachedPackageVersion($version, $identifier, $isVerbose, $isVeryVerbose, $driver->getRootIdentifier() === $branch);
if ($cachedPackage) {
$this->addPackage($cachedPackage);
continue;
}
if ($cachedPackage === false) {
$this->emptyReferences[] = $identifier;
continue;
}
try {
$data = $driver->getComposerInformation($identifier);
if (null === $data) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped branch '.$branch.', no composer file</warning>');
}
$this->emptyReferences[] = $identifier;
continue;
}
// branches are always auto-versioned, read value from branch name
$data['version'] = $version;
$data['version_normalized'] = $parsedBranch;
unset($data['default-branch']);
if ($driver->getRootIdentifier() === $branch) {
$data['default-branch'] = true;
}
if ($isVeryVerbose) {
$this->io->writeError('Importing branch '.$branch.' ('.$data['version'].')');
}
$packageData = $this->preProcess($driver, $data, $identifier);
$package = $this->loader->load($packageData);
if ($this->loader instanceof ValidatingArrayLoader && \count($this->loader->getWarnings()) > 0) {
throw new InvalidPackageException($this->loader->getErrors(), $this->loader->getWarnings(), $packageData);
}
$this->addPackage($package);
} catch (TransportException $e) {
$this->versionTransportExceptions['branches'][$branch] = $e;
if ($e->getCode() === 404) {
$this->emptyReferences[] = $identifier;
}
if ($this->shouldRethrowTransportException($e)) {
throw $e;
}
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped branch '.$branch.', no composer file was found (' . $e->getCode() . ' HTTP status code)</warning>');
}
continue;
} catch (\Exception $e) {
if (!$isVeryVerbose) {
$this->io->writeError('');
}
$this->branchErrorOccurred = true;
$this->io->writeError('<error>Skipped branch '.$branch.', '.$e->getMessage().'</error>');
$this->io->writeError('');
continue;
}
}
$driver->cleanup();
if (!$isVeryVerbose) {
$this->io->overwriteError('', false);
}
if (!$this->getPackages()) {
throw new InvalidRepositoryException('No valid composer.json was found in any branch or tag of '.$this->url.', could not load a package from it.');
}
}
/**
* @param array{name?: string, dist?: array{type: string, url: string, reference: string, shasum: string}, source?: array{type: string, url: string, reference: string}} $data
*
* @return array{name: string|null, dist: array{type: string, url: string, reference: string, shasum: string}|null, source: array{type: string, url: string, reference: string}}
*/
protected function preProcess(VcsDriverInterface $driver, array $data, string $identifier): array
{
// keep the name of the main identifier for all packages
// this ensures that a package can be renamed in one place and that all old tags
// will still be installable using that new name without requiring re-tagging
$dataPackageName = $data['name'] ?? null;
$data['name'] = $this->packageName ?: $dataPackageName;
if (!isset($data['dist'])) {
$data['dist'] = $driver->getDist($identifier);
}
if (!isset($data['source'])) {
$data['source'] = $driver->getSource($identifier);
}
// if custom dist info is provided but does not provide a reference, copy the source reference to it
if (is_array($data['dist']) && !isset($data['dist']['reference']) && isset($data['source']['reference'])) {
$data['dist']['reference'] = $data['source']['reference'];
}
return $data;
}
/**
* @return string|false
*/
private function validateBranch(string $branch)
{
try {
$normalizedBranch = $this->versionParser->normalizeBranch($branch);
// validate that the branch name has no weird characters conflicting with constraints
$this->versionParser->parseConstraints($normalizedBranch);
return $normalizedBranch;
} catch (\Exception $e) {
}
return false;
}
/**
* @return string|false
*/
private function validateTag(string $version)
{
try {
return $this->versionParser->normalize($version);
} catch (\Exception $e) {
}
return false;
}
/**
* @return \Composer\Package\CompletePackage|\Composer\Package\CompleteAliasPackage|null|false null if no cache present, false if the absence of a version was cached
*/
private function getCachedPackageVersion(string $version, string $identifier, bool $isVerbose, bool $isVeryVerbose, bool $isDefaultBranch = false)
{
if (!$this->versionCache) {
return null;
}
$cachedPackage = $this->versionCache->getVersionPackage($version, $identifier);
if ($cachedPackage === false) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped '.$version.', no composer file (cached from ref '.$identifier.')</warning>');
}
return false;
}
if ($cachedPackage) {
$msg = 'Found cached composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $version . '</comment>)';
if ($isVeryVerbose) {
$this->io->writeError($msg);
} elseif ($isVerbose) {
$this->io->overwriteError($msg, false);
}
unset($cachedPackage['default-branch']);
if ($isDefaultBranch) {
$cachedPackage['default-branch'] = true;
}
if ($existingPackage = $this->findPackage($cachedPackage['name'], new Constraint('=', $cachedPackage['version_normalized']))) {
if ($isVeryVerbose) {
$this->io->writeError('<warning>Skipped cached version '.$version.', it conflicts with an another tag ('.$existingPackage->getPrettyVersion().') as both resolve to '.$cachedPackage['version_normalized'].' internally</warning>');
}
$cachedPackage = null;
}
}
if ($cachedPackage) {
return $this->loader->load($cachedPackage);
}
return null;
}
private function shouldRethrowTransportException(TransportException $e): bool
{
return in_array($e->getCode(), [401, 403, 429], true) || $e->getCode() >= 500;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/PackageRepository.php | src/Composer/Repository/PackageRepository.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;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Loader\ValidatingArrayLoader;
use Composer\Package\Version\VersionParser;
use Composer\Pcre\Preg;
/**
* Package repository.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class PackageRepository extends ArrayRepository implements AdvisoryProviderInterface
{
/** @var mixed[] */
private $config;
/** @var mixed[] */
private $securityAdvisories;
/**
* Initializes filesystem repository.
*
* @param array{package: mixed[]} $config package definition
*/
public function __construct(array $config)
{
parent::__construct();
$this->config = $config['package'];
// make sure we have an array of package definitions
if (!is_numeric(key($this->config))) {
$this->config = [$this->config];
}
$this->securityAdvisories = $config['security-advisories'] ?? [];
}
/**
* Initializes repository (reads file, or remote address).
*/
protected function initialize(): void
{
parent::initialize();
$loader = new ValidatingArrayLoader(new ArrayLoader(null, true), true);
foreach ($this->config as $package) {
try {
$package = $loader->load($package);
} catch (\Exception $e) {
throw new InvalidRepositoryException('A repository of type "package" contains an invalid package definition: '.$e->getMessage()."\n\nInvalid package definition:\n".json_encode($package));
}
$this->addPackage($package);
}
}
public function getRepoName(): string
{
return Preg::replace('{^array }', 'package ', parent::getRepoName());
}
public function hasSecurityAdvisories(): bool
{
return count($this->securityAdvisories) > 0;
}
/**
* @todo not sure if this is a good idea, just helped setting up the test fixtures
*/
public function getSecurityAdvisories(array $packageConstraintMap, bool $allowPartialAdvisories = false): array
{
$parser = new VersionParser();
$advisories = [];
foreach ($this->securityAdvisories as $packageName => $packageAdvisories) {
if (isset($packageConstraintMap[$packageName])) {
$advisories[$packageName] = array_values(array_filter(array_map(function (array $data) use ($packageName, $allowPartialAdvisories, $packageConstraintMap, $parser) {
$advisory = PartialSecurityAdvisory::create($packageName, $data, $parser);
if (!$allowPartialAdvisories && !$advisory instanceof SecurityAdvisory) {
throw new \RuntimeException('Advisory for '.$packageName.' could not be loaded as a full advisory from '.$this->getRepoName() . PHP_EOL . var_export($data, true));
}
if (!$advisory->affectedVersions->matches($packageConstraintMap[$packageName])) {
return null;
}
return $advisory;
}, $packageAdvisories)));
}
}
return ['advisories' => array_filter($advisories, static function ($adv): bool { return \count($adv) > 0; }), 'namesFound' => array_keys($advisories)];
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/ConfigurableRepositoryInterface.php | src/Composer/Repository/ConfigurableRepositoryInterface.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;
/**
* Configurable repository interface.
*
* @author Lukas Homza <lukashomz@gmail.com>
*/
interface ConfigurableRepositoryInterface
{
/**
* @return mixed[]
*/
public function getRepoConfig();
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/InvalidRepositoryException.php | src/Composer/Repository/InvalidRepositoryException.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;
/**
* Exception thrown when a package repository is utterly broken
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class InvalidRepositoryException extends \Exception
{
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/ComposerRepository.php | src/Composer/Repository/ComposerRepository.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;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
use Composer\Package\BasePackage;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\PackageInterface;
use Composer\Package\AliasPackage;
use Composer\Package\CompletePackage;
use Composer\Package\CompleteAliasPackage;
use Composer\Package\Version\VersionParser;
use Composer\Package\Version\StabilityFilter;
use Composer\Json\JsonFile;
use Composer\Cache;
use Composer\Config;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Plugin\PostFileDownloadEvent;
use Composer\Semver\CompilingMatcher;
use Composer\Util\HttpDownloader;
use Composer\Util\Loop;
use Composer\Plugin\PluginEvents;
use Composer\Plugin\PreFileDownloadEvent;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Downloader\TransportException;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Util\Http\Response;
use Composer\MetadataMinifier\MetadataMinifier;
use Composer\Util\Url;
use React\Promise\PromiseInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ComposerRepository extends ArrayRepository implements ConfigurableRepositoryInterface, AdvisoryProviderInterface
{
/**
* @var mixed[]
* @phpstan-var array{url: string, options?: mixed[], type?: 'composer', allow_ssl_downgrade?: bool}
*/
private $repoConfig;
/** @var mixed[] */
private $options;
/** @var non-empty-string */
private $url;
/** @var non-empty-string */
private $baseUrl;
/** @var IOInterface */
private $io;
/** @var HttpDownloader */
private $httpDownloader;
/** @var Loop */
private $loop;
/** @var Cache */
protected $cache;
/** @var ?non-empty-string */
protected $notifyUrl = null;
/** @var ?non-empty-string */
protected $searchUrl = null;
/** @var ?non-empty-string a URL containing %package% which can be queried to get providers of a given name */
protected $providersApiUrl = null;
/** @var bool */
protected $hasProviders = false;
/** @var ?non-empty-string */
protected $providersUrl = null;
/** @var ?non-empty-string */
protected $listUrl = null;
/** @var bool Indicates whether a comprehensive list of packages this repository might provide is expressed in the repository root. **/
protected $hasAvailablePackageList = false;
/** @var ?array<string> */
protected $availablePackages = null;
/** @var ?array<non-empty-string> */
protected $availablePackagePatterns = null;
/** @var ?non-empty-string */
protected $lazyProvidersUrl = null;
/** @var ?array<string, array{sha256: string}> */
protected $providerListing;
/** @var ArrayLoader */
protected $loader;
/** @var bool */
private $allowSslDowngrade = false;
/** @var ?EventDispatcher */
private $eventDispatcher;
/** @var ?array<string, list<array{url: non-empty-string, preferred: bool}>> */
private $sourceMirrors;
/** @var ?list<array{url: non-empty-string, preferred: bool}> */
private $distMirrors;
/** @var bool */
private $degradedMode = false;
/** @var mixed[]|true */
private $rootData;
/** @var bool */
private $hasPartialPackages = false;
/** @var ?array<string, mixed[]> */
private $partialPackagesByName = null;
/** @var bool */
private $displayedWarningAboutNonMatchingPackageIndex = false;
/** @var array{metadata: bool, api-url: string|null}|null */
private $securityAdvisoryConfig = null;
/**
* @var array list of package names which are fresh and can be loaded from the cache directly in case loadPackage is called several times
* useful for v2 metadata repositories with lazy providers
* @phpstan-var array<string, true>
*/
private $freshMetadataUrls = [];
/**
* @var array list of package names which returned a 404 and should not be re-fetched in case loadPackage is called several times
* useful for v2 metadata repositories with lazy providers
* @phpstan-var array<string, true>
*/
private $packagesNotFoundCache = [];
/**
* @var VersionParser
*/
private $versionParser;
/**
* @param array<string, mixed> $repoConfig
* @phpstan-param array{url: non-empty-string, options?: mixed[], type?: 'composer', allow_ssl_downgrade?: bool} $repoConfig
*/
public function __construct(array $repoConfig, IOInterface $io, Config $config, HttpDownloader $httpDownloader, ?EventDispatcher $eventDispatcher = null)
{
parent::__construct();
if (!Preg::isMatch('{^[\w.]+\??://}', $repoConfig['url'])) {
if (($localFilePath = realpath($repoConfig['url'])) !== false) {
// it is a local path, add file scheme
$repoConfig['url'] = 'file://'.$localFilePath;
} else {
// otherwise, assume http as the default protocol
$repoConfig['url'] = 'http://'.$repoConfig['url'];
}
}
$repoConfig['url'] = rtrim($repoConfig['url'], '/');
if ($repoConfig['url'] === '') {
throw new \InvalidArgumentException('The repository url must not be an empty string');
}
if (str_starts_with($repoConfig['url'], 'https?')) {
$repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
}
$urlBits = parse_url(strtr($repoConfig['url'], '\\', '/'));
if ($urlBits === false || empty($urlBits['scheme'])) {
throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
}
if (!isset($repoConfig['options'])) {
$repoConfig['options'] = [];
}
if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
$this->allowSslDowngrade = true;
}
$this->options = $repoConfig['options'];
$this->url = $repoConfig['url'];
// force url for packagist.org to repo.packagist.org
if (Preg::isMatch('{^(?P<proto>https?)://packagist\.org/?$}i', $this->url, $match)) {
$this->url = $match['proto'].'://repo.packagist.org';
}
$baseUrl = rtrim(Preg::replace('{(?:/[^/\\\\]+\.json)?(?:[?#].*)?$}', '', $this->url), '/');
assert($baseUrl !== '');
$this->baseUrl = $baseUrl;
$this->io = $io;
$this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($this->url)), 'a-z0-9.$~_');
$this->cache->setReadOnly($config->get('cache-read-only'));
$this->versionParser = new VersionParser();
$this->loader = new ArrayLoader($this->versionParser);
$this->httpDownloader = $httpDownloader;
$this->eventDispatcher = $eventDispatcher;
$this->repoConfig = $repoConfig;
$this->loop = new Loop($this->httpDownloader);
}
public function getRepoName()
{
return 'composer repo ('.Url::sanitize($this->url).')';
}
public function getRepoConfig()
{
return $this->repoConfig;
}
/**
* @inheritDoc
*/
public function findPackage(string $name, $constraint)
{
// this call initializes loadRootServerFile which is needed for the rest below to work
$hasProviders = $this->hasProviders();
$name = strtolower($name);
if (!$constraint instanceof ConstraintInterface) {
$constraint = $this->versionParser->parseConstraints($constraint);
}
if ($this->lazyProvidersUrl) {
if ($this->hasPartialPackages() && isset($this->partialPackagesByName[$name])) {
return $this->filterPackages($this->whatProvides($name), $constraint, true);
}
if ($this->hasAvailablePackageList && !$this->lazyProvidersRepoContains($name)) {
return null;
}
$packages = $this->loadAsyncPackages([$name => $constraint]);
if (count($packages['packages']) > 0) {
return reset($packages['packages']);
}
return null;
}
if ($hasProviders) {
foreach ($this->getProviderNames() as $providerName) {
if ($name === $providerName) {
return $this->filterPackages($this->whatProvides($providerName), $constraint, true);
}
}
return null;
}
return parent::findPackage($name, $constraint);
}
/**
* @inheritDoc
*/
public function findPackages(string $name, $constraint = null)
{
// this call initializes loadRootServerFile which is needed for the rest below to work
$hasProviders = $this->hasProviders();
$name = strtolower($name);
if (null !== $constraint && !$constraint instanceof ConstraintInterface) {
$constraint = $this->versionParser->parseConstraints($constraint);
}
if ($this->lazyProvidersUrl) {
if ($this->hasPartialPackages() && isset($this->partialPackagesByName[$name])) {
return $this->filterPackages($this->whatProvides($name), $constraint);
}
if ($this->hasAvailablePackageList && !$this->lazyProvidersRepoContains($name)) {
return [];
}
$result = $this->loadAsyncPackages([$name => $constraint]);
return $result['packages'];
}
if ($hasProviders) {
foreach ($this->getProviderNames() as $providerName) {
if ($name === $providerName) {
return $this->filterPackages($this->whatProvides($providerName), $constraint);
}
}
return [];
}
return parent::findPackages($name, $constraint);
}
/**
* @param array<BasePackage> $packages
*
* @return BasePackage|array<BasePackage>|null
*/
private function filterPackages(array $packages, ?ConstraintInterface $constraint = null, bool $returnFirstMatch = false)
{
if (null === $constraint) {
if ($returnFirstMatch) {
return reset($packages);
}
return $packages;
}
$filteredPackages = [];
foreach ($packages as $package) {
$pkgConstraint = new Constraint('==', $package->getVersion());
if ($constraint->matches($pkgConstraint)) {
if ($returnFirstMatch) {
return $package;
}
$filteredPackages[] = $package;
}
}
if ($returnFirstMatch) {
return null;
}
return $filteredPackages;
}
public function getPackages()
{
$hasProviders = $this->hasProviders();
if ($this->lazyProvidersUrl) {
if (is_array($this->availablePackages) && !$this->availablePackagePatterns) {
$packageMap = [];
foreach ($this->availablePackages as $name) {
$packageMap[$name] = new MatchAllConstraint();
}
$result = $this->loadAsyncPackages($packageMap);
return array_values($result['packages']);
}
if ($this->hasPartialPackages()) {
if (!is_array($this->partialPackagesByName)) {
throw new \LogicException('hasPartialPackages failed to initialize $this->partialPackagesByName');
}
return $this->createPackages($this->partialPackagesByName, 'packages.json inline packages');
}
throw new \LogicException('Composer repositories that have lazy providers and no available-packages list can not load the complete list of packages, use getPackageNames instead.');
}
if ($hasProviders) {
throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getPackageNames instead.');
}
return parent::getPackages();
}
/**
* @param string|null $packageFilter Package pattern filter which can include "*" as a wildcard
*
* @return string[]
*/
public function getPackageNames(?string $packageFilter = null)
{
$hasProviders = $this->hasProviders();
$filterResults =
/**
* @param list<string> $results
* @return list<string>
*/
static function (array $results): array {
return $results;
}
;
if (null !== $packageFilter && '' !== $packageFilter) {
$packageFilterRegex = BasePackage::packageNameToRegexp($packageFilter);
$filterResults =
/**
* @param list<string> $results
* @return list<string>
*/
static function (array $results) use ($packageFilterRegex): array {
/** @var list<string> $results */
return Preg::grep($packageFilterRegex, $results);
}
;
}
if ($this->lazyProvidersUrl) {
if (is_array($this->availablePackages)) {
return $filterResults(array_keys($this->availablePackages));
}
if ($this->listUrl) {
// no need to call $filterResults here as the $packageFilter is applied in the function itself
return $this->loadPackageList($packageFilter);
}
if ($this->hasPartialPackages() && $this->partialPackagesByName !== null) {
return $filterResults(array_keys($this->partialPackagesByName));
}
return [];
}
if ($hasProviders) {
return $filterResults($this->getProviderNames());
}
$names = [];
foreach ($this->getPackages() as $package) {
$names[] = $package->getPrettyName();
}
return $filterResults($names);
}
/**
* @return list<string>
*/
private function getVendorNames(): array
{
$cacheKey = 'vendor-list.txt';
$cacheAge = $this->cache->getAge($cacheKey);
if (false !== $cacheAge && $cacheAge < 600 && ($cachedData = $this->cache->read($cacheKey)) !== false) {
$cachedData = explode("\n", $cachedData);
return $cachedData;
}
$names = $this->getPackageNames();
$uniques = [];
foreach ($names as $name) {
$uniques[explode('/', $name, 2)[0]] = true;
}
$vendors = array_keys($uniques);
if (!$this->cache->isReadOnly()) {
$this->cache->write($cacheKey, implode("\n", $vendors));
}
return $vendors;
}
/**
* @return list<string>
*/
private function loadPackageList(?string $packageFilter = null): array
{
if (null === $this->listUrl) {
throw new \LogicException('Make sure to call loadRootServerFile before loadPackageList');
}
$url = $this->listUrl;
if (is_string($packageFilter) && $packageFilter !== '') {
$url .= '?filter='.urlencode($packageFilter);
$result = $this->httpDownloader->get($url, $this->options)->decodeJson();
return $result['packageNames'];
}
$cacheKey = 'package-list.txt';
$cacheAge = $this->cache->getAge($cacheKey);
if (false !== $cacheAge && $cacheAge < 600 && ($cachedData = $this->cache->read($cacheKey)) !== false) {
$cachedData = explode("\n", $cachedData);
return $cachedData;
}
$result = $this->httpDownloader->get($url, $this->options)->decodeJson();
if (!$this->cache->isReadOnly()) {
$this->cache->write($cacheKey, implode("\n", $result['packageNames']));
}
return $result['packageNames'];
}
public function loadPackages(array $packageNameMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = [])
{
// this call initializes loadRootServerFile which is needed for the rest below to work
$hasProviders = $this->hasProviders();
if (!$hasProviders && !$this->hasPartialPackages() && null === $this->lazyProvidersUrl) {
return parent::loadPackages($packageNameMap, $acceptableStabilities, $stabilityFlags, $alreadyLoaded);
}
$packages = [];
$namesFound = [];
if ($hasProviders || $this->hasPartialPackages()) {
foreach ($packageNameMap as $name => $constraint) {
$matches = [];
// if a repo has no providers but only partial packages and the partial packages are missing
// then we don't want to call whatProvides as it would try to load from the providers and fail
if (!$hasProviders && !isset($this->partialPackagesByName[$name])) {
continue;
}
$candidates = $this->whatProvides($name, $acceptableStabilities, $stabilityFlags, $alreadyLoaded);
foreach ($candidates as $candidate) {
if ($candidate->getName() !== $name) {
throw new \LogicException('whatProvides should never return a package with a different name than the requested one');
}
$namesFound[$name] = true;
if (!$constraint || $constraint->matches(new Constraint('==', $candidate->getVersion()))) {
$matches[spl_object_hash($candidate)] = $candidate;
if ($candidate instanceof AliasPackage && !isset($matches[spl_object_hash($candidate->getAliasOf())])) {
$matches[spl_object_hash($candidate->getAliasOf())] = $candidate->getAliasOf();
}
}
}
// add aliases of matched packages even if they did not match the constraint
foreach ($candidates as $candidate) {
if ($candidate instanceof AliasPackage) {
if (isset($matches[spl_object_hash($candidate->getAliasOf())])) {
$matches[spl_object_hash($candidate)] = $candidate;
}
}
}
$packages = array_merge($packages, $matches);
unset($packageNameMap[$name]);
}
}
if ($this->lazyProvidersUrl && count($packageNameMap)) {
if ($this->hasAvailablePackageList) {
foreach ($packageNameMap as $name => $constraint) {
if (!$this->lazyProvidersRepoContains(strtolower($name))) {
unset($packageNameMap[$name]);
}
}
}
$result = $this->loadAsyncPackages($packageNameMap, $acceptableStabilities, $stabilityFlags, $alreadyLoaded);
$packages = array_merge($packages, $result['packages']);
$namesFound = array_merge($namesFound, $result['namesFound']);
}
return ['namesFound' => array_keys($namesFound), 'packages' => $packages];
}
/**
* @inheritDoc
*/
public function search(string $query, int $mode = 0, ?string $type = null)
{
$this->loadRootServerFile(600);
if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
$url = str_replace(['%query%', '%type%'], [urlencode($query), $type], $this->searchUrl);
$search = $this->httpDownloader->get($url, $this->options)->decodeJson();
if (empty($search['results'])) {
return [];
}
$results = [];
foreach ($search['results'] as $result) {
// do not show virtual packages in results as they are not directly useful from a composer perspective
if (!empty($result['virtual'])) {
continue;
}
$results[] = $result;
}
return $results;
}
if ($mode === self::SEARCH_VENDOR) {
$results = [];
$regex = '{(?:'.implode('|', Preg::split('{\s+}', $query)).')}i';
$vendorNames = $this->getVendorNames();
foreach (Preg::grep($regex, $vendorNames) as $name) {
$results[] = ['name' => $name, 'description' => ''];
}
return $results;
}
if ($this->hasProviders() || $this->lazyProvidersUrl) {
// optimize search for "^foo/bar" where at least "^foo/" is present by loading this directly from the listUrl if present
if (Preg::isMatchStrictGroups('{^\^(?P<query>(?P<vendor>[a-z0-9_.-]+)/[a-z0-9_.-]*)\*?$}i', $query, $match) && $this->listUrl !== null) {
$url = $this->listUrl . '?vendor='.urlencode($match['vendor']).'&filter='.urlencode($match['query'].'*');
$result = $this->httpDownloader->get($url, $this->options)->decodeJson();
$results = [];
foreach ($result['packageNames'] as $name) {
$results[] = ['name' => $name, 'description' => ''];
}
return $results;
}
$results = [];
$regex = '{(?:'.implode('|', Preg::split('{\s+}', $query)).')}i';
$packageNames = $this->getPackageNames();
foreach (Preg::grep($regex, $packageNames) as $name) {
$results[] = ['name' => $name, 'description' => ''];
}
return $results;
}
return parent::search($query, $mode);
}
public function hasSecurityAdvisories(): bool
{
$this->loadRootServerFile(600);
return $this->securityAdvisoryConfig !== null && ($this->securityAdvisoryConfig['metadata'] || $this->securityAdvisoryConfig['api-url'] !== null);
}
/**
* @inheritDoc
*/
public function getSecurityAdvisories(array $packageConstraintMap, bool $allowPartialAdvisories = false): array
{
$this->loadRootServerFile(600);
if (null === $this->securityAdvisoryConfig) {
return ['namesFound' => [], 'advisories' => []];
}
$advisories = [];
$namesFound = [];
$apiUrl = $this->securityAdvisoryConfig['api-url'];
// respect available-package-patterns / available-packages directives from the repo
if ($this->hasAvailablePackageList) {
foreach ($packageConstraintMap as $name => $constraint) {
if (!$this->lazyProvidersRepoContains(strtolower($name))) {
unset($packageConstraintMap[$name]);
}
}
}
$parser = new VersionParser();
/**
* @param array<mixed> $data
* @param string $name
* @return ($allowPartialAdvisories is false ? SecurityAdvisory|null : PartialSecurityAdvisory|SecurityAdvisory|null)
*/
$create = 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 '.$this->getRepoName() . PHP_EOL . var_export($data, true));
}
if (!$advisory->affectedVersions->matches($packageConstraintMap[$name])) {
return null;
}
return $advisory;
};
if ($this->securityAdvisoryConfig['metadata'] && ($allowPartialAdvisories || $apiUrl === null)) {
$promises = [];
foreach ($packageConstraintMap as $name => $constraint) {
$name = strtolower($name);
// skip platform packages, root package and composer-plugin-api
if (PlatformRepository::isPlatformPackage($name) || '__root__' === $name) {
continue;
}
$promises[] = $this->startCachedAsyncDownload($name, $name)
->then(static function (array $spec) use (&$advisories, &$namesFound, &$packageConstraintMap, $name, $create): void {
[$response] = $spec;
if (!isset($response['security-advisories']) || !is_array($response['security-advisories'])) {
return;
}
$namesFound[$name] = true;
if (count($response['security-advisories']) > 0) {
$advisories[$name] = array_values(array_filter(array_map(
static function ($data) use ($name, $create) {
return $create($data, $name);
},
$response['security-advisories']
)));
}
unset($packageConstraintMap[$name]);
});
}
$this->loop->wait($promises);
}
if ($apiUrl !== null && count($packageConstraintMap) > 0) {
$options = $this->options;
$options['http']['method'] = 'POST';
if (isset($options['http']['header'])) {
$options['http']['header'] = (array) $options['http']['header'];
}
$options['http']['header'][] = 'Content-type: application/x-www-form-urlencoded';
$options['http']['timeout'] = 10;
$options['http']['content'] = http_build_query(['packages' => array_keys($packageConstraintMap)]);
$response = $this->httpDownloader->get($apiUrl, $options);
$warned = false;
/** @var string $name */
foreach ($response->decodeJson()['advisories'] as $name => $list) {
if (!isset($packageConstraintMap[$name])) {
if (!$warned) {
$this->io->writeError('<warning>'.$this->getRepoName().' returned names which were not requested in response to the security-advisories API. '.$name.' was not requested but is present in the response. Requested names were: '.implode(', ', array_keys($packageConstraintMap)).'</warning>');
$warned = true;
}
continue;
}
if (count($list) > 0) {
$advisories[$name] = array_values(array_filter(array_map(
static function ($data) use ($name, $create) {
return $create($data, $name);
},
$list
)));
}
$namesFound[$name] = true;
}
}
return ['namesFound' => array_keys($namesFound), 'advisories' => array_filter($advisories, static function ($adv): bool { return \count($adv) > 0; })];
}
public function getProviders(string $packageName)
{
$this->loadRootServerFile();
$result = [];
if ($this->providersApiUrl) {
try {
$apiResult = $this->httpDownloader->get(str_replace('%package%', $packageName, $this->providersApiUrl), $this->options)->decodeJson();
} catch (TransportException $e) {
if ($e->getStatusCode() === 404) {
return $result;
}
throw $e;
}
foreach ($apiResult['providers'] as $provider) {
$result[$provider['name']] = $provider;
}
return $result;
}
if ($this->hasPartialPackages()) {
if (!is_array($this->partialPackagesByName)) {
throw new \LogicException('hasPartialPackages failed to initialize $this->partialPackagesByName');
}
foreach ($this->partialPackagesByName as $versions) {
foreach ($versions as $candidate) {
if (isset($result[$candidate['name']]) || !isset($candidate['provide'][$packageName])) {
continue;
}
$result[$candidate['name']] = [
'name' => $candidate['name'],
'description' => $candidate['description'] ?? '',
'type' => $candidate['type'] ?? '',
];
}
}
}
if ($this->packages) {
$result = array_merge($result, parent::getProviders($packageName));
}
return $result;
}
/**
* @return string[]
*/
private function getProviderNames(): array
{
$this->loadRootServerFile();
if (null === $this->providerListing) {
$data = $this->loadRootServerFile();
if (is_array($data)) {
$this->loadProviderListings($data);
}
}
if ($this->lazyProvidersUrl) {
// Can not determine list of provided packages for lazy repositories
return [];
}
if (null !== $this->providersUrl && null !== $this->providerListing) {
return array_keys($this->providerListing);
}
return [];
}
protected function configurePackageTransportOptions(PackageInterface $package): void
{
foreach ($package->getDistUrls() as $url) {
if (strpos($url, $this->baseUrl) === 0) {
$package->setTransportOptions($this->options);
return;
}
}
}
private function hasProviders(): bool
{
$this->loadRootServerFile();
return $this->hasProviders;
}
/**
* @param string $name package name
* @param array<string, int>|null $acceptableStabilities
* @phpstan-param array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*>|null $acceptableStabilities
* @param array<string, int>|null $stabilityFlags an array of package name => BasePackage::STABILITY_* value
* @phpstan-param array<string, BasePackage::STABILITY_*>|null $stabilityFlags
* @param array<string, array<string, PackageInterface>> $alreadyLoaded
*
* @return array<string, BasePackage>
*/
private function whatProvides(string $name, ?array $acceptableStabilities = null, ?array $stabilityFlags = null, array $alreadyLoaded = []): array
{
$packagesSource = null;
if (!$this->hasPartialPackages() || !isset($this->partialPackagesByName[$name])) {
// skip platform packages, root package and composer-plugin-api
if (PlatformRepository::isPlatformPackage($name) || '__root__' === $name) {
return [];
}
if (null === $this->providerListing) {
$data = $this->loadRootServerFile();
if (is_array($data)) {
$this->loadProviderListings($data);
}
}
$useLastModifiedCheck = false;
if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) {
$hash = null;
$url = str_replace('%package%', $name, $this->lazyProvidersUrl);
$cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
$useLastModifiedCheck = true;
} elseif ($this->providersUrl) {
// package does not exist in this repo
if (!isset($this->providerListing[$name])) {
return [];
}
$hash = $this->providerListing[$name]['sha256'];
$url = str_replace(['%package%', '%hash%'], [$name, $hash], $this->providersUrl);
$cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
} else {
return [];
}
$packages = null;
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | true |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/FilterRepository.php | src/Composer/Repository/FilterRepository.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;
use Composer\Package\PackageInterface;
use Composer\Package\BasePackage;
use Composer\Pcre\Preg;
/**
* Filters which packages are seen as canonical on this repo by loadPackages
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class FilterRepository implements RepositoryInterface, AdvisoryProviderInterface
{
/** @var ?string */
private $only = null;
/** @var ?non-empty-string */
private $exclude = null;
/** @var bool */
private $canonical = true;
/** @var RepositoryInterface */
private $repo;
/**
* @param array{only?: array<string>, exclude?: array<string>, canonical?: bool} $options
*/
public function __construct(RepositoryInterface $repo, array $options)
{
if (isset($options['only'])) {
if (!is_array($options['only'])) {
throw new \InvalidArgumentException('"only" key for repository '.$repo->getRepoName().' should be an array');
}
$this->only = BasePackage::packageNamesToRegexp($options['only']);
}
if (isset($options['exclude'])) {
if (!is_array($options['exclude'])) {
throw new \InvalidArgumentException('"exclude" key for repository '.$repo->getRepoName().' should be an array');
}
$this->exclude = BasePackage::packageNamesToRegexp($options['exclude']);
}
if ($this->exclude && $this->only) {
throw new \InvalidArgumentException('Only one of "only" and "exclude" can be specified for repository '.$repo->getRepoName());
}
if (isset($options['canonical'])) {
if (!is_bool($options['canonical'])) {
throw new \InvalidArgumentException('"canonical" key for repository '.$repo->getRepoName().' should be a boolean');
}
$this->canonical = $options['canonical'];
}
$this->repo = $repo;
}
public function getRepoName(): string
{
return $this->repo->getRepoName();
}
/**
* Returns the wrapped repositories
*/
public function getRepository(): RepositoryInterface
{
return $this->repo;
}
/**
* @inheritDoc
*/
public function hasPackage(PackageInterface $package): bool
{
return $this->repo->hasPackage($package);
}
/**
* @inheritDoc
*/
public function findPackage($name, $constraint): ?BasePackage
{
if (!$this->isAllowed($name)) {
return null;
}
return $this->repo->findPackage($name, $constraint);
}
/**
* @inheritDoc
*/
public function findPackages($name, $constraint = null): array
{
if (!$this->isAllowed($name)) {
return [];
}
return $this->repo->findPackages($name, $constraint);
}
/**
* @inheritDoc
*/
public function loadPackages(array $packageNameMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = []): array
{
foreach ($packageNameMap as $name => $constraint) {
if (!$this->isAllowed($name)) {
unset($packageNameMap[$name]);
}
}
if (!$packageNameMap) {
return ['namesFound' => [], 'packages' => []];
}
$result = $this->repo->loadPackages($packageNameMap, $acceptableStabilities, $stabilityFlags, $alreadyLoaded);
if (!$this->canonical) {
$result['namesFound'] = [];
}
return $result;
}
/**
* @inheritDoc
*/
public function search(string $query, int $mode = 0, ?string $type = null): array
{
$result = [];
foreach ($this->repo->search($query, $mode, $type) as $package) {
if ($this->isAllowed($package['name'])) {
$result[] = $package;
}
}
return $result;
}
/**
* @inheritDoc
*/
public function getPackages(): array
{
$result = [];
foreach ($this->repo->getPackages() as $package) {
if ($this->isAllowed($package->getName())) {
$result[] = $package;
}
}
return $result;
}
/**
* @inheritDoc
*/
public function getProviders($packageName): array
{
$result = [];
foreach ($this->repo->getProviders($packageName) as $name => $provider) {
if ($this->isAllowed($provider['name'])) {
$result[$name] = $provider;
}
}
return $result;
}
/**
* @inheritDoc
*/
public function count(): int
{
if ($this->repo->count() > 0) {
return count($this->getPackages());
}
return 0;
}
public function hasSecurityAdvisories(): bool
{
if (!$this->repo instanceof AdvisoryProviderInterface) {
return false;
}
return $this->repo->hasSecurityAdvisories();
}
/**
* @inheritDoc
*/
public function getSecurityAdvisories(array $packageConstraintMap, bool $allowPartialAdvisories = false): array
{
if (!$this->repo instanceof AdvisoryProviderInterface) {
return ['namesFound' => [], 'advisories' => []];
}
foreach ($packageConstraintMap as $name => $constraint) {
if (!$this->isAllowed($name)) {
unset($packageConstraintMap[$name]);
}
}
return $this->repo->getSecurityAdvisories($packageConstraintMap, $allowPartialAdvisories);
}
private function isAllowed(string $name): bool
{
if (!$this->only && !$this->exclude) {
return true;
}
if ($this->only) {
return Preg::isMatch($this->only, $name);
}
if ($this->exclude === null) {
return true;
}
return !Preg::isMatch($this->exclude, $name);
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/InstalledFilesystemRepository.php | src/Composer/Repository/InstalledFilesystemRepository.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;
/**
* Installed filesystem repository.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class InstalledFilesystemRepository extends FilesystemRepository implements InstalledRepositoryInterface
{
public function getRepoName()
{
return 'installed '.parent::getRepoName();
}
/**
* @inheritDoc
*/
public function isFresh()
{
return !$this->file->exists();
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/InstalledRepository.php | src/Composer/Repository/InstalledRepository.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;
use Composer\Package\BasePackage;
use Composer\Package\PackageInterface;
use Composer\Package\Version\VersionParser;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Semver\Constraint\Constraint;
use Composer\Semver\Constraint\MatchAllConstraint;
use Composer\Package\RootPackageInterface;
use Composer\Package\Link;
/**
* Installed repository is a composite of all installed repo types.
*
* The main use case is tagging a repo as an "installed" repository, and offering a way to get providers/replacers easily.
*
* Installed repos are LockArrayRepository, InstalledRepositoryInterface, RootPackageRepository and PlatformRepository
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class InstalledRepository extends CompositeRepository
{
/**
* @param ConstraintInterface|string|null $constraint
*
* @return BasePackage[]
*/
public function findPackagesWithReplacersAndProviders(string $name, $constraint = null): array
{
$name = strtolower($name);
if (null !== $constraint && !$constraint instanceof ConstraintInterface) {
$versionParser = new VersionParser();
$constraint = $versionParser->parseConstraints($constraint);
}
$matches = [];
foreach ($this->getRepositories() as $repo) {
foreach ($repo->getPackages() as $candidate) {
if ($name === $candidate->getName()) {
if (null === $constraint || $constraint->matches(new Constraint('==', $candidate->getVersion()))) {
$matches[] = $candidate;
}
continue;
}
foreach (array_merge($candidate->getProvides(), $candidate->getReplaces()) as $link) {
if (
$name === $link->getTarget()
&& ($constraint === null || $constraint->matches($link->getConstraint()))
) {
$matches[] = $candidate;
continue 2;
}
}
}
}
return $matches;
}
/**
* Returns a list of links causing the requested needle packages to be installed, as an associative array with the
* dependent's name as key, and an array containing in order the PackageInterface and Link describing the relationship
* as values. If recursive lookup was requested a third value is returned containing an identically formed array up
* to the root package. That third value will be false in case a circular recursion was detected.
*
* @param string|string[] $needle The package name(s) to inspect.
* @param ConstraintInterface|null $constraint Optional constraint to filter by.
* @param bool $invert Whether to invert matches to discover reasons for the package *NOT* to be installed.
* @param bool $recurse Whether to recursively expand the requirement tree up to the root package.
* @param string[] $packagesFound Used internally when recurring
*
* @return array[] An associative array of arrays as described above.
* @phpstan-return array<array{0: PackageInterface, 1: Link, 2: array<mixed>|false}>
*/
public function getDependents($needle, ?ConstraintInterface $constraint = null, bool $invert = false, bool $recurse = true, ?array $packagesFound = null): array
{
$needles = array_map('strtolower', (array) $needle);
$results = [];
// initialize the array with the needles before any recursion occurs
if (null === $packagesFound) {
$packagesFound = $needles;
}
// locate root package for use below
$rootPackage = null;
foreach ($this->getPackages() as $package) {
if ($package instanceof RootPackageInterface) {
$rootPackage = $package;
break;
}
}
// Loop over all currently installed packages.
foreach ($this->getPackages() as $package) {
$links = $package->getRequires();
// each loop needs its own "tree" as we want to show the complete dependent set of every needle
// without warning all the time about finding circular deps
$packagesInTree = $packagesFound;
// Replacements are considered valid reasons for a package to be installed during forward resolution
if (!$invert) {
$links += $package->getReplaces();
// On forward search, check if any replaced package was required and add the replaced
// packages to the list of needles. Contrary to the cross-reference link check below,
// replaced packages are the target of links.
foreach ($package->getReplaces() as $link) {
foreach ($needles as $needle) {
if ($link->getSource() === $needle) {
if ($constraint === null || ($link->getConstraint()->matches($constraint) === true)) {
// already displayed this node's dependencies, cutting short
if (in_array($link->getTarget(), $packagesInTree)) {
$results[] = [$package, $link, false];
continue;
}
$packagesInTree[] = $link->getTarget();
$dependents = $recurse ? $this->getDependents($link->getTarget(), null, false, true, $packagesInTree) : [];
$results[] = [$package, $link, $dependents];
$needles[] = $link->getTarget();
}
}
}
}
unset($needle);
}
// Require-dev is only relevant for the root package
if ($package instanceof RootPackageInterface) {
$links += $package->getDevRequires();
}
// Cross-reference all discovered links to the needles
foreach ($links as $link) {
foreach ($needles as $needle) {
if ($link->getTarget() === $needle) {
if ($constraint === null || ($link->getConstraint()->matches($constraint) === !$invert)) {
// already displayed this node's dependencies, cutting short
if (in_array($link->getSource(), $packagesInTree)) {
$results[] = [$package, $link, false];
continue;
}
$packagesInTree[] = $link->getSource();
$dependents = $recurse ? $this->getDependents($link->getSource(), null, false, true, $packagesInTree) : [];
$results[] = [$package, $link, $dependents];
}
}
}
}
// When inverting, we need to check for conflicts of the needles against installed packages
if ($invert && in_array($package->getName(), $needles, true)) {
foreach ($package->getConflicts() as $link) {
foreach ($this->findPackages($link->getTarget()) as $pkg) {
$version = new Constraint('=', $pkg->getVersion());
if ($link->getConstraint()->matches($version) === $invert) {
$results[] = [$package, $link, false];
}
}
}
}
// List conflicts against X as they may explain why the current version was selected, or explain why it is rejected if the conflict matched when inverting
foreach ($package->getConflicts() as $link) {
if (in_array($link->getTarget(), $needles, true)) {
foreach ($this->findPackages($link->getTarget()) as $pkg) {
$version = new Constraint('=', $pkg->getVersion());
if ($link->getConstraint()->matches($version) === $invert) {
$results[] = [$package, $link, false];
}
}
}
}
// When inverting, we need to check for conflicts of the needles' requirements against installed packages
if ($invert && $constraint && in_array($package->getName(), $needles, true) && $constraint->matches(new Constraint('=', $package->getVersion()))) {
foreach ($package->getRequires() as $link) {
if (PlatformRepository::isPlatformPackage($link->getTarget())) {
if ($this->findPackage($link->getTarget(), $link->getConstraint())) {
continue;
}
$platformPkg = $this->findPackage($link->getTarget(), '*');
$description = $platformPkg ? 'but '.$platformPkg->getPrettyVersion().' is installed' : 'but it is missing';
$results[] = [$package, new Link($package->getName(), $link->getTarget(), new MatchAllConstraint, Link::TYPE_REQUIRE, $link->getPrettyConstraint().' '.$description), false];
continue;
}
foreach ($this->getPackages() as $pkg) {
if (!in_array($link->getTarget(), $pkg->getNames())) {
continue;
}
$version = new Constraint('=', $pkg->getVersion());
if ($link->getTarget() !== $pkg->getName()) {
foreach (array_merge($pkg->getReplaces(), $pkg->getProvides()) as $prov) {
if ($link->getTarget() === $prov->getTarget()) {
$version = $prov->getConstraint();
break;
}
}
}
if (!$link->getConstraint()->matches($version)) {
// if we have a root package (we should but can not guarantee..) we show
// the root requires as well to perhaps allow to find an issue there
if ($rootPackage) {
foreach (array_merge($rootPackage->getRequires(), $rootPackage->getDevRequires()) as $rootReq) {
if (in_array($rootReq->getTarget(), $pkg->getNames()) && !$rootReq->getConstraint()->matches($link->getConstraint())) {
$results[] = [$package, $link, false];
$results[] = [$rootPackage, $rootReq, false];
continue 3;
}
}
$results[] = [$package, $link, false];
$results[] = [$rootPackage, new Link($rootPackage->getName(), $link->getTarget(), new MatchAllConstraint, Link::TYPE_DOES_NOT_REQUIRE, 'but ' . $pkg->getPrettyVersion() . ' is installed'), false];
} else {
// no root so let's just print whatever we found
$results[] = [$package, $link, false];
}
}
continue 2;
}
}
}
}
ksort($results);
return $results;
}
public function getRepoName(): string
{
return 'installed repo ('.implode(', ', array_map(static function ($repo): string {
return $repo->getRepoName();
}, $this->getRepositories())).')';
}
/**
* @inheritDoc
*/
public function addRepository(RepositoryInterface $repository): void
{
if (
$repository instanceof LockArrayRepository
|| $repository instanceof InstalledRepositoryInterface
|| $repository instanceof RootPackageRepository
|| $repository instanceof PlatformRepository
) {
parent::addRepository($repository);
return;
}
throw new \LogicException('An InstalledRepository can not contain a repository of type '.get_class($repository).' ('.$repository->getRepoName().')');
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositoryInterface.php | src/Composer/Repository/RepositoryInterface.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;
use Composer\Package\PackageInterface;
use Composer\Package\BasePackage;
use Composer\Semver\Constraint\ConstraintInterface;
/**
* Repository interface.
*
* @author Nils Adermann <naderman@naderman.de>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface RepositoryInterface extends \Countable
{
public const SEARCH_FULLTEXT = 0;
public const SEARCH_NAME = 1;
public const SEARCH_VENDOR = 2;
/**
* Checks if specified package registered (installed).
*
* @param PackageInterface $package package instance
*
* @return bool
*/
public function hasPackage(PackageInterface $package);
/**
* Searches for the first match of a package by name and version.
*
* @param string $name package name
* @param string|ConstraintInterface $constraint package version or version constraint to match against
*
* @return BasePackage|null
*/
public function findPackage(string $name, $constraint);
/**
* Searches for all packages matching a name and optionally a version.
*
* @param string $name package name
* @param string|ConstraintInterface $constraint package version or version constraint to match against
*
* @return BasePackage[]
*/
public function findPackages(string $name, $constraint = null);
/**
* Returns list of registered packages.
*
* @return BasePackage[]
*/
public function getPackages();
/**
* Returns list of registered packages with the supplied name
*
* - The packages returned are the packages found which match the constraints, acceptable stability and stability flags provided
* - The namesFound returned are names which should be considered as canonically found in this repository, that should not be looked up in any further lower priority repositories
*
* @param ConstraintInterface[] $packageNameMap package names pointing to constraints
* @param array<string, int> $acceptableStabilities array of stability => BasePackage::STABILITY_* value
* @param array<string, BasePackage::STABILITY_*> $stabilityFlags an array of package name => BasePackage::STABILITY_* value
* @param array<string, array<string, PackageInterface>> $alreadyLoaded an array of package name => package version => package
*
* @return array
*
* @phpstan-param array<key-of<BasePackage::STABILITIES>, BasePackage::STABILITY_*> $acceptableStabilities
* @phpstan-param array<string, ConstraintInterface|null> $packageNameMap
* @phpstan-return array{namesFound: array<string>, packages: array<BasePackage>}
*/
public function loadPackages(array $packageNameMap, array $acceptableStabilities, array $stabilityFlags, array $alreadyLoaded = []);
/**
* Searches the repository for packages containing the query
*
* @param string $query search query, for SEARCH_NAME and SEARCH_VENDOR regular expressions metacharacters are supported by implementations, and user input should be escaped through preg_quote by callers
* @param int $mode a set of SEARCH_* constants to search on, implementations should do a best effort only, default is SEARCH_FULLTEXT
* @param ?string $type The type of package to search for. Defaults to all types of packages
*
* @return array[] an array of array('name' => '...', 'description' => '...'|null, 'abandoned' => 'string'|true|unset) For SEARCH_VENDOR the name will be in "vendor" form
* @phpstan-return list<array{name: string, description: ?string, abandoned?: string|true, url?: string}>
*/
public function search(string $query, int $mode = 0, ?string $type = null);
/**
* Returns a list of packages providing a given package name
*
* Packages which have the same name as $packageName should not be returned, only those that have a "provide" on it.
*
* @param string $packageName package name which must be provided
*
* @return array[] an array with the provider name as key and value of array('name' => '...', 'description' => '...', 'type' => '...')
* @phpstan-return array<string, array{name: string, description: string|null, type: string}>
*/
public function getProviders(string $packageName);
/**
* Returns a name representing this repository to the user
*
* This is best effort and definitely can not always be very precise
*
* @return string
*/
public function getRepoName();
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RootPackageRepository.php | src/Composer/Repository/RootPackageRepository.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;
use Composer\Package\RootPackageInterface;
/**
* Root package repository.
*
* This is used for serving the RootPackage inside an in-memory InstalledRepository
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class RootPackageRepository extends ArrayRepository
{
public function __construct(RootPackageInterface $package)
{
parent::__construct([$package]);
}
public function getRepoName(): string
{
return 'root package repo';
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/AdvisoryProviderInterface.php | src/Composer/Repository/AdvisoryProviderInterface.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;
use Composer\Semver\Constraint\ConstraintInterface;
use Composer\Advisory\PartialSecurityAdvisory;
use Composer\Advisory\SecurityAdvisory;
/**
* Repositories that allow fetching security advisory data
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @internal
*/
interface AdvisoryProviderInterface
{
public function hasSecurityAdvisories(): bool;
/**
* @param array<string, ConstraintInterface> $packageConstraintMap Map of package name to constraint (can be MatchAllConstraint to fetch all advisories)
* @return ($allowPartialAdvisories is true ? array{namesFound: string[], advisories: array<string, list<PartialSecurityAdvisory|SecurityAdvisory>>} : array{namesFound: string[], advisories: array<string, list<SecurityAdvisory>>})
*/
public function getSecurityAdvisories(array $packageConstraintMap, bool $allowPartialAdvisories = false): array;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/ArtifactRepository.php | src/Composer/Repository/ArtifactRepository.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;
use Composer\IO\IOInterface;
use Composer\Json\JsonFile;
use Composer\Package\BasePackage;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Loader\LoaderInterface;
use Composer\Util\Platform;
use Composer\Util\Tar;
use Composer\Util\Zip;
/**
* @author Serge Smertin <serg.smertin@gmail.com>
*/
class ArtifactRepository extends ArrayRepository implements ConfigurableRepositoryInterface
{
/** @var LoaderInterface */
protected $loader;
/** @var string */
protected $lookup;
/** @var array{url: string} */
protected $repoConfig;
/** @var IOInterface */
private $io;
/**
* @param array{url: string} $repoConfig
*/
public function __construct(array $repoConfig, IOInterface $io)
{
parent::__construct();
if (!extension_loaded('zip')) {
throw new \RuntimeException('The artifact repository requires PHP\'s zip extension');
}
$this->loader = new ArrayLoader();
$this->lookup = Platform::expandPath($repoConfig['url']);
$this->io = $io;
$this->repoConfig = $repoConfig;
}
public function getRepoName()
{
return 'artifact repo ('.$this->lookup.')';
}
public function getRepoConfig()
{
return $this->repoConfig;
}
protected function initialize()
{
parent::initialize();
$this->scanDirectory($this->lookup);
}
private function scanDirectory(string $path): void
{
$io = $this->io;
$directory = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS);
$iterator = new \RecursiveIteratorIterator($directory);
$regex = new \RegexIterator($iterator, '/^.+\.(zip|tar|gz|tgz)$/i');
foreach ($regex as $file) {
/* @var $file \SplFileInfo */
if (!$file->isFile()) {
continue;
}
$package = $this->getComposerInformation($file);
if (!$package) {
$io->writeError("File <comment>{$file->getBasename()}</comment> doesn't seem to hold a package", true, IOInterface::VERBOSE);
continue;
}
$template = 'Found package <info>%s</info> (<comment>%s</comment>) in file <info>%s</info>';
$io->writeError(sprintf($template, $package->getName(), $package->getPrettyVersion(), $file->getBasename()), true, IOInterface::VERBOSE);
$this->addPackage($package);
}
}
private function getComposerInformation(\SplFileInfo $file): ?BasePackage
{
$json = null;
$fileType = null;
$fileExtension = pathinfo($file->getPathname(), PATHINFO_EXTENSION);
if (in_array($fileExtension, ['gz', 'tar', 'tgz'], true)) {
$fileType = 'tar';
} elseif ($fileExtension === 'zip') {
$fileType = 'zip';
} else {
throw new \RuntimeException('Files with "'.$fileExtension.'" extensions aren\'t supported. Only ZIP and TAR/TAR.GZ/TGZ archives are supported.');
}
try {
if ($fileType === 'tar') {
$json = Tar::getComposerJson($file->getPathname());
} else {
$json = Zip::getComposerJson($file->getPathname());
}
} catch (\Exception $exception) {
$this->io->write('Failed loading package '.$file->getPathname().': '.$exception->getMessage(), false, IOInterface::VERBOSE);
}
if (null === $json) {
return null;
}
$package = JsonFile::parseJson($json, $file->getPathname().'#composer.json');
$package['dist'] = [
'type' => $fileType,
'url' => strtr($file->getPathname(), '\\', '/'),
'shasum' => hash_file('sha1', $file->getRealPath()),
];
try {
$package = $this->loader->load($package);
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException('Failed loading package in '.$file.': '.$e->getMessage(), 0, $e);
}
return $package;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/PathRepository.php | src/Composer/Repository/PathRepository.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;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\IO\IOInterface;
use Composer\Json\JsonFile;
use Composer\Package\Loader\ArrayLoader;
use Composer\Package\Version\VersionGuesser;
use Composer\Package\Version\VersionParser;
use Composer\Pcre\Preg;
use Composer\Util\HttpDownloader;
use Composer\Util\Platform;
use Composer\Util\ProcessExecutor;
use Composer\Util\Filesystem;
use Composer\Util\Url;
use Composer\Util\Git as GitUtil;
/**
* This repository allows installing local packages that are not necessarily under their own VCS.
*
* The local packages will be symlinked when possible, else they will be copied.
*
* @code
* "require": {
* "<vendor>/<local-package>": "*"
* },
* "repositories": [
* {
* "type": "path",
* "url": "../../relative/path/to/package/"
* },
* {
* "type": "path",
* "url": "/absolute/path/to/package/"
* },
* {
* "type": "path",
* "url": "/absolute/path/to/several/packages/*"
* },
* {
* "type": "path",
* "url": "../../relative/path/to/package/",
* "options": {
* "symlink": false
* }
* },
* {
* "type": "path",
* "url": "../../relative/path/to/package/",
* "options": {
* "reference": "none"
* }
* },
* ]
* @endcode
*
* @author Samuel Roze <samuel.roze@gmail.com>
* @author Johann Reinke <johann.reinke@gmail.com>
*/
class PathRepository extends ArrayRepository implements ConfigurableRepositoryInterface
{
/**
* @var ArrayLoader
*/
private $loader;
/**
* @var VersionGuesser
*/
private $versionGuesser;
/**
* @var string
*/
private $url;
/**
* @var mixed[]
* @phpstan-var array{url: string, options?: array{symlink?: bool, reference?: string, relative?: bool, versions?: array<string, string>}}
*/
private $repoConfig;
/**
* @var ProcessExecutor
*/
private $process;
/**
* @var array{symlink?: bool, reference?: string, relative?: bool, versions?: array<string, string>}
*/
private $options;
/**
* Initializes path repository.
*
* @param array{url?: string, options?: array{symlink?: bool, reference?: string, relative?: bool, versions?: array<string, string>}} $repoConfig
*/
public function __construct(array $repoConfig, IOInterface $io, Config $config, ?HttpDownloader $httpDownloader = null, ?EventDispatcher $dispatcher = null, ?ProcessExecutor $process = null)
{
if (!isset($repoConfig['url'])) {
throw new \RuntimeException('You must specify the `url` configuration for the path repository');
}
$this->loader = new ArrayLoader(null, true);
$this->url = Platform::expandPath($repoConfig['url']);
$this->process = $process ?? new ProcessExecutor($io);
$this->versionGuesser = new VersionGuesser($config, $this->process, new VersionParser(), $io);
$this->repoConfig = $repoConfig;
$this->options = $repoConfig['options'] ?? [];
if (!isset($this->options['relative'])) {
$filesystem = new Filesystem();
$this->options['relative'] = !$filesystem->isAbsolutePath($this->url);
}
parent::__construct();
}
public function getRepoName(): string
{
return 'path repo ('.Url::sanitize($this->repoConfig['url']).')';
}
public function getRepoConfig(): array
{
return $this->repoConfig;
}
/**
* Initializes path repository.
*
* This method will basically read the folder and add the found package.
*/
protected function initialize(): void
{
parent::initialize();
$urlMatches = $this->getUrlMatches();
if (empty($urlMatches)) {
if (Preg::isMatch('{[*{}]}', $this->url)) {
$url = $this->url;
while (Preg::isMatch('{[*{}]}', $url)) {
$url = dirname($url);
}
// the parent directory before any wildcard exists, so we assume it is correctly configured but simply empty
if (is_dir($url)) {
return;
}
}
throw new \RuntimeException('The `url` supplied for the path (' . $this->url . ') repository does not exist');
}
foreach ($urlMatches as $url) {
$path = realpath($url) . DIRECTORY_SEPARATOR;
$composerFilePath = $path.'composer.json';
if (!file_exists($composerFilePath)) {
continue;
}
$json = file_get_contents($composerFilePath);
$package = JsonFile::parseJson($json, $composerFilePath);
$package['dist'] = [
'type' => 'path',
'url' => $url,
];
$reference = $this->options['reference'] ?? 'auto';
if ('none' === $reference) {
$package['dist']['reference'] = null;
} elseif ('config' === $reference || 'auto' === $reference) {
$package['dist']['reference'] = hash('sha1', $json . serialize($this->options));
}
// copy symlink/relative options to transport options
$package['transport-options'] = array_intersect_key($this->options, ['symlink' => true, 'relative' => true]);
// use the version provided as option if available
if (isset($package['name'], $this->options['versions'][$package['name']])) {
$package['version'] = $this->options['versions'][$package['name']];
}
// carry over the root package version if this path repo is in the same git repository as root package
if (!isset($package['version']) && ($rootVersion = Platform::getEnv('COMPOSER_ROOT_VERSION'))) {
if (
0 === $this->process->execute(['git', 'rev-parse', 'HEAD'], $ref1, $path)
&& 0 === $this->process->execute(['git', 'rev-parse', 'HEAD'], $ref2)
&& $ref1 === $ref2
) {
$package['version'] = $this->versionGuesser->getRootVersionFromEnv();
}
}
$output = '';
$command = GitUtil::buildRevListCommand($this->process, array_merge(['-n1', '--format=%H', 'HEAD'], GitUtil::getNoShowSignatureFlags($this->process)));
if ('auto' === $reference && is_dir($path . DIRECTORY_SEPARATOR . '.git') && 0 === $this->process->execute($command, $output, $path)) {
$package['dist']['reference'] = trim(GitUtil::parseRevListOutput($output, $this->process));
}
if (!isset($package['version'])) {
$versionData = $this->versionGuesser->guessVersion($package, $path);
if (is_array($versionData) && $versionData['pretty_version']) {
// if there is a feature branch detected, we add a second packages with the feature branch version
if (!empty($versionData['feature_pretty_version'])) {
$package['version'] = $versionData['feature_pretty_version'];
$this->addPackage($this->loader->load($package));
}
$package['version'] = $versionData['pretty_version'];
} else {
$package['version'] = 'dev-main';
}
}
try {
$this->addPackage($this->loader->load($package));
} catch (\Exception $e) {
throw new \RuntimeException('Failed loading the package in '.$composerFilePath, 0, $e);
}
}
}
/**
* Get a list of all (possibly relative) path names matching given url (supports globbing).
*
* @return string[]
*/
private function getUrlMatches(): array
{
$flags = GLOB_MARK | GLOB_ONLYDIR;
if (defined('GLOB_BRACE')) {
$flags |= GLOB_BRACE;
} elseif (strpos($this->url, '{') !== false || strpos($this->url, '}') !== false) {
throw new \RuntimeException('The operating system does not support GLOB_BRACE which is required for the url '. $this->url);
}
// Ensure environment-specific path separators are normalized to URL separators
return array_map(static function ($val): string {
return rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $val), '/');
}, glob($this->url, $flags));
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/RepositoryManager.php | src/Composer/Repository/RepositoryManager.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;
use Composer\IO\IOInterface;
use Composer\Config;
use Composer\EventDispatcher\EventDispatcher;
use Composer\Package\PackageInterface;
use Composer\Util\HttpDownloader;
use Composer\Util\ProcessExecutor;
/**
* Repositories manager.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
* @author Konstantin Kudryashov <ever.zet@gmail.com>
* @author François Pluchino <francois.pluchino@opendisplay.com>
*/
class RepositoryManager
{
/** @var InstalledRepositoryInterface */
private $localRepository;
/** @var list<RepositoryInterface> */
private $repositories = [];
/** @var array<string, class-string<RepositoryInterface>> */
private $repositoryClasses = [];
/** @var IOInterface */
private $io;
/** @var Config */
private $config;
/** @var HttpDownloader */
private $httpDownloader;
/** @var ?EventDispatcher */
private $eventDispatcher;
/** @var ProcessExecutor */
private $process;
public function __construct(IOInterface $io, Config $config, HttpDownloader $httpDownloader, ?EventDispatcher $eventDispatcher = null, ?ProcessExecutor $process = null)
{
$this->io = $io;
$this->config = $config;
$this->httpDownloader = $httpDownloader;
$this->eventDispatcher = $eventDispatcher;
$this->process = $process ?? new ProcessExecutor($io);
}
/**
* Searches for a package by its name and version in managed repositories.
*
* @param string $name package name
* @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against
*/
public function findPackage(string $name, $constraint): ?PackageInterface
{
foreach ($this->repositories as $repository) {
/** @var RepositoryInterface $repository */
if ($package = $repository->findPackage($name, $constraint)) {
return $package;
}
}
return null;
}
/**
* Searches for all packages matching a name and optionally a version in managed repositories.
*
* @param string $name package name
* @param string|\Composer\Semver\Constraint\ConstraintInterface $constraint package version or version constraint to match against
*
* @return PackageInterface[]
*/
public function findPackages(string $name, $constraint): array
{
$packages = [];
foreach ($this->getRepositories() as $repository) {
$packages = array_merge($packages, $repository->findPackages($name, $constraint));
}
return $packages;
}
/**
* Adds repository
*
* @param RepositoryInterface $repository repository instance
*/
public function addRepository(RepositoryInterface $repository): void
{
$this->repositories[] = $repository;
}
/**
* Adds a repository to the beginning of the chain
*
* This is useful when injecting additional repositories that should trump Packagist, e.g. from a plugin.
*
* @param RepositoryInterface $repository repository instance
*/
public function prependRepository(RepositoryInterface $repository): void
{
array_unshift($this->repositories, $repository);
}
/**
* Returns a new repository for a specific installation type.
*
* @param string $type repository type
* @param array<string, mixed> $config repository configuration
* @param string $name repository name
* @throws \InvalidArgumentException if repository for provided type is not registered
*/
public function createRepository(string $type, array $config, ?string $name = null): RepositoryInterface
{
if (!isset($this->repositoryClasses[$type])) {
throw new \InvalidArgumentException('Repository type is not registered: '.$type);
}
if (isset($config['packagist']) && false === $config['packagist']) {
$this->io->writeError('<warning>Repository "'.$name.'" ('.json_encode($config).') has a packagist key which should be in its own repository definition</warning>');
}
$class = $this->repositoryClasses[$type];
if (isset($config['only']) || isset($config['exclude']) || isset($config['canonical'])) {
$filterConfig = $config;
unset($config['only'], $config['exclude'], $config['canonical']);
}
$repository = new $class($config, $this->io, $this->config, $this->httpDownloader, $this->eventDispatcher, $this->process);
if (isset($filterConfig)) {
$repository = new FilterRepository($repository, $filterConfig);
}
return $repository;
}
/**
* Stores repository class for a specific installation type.
*
* @param string $type installation type
* @param class-string<RepositoryInterface> $class class name of the repo implementation
*/
public function setRepositoryClass(string $type, $class): void
{
$this->repositoryClasses[$type] = $class;
}
/**
* Returns all repositories, except local one.
*
* @return RepositoryInterface[]
*/
public function getRepositories(): array
{
return $this->repositories;
}
/**
* Sets local repository for the project.
*
* @param InstalledRepositoryInterface $repository repository instance
*/
public function setLocalRepository(InstalledRepositoryInterface $repository): void
{
$this->localRepository = $repository;
}
/**
* Returns local repository for the project.
*/
public function getLocalRepository(): InstalledRepositoryInterface
{
return $this->localRepository;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/WritableArrayRepository.php | src/Composer/Repository/WritableArrayRepository.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;
use Composer\Installer\InstallationManager;
/**
* Writable array repository.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class WritableArrayRepository extends ArrayRepository implements WritableRepositoryInterface
{
use CanonicalPackagesTrait;
/**
* @var string[]
*/
protected $devPackageNames = [];
/** @var bool|null */
private $devMode = null;
/**
* @return bool|null true if dev requirements were installed, false if --no-dev was used, null if yet unknown
*/
public function getDevMode()
{
return $this->devMode;
}
/**
* @inheritDoc
*/
public function setDevPackageNames(array $devPackageNames)
{
$this->devPackageNames = $devPackageNames;
}
/**
* @inheritDoc
*/
public function getDevPackageNames()
{
return $this->devPackageNames;
}
/**
* @inheritDoc
*/
public function write(bool $devMode, InstallationManager $installationManager)
{
$this->devMode = $devMode;
}
/**
* @inheritDoc
*/
public function reload()
{
$this->devMode = null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/InstalledRepositoryInterface.php | src/Composer/Repository/InstalledRepositoryInterface.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;
/**
* Installable repository interface.
*
* Just used to tag installed repositories so the base classes can act differently on Alias packages
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
interface InstalledRepositoryInterface extends WritableRepositoryInterface
{
/**
* @return bool|null true if dev requirements were installed, false if --no-dev was used, null if yet unknown
*/
public function getDevMode();
/**
* @return bool true if packages were never installed in this repository
*/
public function isFresh();
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/GitBitbucketDriver.php | src/Composer/Repository/Vcs/GitBitbucketDriver.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\IO\IOInterface;
use Composer\Cache;
use Composer\Downloader\TransportException;
use Composer\Json\JsonFile;
use Composer\Pcre\Preg;
use Composer\Util\Bitbucket;
use Composer\Util\Http\Response;
/**
* @author Per Bernhardt <plb@webfactory.de>
*/
class GitBitbucketDriver extends VcsDriver
{
/** @var string */
protected $owner;
/** @var string */
protected $repository;
/** @var bool */
private $hasIssues = false;
/** @var ?string */
private $rootIdentifier;
/** @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;
/** @var string */
private $branchesUrl = '';
/** @var string */
private $tagsUrl = '';
/** @var string */
private $homeUrl = '';
/** @var string */
private $website = '';
/** @var string */
private $cloneHttpsUrl = '';
/** @var array<string, mixed> */
private $repoData;
/**
* @var ?VcsDriver
*/
protected $fallbackDriver = null;
/** @var string|null if set either git or hg */
private $vcsType;
/**
* @inheritDoc
*/
public function initialize(): void
{
if (!Preg::isMatchStrictGroups('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(?:\.git|/?)?$#i', $this->url, $match)) {
throw new \InvalidArgumentException(sprintf('The Bitbucket repository URL %s is invalid. It must be the HTTPS URL of a Bitbucket repository.', $this->url));
}
$this->owner = $match[1];
$this->repository = $match[2];
$this->originUrl = 'bitbucket.org';
$this->cache = new Cache(
$this->io,
implode('/', [
$this->config->get('cache-repo-dir'),
$this->originUrl,
$this->owner,
$this->repository,
])
);
$this->cache->setReadOnly($this->config->get('cache-read-only'));
}
/**
* @inheritDoc
*/
public function getUrl(): string
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getUrl();
}
return $this->cloneHttpsUrl;
}
/**
* Attempts to fetch the repository data via the BitBucket API and
* sets some parameters which are used in other methods
*
* @phpstan-impure
*/
protected function getRepoData(): bool
{
$resource = sprintf(
'https://api.bitbucket.org/2.0/repositories/%s/%s?%s',
$this->owner,
$this->repository,
http_build_query(
['fields' => '-project,-owner'],
'',
'&'
)
);
$repoData = $this->fetchWithOAuthCredentials($resource, true)->decodeJson();
if ($this->fallbackDriver) {
return false;
}
$this->parseCloneUrls($repoData['links']['clone']);
$this->hasIssues = !empty($repoData['has_issues']);
$this->branchesUrl = $repoData['links']['branches']['href'];
$this->tagsUrl = $repoData['links']['tags']['href'];
$this->homeUrl = $repoData['links']['html']['href'];
$this->website = $repoData['website'];
$this->vcsType = $repoData['scm'];
$this->repoData = $repoData;
return true;
}
/**
* @inheritDoc
*/
public function getComposerInformation(string $identifier): ?array
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->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 ($composer !== null) {
// specials for bitbucket
if (isset($composer['support']) && !is_array($composer['support'])) {
$composer['support'] = [];
}
if (!isset($composer['support']['source'])) {
$label = array_search(
$identifier,
$this->getTags()
) ?: array_search(
$identifier,
$this->getBranches()
) ?: $identifier;
if (array_key_exists($label, $tags = $this->getTags())) {
$hash = $tags[$label];
} elseif (array_key_exists($label, $branches = $this->getBranches())) {
$hash = $branches[$label];
}
if (!isset($hash)) {
$composer['support']['source'] = sprintf(
'https://%s/%s/%s/src',
$this->originUrl,
$this->owner,
$this->repository
);
} else {
$composer['support']['source'] = sprintf(
'https://%s/%s/%s/src/%s/?at=%s',
$this->originUrl,
$this->owner,
$this->repository,
$hash,
$label
);
}
}
if (!isset($composer['support']['issues']) && $this->hasIssues) {
$composer['support']['issues'] = sprintf(
'https://%s/%s/%s/issues',
$this->originUrl,
$this->owner,
$this->repository
);
}
if (!isset($composer['homepage'])) {
$composer['homepage'] = empty($this->website) ? $this->homeUrl : $this->website;
}
}
$this->infoCache[$identifier] = $composer;
}
return $this->infoCache[$identifier];
}
/**
* @inheritDoc
*/
public function getFileContent(string $file, string $identifier): ?string
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getFileContent($file, $identifier);
}
if (strpos($identifier, '/') !== false) {
$branches = $this->getBranches();
if (isset($branches[$identifier])) {
$identifier = $branches[$identifier];
}
}
$resource = sprintf(
'https://api.bitbucket.org/2.0/repositories/%s/%s/src/%s/%s',
$this->owner,
$this->repository,
$identifier,
$file
);
return $this->fetchWithOAuthCredentials($resource)->getBody();
}
/**
* @inheritDoc
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getChangeDate($identifier);
}
if (strpos($identifier, '/') !== false) {
$branches = $this->getBranches();
if (isset($branches[$identifier])) {
$identifier = $branches[$identifier];
}
}
$resource = sprintf(
'https://api.bitbucket.org/2.0/repositories/%s/%s/commit/%s?fields=date',
$this->owner,
$this->repository,
$identifier
);
$commit = $this->fetchWithOAuthCredentials($resource)->decodeJson();
return new \DateTimeImmutable($commit['date']);
}
/**
* @inheritDoc
*/
public function getSource(string $identifier): array
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getSource($identifier);
}
return ['type' => $this->vcsType, 'url' => $this->getUrl(), 'reference' => $identifier];
}
/**
* @inheritDoc
*/
public function getDist(string $identifier): ?array
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getDist($identifier);
}
$url = sprintf(
'https://bitbucket.org/%s/%s/get/%s.zip',
$this->owner,
$this->repository,
$identifier
);
return ['type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => ''];
}
/**
* @inheritDoc
*/
public function getTags(): array
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getTags();
}
if (null === $this->tags) {
$tags = [];
$resource = sprintf(
'%s?%s',
$this->tagsUrl,
http_build_query(
[
'pagelen' => 100,
'fields' => 'values.name,values.target.hash,next',
'sort' => '-target.date',
],
'',
'&'
)
);
$hasNext = true;
while ($hasNext) {
$tagsData = $this->fetchWithOAuthCredentials($resource)->decodeJson();
foreach ($tagsData['values'] as $data) {
$tags[$data['name']] = $data['target']['hash'];
}
if (empty($tagsData['next'])) {
$hasNext = false;
} else {
$resource = $tagsData['next'];
}
}
$this->tags = $tags;
}
return $this->tags;
}
/**
* @inheritDoc
*/
public function getBranches(): array
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getBranches();
}
if (null === $this->branches) {
$branches = [];
$resource = sprintf(
'%s?%s',
$this->branchesUrl,
http_build_query(
[
'pagelen' => 100,
'fields' => 'values.name,values.target.hash,values.heads,next',
'sort' => '-target.date',
],
'',
'&'
)
);
$hasNext = true;
while ($hasNext) {
$branchData = $this->fetchWithOAuthCredentials($resource)->decodeJson();
foreach ($branchData['values'] as $data) {
$branches[$data['name']] = $data['target']['hash'];
}
if (empty($branchData['next'])) {
$hasNext = false;
} else {
$resource = $branchData['next'];
}
}
$this->branches = $branches;
}
return $this->branches;
}
/**
* Get the remote content.
*
* @param string $url The URL of content
*
* @return Response The result
*
* @phpstan-impure
*/
protected function fetchWithOAuthCredentials(string $url, bool $fetchingRepoData = false): Response
{
try {
return parent::getContents($url);
} catch (TransportException $e) {
$bitbucketUtil = new Bitbucket($this->io, $this->config, $this->process, $this->httpDownloader);
if (in_array($e->getCode(), [403, 404], true) || (401 === $e->getCode() && strpos($e->getMessage(), 'Could not authenticate against') === 0)) {
if (!$this->io->hasAuthentication($this->originUrl)
&& $bitbucketUtil->authorizeOAuth($this->originUrl)
) {
return parent::getContents($url);
}
if (!$this->io->isInteractive() && $fetchingRepoData) {
$this->attemptCloneFallback();
return new Response(['url' => 'dummy'], 200, [], 'null');
}
}
throw $e;
}
}
/**
* Generate an SSH URL
*/
protected function generateSshUrl(): string
{
return 'git@' . $this->originUrl . ':' . $this->owner.'/'.$this->repository.'.git';
}
/**
* @phpstan-impure
*
* @return true
* @throws \RuntimeException
*/
protected function attemptCloneFallback(): bool
{
try {
$this->setupFallbackDriver($this->generateSshUrl());
return true;
} catch (\RuntimeException $e) {
$this->fallbackDriver = null;
$this->io->writeError(
'<error>Failed to clone the ' . $this->generateSshUrl() . ' repository, try running in interactive mode'
. ' so that you can enter your Bitbucket OAuth consumer credentials</error>'
);
throw $e;
}
}
protected function setupFallbackDriver(string $url): void
{
$this->fallbackDriver = new GitDriver(
['url' => $url],
$this->io,
$this->config,
$this->httpDownloader,
$this->process
);
$this->fallbackDriver->initialize();
}
/**
* @param array<array{name: string, href: string}> $cloneLinks
*/
protected function parseCloneUrls(array $cloneLinks): void
{
foreach ($cloneLinks as $cloneLink) {
if ($cloneLink['name'] === 'https') {
// Format: https://(user@)bitbucket.org/{user}/{repo}
// Strip username from URL (only present in clone URL's for private repositories)
$this->cloneHttpsUrl = Preg::replace('/https:\/\/([^@]+@)?/', 'https://', $cloneLink['href']);
}
}
}
/**
* @inheritDoc
*/
public function getRootIdentifier(): string
{
if ($this->fallbackDriver) {
return $this->fallbackDriver->getRootIdentifier();
}
if (null === $this->rootIdentifier) {
if (!$this->getRepoData()) {
if (!$this->fallbackDriver) {
throw new \LogicException('A fallback driver should be setup if getRepoData returns false');
}
return $this->fallbackDriver->getRootIdentifier();
}
if ($this->vcsType !== 'git') {
throw new \RuntimeException(
$this->url.' does not appear to be a git repository, use '.
$this->cloneHttpsUrl.' but remember that Bitbucket no longer supports the mercurial repositories. '.
'https://bitbucket.org/blog/sunsetting-mercurial-support-in-bitbucket'
);
}
$this->rootIdentifier = $this->repoData['mainbranch']['name'] ?? 'master';
}
return $this->rootIdentifier;
}
/**
* @inheritDoc
*/
public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool
{
if (!Preg::isMatch('#^https?://bitbucket\.org/([^/]+)/([^/]+?)(\.git|/?)?$#i', $url)) {
return false;
}
if (!extension_loaded('openssl')) {
$io->writeError('Skipping Bitbucket git driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
return false;
}
return true;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/GitHubDriver.php | src/Composer/Repository/Vcs/GitHubDriver.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\Downloader\TransportException;
use Composer\Json\JsonFile;
use Composer\Cache;
use Composer\IO\IOInterface;
use Composer\Pcre\Preg;
use Composer\Util\GitHub;
use Composer\Util\Http\Response;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GitHubDriver extends VcsDriver
{
/** @var string */
protected $owner;
/** @var string */
protected $repository;
/** @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 mixed[] */
protected $repoData;
/** @var bool */
protected $hasIssues = false;
/** @var bool */
protected $isPrivate = false;
/** @var bool */
private $isArchived = false;
/** @var array<int, array{type: string, url: string}>|false|null */
private $fundingInfo;
/** @var bool */
private $allowGitFallback = true;
/**
* Git Driver
*
* @var ?GitDriver
*/
protected $gitDriver = null;
/**
* @inheritDoc
*/
public function initialize(): void
{
if (!Preg::isMatch('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#', $this->url, $match)) {
throw new \InvalidArgumentException(sprintf('The GitHub repository URL %s is invalid.', $this->url));
}
$this->owner = $match[3];
$this->repository = $match[4];
$this->originUrl = strtolower($match[1] ?? (string) $match[2]);
if ($this->originUrl === 'www.github.com') {
$this->originUrl = 'github.com';
}
$this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
$this->cache->setReadOnly($this->config->get('cache-read-only'));
if (isset($this->repoConfig['allow-git-fallback']) && $this->repoConfig['allow-git-fallback'] === false) {
$this->allowGitFallback = false;
}
if ($this->config->get('use-github-api') === false || (isset($this->repoConfig['no-api']) && $this->repoConfig['no-api'])) {
$this->setupGitDriver($this->url);
return;
}
$this->fetchRootIdentifier();
}
public function getRepositoryUrl(): string
{
return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository;
}
/**
* @inheritDoc
*/
public function getRootIdentifier(): string
{
if ($this->gitDriver) {
return $this->gitDriver->getRootIdentifier();
}
return $this->rootIdentifier;
}
/**
* @inheritDoc
*/
public function getUrl(): string
{
if ($this->gitDriver) {
return $this->gitDriver->getUrl();
}
return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
}
protected function getApiUrl(): string
{
if ('github.com' === $this->originUrl) {
$apiUrl = 'api.github.com';
} else {
$apiUrl = $this->originUrl . '/api/v3';
}
return 'https://' . $apiUrl;
}
/**
* @inheritDoc
*/
public function getSource(string $identifier): array
{
if ($this->gitDriver) {
return $this->gitDriver->getSource($identifier);
}
if ($this->isPrivate) {
// Private GitHub repositories should be accessed using the
// SSH version of the URL.
$url = $this->generateSshUrl();
} else {
$url = $this->getUrl();
}
return ['type' => 'git', 'url' => $url, 'reference' => $identifier];
}
/**
* @inheritDoc
*/
public function getDist(string $identifier): ?array
{
$url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier;
return ['type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => ''];
}
/**
* @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 ($composer !== null) {
// specials for github
if (isset($composer['support']) && !is_array($composer['support'])) {
$composer['support'] = [];
}
if (!isset($composer['support']['source'])) {
$label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier;
$composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label);
}
if (!isset($composer['support']['issues']) && $this->hasIssues) {
$composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository);
}
if (!isset($composer['abandoned']) && $this->isArchived) {
$composer['abandoned'] = true;
}
if (!isset($composer['funding']) && $funding = $this->getFundingInfo()) {
$composer['funding'] = $funding;
}
}
$this->infoCache[$identifier] = $composer;
}
return $this->infoCache[$identifier];
}
/**
* @return array<int, array{type: string, url: string}>|false
*/
private function getFundingInfo()
{
if (null !== $this->fundingInfo) {
return $this->fundingInfo;
}
if ($this->originUrl !== 'github.com') {
return $this->fundingInfo = false;
}
foreach ([$this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/.github/FUNDING.yml', $this->getApiUrl() . '/repos/'.$this->owner.'/.github/contents/FUNDING.yml'] as $file) {
try {
$response = $this->httpDownloader->get($file, [
'retry-auth-failure' => false,
])->decodeJson();
} catch (TransportException $e) {
continue;
}
if (empty($response['content']) || $response['encoding'] !== 'base64' || !($funding = base64_decode($response['content']))) {
continue;
}
break;
}
if (empty($funding)) {
return $this->fundingInfo = false;
}
$result = [];
$key = null;
foreach (Preg::split('{\r?\n}', $funding) as $line) {
$line = trim($line);
if (Preg::isMatchStrictGroups('{^(\w+)\s*:\s*(.+)$}', $line, $match)) {
if ($match[2] === '[') {
$key = $match[1];
continue;
}
if (Preg::isMatchStrictGroups('{^\[(.*?)\](?:\s*#.*)?$}', $match[2], $match2)) {
foreach (array_map('trim', Preg::split('{[\'"]?\s*,\s*[\'"]?}', $match2[1])) as $item) {
$result[] = ['type' => $match[1], 'url' => trim($item, '"\' ')];
}
} elseif (Preg::isMatchStrictGroups('{^([^#].*?)(?:\s+#.*)?$}', $match[2], $match2)) {
$result[] = ['type' => $match[1], 'url' => trim($match2[1], '"\' ')];
}
$key = null;
} elseif (Preg::isMatchStrictGroups('{^(\w+)\s*:\s*#\s*$}', $line, $match)) {
$key = $match[1];
} elseif ($key !== null && (
Preg::isMatchStrictGroups('{^-\s*(.+)(?:\s+#.*)?$}', $line, $match)
|| Preg::isMatchStrictGroups('{^(.+),(?:\s*#.*)?$}', $line, $match)
)) {
$result[] = ['type' => $key, 'url' => trim($match[1], '"\' ')];
} elseif ($key !== null && $line === ']') {
$key = null;
}
}
foreach ($result as $key => $item) {
switch ($item['type']) {
case 'community_bridge':
$result[$key]['url'] = 'https://funding.communitybridge.org/projects/' . basename($item['url']);
break;
case 'github':
$result[$key]['url'] = 'https://github.com/' . basename($item['url']);
break;
case 'issuehunt':
$result[$key]['url'] = 'https://issuehunt.io/r/' . $item['url'];
break;
case 'ko_fi':
$result[$key]['url'] = 'https://ko-fi.com/' . basename($item['url']);
break;
case 'liberapay':
$result[$key]['url'] = 'https://liberapay.com/' . basename($item['url']);
break;
case 'open_collective':
$result[$key]['url'] = 'https://opencollective.com/' . basename($item['url']);
break;
case 'patreon':
$result[$key]['url'] = 'https://www.patreon.com/' . basename($item['url']);
break;
case 'tidelift':
$result[$key]['url'] = 'https://tidelift.com/funding/github/' . $item['url'];
break;
case 'polar':
$result[$key]['url'] = 'https://polar.sh/' . basename($item['url']);
break;
case 'buy_me_a_coffee':
$result[$key]['url'] = 'https://www.buymeacoffee.com/' . basename($item['url']);
break;
case 'thanks_dev':
$result[$key]['url'] = 'https://thanks.dev/' . $item['url'];
break;
case 'otechie':
$result[$key]['url'] = 'https://otechie.com/' . basename($item['url']);
break;
case 'custom':
$bits = parse_url($item['url']);
if ($bits === false) {
unset($result[$key]);
break;
}
if (!array_key_exists('scheme', $bits) && !array_key_exists('host', $bits)) {
if (Preg::isMatch('{^[a-z0-9-]++\.[a-z]{2,3}$}', $item['url'])) {
$result[$key]['url'] = 'https://'.$item['url'];
break;
}
$this->io->writeError('<warning>Funding URL '.$item['url'].' not in a supported format.</warning>');
unset($result[$key]);
break;
}
break;
}
}
return $this->fundingInfo = $result;
}
/**
* @inheritDoc
*/
public function getFileContent(string $file, string $identifier): ?string
{
if ($this->gitDriver) {
return $this->gitDriver->getFileContent($file, $identifier);
}
$resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/' . $file . '?ref='.urlencode($identifier);
$resource = $this->getContents($resource)->decodeJson();
// The GitHub 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']))) {
throw new \RuntimeException('Could not retrieve ' . $file . ' for '.$identifier);
}
return $content;
}
/**
* @inheritDoc
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable
{
if ($this->gitDriver) {
return $this->gitDriver->getChangeDate($identifier);
}
$resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier);
$commit = $this->getContents($resource)->decodeJson();
return new \DateTimeImmutable($commit['commit']['committer']['date']);
}
/**
* @inheritDoc
*/
public function getTags(): array
{
if ($this->gitDriver) {
return $this->gitDriver->getTags();
}
if (null === $this->tags) {
$tags = [];
$resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/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;
}
/**
* @inheritDoc
*/
public function getBranches(): array
{
if ($this->gitDriver) {
return $this->gitDriver->getBranches();
}
if (null === $this->branches) {
$branches = [];
$resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100';
do {
$response = $this->getContents($resource);
$branchData = $response->decodeJson();
foreach ($branchData as $branch) {
$name = substr($branch['ref'], 11);
if ($name !== 'gh-pages') {
$branches[$name] = $branch['object']['sha'];
}
}
$resource = $this->getNextPage($response);
} while ($resource);
$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?|git)://([^/]+)/|git@([^:]+):/?)([^/]+)/([^/]+?)(?:\.git|/)?$#', $url, $matches)) {
return false;
}
$originUrl = $matches[2] ?? (string) $matches[3];
if (!in_array(strtolower(Preg::replace('{^www\.}i', '', $originUrl)), $config->get('github-domains'))) {
return false;
}
if (!extension_loaded('openssl')) {
$io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.', true, IOInterface::VERBOSE);
return false;
}
return true;
}
/**
* Gives back the loaded <github-api>/repos/<owner>/<repo> result
*
* @return mixed[]|null
*/
public function getRepoData(): ?array
{
$this->fetchRootIdentifier();
return $this->repoData;
}
/**
* Generate an SSH URL
*/
protected function generateSshUrl(): string
{
if (false !== strpos($this->originUrl, ':')) {
return 'ssh://git@' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
}
return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
}
/**
* @inheritDoc
*/
protected function getContents(string $url, bool $fetchingRepoData = false): Response
{
try {
return parent::getContents($url);
} catch (TransportException $e) {
$gitHubUtil = new GitHub($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 ($gitHubUtil->authorizeOAuth($this->originUrl)) {
return parent::getContents($url);
}
if (!$this->io->isInteractive()) {
$this->attemptCloneFallback($e);
return new Response(['url' => 'dummy'], 200, [], 'null');
}
$scopesIssued = [];
$scopesNeeded = [];
if ($headers = $e->getHeaders()) {
if ($scopes = Response::findHeaderValue($headers, 'X-OAuth-Scopes')) {
$scopesIssued = explode(' ', $scopes);
}
if ($scopes = Response::findHeaderValue($headers, 'X-Accepted-OAuth-Scopes')) {
$scopesNeeded = explode(' ', $scopes);
}
}
$scopesFailed = array_diff($scopesNeeded, $scopesIssued);
// non-authenticated requests get no scopesNeeded, so ask for credentials
// authenticated requests which failed some scopes should ask for new credentials too
if (!$headers || !count($scopesNeeded) || count($scopesFailed)) {
$gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
}
return parent::getContents($url);
case 403:
if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) {
return parent::getContents($url);
}
if (!$this->io->isInteractive() && $fetchingRepoData) {
$this->attemptCloneFallback($e);
return new Response(['url' => 'dummy'], 200, [], 'null');
}
$rateLimited = $gitHubUtil->isRateLimited((array) $e->getHeaders());
if (!$this->io->hasAuthentication($this->originUrl)) {
if (!$this->io->isInteractive()) {
$this->io->writeError('<error>GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>');
throw $e;
}
$gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)');
return parent::getContents($url);
}
if ($rateLimited) {
$rateLimit = $gitHubUtil->getRateLimit($e->getHeaders());
$this->io->writeError(sprintf(
'<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>',
$rateLimit['limit'],
$rateLimit['reset']
));
}
throw $e;
default:
throw $e;
}
}
}
/**
* Fetch root identifier from GitHub
*
* @throws TransportException
*/
protected function fetchRootIdentifier(): void
{
if ($this->repoData) {
return;
}
$repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository;
try {
$this->repoData = $this->getContents($repoDataUrl, true)->decodeJson();
} catch (TransportException $e) {
if ($e->getCode() === 499) {
$this->attemptCloneFallback($e);
} else {
throw $e;
}
}
if (null === $this->repoData && null !== $this->gitDriver) {
return;
}
$this->owner = $this->repoData['owner']['login'];
$this->repository = $this->repoData['name'];
$this->isPrivate = !empty($this->repoData['private']);
if (isset($this->repoData['default_branch'])) {
$this->rootIdentifier = $this->repoData['default_branch'];
} elseif (isset($this->repoData['master_branch'])) {
$this->rootIdentifier = $this->repoData['master_branch'];
} else {
$this->rootIdentifier = 'master';
}
$this->hasIssues = !empty($this->repoData['has_issues']);
$this->isArchived = !empty($this->repoData['archived']);
}
/**
* @phpstan-impure
*
* @return true
* @throws \RuntimeException
*/
protected function attemptCloneFallback(?\Throwable $e = null): bool
{
if (!$this->allowGitFallback) {
throw new \RuntimeException('Fallback to git driver disabled', 0, $e);
}
$this->isPrivate = true;
try {
// If this repository may be private (hard to say for sure,
// GitHub 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->generateSshUrl());
return true;
} catch (\RuntimeException $e) {
$this->gitDriver = null;
$this->io->writeError('<error>Failed to clone the '.$this->generateSshUrl().' repository, try running in interactive mode so that you can enter your GitHub credentials</error>');
throw $e;
}
}
protected function setupGitDriver(string $url): void
{
if (!$this->allowGitFallback) {
throw new \RuntimeException('Fallback to git driver disabled');
}
$this->gitDriver = new GitDriver(
['url' => $url],
$this->io,
$this->config,
$this->httpDownloader,
$this->process
);
$this->gitDriver->initialize();
}
protected function getNextPage(Response $response): ?string
{
$header = $response->getHeader('link');
if (!$header) {
return null;
}
$links = explode(',', $header);
foreach ($links as $link) {
if (Preg::isMatch('{<(.+?)>; *rel="next"}', $link, $match)) {
return $match[1];
}
}
return null;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/PerforceDriver.php | src/Composer/Repository/Vcs/PerforceDriver.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\Pcre\Preg;
use Composer\Util\ProcessExecutor;
use Composer\Util\Perforce;
use Composer\Util\Http\Response;
/**
* @author Matt Whittom <Matt.Whittom@veteransunited.com>
*/
class PerforceDriver extends VcsDriver
{
/** @var string */
protected $depot;
/** @var string */
protected $branch;
/** @var ?Perforce */
protected $perforce = null;
/**
* @inheritDoc
*/
public function initialize(): void
{
$this->depot = $this->repoConfig['depot'];
$this->branch = '';
if (!empty($this->repoConfig['branch'])) {
$this->branch = $this->repoConfig['branch'];
}
$this->initPerforce($this->repoConfig);
$this->perforce->p4Login();
$this->perforce->checkStream();
$this->perforce->writeP4ClientSpec();
$this->perforce->connectClient();
}
/**
* @param array<string, mixed> $repoConfig
*/
private function initPerforce(array $repoConfig): void
{
if (!empty($this->perforce)) {
return;
}
if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) {
throw new \RuntimeException('PerforceDriver requires a usable cache directory, and it looks like you set it to be disabled');
}
$repoDir = $this->config->get('cache-vcs-dir') . '/' . $this->depot;
$this->perforce = Perforce::create($repoConfig, $this->getUrl(), $repoDir, $this->process, $this->io);
}
/**
* @inheritDoc
*/
public function getFileContent(string $file, string $identifier): ?string
{
return $this->perforce->getFileContent($file, $identifier);
}
/**
* @inheritDoc
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable
{
return null;
}
/**
* @inheritDoc
*/
public function getRootIdentifier(): string
{
return $this->branch;
}
/**
* @inheritDoc
*/
public function getBranches(): array
{
return $this->perforce->getBranches();
}
/**
* @inheritDoc
*/
public function getTags(): array
{
return $this->perforce->getTags();
}
/**
* @inheritDoc
*/
public function getDist(string $identifier): ?array
{
return null;
}
/**
* @inheritDoc
*/
public function getSource(string $identifier): array
{
return [
'type' => 'perforce',
'url' => $this->repoConfig['url'],
'reference' => $identifier,
'p4user' => $this->perforce->getUser(),
];
}
/**
* @inheritDoc
*/
public function getUrl(): string
{
return $this->url;
}
/**
* @inheritDoc
*/
public function hasComposerFile(string $identifier): bool
{
$composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier);
return !empty($composerInfo);
}
/**
* @inheritDoc
*/
public function getContents(string $url): Response
{
throw new \BadMethodCallException('Not implemented/used in PerforceDriver');
}
/**
* @inheritDoc
*/
public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool
{
if ($deep || Preg::isMatch('#\b(perforce|p4)\b#i', $url)) {
return Perforce::checkServerExists($url, new ProcessExecutor($io));
}
return false;
}
/**
* @inheritDoc
*/
public function cleanup(): void
{
$this->perforce->cleanupClientSpec();
$this->perforce = null;
}
public function getDepot(): string
{
return $this->depot;
}
public function getBranch(): string
{
return $this->branch;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/HgDriver.php | src/Composer/Repository/Vcs/HgDriver.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\Pcre\Preg;
use Composer\Util\Hg as HgUtils;
use Composer\Util\ProcessExecutor;
use Composer\Util\Filesystem;
use Composer\IO\IOInterface;
use Composer\Util\Url;
/**
* @author Per Bernhardt <plb@webfactory.de>
*/
class HgDriver 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;
/** @var string */
protected $repoDir;
/**
* @inheritDoc
*/
public function initialize(): void
{
if (Filesystem::isLocalPath($this->url)) {
$this->repoDir = $this->url;
} else {
if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) {
throw new \RuntimeException('HgDriver requires a usable cache directory, and it looks like you set it to be disabled');
}
$cacheDir = $this->config->get('cache-vcs-dir');
$this->repoDir = $cacheDir . '/' . Preg::replace('{[^a-z0-9]}i', '-', Url::sanitize($this->url)) . '/';
$fs = new Filesystem();
$fs->ensureDirectoryExists($cacheDir);
if (!is_writable(dirname($this->repoDir))) {
throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$cacheDir.'" directory is not writable by the current user.');
}
// Ensure we are allowed to use this URL by config
$this->config->prohibitUrlByConfig($this->url, $this->io);
$hgUtils = new HgUtils($this->io, $this->config, $this->process);
// update the repo if it is a valid hg repository
if (is_dir($this->repoDir) && 0 === $this->process->execute(['hg', 'summary'], $output, $this->repoDir)) {
if (0 !== $this->process->execute(['hg', 'pull'], $output, $this->repoDir)) {
$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->repoDir);
$repoDir = $this->repoDir;
$command = static function ($url) use ($repoDir): array {
return ['hg', 'clone', '--noupdate', '--', $url, $repoDir];
};
$hgUtils->runCommand($command, $this->url, null);
}
}
$this->getTags();
$this->getBranches();
}
/**
* @inheritDoc
*/
public function getRootIdentifier(): string
{
if (null === $this->rootIdentifier) {
$this->process->execute(['hg', 'tip', '--template', '{node}'], $output, $this->repoDir);
$output = $this->process->splitLines($output);
$this->rootIdentifier = $output[0];
}
return $this->rootIdentifier;
}
/**
* @inheritDoc
*/
public function getUrl(): string
{
return $this->url;
}
/**
* @inheritDoc
*/
public function getSource(string $identifier): array
{
return ['type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier];
}
/**
* @inheritDoc
*/
public function getDist(string $identifier): ?array
{
return null;
}
/**
* @inheritDoc
*/
public function getFileContent(string $file, string $identifier): ?string
{
if (isset($identifier[0]) && $identifier[0] === '-') {
throw new \RuntimeException('Invalid hg identifier detected. Identifier must not start with a -, given: ' . $identifier);
}
$resource = ['hg', 'cat', '-r', $identifier, '--', $file];
$this->process->execute($resource, $content, $this->repoDir);
if (!trim($content)) {
return null;
}
return $content;
}
/**
* @inheritDoc
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable
{
$this->process->execute(
['hg', 'log', '--template', '{date|rfc3339date}', '-r', $identifier],
$output,
$this->repoDir
);
return new \DateTimeImmutable(trim($output), new \DateTimeZone('UTC'));
}
/**
* @inheritDoc
*/
public function getTags(): array
{
if (null === $this->tags) {
$tags = [];
$this->process->execute(['hg', 'tags'], $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $tag) {
if ($tag && Preg::isMatchStrictGroups('(^([^\s]+)\s+\d+:(.*)$)', $tag, $match)) {
$tags[$match[1]] = $match[2];
}
}
unset($tags['tip']);
$this->tags = $tags;
}
return $this->tags;
}
/**
* @inheritDoc
*/
public function getBranches(): array
{
if (null === $this->branches) {
$branches = [];
$bookmarks = [];
$this->process->execute(['hg', 'branches'], $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $branch) {
if ($branch && Preg::isMatchStrictGroups('(^([^\s]+)\s+\d+:([a-f0-9]+))', $branch, $match) && $match[1][0] !== '-') {
$branches[$match[1]] = $match[2];
}
}
$this->process->execute(['hg', 'bookmarks'], $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $branch) {
if ($branch && Preg::isMatchStrictGroups('(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)', $branch, $match) && $match[1][0] !== '-') {
$bookmarks[$match[1]] = $match[2];
}
}
// Branches will have preference over bookmarks
$this->branches = array_merge($bookmarks, $branches);
}
return $this->branches;
}
/**
* @inheritDoc
*/
public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool
{
if (Preg::isMatch('#(^(?:https?|ssh)://(?:[^@]+@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $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 hg repo in that path
if ($process->execute(['hg', 'summary'], $output, $url) === 0) {
return true;
}
}
if (!$deep) {
return false;
}
$process = new ProcessExecutor($io);
$exit = $process->execute(['hg', 'identify', '--', $url], $ignored);
return $exit === 0;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/VcsDriverInterface.php | src/Composer/Repository/Vcs/VcsDriverInterface.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\IO\IOInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
* @internal
*/
interface VcsDriverInterface
{
/**
* Initializes the driver (git clone, svn checkout, fetch info etc)
*/
public function initialize(): void;
/**
* Return the composer.json file information
*
* @param string $identifier Any identifier to a specific branch/tag/commit
* @return mixed[]|null Array containing all infos from the composer.json file, or null to denote that no file was present
*/
public function getComposerInformation(string $identifier): ?array;
/**
* Return the content of $file or null if the file does not exist.
*/
public function getFileContent(string $file, string $identifier): ?string;
/**
* Get the changedate for $identifier.
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable;
/**
* Return the root identifier (trunk, master, default/tip ..)
*
* @return string Identifier
*/
public function getRootIdentifier(): string;
/**
* Return list of branches in the repository
*
* @return array<int|string, string> Branch names as keys, identifiers as values
*/
public function getBranches(): array;
/**
* Return list of tags in the repository
*
* @return array<int|string, string> Tag names as keys, identifiers as values
*/
public function getTags(): array;
/**
* @param string $identifier Any identifier to a specific branch/tag/commit
*
* @return array{type: string, url: string, reference: string, shasum: string}|null
*/
public function getDist(string $identifier): ?array;
/**
* @param string $identifier Any identifier to a specific branch/tag/commit
*
* @return array{type: string, url: string, reference: string}
*/
public function getSource(string $identifier): array;
/**
* Return the URL of the repository
*/
public function getUrl(): string;
/**
* Return true if the repository has a composer file for a given identifier,
* false otherwise.
*
* @param string $identifier Any identifier to a specific branch/tag/commit
* @return bool Whether the repository has a composer file for a given identifier.
*/
public function hasComposerFile(string $identifier): bool;
/**
* Performs any cleanup necessary as the driver is not longer needed
*/
public function cleanup(): void;
/**
* Checks if this driver can handle a given url
*
* @param IOInterface $io IO instance
* @param Config $config current $config
* @param string $url URL to validate/check
* @param bool $deep unless true, only shallow checks (url matching typically) should be done
*/
public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool;
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
composer/composer | https://github.com/composer/composer/blob/be033a851d9ba436ac0d28e14734b012a58c1edc/src/Composer/Repository/Vcs/GitDriver.php | src/Composer/Repository/Vcs/GitDriver.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\Pcre\Preg;
use Composer\Util\ProcessExecutor;
use Composer\Util\Filesystem;
use Composer\Util\Url;
use Composer\Util\Git as GitUtil;
use Composer\IO\IOInterface;
use Composer\Cache;
use Composer\Config;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class GitDriver extends VcsDriver
{
/** @var array<int|string, string> Map of tag name (can be turned to an int by php if it is a numeric name) to identifier */
protected $tags;
/** @var array<int|string, string> Map of branch name (can be turned to an int by php if it is a numeric name) to identifier */
protected $branches;
/** @var string */
protected $rootIdentifier;
/** @var string */
protected $repoDir;
/**
* @inheritDoc
*/
public function initialize(): void
{
if (Filesystem::isLocalPath($this->url)) {
$this->url = Preg::replace('{[\\/]\.git/?$}', '', $this->url);
if (!is_dir($this->url)) {
throw new \RuntimeException('Failed to read package information from '.$this->url.' as the path does not exist');
}
$this->repoDir = $this->url;
$cacheUrl = realpath($this->url);
} else {
if (!Cache::isUsable($this->config->get('cache-vcs-dir'))) {
throw new \RuntimeException('GitDriver requires a usable cache directory, and it looks like you set it to be disabled');
}
$this->repoDir = $this->config->get('cache-vcs-dir') . '/' . Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($this->url)) . '/';
GitUtil::cleanEnv($this->process);
$fs = new Filesystem();
$fs->ensureDirectoryExists(dirname($this->repoDir));
if (!is_writable(dirname($this->repoDir))) {
throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.dirname($this->repoDir).'" directory is not writable by the current user.');
}
if (Preg::isMatch('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) {
throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
}
$gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs);
if (!$gitUtil->syncMirror($this->url, $this->repoDir)) {
if (!is_dir($this->repoDir)) {
throw new \RuntimeException('Failed to clone '.$this->url.' to read package information from it');
}
$this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated</error>');
}
$cacheUrl = $this->url;
}
$this->getTags();
$this->getBranches();
$this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.Preg::replace('{[^a-z0-9.]}i', '-', Url::sanitize($cacheUrl)));
$this->cache->setReadOnly($this->config->get('cache-read-only'));
}
/**
* @inheritDoc
*/
public function getRootIdentifier(): string
{
if (null === $this->rootIdentifier) {
$this->rootIdentifier = 'master';
$gitUtil = new GitUtil($this->io, $this->config, $this->process, new Filesystem());
if (!Filesystem::isLocalPath($this->url)) {
$defaultBranch = $gitUtil->getMirrorDefaultBranch($this->url, $this->repoDir, false);
if ($defaultBranch !== null) {
return $this->rootIdentifier = $defaultBranch;
}
}
// select currently checked out branch as default branch
$this->process->execute(['git', 'branch', '--no-color'], $output, $this->repoDir);
$branches = $this->process->splitLines($output);
if (!in_array('* master', $branches)) {
foreach ($branches as $branch) {
if ($branch && Preg::isMatchStrictGroups('{^\* +(\S+)}', $branch, $match)) {
$this->rootIdentifier = $match[1];
break;
}
}
}
}
return $this->rootIdentifier;
}
/**
* @inheritDoc
*/
public function getUrl(): string
{
return $this->url;
}
/**
* @inheritDoc
*/
public function getSource(string $identifier): array
{
return ['type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier];
}
/**
* @inheritDoc
*/
public function getDist(string $identifier): ?array
{
return null;
}
/**
* @inheritDoc
*/
public function getFileContent(string $file, string $identifier): ?string
{
if (isset($identifier[0]) && $identifier[0] === '-') {
throw new \RuntimeException('Invalid git identifier detected. Identifier must not start with a -, given: ' . $identifier);
}
$this->process->execute(['git', 'show', $identifier.':'.$file], $content, $this->repoDir);
if (trim($content) === '') {
return null;
}
return $content;
}
/**
* @inheritDoc
*/
public function getChangeDate(string $identifier): ?\DateTimeImmutable
{
$command = GitUtil::buildRevListCommand($this->process, ['-n1', '--format=%at', $identifier]);
$this->process->execute($command, $output, $this->repoDir);
return new \DateTimeImmutable('@'.trim(GitUtil::parseRevListOutput($output, $this->process)), new \DateTimeZone('UTC'));
}
/**
* @inheritDoc
*/
public function getTags(): array
{
if (null === $this->tags) {
$this->tags = [];
$this->process->execute(['git', 'show-ref', '--tags', '--dereference'], $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $tag) {
if ($tag !== '' && Preg::isMatch('{^([a-f0-9]{40}) refs/tags/(\S+?)(\^\{\})?$}', $tag, $match)) {
$this->tags[$match[2]] = $match[1];
}
}
}
return $this->tags;
}
/**
* @inheritDoc
*/
public function getBranches(): array
{
if (null === $this->branches) {
$branches = [];
$this->process->execute(['git', 'branch', '--no-color', '--no-abbrev', '-v'], $output, $this->repoDir);
foreach ($this->process->splitLines($output) as $branch) {
if ($branch !== '' && !Preg::isMatch('{^ *[^/]+/HEAD }', $branch)) {
if (Preg::isMatchStrictGroups('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match) && $match[1][0] !== '-') {
$branches[$match[1]] = $match[2];
}
}
}
$this->branches = $branches;
}
return $this->branches;
}
/**
* @inheritDoc
*/
public static function supports(IOInterface $io, Config $config, string $url, bool $deep = false): bool
{
if (Preg::isMatch('#(^git://|\.git/?$|git(?:olite)?@|//git\.|//github.com/)#i', $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 git repo in that path
if ($process->execute(['git', 'tag'], $output, $url) === 0) {
return true;
}
GitUtil::checkForRepoOwnershipError($process->getErrorOutput(), $url);
}
if (!$deep) {
return false;
}
$process = new ProcessExecutor($io);
$gitUtil = new GitUtil($io, $config, $process, new Filesystem());
GitUtil::cleanEnv($process);
try {
$gitUtil->runCommands([['git', 'ls-remote', '--heads', '--', '%url%']], $url, sys_get_temp_dir());
} catch (\RuntimeException $e) {
return false;
}
return true;
}
}
| php | MIT | be033a851d9ba436ac0d28e14734b012a58c1edc | 2026-01-04T15:02:34.256072Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.